diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/METADATA b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..347f50c3e542f89c0f65e371c1607b32844b6d31 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/METADATA @@ -0,0 +1,56 @@ +Metadata-Version: 2.4 +Name: mypy +Version: 1.20.2 +Summary: Optional static typing for Python +Author-email: Jukka Lehtosalo +License-Expression: MIT +Project-URL: Homepage, https://www.mypy-lang.org/ +Project-URL: Documentation, https://mypy.readthedocs.io/en/stable/index.html +Project-URL: Repository, https://github.com/python/mypy +Project-URL: Changelog, https://github.com/python/mypy/blob/master/CHANGELOG.md +Project-URL: Issues, https://github.com/python/mypy/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development +Classifier: Typing :: Typed +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: mypy/typeshed/LICENSE +Requires-Dist: typing_extensions>=4.6.0; python_version < "3.15" +Requires-Dist: typing_extensions>=4.14.0; python_version >= "3.15" +Requires-Dist: mypy_extensions>=1.0.0 +Requires-Dist: pathspec>=1.0.0 +Requires-Dist: tomli>=1.1.0; python_version < "3.11" +Requires-Dist: librt>=0.8.0; platform_python_implementation != "PyPy" +Provides-Extra: dmypy +Requires-Dist: psutil>=4.0; extra == "dmypy" +Provides-Extra: mypyc +Requires-Dist: setuptools>=50; extra == "mypyc" +Provides-Extra: python2 +Provides-Extra: reports +Requires-Dist: lxml; extra == "reports" +Provides-Extra: install-types +Requires-Dist: pip; extra == "install-types" +Provides-Extra: faster-cache +Requires-Dist: orjson; extra == "faster-cache" +Provides-Extra: native-parser +Requires-Dist: ast-serialize<1.0.0,>=0.1.1; extra == "native-parser" +Dynamic: license-file + +Mypy -- Optional Static Typing for Python +========================================= + +Add type annotations to your Python programs, and use mypy to type +check them. Mypy is essentially a Python linter on steroids, and it +can catch many programming errors by analyzing your program, without +actually having to run it. Mypy has a powerful type system with +features such as type inference, gradual typing, generics and union +types. diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/RECORD b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1f14aea59ad94b8b4ed286372f27d323cf623bba --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/RECORD @@ -0,0 +1,1751 @@ +../../Scripts/dmypy.exe,sha256=8m9-45LJjmBe1badNKA4SJDVIRUeYB85CyPXgl2w8gY,108367 +../../Scripts/mypy.exe,sha256=-udwjXHXS4MiUafRWHrGOpqf8cvJWC-YL5BET9iG56M,108363 +../../Scripts/mypyc.exe,sha256=VoXZXVH7lICHcYU4LwKqTtlzt-SeuuhRsV1EmWS2AqU,108346 +../../Scripts/stubgen.exe,sha256=Q2Ib8EhhjOMkqDEvU0cxikQy9FDSHo58Jk2RUxSuPKc,108344 +../../Scripts/stubtest.exe,sha256=sd_WKoo9o0vLe-KBZYniLw6K6iOJY-Pbb0LAo_x3ATg,108345 +0aca9ce3d91742c5b361__mypyc.cp314-win_amd64.pyd,sha256=YCSII9VFhPRfzw3Y7Z6CrDO1STgD1PE2GaKPYXMl3No,19105792 +mypy-1.20.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +mypy-1.20.2.dist-info/METADATA,sha256=Jvm8hH-Guu4rwFicZM_y5L1EU-Ywk-UKU67wzxunfJg,2428 +mypy-1.20.2.dist-info/RECORD,, +mypy-1.20.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy-1.20.2.dist-info/WHEEL,sha256=jhxrRP3tdEfm7toB1X7dl5x6f0bu6Tve2cWwIdkbL8U,101 +mypy-1.20.2.dist-info/direct_url.json,sha256=kUJhAYWBUJHFeA4dWuzyVkqmFodZTtWS8hslocG19qE,71 +mypy-1.20.2.dist-info/entry_points.txt,sha256=DKRnGYlnjnz9_6jxYhHskdeZLwNC69R-ZPVxv3b9dpc,179 +mypy-1.20.2.dist-info/licenses/LICENSE,sha256=_fHNF_UOEwXtjP03RnMS0nqYRkjbpiLO9wVztVEuThs,12842 +mypy-1.20.2.dist-info/licenses/mypy/typeshed/LICENSE,sha256=KV-FOMlK5cMEMwHPfP8chS2ranhqjd7kceBhtA1eyr4,12657 +mypy-1.20.2.dist-info/top_level.txt,sha256=2PVTSlWteH8U4UMJ1XWOKLNMLYFRUzMlNvp0NaUVIHo,39 +mypy/__init__.cp314-win_amd64.pyd,sha256=tISpc1vaosVSoMVMlF7vIMczuoME7vAFhFDG0wCzWZY,10240 +mypy/__init__.py,sha256=4yp43qNAZZ0ViBpVn56Bc7MA4H2UMXe0WTVPdkODP6k,37 +mypy/__main__.py,sha256=F3MoYIPepYJOIKr7lWGCPsMX7PpWxuywYbqXZtKqXV8,1524 +mypy/__pycache__/__init__.cpython-314.pyc,, +mypy/__pycache__/__main__.cpython-314.pyc,, +mypy/__pycache__/api.cpython-314.pyc,, +mypy/__pycache__/applytype.cpython-314.pyc,, +mypy/__pycache__/argmap.cpython-314.pyc,, +mypy/__pycache__/binder.cpython-314.pyc,, +mypy/__pycache__/bogus_type.cpython-314.pyc,, +mypy/__pycache__/build.cpython-314.pyc,, +mypy/__pycache__/cache.cpython-314.pyc,, +mypy/__pycache__/checker.cpython-314.pyc,, +mypy/__pycache__/checker_shared.cpython-314.pyc,, +mypy/__pycache__/checker_state.cpython-314.pyc,, +mypy/__pycache__/checkexpr.cpython-314.pyc,, +mypy/__pycache__/checkmember.cpython-314.pyc,, +mypy/__pycache__/checkpattern.cpython-314.pyc,, +mypy/__pycache__/checkstrformat.cpython-314.pyc,, +mypy/__pycache__/config_parser.cpython-314.pyc,, +mypy/__pycache__/constant_fold.cpython-314.pyc,, +mypy/__pycache__/constraints.cpython-314.pyc,, +mypy/__pycache__/copytype.cpython-314.pyc,, +mypy/__pycache__/defaults.cpython-314.pyc,, +mypy/__pycache__/dmypy_os.cpython-314.pyc,, +mypy/__pycache__/dmypy_server.cpython-314.pyc,, +mypy/__pycache__/dmypy_util.cpython-314.pyc,, +mypy/__pycache__/erasetype.cpython-314.pyc,, +mypy/__pycache__/error_formatter.cpython-314.pyc,, +mypy/__pycache__/errorcodes.cpython-314.pyc,, +mypy/__pycache__/errors.cpython-314.pyc,, +mypy/__pycache__/evalexpr.cpython-314.pyc,, +mypy/__pycache__/expandtype.cpython-314.pyc,, +mypy/__pycache__/exportjson.cpython-314.pyc,, +mypy/__pycache__/exprtotype.cpython-314.pyc,, +mypy/__pycache__/fastparse.cpython-314.pyc,, +mypy/__pycache__/find_sources.cpython-314.pyc,, +mypy/__pycache__/fixup.cpython-314.pyc,, +mypy/__pycache__/freetree.cpython-314.pyc,, +mypy/__pycache__/fscache.cpython-314.pyc,, +mypy/__pycache__/fswatcher.cpython-314.pyc,, +mypy/__pycache__/gclogger.cpython-314.pyc,, +mypy/__pycache__/git.cpython-314.pyc,, +mypy/__pycache__/graph_utils.cpython-314.pyc,, +mypy/__pycache__/indirection.cpython-314.pyc,, +mypy/__pycache__/infer.cpython-314.pyc,, +mypy/__pycache__/inspections.cpython-314.pyc,, +mypy/__pycache__/ipc.cpython-314.pyc,, +mypy/__pycache__/join.cpython-314.pyc,, +mypy/__pycache__/literals.cpython-314.pyc,, +mypy/__pycache__/lookup.cpython-314.pyc,, +mypy/__pycache__/main.cpython-314.pyc,, +mypy/__pycache__/maptype.cpython-314.pyc,, +mypy/__pycache__/meet.cpython-314.pyc,, +mypy/__pycache__/memprofile.cpython-314.pyc,, +mypy/__pycache__/message_registry.cpython-314.pyc,, +mypy/__pycache__/messages.cpython-314.pyc,, +mypy/__pycache__/metastore.cpython-314.pyc,, +mypy/__pycache__/mixedtraverser.cpython-314.pyc,, +mypy/__pycache__/modulefinder.cpython-314.pyc,, +mypy/__pycache__/moduleinspect.cpython-314.pyc,, +mypy/__pycache__/mro.cpython-314.pyc,, +mypy/__pycache__/nativeparse.cpython-314.pyc,, +mypy/__pycache__/nodes.cpython-314.pyc,, +mypy/__pycache__/operators.cpython-314.pyc,, +mypy/__pycache__/options.cpython-314.pyc,, +mypy/__pycache__/parse.cpython-314.pyc,, +mypy/__pycache__/partially_defined.cpython-314.pyc,, +mypy/__pycache__/patterns.cpython-314.pyc,, +mypy/__pycache__/plugin.cpython-314.pyc,, +mypy/__pycache__/pyinfo.cpython-314.pyc,, +mypy/__pycache__/reachability.cpython-314.pyc,, +mypy/__pycache__/refinfo.cpython-314.pyc,, +mypy/__pycache__/renaming.cpython-314.pyc,, +mypy/__pycache__/report.cpython-314.pyc,, +mypy/__pycache__/scope.cpython-314.pyc,, +mypy/__pycache__/semanal.cpython-314.pyc,, +mypy/__pycache__/semanal_classprop.cpython-314.pyc,, +mypy/__pycache__/semanal_enum.cpython-314.pyc,, +mypy/__pycache__/semanal_infer.cpython-314.pyc,, +mypy/__pycache__/semanal_main.cpython-314.pyc,, +mypy/__pycache__/semanal_namedtuple.cpython-314.pyc,, +mypy/__pycache__/semanal_newtype.cpython-314.pyc,, +mypy/__pycache__/semanal_pass1.cpython-314.pyc,, +mypy/__pycache__/semanal_shared.cpython-314.pyc,, +mypy/__pycache__/semanal_typeargs.cpython-314.pyc,, +mypy/__pycache__/semanal_typeddict.cpython-314.pyc,, +mypy/__pycache__/sharedparse.cpython-314.pyc,, +mypy/__pycache__/solve.cpython-314.pyc,, +mypy/__pycache__/split_namespace.cpython-314.pyc,, +mypy/__pycache__/state.cpython-314.pyc,, +mypy/__pycache__/stats.cpython-314.pyc,, +mypy/__pycache__/strconv.cpython-314.pyc,, +mypy/__pycache__/stubdoc.cpython-314.pyc,, +mypy/__pycache__/stubgen.cpython-314.pyc,, +mypy/__pycache__/stubgenc.cpython-314.pyc,, +mypy/__pycache__/stubinfo.cpython-314.pyc,, +mypy/__pycache__/stubtest.cpython-314.pyc,, +mypy/__pycache__/stubutil.cpython-314.pyc,, +mypy/__pycache__/subtypes.cpython-314.pyc,, +mypy/__pycache__/suggestions.cpython-314.pyc,, +mypy/__pycache__/traverser.cpython-314.pyc,, +mypy/__pycache__/treetransform.cpython-314.pyc,, +mypy/__pycache__/tvar_scope.cpython-314.pyc,, +mypy/__pycache__/type_visitor.cpython-314.pyc,, +mypy/__pycache__/typeanal.cpython-314.pyc,, +mypy/__pycache__/typeops.cpython-314.pyc,, +mypy/__pycache__/types.cpython-314.pyc,, +mypy/__pycache__/types_utils.cpython-314.pyc,, +mypy/__pycache__/typestate.cpython-314.pyc,, +mypy/__pycache__/typetraverser.cpython-314.pyc,, +mypy/__pycache__/typevars.cpython-314.pyc,, +mypy/__pycache__/typevartuples.cpython-314.pyc,, +mypy/__pycache__/util.cpython-314.pyc,, +mypy/__pycache__/version.cpython-314.pyc,, +mypy/__pycache__/visitor.cpython-314.pyc,, +mypy/api.cp314-win_amd64.pyd,sha256=QdCgDC8yI9WreBgLELLCwPaosd5uLVPoLBnQ1w43bAQ,10240 +mypy/api.py,sha256=QlzdLRQb86I8d6p7Ph9HPxq1miRg_mrXl0UYDr9Vxsc,2949 +mypy/applytype.cp314-win_amd64.pyd,sha256=wleeW7G4LtVDQdkITbAz97t1OQgi_dsAZymrH9JpS58,10240 +mypy/applytype.py,sha256=MS5D8lbxsCAwVwoaRdd8Syh2_PddlnSlnx9tIA74Olk,12032 +mypy/argmap.cp314-win_amd64.pyd,sha256=jRn_JByuTuLi6piaq4LoTVEWOcDAgBDjwayKLNY4z7Y,10240 +mypy/argmap.py,sha256=05e1yn4g89hbXkPDMgUb6iKZfcAVmplMBbdKV0vL5gI,11416 +mypy/binder.cp314-win_amd64.pyd,sha256=LCqWPIi8R_Fp_MB4dpnB_6jcz9QLV3bVN_nuEwP2srs,10240 +mypy/binder.py,sha256=hH54Bn3DUqHaa0el76KcJwHAv-Xs7VIoddFhr3em7Xg,28610 +mypy/bogus_type.py,sha256=w3GrsWoj5FKbfEUsc87OVFO812HC9BvnWnSaV2T4u1c,816 +mypy/build.cp314-win_amd64.pyd,sha256=8RmZhqx4NNOG9NaVW_Gpu6AjA7d7SR0QPTKyzjTTY8U,10240 +mypy/build.py,sha256=5ABbHtNyahBOM03wQKisDloionskpTradQkGbENXpaE,193755 +mypy/build_worker/__init__.cp314-win_amd64.pyd,sha256=R4hrX-0uJblxocgASP6rMoEYSHUncw_BR857F36gt3k,10240 +mypy/build_worker/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/build_worker/__main__.py,sha256=v97-y5Te1hke8wIUJj4AtYyXRc6vKBimTz8vl2HUGAw,135 +mypy/build_worker/__pycache__/__init__.cpython-314.pyc,, +mypy/build_worker/__pycache__/__main__.cpython-314.pyc,, +mypy/build_worker/__pycache__/worker.cpython-314.pyc,, +mypy/build_worker/worker.cp314-win_amd64.pyd,sha256=l4Z8VqxwzzPbHsJBNmH6bsGYxOeKM5fyCiyQA4b3_BU,10240 +mypy/build_worker/worker.py,sha256=ss8bZabamRZxIWFIap4ybitcKx6Od2AtDpwrPbXNIZc,9272 +mypy/cache.cp314-win_amd64.pyd,sha256=yDFEu3k5C2NOY0RAef14K3lHhREb6_dBpTrl-oN8--w,10240 +mypy/cache.py,sha256=gphQeVLtG2mF0WjqlmiSdGQpQnsyeKhJWu3zKxjrdRM,19278 +mypy/checker.cp314-win_amd64.pyd,sha256=Zmv4u3Y9lofeEguOGAvCYLB_OwfIo8HwQ3KDSYKaJrI,10240 +mypy/checker.py,sha256=olknIUeqq2maiNP5_10SPXDPB5f4DK94etFmtECfVIs,430682 +mypy/checker_shared.cp314-win_amd64.pyd,sha256=G_aNwq4Dx8b_APGspLmGNHZJjTMs0mk2ssGSi1joYOU,10240 +mypy/checker_shared.py,sha256=YdeUPR4m0aBNBxNI55aqCJVUM_WQ-Zs7boRfqfNi7y0,10613 +mypy/checker_state.cp314-win_amd64.pyd,sha256=8so07UrLc95rqaotsa7KXtVm_IKNXYvmoPw65FatZfs,10240 +mypy/checker_state.py,sha256=JqVXZnHaqh0oWmLIWPZdLEct9lUCUe9gUFCTu8WT0hQ,858 +mypy/checkexpr.cp314-win_amd64.pyd,sha256=0hPVI9iabKu5I8Lsc_LhSedMUc31RPhvbi6A3aRWkKQ,10240 +mypy/checkexpr.py,sha256=HfrcO__WJtAcYKASi4uqUQmY__r1g4kkqXeKIxu5E3Y,303324 +mypy/checkmember.cp314-win_amd64.pyd,sha256=9TcnqaHmRboCU7SmmfAjiqYYCKI85_zI5UD16vjla84,10240 +mypy/checkmember.py,sha256=j5zPRGGz1odKJG1rGQ7QwazyW4zvsdVh0WWizS1DS1Q,64435 +mypy/checkpattern.cp314-win_amd64.pyd,sha256=iw67_WjhdtkwcVt0eT-XlZep2fH0umDAV4lV43Kt6f8,10240 +mypy/checkpattern.py,sha256=iP7rtUHnkvrOqiDYOBfunkplJHIJb9YhgL4rb2UQKAs,36820 +mypy/checkstrformat.cp314-win_amd64.pyd,sha256=J6GcI_5kGEfr_87QSuNwJZNnciTMop1IKZPwTWwDY6I,10240 +mypy/checkstrformat.py,sha256=eFxoYgS5IM73Hqzi-bUENJmbUe-Vo1PAbGo04AMjLF0,46015 +mypy/config_parser.cp314-win_amd64.pyd,sha256=73yl6wLWwGTddu1cW26HAvpW-F55sx1wXLPlxePjogo,10240 +mypy/config_parser.py,sha256=p4UjHSpaPgyAnGrXtF3-4QBt9Z2Bl5XYMpIYl2LDW-k,26326 +mypy/constant_fold.cp314-win_amd64.pyd,sha256=04HGphVtyjrF9KiRctf8AdFugAG3xVFkrI2s5lVFGVo,10240 +mypy/constant_fold.py,sha256=-s2aJ5GEIUPuzAP5Gh7b1lv6EOO-ILMKabTlC50ymeQ,6061 +mypy/constraints.cp314-win_amd64.pyd,sha256=2oAHekJRWvflYj8eBl0KYFq-QxJ6Ce9cw4FkBrD2SPc,10240 +mypy/constraints.py,sha256=1SP9ZeVOCowI2vmlHEG97VbZiPcY3nJP2pe20zlc2s8,79294 +mypy/copytype.cp314-win_amd64.pyd,sha256=xN9nx_Qhr_VTcKDNVlmIbJN2zHoN1GgznOPv5Rb-Maw,10240 +mypy/copytype.py,sha256=aDVQNWXI98-DyxvtB6inUaEO3B_IZCN9HIpUtmkZcdU,4448 +mypy/defaults.cp314-win_amd64.pyd,sha256=NUpt2tdt3kHAV3qGkMapcGA3broV26e3mi6OuWkAnUs,10240 +mypy/defaults.py,sha256=-M_v4prk46YcNEHGsSH_fuRci_noEE0T3S-CpIwTKg0,1666 +mypy/dmypy/__init__.cp314-win_amd64.pyd,sha256=2krnVnQT_Oftm0BAGCS4NoepteuWzmjtyb1XB_9EKvU,10240 +mypy/dmypy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/dmypy/__main__.py,sha256=u6ZYw52bfIJ11Oo88mzx7p4WD2WUo1-H9PRsT45eswU,128 +mypy/dmypy/__pycache__/__init__.cpython-314.pyc,, +mypy/dmypy/__pycache__/__main__.cpython-314.pyc,, +mypy/dmypy/__pycache__/client.cpython-314.pyc,, +mypy/dmypy/client.cp314-win_amd64.pyd,sha256=2c6k7hfF8YUOfVYrQ2Ynd8qBptHXR3-PXHpNOx9t3NI,10240 +mypy/dmypy/client.py,sha256=8LN2G1OWXWOzrWcA5LaSRhwmVtBCLgGdHdcOxtnVWzQ,24276 +mypy/dmypy_os.cp314-win_amd64.pyd,sha256=KMqYYQb7Nq1Kk8v3udOfvQHPFmbpaaqSgZnpyvVAFD4,10240 +mypy/dmypy_os.py,sha256=ON1h-kGywstKXeIYkBEuv6Tk-XammrZrDy1PhskETXs,1181 +mypy/dmypy_server.cp314-win_amd64.pyd,sha256=b46yUHEIBli4v98HT66qZDUWL6BGnzpkh9k9E8QQllk,10240 +mypy/dmypy_server.py,sha256=y9dw8OFJS__cAGH04icnvTimwW29qgMbLt7pRp2x3UQ,45611 +mypy/dmypy_util.cp314-win_amd64.pyd,sha256=7JK8GnqlR5HYuTnUW4Lgw0lr4hZ-fXt7H9OohZahRQc,10240 +mypy/dmypy_util.py,sha256=Qmmxof6Jdzy5zD6lX4-DF47dqAJNmoRmLYy_lJag9PY,3006 +mypy/erasetype.cp314-win_amd64.pyd,sha256=Z1oU5h6-tFJejPbPFzkBiDIC7OAxfR7D3ypdoqbHykA,10240 +mypy/erasetype.py,sha256=LI9br4FTWqK7ns-lcks4bnrTu31xR_3vPmfWuhFIyaU,11309 +mypy/error_formatter.cp314-win_amd64.pyd,sha256=PXPaePKgXW2yK-EWaDv0f_T0fIoT9ALqN7jWfq1oG3M,10240 +mypy/error_formatter.py,sha256=xBGtUNrEjzB-W6TZaSLLpwPH2XFGcjVk2tltaImNYxo,1165 +mypy/errorcodes.cp314-win_amd64.pyd,sha256=rvTju4wI2zm20IWO55gIBRQs8jUSJv63x6xT0M1kyNc,10240 +mypy/errorcodes.py,sha256=ydp7yz98G0lHqd6IVRV_hk05Rv7_t1qVfTSBFTUlyoc,11892 +mypy/errors.cp314-win_amd64.pyd,sha256=J4ZNcR5LUeiAz9OQst0K4Kfk0UJF50yldChyb0MO3Uo,10240 +mypy/errors.py,sha256=Uyua4SUD1hqOkLqCKJtUk7Rllk4unK-wOCZQeJEGEVk,57154 +mypy/evalexpr.cp314-win_amd64.pyd,sha256=FcqRCNEPWYjyhWTORXt1N5DjKgialxpDEt3WoyogPDs,10240 +mypy/evalexpr.py,sha256=Xhf7PqYRdp9IPQ8anGl-o6iyUYJB3oxG0j0UVUnSyCI,6764 +mypy/expandtype.cp314-win_amd64.pyd,sha256=3jCQr2I2GPmEOqMp2uiuxhk1dKrPDYiWtVAzSy-4GjE,10240 +mypy/expandtype.py,sha256=ch-DfjNd_E8yfE2Q5UplYHr0QirXPNSTdjHoXmQSBuM,29037 +mypy/exportjson.py,sha256=KVZ2fmZb6ZYaAJyG3WcsoBBdFrx1jCNsKxvVSXKaGq4,20250 +mypy/exprtotype.cp314-win_amd64.pyd,sha256=mXurnqq-JRPObbo1tOj7glElFmvFZsxHS85BslymdYY,10240 +mypy/exprtotype.py,sha256=-RJZodKL7whZ885BGGrQDNvTYByy9AXwHXaTfpdiKHw,10598 +mypy/fastparse.cp314-win_amd64.pyd,sha256=I90dsZyXLW_73VbEY0BnMp93F2olLB8z0YuGfs0YCKM,10240 +mypy/fastparse.py,sha256=u5qU6oEmJB_FiFhwo5tb8H0XQ42hIxMc0lxCSEzrVp8,87410 +mypy/find_sources.cp314-win_amd64.pyd,sha256=nkyCZucDVvyAj5XrCdpyCqdKozHkrzeb-d5jTFzNHww,10240 +mypy/find_sources.py,sha256=4Fqa1H1js009UUDVGpaW1BwT0Sm-hm7HzUUtxeEgiFY,9734 +mypy/fixup.cp314-win_amd64.pyd,sha256=VB37ZJqaK8hPVuMuTR8iYZaI61VQpQ1j1ymQ_14muU8,10240 +mypy/fixup.py,sha256=OCBOWLUaOv38M-7Lp_5CZ6lexfvp6D4-s_vfcy2TiM0,16600 +mypy/freetree.cp314-win_amd64.pyd,sha256=vLQntz8cfOVZY_sIOMyUqmJTllT1zXA1FVG21BUNaD4,10240 +mypy/freetree.py,sha256=yz4_ZUq8Ja89176nbDEAiBk-Et2nP74_KXyCcaW4inA,617 +mypy/fscache.cp314-win_amd64.pyd,sha256=-hNS8U7rkavvvjeGuBInwiXTfyG60q6-GaB_7iRVNmA,10240 +mypy/fscache.py,sha256=9YJBIKHPjk8Vzd9Yube6sXIzxrOdq-b2bG8kebzAUV0,11102 +mypy/fswatcher.cp314-win_amd64.pyd,sha256=_y54Rdtz7kNYJQLrVQ3rwSyDu7Elc-NBiz52lZ6ubrw,10240 +mypy/fswatcher.py,sha256=FSTEaV9NmgNZArX_A9Wox7wofa5vg9-GPgTEZWqx3yY,3985 +mypy/gclogger.cp314-win_amd64.pyd,sha256=pR-D8bKi-lOxLlEyXPlMNM6OcowN64SeMFk2ynYJXWE,10240 +mypy/gclogger.py,sha256=E-xdukA7h0ttgwFquruln_thKmREjbYA3dIkj8fYC-k,1639 +mypy/git.cp314-win_amd64.pyd,sha256=b0SEA6_GKUIYQ84DWMnZ6058vEJoe1mUMmBsWjG4rTY,10240 +mypy/git.py,sha256=FYdMg-3fTtikKjUwfFPXbWiNmpOIMG4rNgMAWIPBsLM,980 +mypy/graph_utils.cp314-win_amd64.pyd,sha256=ovEImSnOhge6t79Bn6AW1F-dZ1zk70PPrOz8LFGEdXE,10240 +mypy/graph_utils.py,sha256=WWjUg_g9DkwEL9xAHprtnkda7J3LWC-8gES-NNOS5XA,4983 +mypy/indirection.cp314-win_amd64.pyd,sha256=BEYR7xclWRDfSNIOBRGZnabrEqfTwgYifpBNvZSo7IQ,10240 +mypy/indirection.py,sha256=KkInogFEpns3MjtSQpVXgK64T7Dc5_4_0xb8qUhaopw,6432 +mypy/infer.cp314-win_amd64.pyd,sha256=yzCf0XtuugYu5J3dF0YN4he30j08jqwo7NGdP-lUq3E,10240 +mypy/infer.py,sha256=J8bcCjYFX7VZ4UjazbYC9SmAR2LA8eczsLvh1Ay14Yw,2538 +mypy/inspections.cp314-win_amd64.pyd,sha256=0bcVVwhgYh-7wrAgdkG4Q4fQrpjPi4lmiHQbfeejtGc,10240 +mypy/inspections.py,sha256=PWBbzmgERls2fKj5_5UGbBIr0xdsDUDn7adt5phMWak,23813 +mypy/ipc.cp314-win_amd64.pyd,sha256=QZThVN5sXSyfZehaUGULzAgyRKN7LRWc-mZoRgijr5w,10240 +mypy/ipc.py,sha256=pn5Z3TVEdFWJ0IyVRLQmkQe3ctn-qGvPtf3vQ3s5iAU,17139 +mypy/join.cp314-win_amd64.pyd,sha256=LBcG5owhHhr4jZ8WBI7XV8oDY_ykVGsEnM3tygIy8Fc,10240 +mypy/join.py,sha256=2o27_dKqCw8zv2wmWUqkFNAE4HG5BSvkKR4QFkTACLs,39575 +mypy/literals.cp314-win_amd64.pyd,sha256=tdYKOYlvCcUlix1rnipxREaXSBHT0tWDctEyuHw1p3c,10240 +mypy/literals.py,sha256=O6utOL4wLNztx8Lp1bg7ICQ58Sprh1_DYFdTGtUm36Y,9412 +mypy/lookup.cp314-win_amd64.pyd,sha256=AXbRqv-8vuuC7ktwjpL5zH3GsZvEuw9UgrVoCT1SJ3A,10240 +mypy/lookup.py,sha256=deiZ7pNVOYZiF0ShjGj47nOgmJ6AgREIdEbYrDdiGPk,2454 +mypy/main.cp314-win_amd64.pyd,sha256=BSB-OLCxsGwbyDn02k6XKqNh3Svv4-3g4a9-4abDxT4,10240 +mypy/main.py,sha256=94z8Vwa4EpgHNywMfouyWZ3GGinSh1N2kWqeRhsxHqA,64579 +mypy/maptype.cp314-win_amd64.pyd,sha256=KcFEz_ya8q9cTCIQb7HdrUoZIHTNIUay-brDNoa1NyA,10240 +mypy/maptype.py,sha256=USEg3N_4LCesekOVOLhwFoq65urhcR5CotSkprcJleU,4331 +mypy/meet.cp314-win_amd64.pyd,sha256=0kbn-9O4-vvbloZG-d71XwC4pCaMhmgYaqs1Mrp43_A,10240 +mypy/meet.py,sha256=Zt97DMWfZIpAaSNGEdVGEwjD2kLTnY4mSO39JaKmMQw,54063 +mypy/memprofile.cp314-win_amd64.pyd,sha256=jbX4W1SmiWtTLQsINEjYBX2mE1D4C0M5CofnOCweDUY,10240 +mypy/memprofile.py,sha256=Ar4FwaVBON42iT2OHHoj6_G5VL1YNnPAZU_cp4mgll8,4174 +mypy/message_registry.cp314-win_amd64.pyd,sha256=dk3oiKm_lBqBmc1apSDYXTLBsg3eyCV72gRrwZaZ4bU,10240 +mypy/message_registry.py,sha256=K4DTLVvT4K6TcT2rmg6AxCm5GInRag3c4AwF3WZlh3o,17320 +mypy/messages.cp314-win_amd64.pyd,sha256=0uek2lKd0QLrU99i-foYN_J0W12ooOXAFtA_1RMbMPg,10240 +mypy/messages.py,sha256=9TPr3XXaqa5QnuSHmftglX5M5WELOsEB4k5KwMhFJGc,137038 +mypy/metastore.cp314-win_amd64.pyd,sha256=e6c_jRQNLlkipHS8at0uF5ftxTiFMX3uxF0X5Dvd8ps,10240 +mypy/metastore.py,sha256=8934plg_MMhbyknKYG88jRmJROIGQQD3nlrO99I6k30,7339 +mypy/mixedtraverser.cp314-win_amd64.pyd,sha256=Ejr0rnC0RWwKWaxiC4lI4kpvd50nMbfCcQHRMsJaAE8,10240 +mypy/mixedtraverser.py,sha256=q0VwDWsSDmjkD4h0tBSWSj74WXkkXiBSXerSFeBiNzg,3852 +mypy/modulefinder.cp314-win_amd64.pyd,sha256=bbr5LPBVnx9UsjBOq5BNil_1X47-dEDcxZBazBv3EYI,10240 +mypy/modulefinder.py,sha256=abTHalmYq4MxEpVxzfuyF1rAIKT502eguO4hQpD_DuI,42875 +mypy/moduleinspect.cp314-win_amd64.pyd,sha256=Tz6NlCV46FEPFo6MylMZe9aPwu2oiWaROfQaGMR0t4I,10240 +mypy/moduleinspect.py,sha256=HCEI7yW61OkMNFqUqjuRB09HcTDpalcmtVBYjlWfxyo,6326 +mypy/mro.cp314-win_amd64.pyd,sha256=GQ0p-yt9MDErhuMfYjwjQkctc13UYb0QCmVr0UHMitU,10240 +mypy/mro.py,sha256=hSrgh1E8QhWpxpgTKe-Jt2OyjSyjIr8wDwpZoSLOf1g,2002 +mypy/nativeparse.cp314-win_amd64.pyd,sha256=94Fhh13MoL-AMEkvHcrrzb1VJqtr277bT_UexldHrpg,10240 +mypy/nativeparse.py,sha256=G7zkISdW3JgPyVBfmGeE9tZTQexnp_kvIrqEgnAEuHY,72662 +mypy/nodes.cp314-win_amd64.pyd,sha256=qrjQ513Sd1cc7qgK88BXZsxbooxFKs5Ma8dkkJSoLWs,10240 +mypy/nodes.py,sha256=JmEUCuALJTC_coi0CssawjCRi3XUKmCTvUW0Iw_bVIg,179975 +mypy/operators.cp314-win_amd64.pyd,sha256=S1Eh5HbMcStYCN5H2WDFnAsAuC5809ZV12UJuhFCcCg,10240 +mypy/operators.py,sha256=BHafr2ENZYPmUytEgKOYMS1GwPKFebWBs5pnk8pyZk8,2866 +mypy/options.cp314-win_amd64.pyd,sha256=Te1LYresdDJJ38nhvDWtpVCuJBcrtAceI1zZ18qiG7E,10240 +mypy/options.py,sha256=luzjO9dHrqoekP78_4agKrw_vK05G2bl0q1COf9i6WQ,27389 +mypy/parse.cp314-win_amd64.pyd,sha256=V8LEtVDSK-uPxxBEtyi0nvxs_gMulOFhSrYTuq2TEv4,10240 +mypy/parse.py,sha256=NmFWX6KHKYJN5KW9ckP5M0RwSv1MkS7cn4e8SGH1d8g,4996 +mypy/partially_defined.cp314-win_amd64.pyd,sha256=OmrCFIEIPV6u9RwIZFOqYmoaKz6o-6LpZOBrvwgjVRQ,10240 +mypy/partially_defined.py,sha256=FBqB9W4v27q6Mj9No5WNf5jjsUsEkTvyMKaTueI7quQ,26746 +mypy/patterns.cp314-win_amd64.pyd,sha256=_pjR2abjKud250-6nDqvUrNEai61-menG65H5Q9jGkU,10240 +mypy/patterns.py,sha256=epS_R9Fv5mnSAGsc6EtUxtmo34_DD1lJ5BevTdMn8Ak,4048 +mypy/plugin.cp314-win_amd64.pyd,sha256=STqV0V01TxsGq2WSDspPtYDgmS1HWZ2azDwlOFN97xU,10240 +mypy/plugin.py,sha256=yAcCukIWW2zflHpeiltIO6wKxXzoJr5s_cgfLep5Ngw,36250 +mypy/plugins/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/plugins/__pycache__/__init__.cpython-314.pyc,, +mypy/plugins/__pycache__/attrs.cpython-314.pyc,, +mypy/plugins/__pycache__/common.cpython-314.pyc,, +mypy/plugins/__pycache__/constants.cpython-314.pyc,, +mypy/plugins/__pycache__/ctypes.cpython-314.pyc,, +mypy/plugins/__pycache__/dataclasses.cpython-314.pyc,, +mypy/plugins/__pycache__/default.cpython-314.pyc,, +mypy/plugins/__pycache__/enums.cpython-314.pyc,, +mypy/plugins/__pycache__/functools.cpython-314.pyc,, +mypy/plugins/__pycache__/proper_plugin.cpython-314.pyc,, +mypy/plugins/__pycache__/singledispatch.cpython-314.pyc,, +mypy/plugins/attrs.cp314-win_amd64.pyd,sha256=xZKIEEkGMhN8L1i7FYL_e_caSmOhTQJsv2lGyVtCeWs,10240 +mypy/plugins/attrs.py,sha256=iMslFOlnQDVAhx9sYpj_yIDtKe_0uBXX0LcwREcEt30,46508 +mypy/plugins/common.cp314-win_amd64.pyd,sha256=6jXyGezukiFHoImKjqmiCw-07ogmbsz6TOMLE-Ogd8w,10240 +mypy/plugins/common.py,sha256=ikFQb2netqmmSW_72Ydz7j1TeUqG4teFuP1DnpOOLDY,14117 +mypy/plugins/constants.cp314-win_amd64.pyd,sha256=vFo-uwHl3d78LwAolUk4j5ArtZy5-JPmw2iHCjXQV3U,10240 +mypy/plugins/constants.py,sha256=EhWnIlkU1lHkF6CwlVqEitQE9dM9PfdZn35bHMI37jc,819 +mypy/plugins/ctypes.cp314-win_amd64.pyd,sha256=BVCQ1wVWv9cFJUA4DVykPAuaigLDx6dTkuY71lP6VvA,10240 +mypy/plugins/ctypes.py,sha256=uB84xNCEzCVfeKjC7FHy7dFF5o55V3L-Rve9OD3YoxM,10675 +mypy/plugins/dataclasses.cp314-win_amd64.pyd,sha256=-MnmxIB5a27ac0UO-Ri1bIHxRMHXW1tLciLx69K5gF4,10240 +mypy/plugins/dataclasses.py,sha256=W9IL9DM6m8vS1QSk19ErChLQtn3R3IMrJCHWlXj48lY,47255 +mypy/plugins/default.cp314-win_amd64.pyd,sha256=MfE3fFmASpJiL7I0Z4I8KkfHzhBxCxYuhvpoRfVIfc0,10240 +mypy/plugins/default.py,sha256=lzAE4nBuduJ7_hDRkRdFU0h1Y6lxXNi_heEosgzfDWE,24118 +mypy/plugins/enums.cp314-win_amd64.pyd,sha256=8tWMhLAtlMG47B9wToz0wIegqi_yNF-rwF3niSkvaYI,10240 +mypy/plugins/enums.py,sha256=XocRVf78mw3sOih8fVgjrhuEWfp1simmjKOyXbcdgZs,12110 +mypy/plugins/functools.cp314-win_amd64.pyd,sha256=VxuU-rG9HIEcwgVo0EfRthKC17cuODmhusSNBaZmdQg,10240 +mypy/plugins/functools.py,sha256=EcsCnQbhzfRBsePy3K7T3HNziDU5n84GLdAJb9ayX4s,15527 +mypy/plugins/proper_plugin.cp314-win_amd64.pyd,sha256=vwwX0o9GGY_NBlYMOKDQTdwWQaLi4rL9BxZAmjG3vh4,10240 +mypy/plugins/proper_plugin.py,sha256=HcrOREPKTWcvnA2BRW7m_-xxOQnnk4wU1Y3YKk9duoc,6574 +mypy/plugins/singledispatch.cp314-win_amd64.pyd,sha256=QX8HgCzEN94cJRbnTizohzSRDqLWH0rW-Ou1_ejwwgc,10240 +mypy/plugins/singledispatch.py,sha256=rEHOqk3DUvt4WUcI7ShnNJCg_QHj4kggEqDwPa8gcy4,8151 +mypy/py.typed,sha256=zlBhTdAQBRfJxeJXD-QnlXiZYsiAJYYkr3mbEsmwSac,64 +mypy/pyinfo.py,sha256=URtMQq4FxPkrPWB2jd8wQGDegZFoIvO8jM_AWTayOiY,3014 +mypy/reachability.cp314-win_amd64.pyd,sha256=kp7i6FjW70WankX_vLgEOd9--nNhDDgoSNtDUq-Lu4U,10240 +mypy/reachability.py,sha256=ti74QpP4fGo_2jqKdECU4lA2yUNtQKnoOF9X5gICviA,12977 +mypy/refinfo.cp314-win_amd64.pyd,sha256=ShIAj6cmCnPAWWyRPAaUXJ4Og1foO-wQo7EVQG2SYZU,10240 +mypy/refinfo.py,sha256=qaWKWtkgdlYQVxNucU3KG-4U2OsOBCSG8K8lqupc2S8,2784 +mypy/renaming.cp314-win_amd64.pyd,sha256=IXUfZRu-er6RGaTQCtQ1uz6Tt6qzVFnEJyVXkhSHc1M,10240 +mypy/renaming.py,sha256=-Ju3NKpUnJyvU8FSzZR-KgipUAIpRhrLiIVE2395NVo,20494 +mypy/report.cp314-win_amd64.pyd,sha256=vdSuKlT6aJHn1wO05K4fb_Nvxg3teewnYbcSk6nB9H4,10240 +mypy/report.py,sha256=885-LtqRZy2cawgZQ3Nw1NRL5hXSb-EAjCnmhjm2M3E,34700 +mypy/scope.cp314-win_amd64.pyd,sha256=P2WUV5EynAo9TQACcgM75ndbZq14XU9pRduDYrV8Rw4,10240 +mypy/scope.py,sha256=G9RJNrV_mJkkaNgWn5G4uNgJgNsMsA6ZBVGu7K7AGLI,4233 +mypy/semanal.cp314-win_amd64.pyd,sha256=cjH143SYu_uO86_aTgQLuLobMPLRMqGLbxn-NFjkVgc,10240 +mypy/semanal.py,sha256=7tHKS6ChLYfjvNmdFWdOyFZ-xo-zV6qoiOwJ0T2W408,361221 +mypy/semanal_classprop.cp314-win_amd64.pyd,sha256=4MqVpiW6Llw8ZUtyuOJrQzRAxDTfuuzEa_r6owFoods,10240 +mypy/semanal_classprop.py,sha256=81ClR1KA27TDEIl04vN3cpLPTVMEJphFiGp4n87kRjY,7673 +mypy/semanal_enum.cp314-win_amd64.pyd,sha256=OArncgp021mKk33070XyQiwOqnZ_jgTo_zK4B6q8Jy0,10240 +mypy/semanal_enum.py,sha256=NfHeW7rlHu0qzuXOOWFkCrITCHsNcMJxZDb58hNobCw,10197 +mypy/semanal_infer.cp314-win_amd64.pyd,sha256=_XWAC8xuQSjhr7IXbUJ2463Zm2P0mpf2li495ltnPgU,10240 +mypy/semanal_infer.py,sha256=ysch4tIEiwxefw_1LPSqB2wTyoJbnlOmCfO4Iq-_bC4,5350 +mypy/semanal_main.cp314-win_amd64.pyd,sha256=vnz45JGPwaZcab6wHFFXzFyqtidOnHEUBiQgNgqCXrY,10240 +mypy/semanal_main.py,sha256=B-1rINrKkpvt4J3iAk4ffPgMZWAH5kGpGx3yNMiGI6Q,21554 +mypy/semanal_namedtuple.cp314-win_amd64.pyd,sha256=RMy5lPa6Og3VdyoB7kxE3REetVjKGyPgcWT217PcMs8,10240 +mypy/semanal_namedtuple.py,sha256=aXCavynnPDXGStwD2nODpYOGYGCuZPfZjbZNp31RZGI,31368 +mypy/semanal_newtype.cp314-win_amd64.pyd,sha256=kfUsIKlt5SuuZCQrleGX0dYk1iQQM73QZO0pQBNFaXg,10240 +mypy/semanal_newtype.py,sha256=-kKdzbYvTuUpRqKMN9GpFSBqkKGZqFIDKf57pkoscUs,10576 +mypy/semanal_pass1.cp314-win_amd64.pyd,sha256=mpjfJ-6oC98n_DFptomEbp_N-9Ww0y84hec6Womouv4,10240 +mypy/semanal_pass1.py,sha256=6rhzEF6V7orOsgjYsnGHz8lqaG3TA-gr8QFA_ytihkc,5584 +mypy/semanal_shared.cp314-win_amd64.pyd,sha256=LWq77NaqA8qILYgC0mVkq4_qeZgeLiT_FttoMUnuB7c,10240 +mypy/semanal_shared.py,sha256=cw9UZAp1sPzXAmLuiIuTL_vK8lAx_Y8V4fW9iP515RI,15795 +mypy/semanal_typeargs.cp314-win_amd64.pyd,sha256=p0bmkDe-vBVzoU02P3fEzRM4yslr2GBw9CiLv3Tj34c,10240 +mypy/semanal_typeargs.py,sha256=Qw8UCzpRATUXSILVSLi8PvPqOzsTf5BiNV2RTorwlP4,13338 +mypy/semanal_typeddict.cp314-win_amd64.pyd,sha256=V_cKWZ3p1rxaT0EuvyDuGXDyZP3M8Zp1TPvV8mw274s,10240 +mypy/semanal_typeddict.py,sha256=P499w_SQXrTdw_4w_zvOW4YwlDxixKwQeB0yGfOncV4,26043 +mypy/server/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/server/__pycache__/__init__.cpython-314.pyc,, +mypy/server/__pycache__/astdiff.cpython-314.pyc,, +mypy/server/__pycache__/astmerge.cpython-314.pyc,, +mypy/server/__pycache__/aststrip.cpython-314.pyc,, +mypy/server/__pycache__/deps.cpython-314.pyc,, +mypy/server/__pycache__/mergecheck.cpython-314.pyc,, +mypy/server/__pycache__/objgraph.cpython-314.pyc,, +mypy/server/__pycache__/subexpr.cpython-314.pyc,, +mypy/server/__pycache__/target.cpython-314.pyc,, +mypy/server/__pycache__/trigger.cpython-314.pyc,, +mypy/server/__pycache__/update.cpython-314.pyc,, +mypy/server/astdiff.cp314-win_amd64.pyd,sha256=gtdpFL8_XPdBslRScB9KtXvQqgWIvQQBOVy0qNMc9pc,10240 +mypy/server/astdiff.py,sha256=gw6zjRsETX73Rb6ZGFKJZikEH7fK_TcJbxB0ep8M0DE,21362 +mypy/server/astmerge.cp314-win_amd64.pyd,sha256=VqZfirPHoUmpVgu04xhU81tfmUhImdjkjj5z-5RHqlM,10240 +mypy/server/astmerge.py,sha256=4_uLEbB2qQhdorpr8EwrGtBnVk5Dw8PhjEkuBlmHThw,20982 +mypy/server/aststrip.cp314-win_amd64.pyd,sha256=K6G_mmIedQNhjIQL7ndFQtYrmQtJ6hFrWVp1prOicao,10240 +mypy/server/aststrip.py,sha256=f8EY1kzRCUL_sR1SufJgwkbLC7A5IAOjwDRJE9Hhr2o,9789 +mypy/server/deps.cp314-win_amd64.pyd,sha256=QWDkRMl_YzuOalsv1vWAYDR-2rP3KxuImxvAPlvireU,10240 +mypy/server/deps.py,sha256=MJxOLZF08Ta9XgzBh982CVtknZ2DJ9QL928v36PBFiM,49683 +mypy/server/mergecheck.cp314-win_amd64.pyd,sha256=e44iIi5plCPDF7tVQ5MpoGNnkao7znQ5HeZbw2R8qjQ,10240 +mypy/server/mergecheck.py,sha256=yFpGbyK9JX_5VCB9V0Zz-b3o__PKmejRwgAL9LF0bUc,2757 +mypy/server/objgraph.cp314-win_amd64.pyd,sha256=m4FQFn3xeUJInlwtitwr-ppHlr6P5gUdd7R-VsnJ-_o,10240 +mypy/server/objgraph.py,sha256=l2otuEtyy6J67pfWgU17dg8LIWkDqP34YrBNjDrjytc,3230 +mypy/server/subexpr.cp314-win_amd64.pyd,sha256=n6f1s9IQ2fU28o5ydWWf-gXiPhmzXIj_izYvpAQuy8Y,10240 +mypy/server/subexpr.py,sha256=1BZiO7TmuOQBpwRN6t1DymbFowRSsguM_TQ-N-6nj28,5494 +mypy/server/target.cp314-win_amd64.pyd,sha256=qTEJb4k0c6OQnnZmqIibM0OZ4bm7cBbutfVS1ihHTEw,10240 +mypy/server/target.py,sha256=IbuK2qqtMvEPAof83BdgYJv6AGW2q_o4CQxC5TnB-Bg,273 +mypy/server/trigger.cp314-win_amd64.pyd,sha256=KITCqy1o1QRGf_xG-n-ScYg9Ip7E4Zgvw9w58B08niQ,10240 +mypy/server/trigger.py,sha256=qvo4tCLyrhI48oPTfDO_nWOVZfjMcYjoMdGgWsocEKg,793 +mypy/server/update.cp314-win_amd64.pyd,sha256=Mpp5QrVeXNNa2lBgbsY5wQTYaH3SR6wBDH1O1TWufmY,10240 +mypy/server/update.py,sha256=T8TmGRtc92uebhChVbeXFyyHpgF2scNWdp5ugF0xhIo,54315 +mypy/sharedparse.cp314-win_amd64.pyd,sha256=fluIPl7gDtXdtckuYRw24h19zXyVN-t7UjkDKYeK6DQ,10240 +mypy/sharedparse.py,sha256=tPLG0cUbBkZU7Pc37G80K5s24Fb8hkevp7qJIJBTplk,2146 +mypy/solve.cp314-win_amd64.pyd,sha256=IhjqxBjKpi2AcxrQMfPhIlGXj0fVk-jcXGmdaEW18kw,10240 +mypy/solve.py,sha256=yz2p2Mf1E4IZxpph5MSwWvT8D1yRoVdui2kCYHX8KWg,24530 +mypy/split_namespace.py,sha256=P67HianSrsMSZoeuS6F9swM5eK-B2fEBU3XJ6RFtYo0,1289 +mypy/state.cp314-win_amd64.pyd,sha256=CcMdtdLVZEVSLJNNHyvQ69FOroEhGdScEkUpXOkbz1I,10240 +mypy/state.py,sha256=yGfTdStRI9BJ3MpFvZS89uvVOLuqWxNy9DCY-SDHwcw,850 +mypy/stats.cp314-win_amd64.pyd,sha256=Z5ZFTKEDsJ5koIUP1jjh7K3ryux8mN5EFcWD1mb0Cnk,10240 +mypy/stats.py,sha256=661ysjBeZayvB16uK_bFr98KjqLamNm9BQpFO8iR9zA,16846 +mypy/strconv.cp314-win_amd64.pyd,sha256=guJZGCgRj7aHPjTL1ovCB57PQG0XCuoyb1B3YhTgtOc,10240 +mypy/strconv.py,sha256=dW3mTKd5wHuUswt0Af5KqmSfCeM7QRzIw73auzjjbsU,25969 +mypy/stubdoc.py,sha256=lrFgkX4kCMamVHbFwuARJziY21hSesBb-0LR5HIozAw,19328 +mypy/stubgen.cp314-win_amd64.pyd,sha256=wql9WTgUY13apMl9PR4jbkq23ogqc8jxxyqJtIIYPpo,10240 +mypy/stubgen.py,sha256=dGCPp5rLRcNi03rQLJ43s7LgnH23kwZZuI6IO52yGcY,78760 +mypy/stubgenc.py,sha256=4_TSpSPyCucpFqRTDdjnQn85dZOpchmeYr6o4NRQdR0,39265 +mypy/stubinfo.cp314-win_amd64.pyd,sha256=XWS7tLHLIG888YBn_LqeA2_M6ZFWhHS7ad3KxltdWFk,10240 +mypy/stubinfo.py,sha256=1RvGVmW0e1YwFRPNHtxjHuLTW7sdEiMAjyewVLEXy7o,11681 +mypy/stubtest.py,sha256=us8E7pDYor3s5jS1K5VO04-oKBxXY6SZGYXEFx1yiv0,103787 +mypy/stubutil.cp314-win_amd64.pyd,sha256=nLKErM32Sb5HnQKGzSwTmrJhccgK1c0YgsVAY58qk3M,10240 +mypy/stubutil.py,sha256=kX27FzBaIQlNVk6GO1oZEjsUsGFsjRN9leDDMnQ62F4,33495 +mypy/subtypes.cp314-win_amd64.pyd,sha256=5cDNS-Nzc4I9_bHzKgGvvcwAXBukfD4TooWY5rw7AuA,10240 +mypy/subtypes.py,sha256=CwQHZVVb2GEzhXGsjKsMy2rcriOdhB8sqa-OQj3Tsrg,100651 +mypy/suggestions.cp314-win_amd64.pyd,sha256=a71-RwIbbyOrgFaNJgHK_wtimpZjD74bDVw-W09MSq4,10240 +mypy/suggestions.py,sha256=UrxUFOwC1mG4DNTMY0RODTyvcQrZFKPYiYLquHwtVBY,39056 +mypy/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/test/__pycache__/__init__.cpython-314.pyc,, +mypy/test/__pycache__/config.cpython-314.pyc,, +mypy/test/__pycache__/data.cpython-314.pyc,, +mypy/test/__pycache__/helpers.cpython-314.pyc,, +mypy/test/__pycache__/test_config_parser.cpython-314.pyc,, +mypy/test/__pycache__/test_diff_cache.cpython-314.pyc,, +mypy/test/__pycache__/test_find_sources.cpython-314.pyc,, +mypy/test/__pycache__/test_nativeparse.cpython-314.pyc,, +mypy/test/__pycache__/test_ref_info.cpython-314.pyc,, +mypy/test/__pycache__/testapi.cpython-314.pyc,, +mypy/test/__pycache__/testargs.cpython-314.pyc,, +mypy/test/__pycache__/testcheck.cpython-314.pyc,, +mypy/test/__pycache__/testcmdline.cpython-314.pyc,, +mypy/test/__pycache__/testconstraints.cpython-314.pyc,, +mypy/test/__pycache__/testdaemon.cpython-314.pyc,, +mypy/test/__pycache__/testdeps.cpython-314.pyc,, +mypy/test/__pycache__/testdiff.cpython-314.pyc,, +mypy/test/__pycache__/testerrorstream.cpython-314.pyc,, +mypy/test/__pycache__/testexportjson.cpython-314.pyc,, +mypy/test/__pycache__/testfinegrained.cpython-314.pyc,, +mypy/test/__pycache__/testfinegrainedcache.cpython-314.pyc,, +mypy/test/__pycache__/testformatter.cpython-314.pyc,, +mypy/test/__pycache__/testfscache.cpython-314.pyc,, +mypy/test/__pycache__/testgraph.cpython-314.pyc,, +mypy/test/__pycache__/testinfer.cpython-314.pyc,, +mypy/test/__pycache__/testipc.cpython-314.pyc,, +mypy/test/__pycache__/testmerge.cpython-314.pyc,, +mypy/test/__pycache__/testmodulefinder.cpython-314.pyc,, +mypy/test/__pycache__/testmypyc.cpython-314.pyc,, +mypy/test/__pycache__/testoutput.cpython-314.pyc,, +mypy/test/__pycache__/testparse.cpython-314.pyc,, +mypy/test/__pycache__/testpep561.cpython-314.pyc,, +mypy/test/__pycache__/testpythoneval.cpython-314.pyc,, +mypy/test/__pycache__/testreports.cpython-314.pyc,, +mypy/test/__pycache__/testsemanal.cpython-314.pyc,, +mypy/test/__pycache__/testsolve.cpython-314.pyc,, +mypy/test/__pycache__/teststubgen.cpython-314.pyc,, +mypy/test/__pycache__/teststubinfo.cpython-314.pyc,, +mypy/test/__pycache__/teststubtest.cpython-314.pyc,, +mypy/test/__pycache__/testsubtypes.cpython-314.pyc,, +mypy/test/__pycache__/testtransform.cpython-314.pyc,, +mypy/test/__pycache__/testtypegen.cpython-314.pyc,, +mypy/test/__pycache__/testtypes.cpython-314.pyc,, +mypy/test/__pycache__/testutil.cpython-314.pyc,, +mypy/test/__pycache__/typefixture.cpython-314.pyc,, +mypy/test/__pycache__/update_data.cpython-314.pyc,, +mypy/test/__pycache__/visitors.cpython-314.pyc,, +mypy/test/config.py,sha256=VEePvz7BHWcNCQS1qY5H-sOvCgNuIN2yY6zZmXbo9kU,1301 +mypy/test/data.py,sha256=kdCcRf7Em4y2WqA5jXgr6_SFS43Ga1G5Ywe2_nrXcIc,30791 +mypy/test/helpers.py,sha256=JUeqUJVp4vm6vOj7VAUHPyJ2dofe-WA7allgtuHw9hk,16992 +mypy/test/meta/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/test/meta/__pycache__/__init__.cpython-314.pyc,, +mypy/test/meta/__pycache__/_pytest.cpython-314.pyc,, +mypy/test/meta/__pycache__/test_diff_helper.cpython-314.pyc,, +mypy/test/meta/__pycache__/test_parse_data.cpython-314.pyc,, +mypy/test/meta/__pycache__/test_update_data.cpython-314.pyc,, +mypy/test/meta/_pytest.py,sha256=BHGoXuST1N2IqVBlWsJPAvBSxc0qVpALDjyLWVVvxPA,2276 +mypy/test/meta/test_diff_helper.py,sha256=ETTk0kyEvdKP_CMIKddY2sX6oSwTeUzEqNgDeBPLI6E,1692 +mypy/test/meta/test_parse_data.py,sha256=3sfb9tQbgaM_ioyzwJ8Wtn_i_ve17VLrv3PhYSOpSQs,1895 +mypy/test/meta/test_update_data.py,sha256=Ddg5vR2aRTshhcoi083FMvVBSM5K95ycBukxwLlVerU,4770 +mypy/test/test_config_parser.py,sha256=40D_aqRD6QCqJU4BsDBm_47b4X-Dnu05n36I2BY1lOU,4167 +mypy/test/test_diff_cache.py,sha256=wYtHiMzl4AzQSoZLDH6wW6vuM8NKqH58EKdozNefD2w,8601 +mypy/test/test_find_sources.py,sha256=X_YRHcS6F7sp2MC2YepatigrfxxShIA6q2zj6Yh0JfA,13693 +mypy/test/test_nativeparse.py,sha256=Wa-7XwK_v7_gZkSdv3ppUi6XhU_Gu3rOKYJ5MaNMED0,8609 +mypy/test/test_ref_info.py,sha256=MMbcYA8tX_kCgVhPdLX507vkzJsX13cN93u65h-30ls,1469 +mypy/test/testapi.py,sha256=Xinte9ICqFeoe9AUweIEKiHvjbgD8H_Xv6Leck_sUoA,1447 +mypy/test/testargs.py,sha256=QSkID7us5fc0YzJDoKrPldi9gdPI0QwQ7HOBl1bRl8s,3253 +mypy/test/testcheck.py,sha256=at5voKjwJ3Mwy5Fb-gffyWF9eUOdYsDOfe4dOlwklSM,14858 +mypy/test/testcmdline.py,sha256=PiVnlUbHd02V81ETs8zHBEOGLvAr6HcRC3lCsnmzp1Y,5081 +mypy/test/testconstraints.py,sha256=s3a2C6JcqTzzQeh2IFSKEXHF_OchhtmttX-TTmXYIJ8,5267 +mypy/test/testdaemon.py,sha256=9OACkimdIGIsqx7x7yhl78Zqwz-xpD860kCh0JcfbI0,4511 +mypy/test/testdeps.py,sha256=bYQ_g6sHA2VCWsrapenHOtZRkfBlsYg4PUH6Y5sNFVw,3236 +mypy/test/testdiff.py,sha256=VdM_0vp0NSOxlYifl0_ElvGEHhMoqsp6g9wWBfk5Rt4,2510 +mypy/test/testerrorstream.py,sha256=bEAw3kMIfSJNec8G2iR2VgcsvbupguGxhW71EZ_Cias,1441 +mypy/test/testexportjson.py,sha256=SVcIX9ov8_ZGI7SmtGEdYeswdpF4a4TJPQjgHy1PKFc,3983 +mypy/test/testfinegrained.py,sha256=V0B3PQI0WNMPigafrARqlzCyAzvBkkhwo7J082vkAo8,17820 +mypy/test/testfinegrainedcache.py,sha256=AocgzZWRs8dlNcaaKzwY3QSBwxbbdwi3xwq5qcH9XTI,580 +mypy/test/testformatter.py,sha256=QwuFdblCF28X2J6K43mSUw95pl_VRdwqrAfOkCQr1xM,2639 +mypy/test/testfscache.py,sha256=1QDTTg7Towo5GI31NIwamXiIhbpS8o1zVmYcRNzHwh8,4465 +mypy/test/testgraph.py,sha256=NI1Z1FaBeUcxuLBQL8cel2YliUCtMk8QdPWdkxXsjkY,5303 +mypy/test/testinfer.py,sha256=d3NV8bTBrNJbaY1aO_IiYfMBeiWIeZjgeyYeQVShQwA,13856 +mypy/test/testipc.py,sha256=pBz9DjZzPK_9l3EZVtrdzvUQr8aenIHCayatDi2YPuY,3966 +mypy/test/testmerge.py,sha256=8t54I0Yn8uaaBTXCdkjAikT0nKrj7M2nt_zbPC0y_Fo,8594 +mypy/test/testmodulefinder.py,sha256=T4bQKD0C6SQJsQdkXJ0ZqFKM47Bdaoqe8sUCeIoVp5U,13957 +mypy/test/testmypyc.py,sha256=qxqOJLOG1iOKlCt-_K3a5x_X1F0deY8Vb7ON3m2xVAI,869 +mypy/test/testoutput.py,sha256=YJqb5Utxrl2r18PMacgHr9jTd68I-1EUk2y8Pdp10zg,1980 +mypy/test/testparse.py,sha256=QDwxQj4wzq3EYpaNC1K7bJYnhJzDHaZaIntKxwhB67k,3834 +mypy/test/testpep561.py,sha256=hxowZEKsmA5bWLr4lFD1fxLF8aZmX47lf4Oncpe6LlY,6839 +mypy/test/testpythoneval.py,sha256=VrmzHfwenbJ7O0UeBO6WtXeWdhD3PYEBFEdO6ln7uIY,4586 +mypy/test/testreports.py,sha256=GOP5LgXn5r9ADErKNEsjyhzBcMInm_Qy_6QY9TEO9hI,1953 +mypy/test/testsemanal.py,sha256=qGir53aoBcCJhhURY-6NI2_I_YC6e-5yMMyiEKrL-pY,6975 +mypy/test/testsolve.py,sha256=e_2Yagxy7AsA4SkqwKVYXsjh1z5z6V9D5k2cMzwNdeU,10069 +mypy/test/teststubgen.py,sha256=haASr18XXBuGXMWq4PVrAYze4u2jQJqev2E-enwqSB8,60928 +mypy/test/teststubinfo.py,sha256=yx1VeSL53qh_MimncCq8gKT9tyD-84ZDeYLk_tOf214,1587 +mypy/test/teststubtest.py,sha256=vPZQhuxmMkDId23WlQRWpI3EGo5Mtlxgr_02CUpRrtQ,100706 +mypy/test/testsubtypes.py,sha256=UqehkYlJVgs-IsQa8XsZUgJqBawHgsDD78pguXKiWYo,12426 +mypy/test/testtransform.py,sha256=kg_-7Rl4tyVf5-Frs07_6fBBJ8DlG6a6CY_XgyNZeSc,2195 +mypy/test/testtypegen.py,sha256=tcvK_V2JXthKarGwIvOplp-m3Pp_3i_mHTSLV6OYhNA,3149 +mypy/test/testtypes.py,sha256=tKvqgMz4j0wn8nDYXZHzqgfJcqdSs5e7rSBd7Yh6jNY,64454 +mypy/test/testutil.py,sha256=HqmkgHC3TBnm7VUF5059l394PKLhS-YItLheKq8htLU,4233 +mypy/test/typefixture.py,sha256=-qWDr5Wxl8jURtrMVweDBNusUEuJb0nWg5r4iwwgX40,16014 +mypy/test/update_data.py,sha256=IOqTyP5RTOd2SUsj1faveoFKYc3q0i1kqP-_WBLVVmU,3685 +mypy/test/visitors.cp314-win_amd64.pyd,sha256=cRIRo4UBWcDkgVXzGZ_Kl5od-kraLpRx7lfXEvk7zAY,10240 +mypy/test/visitors.py,sha256=cfsPawFO9J2UnoeZGzkYbAbZcuZ8HRDc1FKGd9SV1E0,2089 +mypy/traverser.cp314-win_amd64.pyd,sha256=7Mo5MHF0nWk1h2f1mzKvKXkGMjMesjQEZ5xK6ECZ5L4,10240 +mypy/traverser.py,sha256=x6TYVDFBiAa6usETAxrE03WAns3uON3Cnu2zCBOEqRA,31313 +mypy/treetransform.cp314-win_amd64.pyd,sha256=jvQUm9aa6TA2taIUvvVR2cgBbVF9_JyzvKdkEbIy6V8,10240 +mypy/treetransform.py,sha256=OT9rMjZto4xJuZHfBq0cx2W1TvB-Rb04DspKvLHFepU,29360 +mypy/tvar_scope.cp314-win_amd64.pyd,sha256=47aiHViOl-ZlNeUM6k65yUhmlEAVw8Nx2HqePhiNwIk,10240 +mypy/tvar_scope.py,sha256=KrjzxZ_FMfmRAyb_mT5BlKlKadKzoSS4wkHXfjXgmkI,7356 +mypy/type_visitor.cp314-win_amd64.pyd,sha256=PyGDB-L6VKubrZPpIyHHkRmsZSlhbNjnTBqOd8DL3Nc,10240 +mypy/type_visitor.py,sha256=rfjJOstoCbI2ahlF9Hn8EZBoDcS4Cn-LvOuROHRQOic,19975 +mypy/typeanal.cp314-win_amd64.pyd,sha256=Lt1n95XPiYag-UKeevRlBtEOmSNJYZe3GZ7UAilKeco,10240 +mypy/typeanal.py,sha256=LfjMjHLxfMq-VGZmRSsS5pt-iT5WNaY2H-0ztW7HbM0,119559 +mypy/typeops.cp314-win_amd64.pyd,sha256=8Qrtzvm_M1sToCJ3u3Jsrs_oXhDQPeh-jGQh6_kHMWE,10240 +mypy/typeops.py,sha256=4W3kBRwtGs922R0IOhJUnvyXSkkNy10jqzIdqFfroQA,51180 +mypy/types.cp314-win_amd64.pyd,sha256=IywigBtJI3NuHOBZEK8NC007lE2opDPWlCet-XUKciY,10240 +mypy/types.py,sha256=j8Yx3uPHqjdR1CxPZRutTQldh51WxYsLowOSjggHzE0,159937 +mypy/types_utils.cp314-win_amd64.pyd,sha256=8ck-eybreBDlpfQx-yXxTtV0u_Jw1zjMt1W6Jc3-hSQ,10240 +mypy/types_utils.py,sha256=eqsCmSgcbyeIQGlJswM2IDCWejGEPsOCmdOZpa1bXjI,6216 +mypy/typeshed/LICENSE,sha256=KV-FOMlK5cMEMwHPfP8chS2ranhqjd7kceBhtA1eyr4,12657 +mypy/typeshed/stdlib/VERSIONS,sha256=PEsgFQAWjZl9toKVh62RCuAisUTrrlizbtvfja3zs9o,6442 +mypy/typeshed/stdlib/__future__.pyi,sha256=qIwWDmjaw3XCiulKYoKBQB_eJjLxweesUKwBdpkgQkU,915 +mypy/typeshed/stdlib/__main__.pyi,sha256=hcfHKThQRiibOXGnPeEUHunrtviMdorj0MtdnIwLtl8,53 +mypy/typeshed/stdlib/_ast.pyi,sha256=Hn23xk9t6_M5kuMZHkcgjAWeNcwktovuyMbMLjZbtEQ,3344 +mypy/typeshed/stdlib/_asyncio.pyi,sha256=7yPRcejEUZ1k1CbRFVgPyvx1EHoLqCokMRHiKG0Y0-s,4872 +mypy/typeshed/stdlib/_bisect.pyi,sha256=jndBnhfr-GmrZ4W11uW-L10_e7nv9nDd2uFlpQTUNpA,4854 +mypy/typeshed/stdlib/_blake2.pyi,sha256=_qavMws5SSi8fWHc3J4WsFll6N2SORWBegj7qQX5_u4,3542 +mypy/typeshed/stdlib/_bootlocale.pyi,sha256=vSVnoBvURsNzi7MPLR1b_wpuh-yySKzPValAwQ3OVT8,64 +mypy/typeshed/stdlib/_bz2.pyi,sha256=rFCr1AYojWvE59rRz5njFVK1m1vMC2wNmTm-F7nrx_E,678 +mypy/typeshed/stdlib/_codecs.pyi,sha256=ryICMIWdfKvRj4jRQTwniDw7bMOdhyCuduSX0nb6Z40,6721 +mypy/typeshed/stdlib/_collections_abc.pyi,sha256=b9lKh_z4afqI04pPZ1EcpPeUzGQ5tfC7SPIo4NmviXQ,3041 +mypy/typeshed/stdlib/_compat_pickle.pyi,sha256=3WH0XDg8YMQ_EzfT7cnBKrU5WjpXIRJ5aec8h0xrDbU,438 +mypy/typeshed/stdlib/_compression.pyi,sha256=qEdmEzjcfQ9rOKRLjVtkpPSfvNEViEc43FouPF3XAfA,1377 +mypy/typeshed/stdlib/_contextvars.pyi,sha256=CeOt4eddnDTydVq4R1qOE9J7n7hQN6Moo_vstCY0EfQ,2370 +mypy/typeshed/stdlib/_csv.pyi,sha256=AJt3gWebsJJwgTBsKC3aCwWKInuKZz00_5qNlKv4rKw,4041 +mypy/typeshed/stdlib/_ctypes.pyi,sha256=5NsU-2HxMfZSMJVZ5LpusBQHblRYcWsSU1HM2wFlJY8,17676 +mypy/typeshed/stdlib/_curses.pyi,sha256=jl9jHbBJlbuMfFvl_ho97IjmwPXo-JUl9iKJ9Nq13MM,16854 +mypy/typeshed/stdlib/_curses_panel.pyi,sha256=w1RxG64bD2C8OGi2sXQmVIrNRv3q9aB7XrfYMGCkPF0,757 +mypy/typeshed/stdlib/_dbm.pyi,sha256=QtTE7l0xah6cJnDhlnIYOiqwsK3UsNIj9xm0WM-uVnw,1775 +mypy/typeshed/stdlib/_decimal.pyi,sha256=mU59vCxZe6aFeK7eCfAfYUUTy87ox8yD4bbpw0S-9sU,2058 +mypy/typeshed/stdlib/_frozen_importlib.pyi,sha256=7r6dPA7W9aOIdRmf4jNDEpqbSQDbT4ITSVmb6qmZQWc,4679 +mypy/typeshed/stdlib/_frozen_importlib_external.pyi,sha256=nhmOFkagtckI1GvEBroRwCaxk2ECNFA_uXdzWIM1vMM,9607 +mypy/typeshed/stdlib/_gdbm.pyi,sha256=_xrxJzc3WMpbJSc5uzWb1v2-Q2rkyxRFtUg85Ze7r6g,1946 +mypy/typeshed/stdlib/_hashlib.pyi,sha256=Dwc-lt0zwAvmrJ_lvV58s7NKK85zmC19iXT2HkDaYsg,5593 +mypy/typeshed/stdlib/_heapq.pyi,sha256=SQZxb-0v3sujrUDvauFD1kgbQf9OuhRELp3J68-iC50,755 +mypy/typeshed/stdlib/_imp.pyi,sha256=yUAJduUklNqp7sHZ8mV-4MPnacchatn1xd4v23clNdc,1185 +mypy/typeshed/stdlib/_interpchannels.pyi,sha256=WvlfKacmFX89HoVOrEElyAmRsxotgbEiSAKKzUp4S1o,3204 +mypy/typeshed/stdlib/_interpqueues.pyi,sha256=0OTlJA5tszfEGyCralyqa1ZxyVdbd0jbDQLlqB7YeKg,866 +mypy/typeshed/stdlib/_interpreters.pyi,sha256=PR8fkrZPGLvMbTovssuuTn2j0SNhlLNQNUt0nx4eE8M,2654 +mypy/typeshed/stdlib/_io.pyi,sha256=rGC1-_e7nq2oiuFzIx7KOlIVF7626YoxZAFUl6RWoK4,13142 +mypy/typeshed/stdlib/_json.pyi,sha256=yhbNNpPlgcNr7UbLWYlJLRT_GJAs6cec5nR1Ze_lvDo,1532 +mypy/typeshed/stdlib/_locale.pyi,sha256=uK5szB547hvi-ZQ9mIhaQXhDKD5-oO1hWvXAhd2g4fk,3287 +mypy/typeshed/stdlib/_lsprof.pyi,sha256=SnrMRZ7reYUpO4aspszvPl08o-zfyIZwixON_SP97bU,1323 +mypy/typeshed/stdlib/_lzma.pyi,sha256=vhTkKz-psYRTdZS5z31HZ71LtUPiUs5jRnxti7w23VA,2090 +mypy/typeshed/stdlib/_markupbase.pyi,sha256=jXh5gaXQuqr2KmmACztGc8xDjWm48itq1NkaH1eupMA,730 +mypy/typeshed/stdlib/_msi.pyi,sha256=jm1bAk_feToRYsWSLcQknCl2T_X2XwGtTwDzzl32VJE,3652 +mypy/typeshed/stdlib/_multibytecodec.pyi,sha256=48jNSq3IH_FejpnGX0_qMinWaLFOVjox0b28466ywrU,1890 +mypy/typeshed/stdlib/_operator.pyi,sha256=uC0DFWn11LMIxHzILUz_RGv2Vy8QIrAdDEvcPSIwsso,4867 +mypy/typeshed/stdlib/_osx_support.pyi,sha256=3cwesRBNoUgiThjIsAiPNKoODAGoaRg9je4-A-QpOU8,1900 +mypy/typeshed/stdlib/_pickle.pyi,sha256=EiGJBPWfyp1VlFuXDsLX2tNAwNKpZc5oAsgdQnJUO2k,3295 +mypy/typeshed/stdlib/_posixsubprocess.pyi,sha256=sszb90KfUWD1Mnk8eJti8-O_PPr95u4vGJh4XSoyEUQ,1836 +mypy/typeshed/stdlib/_py_abc.pyi,sha256=yKisRv9tmwucBsWB1ILLo35NcNrZWwIkKRL6Pu8GH5s,397 +mypy/typeshed/stdlib/_pydecimal.pyi,sha256=wssuLOIKIuBbxUlyTcxx8ech_vGbA1A9EH9hqyHkG-4,995 +mypy/typeshed/stdlib/_queue.pyi,sha256=KX-GSZ_-tpD0mLw1WqfXW5WGCXaR7C10YwaZuexOUho,634 +mypy/typeshed/stdlib/_random.pyi,sha256=uOdUKAg2zvcoUlAwSYR5_1dc8Md0hsvJ6h7HGyvAeAU,571 +mypy/typeshed/stdlib/_sitebuiltins.pyi,sha256=Hw17bWzQybJdwlnQceJ8BMHzSuTYiAn65Ro7sZu5MoI,538 +mypy/typeshed/stdlib/_socket.pyi,sha256=WpkBcqyvVW2PQeYNbO4_yrb6n0FrG7o913IcJqK51HA,27852 +mypy/typeshed/stdlib/_sqlite3.pyi,sha256=WAqfvEdYY1Rcn0oByDEF_xh83BxJErT1FrKX7kSLkAE,10622 +mypy/typeshed/stdlib/_ssl.pyi,sha256=X9JlIuSp4SIFxu-Za5YoV0izW_T20Bp3vL-PTQRN8Nw,10060 +mypy/typeshed/stdlib/_stat.pyi,sha256=hUl5rnhbcV4UkNu4MASQinuAccNDU0MiHrdG8Bh_92Q,3441 +mypy/typeshed/stdlib/_struct.pyi,sha256=HwlQXLJV_jIckbuof-hIacm5RQpGsNyz6kO7L07MjQE,1196 +mypy/typeshed/stdlib/_thread.pyi,sha256=CNTZi_IhZAAZsGpsRckoiwVDeqjs0Vx2XeZ7DVo-wNA,4918 +mypy/typeshed/stdlib/_threading_local.pyi,sha256=vnzj6ILLO3h6_TkLIXlqQZmKnfRG6wxBfvA2IP1iHFE,880 +mypy/typeshed/stdlib/_tkinter.pyi,sha256=gquIfnhC8Y8aBbhZXmX8LdmV2-iGwekOlXyEX8Bavgg,5563 +mypy/typeshed/stdlib/_tracemalloc.pyi,sha256=bPNYXniUfh6u6NCEkkmpNDClCx7JD1EYRdl-87cY8ps,500 +mypy/typeshed/stdlib/_typeshed/__init__.pyi,sha256=XUzwRD9roAEluSa4y1Hxky4_nKno7DZuhjZUxYvUe78,13255 +mypy/typeshed/stdlib/_typeshed/_type_checker_internals.pyi,sha256=aS3E_CYU0Q1szNLqKjyGfub4-0rSBXK-znvd9FVVU08,4157 +mypy/typeshed/stdlib/_typeshed/dbapi.pyi,sha256=DbFvZC7aeSFuw_hopshe-nz6OL_btPB06zIoJ8O-9tA,1636 +mypy/typeshed/stdlib/_typeshed/importlib.pyi,sha256=iSR1SQrIgH39dZwu1o0M0qk8ZsxRUkn4DtG2_K5tO4o,727 +mypy/typeshed/stdlib/_typeshed/wsgi.pyi,sha256=qNH7QQT9Y_i8GxSoS2LUViFSmM4mH3-K5hxh7sGT5K4,1637 +mypy/typeshed/stdlib/_typeshed/xml.pyi,sha256=W4c9PcHw737FUoezcPAkfRuoMB--7Up7uKlZ0ShNIG0,499 +mypy/typeshed/stdlib/_warnings.pyi,sha256=fkbpcOeB7WnJshHYcNvXGB86qDMkDDtM52o_00I6Bzw,1569 +mypy/typeshed/stdlib/_weakref.pyi,sha256=UVIE-iE6GyVOBeCKC0CXABnd7t-PvxC8ZtrTV6IaI8M,643 +mypy/typeshed/stdlib/_weakrefset.pyi,sha256=_n_kXqzC0K_qb4uEtA6WUsgmHD70uCp6YuTUtZxfK3c,2345 +mypy/typeshed/stdlib/_winapi.pyi,sha256=sIvrVvBOiL3MXrrTL7XJRuaYNtgAWcefv9CpCdKDnDE,11325 +mypy/typeshed/stdlib/_zstd.pyi,sha256=ojiC5JC6u70gcWkD4PptHHnDzACxytrI8KOCoRZkOrI,3647 +mypy/typeshed/stdlib/abc.pyi,sha256=oFvki8FBAHlhrRRDXkoEBcYJVQzb9nnTUdU7kSd9wPA,2128 +mypy/typeshed/stdlib/aifc.pyi,sha256=j7qx4qEI_YH90FPfekf7fqRBDs2HXALqfv--MuXo0DQ,2986 +mypy/typeshed/stdlib/annotationlib.pyi,sha256=kiftU52i0S5cIqUf_xPiyl6SgnewDWt_0c942HhGsus,5435 +mypy/typeshed/stdlib/antigravity.pyi,sha256=AT_uMXdsZR3AL8NfPU7aH05CAQaYpiM7yv2pBm7F78k,123 +mypy/typeshed/stdlib/argparse.pyi,sha256=OX5_CaCtqUv-T_iv5NS1n5F9SDsXC7SADrcdZ9DyGvI,32065 +mypy/typeshed/stdlib/array.pyi,sha256=pMXARXYsQVcW4QHPexydiIOMMYr2qQAIfe8vBCxueVE,4741 +mypy/typeshed/stdlib/ast.pyi,sha256=O7dOu-BpucY17aIKFEiO0gQPAcwikmCTmb4HMsoni-8,77826 +mypy/typeshed/stdlib/asynchat.pyi,sha256=jFTiOSXClcmhNvWXQc9JdRD44AT5o9Cq7xSC2fbVC2k,787 +mypy/typeshed/stdlib/asyncio/__init__.pyi,sha256=KEWLcIiMBDio8lNUZpHu3wW0G9JlMc-HDjpYh0kL3Cc,44530 +mypy/typeshed/stdlib/asyncio/base_events.pyi,sha256=lPYGjH7Cr7gCH3-8xtOeUGJk4HtxvfaTZiq9WDKUfxs,20014 +mypy/typeshed/stdlib/asyncio/base_futures.pyi,sha256=Jy9MidrOMwCSy-ZkrbjLoKNNPcuVK9ASOX_RBLDAS3M,609 +mypy/typeshed/stdlib/asyncio/base_subprocess.pyi,sha256=CjBQyvXQcYWcmmVfWAq3z6ZY3MhXntxMh_xgtJhwKUQ,2680 +mypy/typeshed/stdlib/asyncio/base_tasks.pyi,sha256=1qMENIsXTar5-dVXn33qy8hpWzOtFOs_I-kf5I92dsI,404 +mypy/typeshed/stdlib/asyncio/constants.pyi,sha256=-Eu35n-kT7I8W9YNfoY1lXmrZKATdDBojxBOwMiPw6g,556 +mypy/typeshed/stdlib/asyncio/coroutines.pyi,sha256=yuB4AGXiDVOfPrJOL3aQaxUS6N1br9WD9zrNo18JRLs,2296 +mypy/typeshed/stdlib/asyncio/events.pyi,sha256=luf-9au-gOYMsTZhM6jOPvhWFOjBk99CxFKF-j5XFOA,25851 +mypy/typeshed/stdlib/asyncio/exceptions.pyi,sha256=livPkrVx3OkV5T5BXlmuiI0rQx-aRLCPkrkEOQlalh8,1163 +mypy/typeshed/stdlib/asyncio/format_helpers.pyi,sha256=2woQu8erzdP7jbY3DZcfWyOwEUjkKQbYIvGW5wwu59w,1353 +mypy/typeshed/stdlib/asyncio/futures.pyi,sha256=mcUrrMBgux4VvCIkAYEoXkiU5tb8hBrJsW0DJFcT7DM,721 +mypy/typeshed/stdlib/asyncio/graph.pyi,sha256=EMHKHA_90qYP4OB6lFtG2CGBtNKkefB-wzh8y1AR_WQ,1194 +mypy/typeshed/stdlib/asyncio/locks.pyi,sha256=QDXBtjjRszT62G52f6icc_qzozDPlr_qrVT7spcnj5E,3514 +mypy/typeshed/stdlib/asyncio/log.pyi,sha256=Ql97njxNKmNn76c8-vomSAM7P-V14o-17SOIgG47V-U,39 +mypy/typeshed/stdlib/asyncio/mixins.pyi,sha256=YqQRvFzqgxJ0BvStd6F56A4DaIEM3KvD4fDELKCYhco,215 +mypy/typeshed/stdlib/asyncio/proactor_events.pyi,sha256=vCZEY77LmyjcjJt_UgGuMqFSCG9BQmOTX-2aqArcYP8,2598 +mypy/typeshed/stdlib/asyncio/protocols.pyi,sha256=MV0bmW9iU_c5qw0vOdG9V7fvMA-RoB0PjxTRP7wIN-4,1927 +mypy/typeshed/stdlib/asyncio/queues.pyi,sha256=QFNRsudiTUFQ9eEVKvgQ4LKCGz7UxRFs3KEvsWqpW0s,1918 +mypy/typeshed/stdlib/asyncio/runners.pyi,sha256=xU7eEwtwajK_ATU37Bb9Y4B2QnIpdTwGFtdVeV6BRKo,1369 +mypy/typeshed/stdlib/asyncio/selector_events.pyi,sha256=99QJmKi-74k50L6pmkcfO9B716oIJt4uIU8g2nG6pCQ,315 +mypy/typeshed/stdlib/asyncio/sslproto.pyi,sha256=buih3k56xpku7kwDWaioIPO7ibOkN_d6df26ONKGDgo,6489 +mypy/typeshed/stdlib/asyncio/staggered.pyi,sha256=vtlD5Xfya4AEfvkwJmIL9zXXgRlsI8MmGOFitDK9h7g,341 +mypy/typeshed/stdlib/asyncio/streams.pyi,sha256=fTNtnQq_6s6ljW7B4xl-U4uO-zDTNsuS5zQi-ZJ61iw,6007 +mypy/typeshed/stdlib/asyncio/subprocess.pyi,sha256=7hdI_BmLWsvLtzz_mrabrGCibuHNHfbUlRyF2BB7MiE,9295 +mypy/typeshed/stdlib/asyncio/taskgroups.pyi,sha256=EREr5whbcIyL0gdD3nKDMLibfWSgKA0-wRxgqXDH1yg,1180 +mypy/typeshed/stdlib/asyncio/tasks.pyi,sha256=FUqGLtG9zWcz_vTwh7R1R5stGFfUEeG_0bvUDIySiYQ,17102 +mypy/typeshed/stdlib/asyncio/threads.pyi,sha256=mPM3TlwpYs5UUus7d-pob5vcrsehEp6Lp2a8JxwBbqk,330 +mypy/typeshed/stdlib/asyncio/timeouts.pyi,sha256=Py2VPr85sJCC48s63cQvCQQCVsk-T-9znyjQDaIs-o8,717 +mypy/typeshed/stdlib/asyncio/tools.pyi,sha256=zjh-ntujiZ_cIJIAgiFbV4R_CT_cYiOKF-mlP31PmMw,1489 +mypy/typeshed/stdlib/asyncio/transports.pyi,sha256=pzLqWKPGJmQyrtCoCMaK4hKVft-I-FwEmvNJe4rP08k,2390 +mypy/typeshed/stdlib/asyncio/trsock.pyi,sha256=hj0UMyDehb7QyWVpeauw2DVc-2X4Y2hi8_dqbJTGHqI,6096 +mypy/typeshed/stdlib/asyncio/unix_events.pyi,sha256=lv_QLe9gpKp7zJWB78MJL9p1hAeMNG0SVtB5EloIRcY,11341 +mypy/typeshed/stdlib/asyncio/windows_events.pyi,sha256=fL5j2FWLD1tixaAFnXOuFoveXgU--PktycxLPhCWAME,5397 +mypy/typeshed/stdlib/asyncio/windows_utils.pyi,sha256=muNyuM_00Nog2RVk6k46NCWwk7C761dbCNOe-HZIpI8,1955 +mypy/typeshed/stdlib/asyncore.pyi,sha256=xRANk6i8v5AshNfEgtRCInPWVEwL1NP40G7aRRqaaWs,3670 +mypy/typeshed/stdlib/atexit.pyi,sha256=YPzhxFxGPqJ1k5G-Iab8lqfJNum1kQ_UsmI84I_5zEk,398 +mypy/typeshed/stdlib/audioop.pyi,sha256=9k9vD1-ArGE3bl0iSGPn6Oh4-XOftsyuN5MbFi1W8xw,2122 +mypy/typeshed/stdlib/base64.pyi,sha256=wxttkEgPJROdDrk55N1uYnzCiTiqWZo54fDHJLKXS2I,2264 +mypy/typeshed/stdlib/bdb.pyi,sha256=b7zH0KfmVkWBje1oo3cwHw6VX2pvfONj300oua42YDs,5866 +mypy/typeshed/stdlib/binascii.pyi,sha256=tq0U58aXORL5lgMkufQHEcwVzYl0BUfJsXX8IR0AJFk,1822 +mypy/typeshed/stdlib/binhex.pyi,sha256=vyLQVbmIET6tr9sHDh-vewAJvpfCcaRIw3h9hRGs4xE,1274 +mypy/typeshed/stdlib/bisect.pyi,sha256=sQn9UUS0Cw5XZMEGcEj8Ka5VKPVobL43Pex_SagjXg8,67 +mypy/typeshed/stdlib/builtins.pyi,sha256=EDpa-vfBx0CwvgsMOkUzSMFAIlci5CdBN9wAdQCSWvE,92537 +mypy/typeshed/stdlib/bz2.pyi,sha256=xOkSxmwk1lYrayAxjpWi5dY5-WiUmeyE04eBmX5vxkw,4008 +mypy/typeshed/stdlib/cProfile.pyi,sha256=gnkhMSDZOdLpA3atsotilOXWNzqok4SXcsnvAKQH31E,1313 +mypy/typeshed/stdlib/calendar.pyi,sha256=Lmm4ZTTvJ9h1fZC-ofuty9BCv6BkENC7doe7TvuvAC0,7388 +mypy/typeshed/stdlib/cgi.pyi,sha256=0roTC0MUUXUS4xO7mhzY13Oa0GvlaD6UZF6UheEs6Qc,3810 +mypy/typeshed/stdlib/cgitb.pyi,sha256=l7aliv3yXrfw0MM15pXDdgeNpbIK1N1e84OjSEt2TFU,1394 +mypy/typeshed/stdlib/chunk.pyi,sha256=691YVfWjwx20ngjDSBGS5Pjs7IrLViQinuTBg8ddmX4,614 +mypy/typeshed/stdlib/cmath.pyi,sha256=i3ZCUsvAaek0Sebb5qYwgBxTatHzyq3f_f8Rs2MuGz8,1271 +mypy/typeshed/stdlib/cmd.pyi,sha256=Mbl8vjsuh_FXsT64NErKMK1FdPYlOdbC-jVLg7tiLoc,1783 +mypy/typeshed/stdlib/code.pyi,sha256=UnBJGRyi3C4lNtXYsC4wkMyAcF_k8FuM9aFq3uooSMc,2140 +mypy/typeshed/stdlib/codecs.pyi,sha256=oN6h8bIgdQhkPiGIO4ihlBWO_pQCiQ-HOczXZ3iJ2Jo,14124 +mypy/typeshed/stdlib/codeop.pyi,sha256=DAkqqHHsxirkzPomzRmpsL2dVW5FyhLdj27YTZ2jc7o,799 +mypy/typeshed/stdlib/collections/__init__.pyi,sha256=PtOWMNd56e-GBFAAv9mZUdZ_3qaSQkQMlJJze2BSUK8,23698 +mypy/typeshed/stdlib/collections/abc.pyi,sha256=kBiZAN0VPf8qpkInbjqKZRRe0PXrZ7jxNmCGs4o5UOc,79 +mypy/typeshed/stdlib/colorsys.pyi,sha256=o4IcMv2OA9R-5pwBWvEpW_kOzFsjZWtWZARpwMHTkv8,696 +mypy/typeshed/stdlib/compileall.pyi,sha256=eqS3LbYNS0f_aKhX5g-NPgTaMuF1PIzwxT_TdRm_q7A,2757 +mypy/typeshed/stdlib/compression/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/compression/_common/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/compression/_common/_streams.pyi,sha256=GbmwTLxClok7eRsWhgTX9884eLyPByx_7Czu1XKD9NA,1339 +mypy/typeshed/stdlib/compression/bz2.pyi,sha256=_Tb-V0PrToWQt38Y_XXS0FmJfRWIc2X5jnGeEwH7gmE,18 +mypy/typeshed/stdlib/compression/gzip.pyi,sha256=HRqVg9hDWsKJ83Ur28v1-WB7sLQzxADzxJPP7FTumec,19 +mypy/typeshed/stdlib/compression/lzma.pyi,sha256=nNMih_mDY-jxO3tY65zkpT9nT6r293X7fxwXk1SAJjU,19 +mypy/typeshed/stdlib/compression/zlib.pyi,sha256=UQc5WSd45ZWjhEc1Za5pOtEsoBi-kbrrOidCv7aguBw,19 +mypy/typeshed/stdlib/compression/zstd/__init__.pyi,sha256=8A6ZP2_83c7gq4Z0vwrgxKFBSgxJzIcM6wESC2zcnJc,3102 +mypy/typeshed/stdlib/compression/zstd/_zstdfile.pyi,sha256=Au10oAAxPlrl6EpSfsmse7s_5Tu9X-o0Y5kaL79txw4,3781 +mypy/typeshed/stdlib/concurrent/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/concurrent/futures/__init__.pyi,sha256=Ma8QgM22nhptstCwPahwrLn3yfYIokNZGBfVjRGvVnc,1765 +mypy/typeshed/stdlib/concurrent/futures/_base.pyi,sha256=cpRZfzzvOtgWhtlBGkCiTcps9InisdJIU_qJVDyfh2k,4346 +mypy/typeshed/stdlib/concurrent/futures/interpreter.pyi,sha256=6BNtvdAt0z5BDVO7YZPDepgTn9gV85C0FULjDKj9oOw,3053 +mypy/typeshed/stdlib/concurrent/futures/process.pyi,sha256=cBSyTr_2IMdujvLEIaJCWTzCrtJdQwcxj3nyYpqC_fM,8168 +mypy/typeshed/stdlib/concurrent/futures/thread.pyi,sha256=emnAXhk2GmHQoKx40vC3ihLDacCRzAAZssbT1OtX7CU,4738 +mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi,sha256=5E7AB0WNoIBkid5LhXlys78KudhHuHKve3dvKGLxbGE,2441 +mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi,sha256=gIXVsaVcPvE6gAOlmSVCDFzmZ4pdssdmKQZufKikzNM,1257 +mypy/typeshed/stdlib/concurrent/interpreters/_queues.pyi,sha256=vHO4wi4vRMqtMw7GNdHTZXYe3v9FptKu2nhhDoIPSKE,2603 +mypy/typeshed/stdlib/configparser.pyi,sha256=8B8lFsXku9FCcxEgcfTofDajhOJoLjCaT8eg5ckPYX0,19610 +mypy/typeshed/stdlib/contextlib.pyi,sha256=U8yYhkL1nc14ci7FNWO2b3LuCXhVUGr12isDXSfLJR8,9523 +mypy/typeshed/stdlib/contextvars.pyi,sha256=dqUvNxlpq9-0XgvzzKlCz4kWsA7qWEEIXIn73jxpaf0,178 +mypy/typeshed/stdlib/copy.pyi,sha256=e0uVQHOXyuOSyeCibpPIDOjBiZhrc--BU1oYKJyosyQ,856 +mypy/typeshed/stdlib/copyreg.pyi,sha256=59YPSECQJ5ppsEmYJxcvb1NOac6UTAu5CqP3SMd6VL4,983 +mypy/typeshed/stdlib/crypt.pyi,sha256=OA9MXjgoTY0jyd4cn6ZypXL1TqHtOAA_udosFL0OldI,792 +mypy/typeshed/stdlib/csv.pyi,sha256=QoR9Mr8E9wHipM3ehLPHPb3ZWNmJqKFov1sRBGOdRjY,4535 +mypy/typeshed/stdlib/ctypes/__init__.pyi,sha256=xJlPx4xZNRV3NY77ERcNffCmfrPtMbWROapHSx670jg,11584 +mypy/typeshed/stdlib/ctypes/_endian.pyi,sha256=raioVluH0dlcLoayGs1jELpcBkPKmO7Wbwr2OcpZAUE,461 +mypy/typeshed/stdlib/ctypes/macholib/__init__.pyi,sha256=G8DxraRu5jEG-ve06msp9XoHqQwtnFEjVtCSLe7vaTw,50 +mypy/typeshed/stdlib/ctypes/macholib/dyld.pyi,sha256=K0ZDg1MB-_Y_n49CDgrEJytsEVOWgXgHN1THza5UQ9k,467 +mypy/typeshed/stdlib/ctypes/macholib/dylib.pyi,sha256=HVkz1Oyol9QCJcjdnwtkgW5iq-yFJwiQ-jZCAGzPjTU,326 +mypy/typeshed/stdlib/ctypes/macholib/framework.pyi,sha256=bWwjubZ_zKOiGqAlqByzonpxD4AJQemGiFIfS4emGm8,342 +mypy/typeshed/stdlib/ctypes/util.pyi,sha256=4dyWcDlzw6yUtBFC1j17JsnSzhJV8q94ZJfvo-07kng,222 +mypy/typeshed/stdlib/ctypes/wintypes.pyi,sha256=s59HOt-zLzzEeXbTeCSsB-wXiEBL-wxiy5Yff43agtc,6967 +mypy/typeshed/stdlib/curses/__init__.pyi,sha256=YM2Eo7wYTP_QgiElaBzMTWsWJFHsaHFznnp-9o8errs,1284 +mypy/typeshed/stdlib/curses/ascii.pyi,sha256=7xKdmHqbNJu7zXzLc36MKVuEsOoWmqDAFWrdDwVT6Zc,1465 +mypy/typeshed/stdlib/curses/has_key.pyi,sha256=1EoxgUM4xlB7ggY4Ru4eqnSa0Wn2mP7ylUE7p9V7Yc0,40 +mypy/typeshed/stdlib/curses/panel.pyi,sha256=tiz6sEiozlgKp3eC7goXP0irXp9PwWHSfWiMahWMRRs,28 +mypy/typeshed/stdlib/curses/textpad.pyi,sha256=2UsLwIhJh5iwWSN-1SJlzwvn--sJqh8zJYQ8pYCP8f8,422 +mypy/typeshed/stdlib/dataclasses.pyi,sha256=Cl6Lvi5YAzPZ0rcZjnDkOMAOHtHJdJeYRIjBF92HRsw,14451 +mypy/typeshed/stdlib/datetime.pyi,sha256=CiWGFuYlJcGsCDxyBUhYGbRDesevvX0V5Ndi3wol_cM,12256 +mypy/typeshed/stdlib/dbm/__init__.pyi,sha256=KZb9l0guolhsjOyfqZk1_r0-vdN8nt4a7ach5lOXe20,2143 +mypy/typeshed/stdlib/dbm/dumb.pyi,sha256=dsAfzLKJnXAW6xJMnw-47D-xdaiwuXwaQC_-c1If2ZE,1467 +mypy/typeshed/stdlib/dbm/gnu.pyi,sha256=QR25FB7f-Rxi5RzWWki9npyEF1JKu5A5RjOWDmR7T2U,20 +mypy/typeshed/stdlib/dbm/ndbm.pyi,sha256=dc0BCDY0QiGbHA0lcqZL4NqOfCES4htigqb4uM5UaSo,19 +mypy/typeshed/stdlib/dbm/sqlite3.pyi,sha256=v1uUMPBFIH7G34tYJ9HrcoYAt4E1zq8EWYGbVEbIQsQ,1228 +mypy/typeshed/stdlib/decimal.pyi,sha256=TVKrr33muv01oCyW1j1ZcMtkRMDYgmY03R8IUwTqs1Q,14077 +mypy/typeshed/stdlib/difflib.pyi,sha256=pv2JXhDbVzQF1UdfSrblMHZvHFMPcldu-FbRwtdJuJw,4512 +mypy/typeshed/stdlib/dis.pyi,sha256=GYfqrpaWw0vlhlhdY37xdw7mTqY_9h5uGa-qeRU8YVo,9643 +mypy/typeshed/stdlib/distutils/__init__.pyi,sha256=o-D0LAC_8LmRTahqNjjRUXycRSMyJ537NHeFaduZKVc,351 +mypy/typeshed/stdlib/distutils/_msvccompiler.pyi,sha256=HOTrNPKFYHGnaIggO2_-F2BTCF878cRQf-ge7Ng425k,437 +mypy/typeshed/stdlib/distutils/archive_util.pyi,sha256=E6T3Q7SSWW8UvxEkJlXbW_wr4UaY_ddLEb8MWFN0_KA,1040 +mypy/typeshed/stdlib/distutils/bcppcompiler.pyi,sha256=fge2cMbG4jp--o0I2zNcwykh24tJWZtk6leQgAH2NJw,78 +mypy/typeshed/stdlib/distutils/ccompiler.pyi,sha256=BCSgVAvfMJVh8EyX_HqNcggwpF_NEcTTnVournS-UUk,7358 +mypy/typeshed/stdlib/distutils/cmd.pyi,sha256=Dm_n741c6n7C-8bk3RBLOjW5hPPOy4FvRYpxuATINo4,11116 +mypy/typeshed/stdlib/distutils/command/__init__.pyi,sha256=AtZpmh1mhLqsWO11mGBB-CrtRWprrdDs6ylbXlXeTeQ,711 +mypy/typeshed/stdlib/distutils/command/bdist.pyi,sha256=YLLeluU6gqN_RNDL463SiE3aNQaNKDscuCC_Zm0bj3I,875 +mypy/typeshed/stdlib/distutils/command/bdist_dumb.pyi,sha256=tIuYyjsOwPpl1hSJK24tcjom5dTJ98id0ckXH4wN6ME,614 +mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi,sha256=GTn4n9D6tLwyQyuPtNH-hk1JL37l6Kkr3OHA3TMVv8o,1735 +mypy/typeshed/stdlib/distutils/command/bdist_packager.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/distutils/command/bdist_rpm.pyi,sha256=PeCQM0O6QWBoWD9se0GSzoLPwBf16HK5yANxdJ37qBs,1457 +mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi,sha256=wON2ucrSRQI8V1q2_wi8U4TW-GQpjUe_XRPvX4Z1lKw,646 +mypy/typeshed/stdlib/distutils/command/build.pyi,sha256=ufnjRjuH62Pb0e-cBDyvVEw67PFV4cOYv1_gP4MIkVE,1081 +mypy/typeshed/stdlib/distutils/command/build_clib.pyi,sha256=qR3q8TLdF63c0p33peUo284iEiLH9-2VLUJ2DleCpJA,918 +mypy/typeshed/stdlib/distutils/command/build_ext.pyi,sha256=a8kGtFnC6UtXGU7XOG80dfSd9G5zeD1fAQulKS7f1aI,1648 +mypy/typeshed/stdlib/distutils/command/build_py.pyi,sha256=omRTnXsWj7TFKmgC9IwhqGmC5Buh7ER9e3WdOB9l54A,1659 +mypy/typeshed/stdlib/distutils/command/build_scripts.pyi,sha256=Fv03MGtaBwwfdI66zTqJNPeD2BMAF98sdJnDRzBhLnM,703 +mypy/typeshed/stdlib/distutils/command/check.pyi,sha256=b_7HEEEs0Zr7lvIaDDg5yWeQBgoXInV-flLTTeg2KGw,1236 +mypy/typeshed/stdlib/distutils/command/clean.pyi,sha256=wagR3bxqh6UAXnvhsDf7qYQY_1jMTEP30QXuq6mJIoc,513 +mypy/typeshed/stdlib/distutils/command/config.pyi,sha256=d2h1OIMfkadYMGT96DPQEtL39QpLk-rCRjQRAGOGBFI,2781 +mypy/typeshed/stdlib/distutils/command/install.pyi,sha256=rFV8ukandp2i7iE23smdT8xL6jidpw3cY-HTSpzDMXo,2290 +mypy/typeshed/stdlib/distutils/command/install_data.pyi,sha256=09diiWpTZv5g5May_za9UEKw_m2fvwVbevMin63lxBs,558 +mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi,sha256=pXV3L3dEjK0NnGiO7tyXgxIMzx5nwpu5v9OEF4jFyzk,532 +mypy/typeshed/stdlib/distutils/command/install_headers.pyi,sha256=2ZePm_2is9uIck2c7iIwLwJet7Ef6JopFVuHF6D6aGE,488 +mypy/typeshed/stdlib/distutils/command/install_lib.pyi,sha256=8hNzKDsNWLb_T9O0Kc75M4WuXpanTeJB-_CrFHebDnU,765 +mypy/typeshed/stdlib/distutils/command/install_scripts.pyi,sha256=lpExgrCH1wnyLS2S-bZwR12gqQTcHEffqWeezL51qu0,548 +mypy/typeshed/stdlib/distutils/command/register.pyi,sha256=P7m44QOal6qsDtw66FfA_amKyxLouynR7s5XtiBP6wE,697 +mypy/typeshed/stdlib/distutils/command/sdist.pyi,sha256=AxkvvnWR2K6xYmTKXqiDM7DUPaneriPiSgtJiYMG4O0,1517 +mypy/typeshed/stdlib/distutils/command/upload.pyi,sha256=re0EVwgTn6jWVMoOWTfsZStLXozX66LSiXokPEHM_74,511 +mypy/typeshed/stdlib/distutils/config.pyi,sha256=Bmpm5-txSuUYd92XnDnfpAevSl9bk5YfXO-I_wXC2QI,497 +mypy/typeshed/stdlib/distutils/core.pyi,sha256=oc3E79ctJ90TJsLmy88jM5XqkqmVyXNOxXYuDMOYy-E,1973 +mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi,sha256=A22lj-kl_06GMoQcl-M7yhWbmjzsTXml6KDjB3in5gM,586 +mypy/typeshed/stdlib/distutils/debug.pyi,sha256=xsHjfIMduqS9E5C28fFERqXr8Ss8y1GGO1rR9VR8vLs,51 +mypy/typeshed/stdlib/distutils/dep_util.pyi,sha256=G_1dehLB4Nq9vEmNKFqTasQtG-A8Ybpqxs1M2-GZwjI,647 +mypy/typeshed/stdlib/distutils/dir_util.pyi,sha256=pGJrASr0CVE9JqaQMcOhV9rkgsXUCI4qoFpyvF3UB18,875 +mypy/typeshed/stdlib/distutils/dist.pyi,sha256=_NHkVAtGXaru8FyZX8cmB0wy1WUN0uM1fpJdiPCKUBo,15218 +mypy/typeshed/stdlib/distutils/errors.pyi,sha256=l1W_FgoP9L-D-hEPFA2BzZuybjN0lV4WBXl0VJ-k7J8,852 +mypy/typeshed/stdlib/distutils/extension.pyi,sha256=KosWjLSvvyfdQTtOCu3fibblHyiFIXm8iHHWrWk916E,1236 +mypy/typeshed/stdlib/distutils/fancy_getopt.pyi,sha256=WmGW8EhQqL1yd6jPgBcCc9JFo9PMqIS8dvslu2IrWpE,1673 +mypy/typeshed/stdlib/distutils/file_util.pyi,sha256=zikh8dhZ0i8b2Pmw3-OtqqpS-w3gAF5GwN9GXEy1EbM,1323 +mypy/typeshed/stdlib/distutils/filelist.pyi,sha256=RiXyurPBQ_d4U0siqqxHk22qsUqAP2EZbX5LWA40lm0,2292 +mypy/typeshed/stdlib/distutils/log.pyi,sha256=8Fv8JYP-w6djwB7ad2fkWaABI-1xk1loqdEJOZiS_go,940 +mypy/typeshed/stdlib/distutils/msvccompiler.pyi,sha256=qQLr26msfhjz-omJutWcRHik3shLh1CIt7CDI3jBd3I,78 +mypy/typeshed/stdlib/distutils/spawn.pyi,sha256=o36CbAwOl3mVBnlyasqqYIBrYT-3v7fjYjyAyL4dFzk,317 +mypy/typeshed/stdlib/distutils/sysconfig.pyi,sha256=AIHwWAmZHKRcRC4ce6Ti9NWJJKu7P2x6b3xTjjOwPic,1210 +mypy/typeshed/stdlib/distutils/text_file.pyi,sha256=t-pGs6Li5ySUocSO0CEUoRYDUl2Uk-RhswWeECigR_Y,787 +mypy/typeshed/stdlib/distutils/unixccompiler.pyi,sha256=R3VKldSfFPIPPIhygeq0KEphtTp0gxUzLoOHd0QoWW8,79 +mypy/typeshed/stdlib/distutils/util.pyi,sha256=HJpxYeb-4XG_U5o4-GOUnAtUR776jsgUbs3a3Din2ZU,1736 +mypy/typeshed/stdlib/distutils/version.pyi,sha256=yIGp2uvie77qTBWlT2ffBGNXIKJmPfJLPzaE2zua1fc,1308 +mypy/typeshed/stdlib/doctest.pyi,sha256=ItHbQuL_dcVa4ZYZI9Iy96yv_g94X4qveq1GWGX5k0U,7932 +mypy/typeshed/stdlib/email/__init__.pyi,sha256=36My0D09zCOfT26GrMGtXQcX8V4Xp2o5KIuT4ZLRUwY,2769 +mypy/typeshed/stdlib/email/_header_value_parser.pyi,sha256=Qv50YMiDQCU_-oZv-n5M9iAiZ2ovhlgcMCI3Tn9pzQk,11936 +mypy/typeshed/stdlib/email/_policybase.pyi,sha256=swUeIOQDH3lf9NETZ3xa_21iW79bWP3WyDslKBuV5u8,3331 +mypy/typeshed/stdlib/email/base64mime.pyi,sha256=g98A7lvsErIaif8dVjP_LyoVFSXd6lNuJ_pOiTHudqs,559 +mypy/typeshed/stdlib/email/charset.pyi,sha256=K2kZQPiVXjmV9O1dRcRkIG-YkD6zRzimCJ6iy88z2KA,1713 +mypy/typeshed/stdlib/email/contentmanager.pyi,sha256=UwmeUcRuRTCDHXVEDzDASBN4lEtVG1A9BonNaMmv0b8,480 +mypy/typeshed/stdlib/email/encoders.pyi,sha256=dJc5t6R6TtZGffzRC_ji2O2KNj9n_fJHzkAnKWTbfcQ,293 +mypy/typeshed/stdlib/email/errors.pyi,sha256=YytDsUjPrDoI4fpZktf-mhKVCosZOedsS6pQfAFhDg4,1627 +mypy/typeshed/stdlib/email/feedparser.pyi,sha256=tCckWKeyn3VByGY8oWuHWJryiEMgrMI-ehJg0TaQeOI,978 +mypy/typeshed/stdlib/email/generator.pyi,sha256=rPe8JphvX-0-PtPiwWWPabik9A5DdyleteBCXSJi57g,2373 +mypy/typeshed/stdlib/email/header.pyi,sha256=qSEdPSMNtA22vkNbZ82enBddW0sZ6sq7GxBASj1-i6U,1332 +mypy/typeshed/stdlib/email/headerregistry.pyi,sha256=02TipcviVu8S0hwdnIYs8Bl3Xi80hOscPiU-_LmfIqU,6664 +mypy/typeshed/stdlib/email/iterators.pyi,sha256=Vou7LSsfU52ckW-lKx4i49KGi0rd54LctjXHimRblrc,648 +mypy/typeshed/stdlib/email/message.pyi,sha256=S0Rj-3C9_AylKvSJEAtTHPLQDEQmpwxN2AoHFpO0vBw,9210 +mypy/typeshed/stdlib/email/mime/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/email/mime/application.pyi,sha256=PkqCQXJMdIRSXBV14unvCnpQTuNcEQO23W8CJ8hhtAc,498 +mypy/typeshed/stdlib/email/mime/audio.pyi,sha256=hsnNC5xAaI2pvS7DYMr58Y46U-hv4MjAKUF0wXWnDfs,482 +mypy/typeshed/stdlib/email/mime/base.pyi,sha256=zMUOzyzRFw00inwMFYk-GG8ap-SM9dtp1GRTxjfAiWU,271 +mypy/typeshed/stdlib/email/mime/image.pyi,sha256=E3zejA7f_g0NY09tvTj8y1jzGQ0IPrhsKDAofd6ZObA,482 +mypy/typeshed/stdlib/email/mime/message.pyi,sha256=bsaprH4pzYNkTvgmycx-y5dLBHIk9jCgnnyiBtVZ0VA,313 +mypy/typeshed/stdlib/email/mime/multipart.pyi,sha256=F2NodkSKHx_3Vzad43ESWUF1LVYzGjpJGszm8NGsb-Q,504 +mypy/typeshed/stdlib/email/mime/nonmultipart.pyi,sha256=YW7_zxIBEwStGGAuw7nQEYYS7Yz_TMuTW4-ZIFpIpM4,108 +mypy/typeshed/stdlib/email/mime/text.pyi,sha256=wgYFMCXnpeiM7zp8gpxkLRLCh-7wrGuZUNvRqSHzbG8,298 +mypy/typeshed/stdlib/email/parser.pyi,sha256=Nf0GvqrZFcpD2sQzUTByKAtvevJVUdnAYSXs7-k-Qs0,1975 +mypy/typeshed/stdlib/email/policy.pyi,sha256=HIZ7t_nZivqGEuZouZg9OwehEOggKg6-it_wsrKda5s,2813 +mypy/typeshed/stdlib/email/quoprimime.pyi,sha256=bSFnFlSadE1pXHmqDzvAEnWwNyeWSLm-i21Kczwrt6A,835 +mypy/typeshed/stdlib/email/utils.pyi,sha256=ehSBF_IbXENAGCL-0WCokbKNI3Qap3q5j-sOF4MYn8s,2735 +mypy/typeshed/stdlib/encodings/__init__.pyi,sha256=LUuWxhvArWso6nBkQPJLAL_rbz3Bzd8-ydF4FWn_MJc,469 +mypy/typeshed/stdlib/encodings/aliases.pyi,sha256=NBl4ko1LeUclvHYI0p7ALF_qM5n2aJnXH5HXapTR95E,24 +mypy/typeshed/stdlib/encodings/ascii.pyi,sha256=JXS9tp2DG26Xrrhjf5-3JwR_6EK_qcZuK8WLcw_GCA8,1346 +mypy/typeshed/stdlib/encodings/base64_codec.pyi,sha256=BPqaBf4QojblNqNABf4bHmapZ9UJE0jlVB2C3depZ9I,1105 +mypy/typeshed/stdlib/encodings/big5.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/big5hkscs.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/bz2_codec.pyi,sha256=tpV7-M_UeQQDj6g3W2yDQz-rKjp2Ji_7A30aCc611t8,1099 +mypy/typeshed/stdlib/encodings/charmap.pyi,sha256=MrYgD5r621vymhH0pMTJOyoD9MBtf3GDmbnAG_7bhcA,1652 +mypy/typeshed/stdlib/encodings/cp037.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1006.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1026.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1125.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp1140.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1250.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1251.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1252.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1253.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1254.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1255.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1256.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1257.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1258.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp273.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp424.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp437.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp500.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp720.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp737.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp775.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp850.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp852.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp855.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp856.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp857.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp858.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp860.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp861.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp862.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp863.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp864.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp865.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp866.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp869.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp874.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp875.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp932.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/cp949.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/cp950.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_jis_2004.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_jisx0213.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_jp.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_kr.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/gb18030.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/gb2312.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/gbk.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/hex_codec.pyi,sha256=6bEBV4unOUo8eopKjspIfrarAnyMTCccp71cZNX9usQ,1099 +mypy/typeshed/stdlib/encodings/hp_roman8.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/hz.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/idna.pyi,sha256=B9b4Xh5OeA3WSMD62Q-0i8N4OOBVjPsoAth6Zwjqpik,924 +mypy/typeshed/stdlib/encodings/iso2022_jp.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_1.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_2.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_2004.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_3.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_ext.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_kr.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso8859_1.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_10.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_11.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_13.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_14.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_15.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_16.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_2.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_3.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_4.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_5.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_6.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_7.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_8.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_9.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/johab.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/koi8_r.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/koi8_t.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/koi8_u.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/kz1048.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/latin_1.pyi,sha256=dGwLgYjYgcDVLAqJXzaOltDLDNgQNC-AkFvwfzgT2ls,1354 +mypy/typeshed/stdlib/encodings/mac_arabic.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/mac_croatian.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_cyrillic.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_farsi.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_greek.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_iceland.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_latin2.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_roman.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_romanian.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_turkish.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mbcs.pyi,sha256=UiUp0WbMdEMZHIt8SnKjHg69ytiUNItKVAqF_DQMBGc,1091 +mypy/typeshed/stdlib/encodings/oem.pyi,sha256=N9CqMmApOhl7nSiLzjurOoNE2RLhmZNdP6HknNp_fm0,1087 +mypy/typeshed/stdlib/encodings/palmos.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/ptcp154.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/punycode.pyi,sha256=UkVSNYEFRPDcRIKMbI31RzSlUoE7zrV0CWXsXBHlne8,1593 +mypy/typeshed/stdlib/encodings/quopri_codec.pyi,sha256=vBA4qnjYHR5HgJtXe4fCziiPxHYkivKgS0kV-nppjX8,1105 +mypy/typeshed/stdlib/encodings/raw_unicode_escape.pyi,sha256=0fWozv5f1XYye3i6HZPnrrMUGqyqxJpDxq3KxJcsug0,1000 +mypy/typeshed/stdlib/encodings/rot_13.pyi,sha256=dU8Pz0tT7qe9xXipOvYcO6mcdPPXWvIIUJ7nsJVxkjQ,889 +mypy/typeshed/stdlib/encodings/shift_jis.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/shift_jis_2004.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/shift_jisx0213.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/tis_620.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/undefined.pyi,sha256=kCUblX0Okd8hRsoTvKG6UvdQUbnLAbCr7z4MrfuhpU8,755 +mypy/typeshed/stdlib/encodings/unicode_escape.pyi,sha256=w981JOse_RTIukRgKiOqbCcktW5eaBUdyLNMoAIeWzA,992 +mypy/typeshed/stdlib/encodings/utf_16.pyi,sha256=SRka2t2ru2-Psn1H98shycpPpmxZhFn69wEFTXSuDck,761 +mypy/typeshed/stdlib/encodings/utf_16_be.pyi,sha256=k-ApL-tptz_Qby4BnAVsmUxfgzA2SDVcZBlgNdIyfes,1004 +mypy/typeshed/stdlib/encodings/utf_16_le.pyi,sha256=ShA30MIHkKSurNzu8CE0d1PxGrXqcO_JIpEshtIOALg,1004 +mypy/typeshed/stdlib/encodings/utf_32.pyi,sha256=PfqJtFEQglw65eSDJnvYofUWiQG-QZ9Z8RY3QHYr0yg,761 +mypy/typeshed/stdlib/encodings/utf_32_be.pyi,sha256=RF2NNlVWIYAzZ4kd97J5GaSYFm0uwiZeWMDdaWbXl0U,1004 +mypy/typeshed/stdlib/encodings/utf_32_le.pyi,sha256=wDx-GPbmCG3z_8VLu4Bm4VIcgBXXcxrmkyDt9-QW_0Y,1004 +mypy/typeshed/stdlib/encodings/utf_7.pyi,sha256=P-9LUl4xTXFeZofgd3n7OeR7euVOs5nM-zmMD_MJhf0,988 +mypy/typeshed/stdlib/encodings/utf_8.pyi,sha256=uENG0zdTfNG6D-Hwpjmtpsn937wGk9LcaXB05dqgKY4,988 +mypy/typeshed/stdlib/encodings/utf_8_sig.pyi,sha256=CAvKrplGLrXKmpdEW4-PjihiA5UICRtcD8YaJX5dhiM,1059 +mypy/typeshed/stdlib/encodings/uu_codec.pyi,sha256=Se3B9axmM6vAb3QORy3eL3ZXR9yrW96-3PhugTE0Ww0,1148 +mypy/typeshed/stdlib/encodings/zlib_codec.pyi,sha256=qVKqhqMfl5_AOj2gr6lfLi_KwOA3kotTpygyaGL6BZk,1101 +mypy/typeshed/stdlib/ensurepip/__init__.pyi,sha256=8tmoDM1Cy7ojGznNaYzp_-zzoTYP_FunKhPvKpsVU4I,264 +mypy/typeshed/stdlib/enum.pyi,sha256=CXcJRqgYi7a49ih39CfOjwrXhVbTf3X2ixiIpJ7sRRM,13512 +mypy/typeshed/stdlib/errno.pyi,sha256=9mBovztCB7JiBa_Vnqd8IcLEIY1SGQkoiXb0Ua6of_E,5522 +mypy/typeshed/stdlib/faulthandler.pyi,sha256=Z9827Vz1J1H-7Oe8RGn0n5-2GkScs32mV0J1pPZgeGc,957 +mypy/typeshed/stdlib/fcntl.pyi,sha256=_qHO3krIV030nllkmIUy9DZwPtus6ETGJ3XGXl02FUQ,5495 +mypy/typeshed/stdlib/filecmp.pyi,sha256=_8kalXH1bxz2bhbKjN37Axjbd-4VZ34Id3uW80IwHIE,2237 +mypy/typeshed/stdlib/fileinput.pyi,sha256=TeQEIAgfs7c22mjaZhDO16LSn1xcg4IxE22TC_tzSTQ,7378 +mypy/typeshed/stdlib/fnmatch.pyi,sha256=a4FS6DccPaFufmc4RaWyx6_YUwJn5EY1Y1dAWiDeN6Q,525 +mypy/typeshed/stdlib/formatter.pyi,sha256=PoCFa7jJ7efz-ZO-IJU73MK_O9t7mjbYwjxBaSppqpU,3711 +mypy/typeshed/stdlib/fractions.pyi,sha256=Ittk8E5Yt-PTbrhkgsoyQkJ9x2JvUo2E0qE7ja0UwsU,5879 +mypy/typeshed/stdlib/ftplib.pyi,sha256=8X5Bz9PymgF7APau-y2WV9wusJSurerkOvtqScuhs8c,6471 +mypy/typeshed/stdlib/functools.pyi,sha256=Ff9DT41crRL6n1DWN7o8Xr-HxVDeCJ4i4B4Y4RL9CSQ,9984 +mypy/typeshed/stdlib/gc.pyi,sha256=2oqPKzdagg0sTQiNweKlg_GblP1nKgln5SUxOyufW8Q,1153 +mypy/typeshed/stdlib/genericpath.pyi,sha256=z8Eq4qv3HvhYTk9WA69SzQ6n8-7eq59Kd0ROXfLkpHk,2384 +mypy/typeshed/stdlib/getopt.pyi,sha256=Gn-k7sstt-bKMRdLzdBORwZuWF12zbz53R4Lyp26NUk,909 +mypy/typeshed/stdlib/getpass.pyi,sha256=ftJHHXPw2nli4yEyEIaavmo2LKxaeuKthi4n0g1qS24,401 +mypy/typeshed/stdlib/gettext.pyi,sha256=z0oFjNUalU5YRjnAnPETfONgWcuMdgiB5eoBy2sk3_s,7574 +mypy/typeshed/stdlib/glob.pyi,sha256=nhNUCpB0XuONiJ7sX9hsRVPbcwo033QG5Dj7w3XR7bg,2201 +mypy/typeshed/stdlib/graphlib.pyi,sha256=3loMDkMk4j-vtp5dGRaOa_RNqyM3FUZCJhTJIyrplzE,917 +mypy/typeshed/stdlib/grp.pyi,sha256=2hJQL4kCKhQ-QBAa87oM83ldvW4WaOkWTlySGzB9VGg,702 +mypy/typeshed/stdlib/gzip.pyi,sha256=nRks2mwqCa2sb8Rw-hSzv4GGpd-z3LfLtGu-qyfamXk,5567 +mypy/typeshed/stdlib/hashlib.pyi,sha256=pJUJEmUpvp9MijK7Dlb4w5AVkzHv0dMR86x7s-vaaHM,2208 +mypy/typeshed/stdlib/heapq.pyi,sha256=pk3bixMpPG0XvHwoJ6Hb7TcF3ZNVawMts7TlV3AHIRo,949 +mypy/typeshed/stdlib/hmac.pyi,sha256=40bupGra_ng8jZ3ACrLf6chzc-vdo9YVWDBPddosgy0,1258 +mypy/typeshed/stdlib/html/__init__.pyi,sha256=TKNt2K9D-oAvCTmt9_EtgRndcpb--8rawxYFMPHTSC0,157 +mypy/typeshed/stdlib/html/entities.pyi,sha256=RC8NoJ_AMu5IUWVuSXkGvKD5O-6ZNShjHOL0NQgXNpo,236 +mypy/typeshed/stdlib/html/parser.pyi,sha256=WuDpXERSFK3XaJaDI4cIxkFl9Iudvifpm-JpBL2XbyU,2098 +mypy/typeshed/stdlib/http/__init__.pyi,sha256=QP08bjXK5harBEh319rMNwQmB3WrtFYMvSNPGs3CH0w,3030 +mypy/typeshed/stdlib/http/client.pyi,sha256=-t3te4k6kfKeucd8_snpxM3Op6n8O7R73r6ckd4NP6o,9790 +mypy/typeshed/stdlib/http/cookiejar.pyi,sha256=K1OKZM_u4Tf-NlITqc6DkMzi63EgJeLyyIrQ6ZEQI1w,6667 +mypy/typeshed/stdlib/http/cookies.pyi,sha256=rDnxuhD_248ig-SdmenZphkGueDCnQbwbKp4eF7yqKs,2298 +mypy/typeshed/stdlib/http/server.pyi,sha256=8aCsv0TBG8dfl_9vqf2BdcKDiVYuU2j9d_DRGhLNJ2A,5726 +mypy/typeshed/stdlib/imaplib.pyi,sha256=JV-fusQAQBWqKsyvu4ZaoQzQiUh4jT6GDEEtWy8jT-8,8949 +mypy/typeshed/stdlib/imghdr.pyi,sha256=syq6jKngvEHgcopZE0xDIZRok2gbjdCW4mT6DBPDNtI,541 +mypy/typeshed/stdlib/imp.pyi,sha256=EZyon6q6zcsDFy2qM0f5RQqyIGAnQ598mt85lWiTo54,2484 +mypy/typeshed/stdlib/importlib/__init__.pyi,sha256=s5reSVWSp1cZl-U2HSPsg5QXbM1zpY1IcHnnQsrWV5U,724 +mypy/typeshed/stdlib/importlib/_abc.pyi,sha256=CZnLlR8x_ckCsQ4W9qGS-iIv1CiYoOYma6n8aCVTBTM,858 +mypy/typeshed/stdlib/importlib/_bootstrap.pyi,sha256=qdoz8OV6L4bWxFlroAznM-KSVf0bYNCQeYTz-Uk1cUU,129 +mypy/typeshed/stdlib/importlib/_bootstrap_external.pyi,sha256=pfdzy0vceWdL5QBZyMak6yLi9ULR0xR3PgGQbO6M2BI,117 +mypy/typeshed/stdlib/importlib/abc.pyi,sha256=0THKS1Fkt8M1WFd-y-xCJrlK8Hjs_88wInME7eEn-TU,8119 +mypy/typeshed/stdlib/importlib/machinery.pyi,sha256=UsDZB7rAhKUwQw3ZRWHisxYl9VT6sI764eEIVCtzQ_Q,1503 +mypy/typeshed/stdlib/importlib/metadata/__init__.pyi,sha256=rRYAJosHlfIW29h3hvm3NiDXxRi-QwGJES2chNlGbns,10488 +mypy/typeshed/stdlib/importlib/metadata/_meta.pyi,sha256=dtApBQ2RiMU-m2Y1B_7yLfMRlLHEXVD1OACZdPKwGVw,2552 +mypy/typeshed/stdlib/importlib/metadata/diagnose.pyi,sha256=sf4qsMlUFHtdxkUxCQbo-hL0app08cWTq9c-z0HaHy4,59 +mypy/typeshed/stdlib/importlib/readers.pyi,sha256=7L8VwCKFo2l-XObbzjFIMRxy0WJEH3Zl2g6hB4rPskI,2737 +mypy/typeshed/stdlib/importlib/resources/__init__.pyi,sha256=juDRPr265zenEXFKtpTHr5RN2IrG7-Dvki77giGYjUE,2771 +mypy/typeshed/stdlib/importlib/resources/_common.pyi,sha256=5NPtrEBMicBxF4ozU69dVj7AtARLyl8Z1zsWSmkBlzU,1600 +mypy/typeshed/stdlib/importlib/resources/_functional.pyi,sha256=2WKLITIOtf0yZkrvsr9BcFB-Rn458TqFhmH7a_tUqzk,1597 +mypy/typeshed/stdlib/importlib/resources/abc.pyi,sha256=KYNT7Qe9NM9ym6H5xRUmiq9Xmr3spvOXZVaEiVQUZNk,2325 +mypy/typeshed/stdlib/importlib/resources/readers.pyi,sha256=L9ISdjyiVx8ppnP2bTSjbdd_dzvr1lY3_aRn6ZfitsM,398 +mypy/typeshed/stdlib/importlib/resources/simple.pyi,sha256=jXtnKAAwsnhFm1AsPBgbkXwCwMdhMEG0-Jh5fTgLsmY,2234 +mypy/typeshed/stdlib/importlib/simple.pyi,sha256=Px9D1mMPoXrh__Iy1JacqIN2AEUSTLHrV2fVGRRkTZI,354 +mypy/typeshed/stdlib/importlib/util.pyi,sha256=ufNdpvJwZjkC2rnGtIcvcCnCJB02lLj7rFpBhAzYxjE,2832 +mypy/typeshed/stdlib/inspect.pyi,sha256=OzruGvxWkCMRrcMkXh2kEIQM5e9PAl7Y39kPSvx4xPY,24080 +mypy/typeshed/stdlib/io.pyi,sha256=VVN4o6zv2BYaAAO9tHPKmAMx_-euN2qG6E8A5n02rzo,1944 +mypy/typeshed/stdlib/ipaddress.pyi,sha256=QsCpKNUg5SUfwsyQw-yuG7lw3fNGyIaIL48YXSBUiMo,8469 +mypy/typeshed/stdlib/itertools.pyi,sha256=QwLu8w3W9GM9KTcbz5canlUuLxnUx4TIpnedzzSaP40,14005 +mypy/typeshed/stdlib/json/__init__.pyi,sha256=XhcpH-7ynXInaWJyf2TG0DKKt3fC_1Owvn2s6E6aefY,2061 +mypy/typeshed/stdlib/json/decoder.pyi,sha256=XdU0nhYShlWZbSXpxGdsgurtM3S_l0C9mDYCV9Tfaik,1117 +mypy/typeshed/stdlib/json/encoder.pyi,sha256=f9FjO4Rjf_lLqLjPkusYRgCdrtG8hq7myq7p6_c3Bec,1323 +mypy/typeshed/stdlib/json/scanner.pyi,sha256=4UhE-14W8W3ciJpWohjD7YmE8NJb5W1z-csoM_de_oY,171 +mypy/typeshed/stdlib/json/tool.pyi,sha256=d4f22QGwpb1ZtDk-1Sn72ftvo4incC5E2JAikmjzfJI,24 +mypy/typeshed/stdlib/keyword.pyi,sha256=eCmwLAJJZkNZG5hADH8mPsiQVmSLO8FGKYctaFcmabo,434 +mypy/typeshed/stdlib/lib2to3/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/lib2to3/btm_matcher.pyi,sha256=zWMSDahNavhi40hkU1rK-3lPsSgvlsDJtwhQfqAlmSU,860 +mypy/typeshed/stdlib/lib2to3/fixer_base.pyi,sha256=NacQW1e6fooBSu5crrweMC0KKcBhXDQmsQbe11U3cj0,1692 +mypy/typeshed/stdlib/lib2to3/fixes/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi,sha256=xMqbvuWy1ujOd9odCGJi3UpeSLmlYk6jNK9L5jydnAc,215 +mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi,sha256=UI605ggRRcCzfho7-zYV7NelkKfOxP4pG9518pIgQJM,259 +mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi,sha256=lY1h20fQ_HpI-54CXXjhRpazbh-I8PMasjxPau1iJjc,240 +mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi,sha256=RysLZN7QX0ouBHx4bD5sRCTtV_p6GQlF-PKTFpePqHo,224 +mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi,sha256=qcbZRE3X7cFCwAQ-BH_0Nkxk0wEvS04tPUOfJbcae4c,424 +mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi,sha256=Df6KW8jrbtYWU_kWAqlY5FRLc8drkCgE8pmpp1S14Lo,415 +mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi,sha256=2qmp1Dmizd6ZgyeC8J5HvjLXpYBYT5oBBGCD9C7idWg,214 +mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi,sha256=Ms7SLIU2e4kOB_ozEAs7Q5Oo86ka1k214dr8Iw_dQnc,218 +mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi,sha256=gtX9wmo7ARiCUZdcYTFfmNsnbOXTudXM6yUzXf0Hui8,445 +mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi,sha256=J4qoUbRK8teogKnr91NZA17UlcWexU8YhcM8OCpYG60,280 +mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi,sha256=2gPueWngu_FThhvFNXCbHzJzJfdez0m88wdfu_FBrCg,227 +mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi,sha256=D2C_mtrnL2BZofMuWARTRX21Is6U1oKTUSy5T7-98d0,216 +mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi,sha256=tredl7rFWBAEJs2ZPtiEd5jD0FP0Hyr7sQkwlms554A,225 +mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi,sha256=oCI0xQcAIh4X8qW6ZF952bMpHCgp3lOJVFZLVwdTmDA,216 +mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi,sha256=z73__dxQnDnXOmtl97XsDj0OcwwXVomz161RiJ-XmTY,459 +mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi,sha256=atLYbUa9wDEYsm8ImyHmmlfT6WVdiddPK0FUr0jtS8o,507 +mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi,sha256=cBkDJycNw0JcPQ3U63ODaqb2LNVW3MWbvxFD1v7SDmg,653 +mypy/typeshed/stdlib/lib2to3/fixes/fix_imports2.pyi,sha256=QDdVrRYdDeFHQ7d5qar8TK7derNWpJdMrwfUvMm2NTI,150 +mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi,sha256=QYFs7CJ4jZZ-JwEVl1tjfFdPZsyACH9VfYoY2GWkW-I,269 +mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi,sha256=kmI0_JFByQJiRnumNO6lHjHpVZqdiw0Qs-vVFoix2nk,252 +mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi,sha256=LCDztGYxR0NBoLaNfU6kBxBUUG_VInMqccPxIQ3LOA8,228 +mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi,sha256=LMCpC8O9x9EmdL2QLy5QUHnCG3nMhx0hrW8KMsNgx60,245 +mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi,sha256=RSOaZS-pyByKNWYwmD91NHE51PCNZp8BkoR7V8N4K3k,230 +mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi,sha256=DFYBWAAkdgf09ftU0Hkdv7X3KPiJgHVf6URHpnyCyCQ,240 +mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi,sha256=LPR5jxzCxakicFoFqCKGF1iM4wQbSM1ZfO-gl2OiwRc,274 +mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi,sha256=vr0_fJbfJEDXgt0RGMprEsR3Jwq934IHVOYitO-Yvbk,587 +mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi,sha256=rCRrKsYEcXFsMLayDRnWG_X4tE7vHqxMGgOAbYM26pw,264 +mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi,sha256=za5_699UQ5u7gExpW0rFQWLoz0gBWiaL2bdM-Uk8XkE,217 +mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi,sha256=4OdBIkvhFM1Ek3QWe9ACAUW2aqBE48SLKiY69RIG9YA,518 +mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi,sha256=BJ-vs3pK9DLUFfA-BjFExiPExmcDwyoNofwrY0ZPu4I,225 +mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi,sha256=DA_3aqN1HEiG2MaxlQYmmwGFX3UkxGoTlq2ipJskiTk,226 +mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi,sha256=Qph9PS3cZMsJBpxSnyqvdLXm4Wz6MRoM9OhIChvkBBw,312 +mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi,sha256=LHA6O3-Pc0iVRgFxTnk5SwdrhzD9ibtsb2xYVjxN5zw,223 +mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi,sha256=PCnNJjkjn32OyMZDGt9I-tyuNF2rDeulcCHPaCdnN1Y,334 +mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi,sha256=kWLdHKgrCjNgWxy8_S8t1GLE_-RmCxzdV6EUDPGFRLA,215 +mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi,sha256=6JYhq6treAVEVMIJWogmw7a_7b7OQnGQCTdSTPaUhJM,226 +mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi,sha256=gx_ts6bc5MOHO2RI_uK5WsH-ibfTHoqewnOq6bMCttI,264 +mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi,sha256=jDt5tEFPpe5bpW2_xX_K7g2mXZHBgD5daf1YLq1xrgk,252 +mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi,sha256=CE1ZA-tAamCMq6Gft9Kl9z15jtuAr6OBywN3fo5fAJ8,507 +mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi,sha256=91OLJrm0eK1k1FzpE4563_J_RnHfERocHeSrj6DE8qw,214 +mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi,sha256=b-wHK26YV2c2R5cBOhIU63gf25JYqXbycta1zHqyrik,224 +mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi,sha256=RQP7prg227V7Lm5grhrzD7MHg3ApogLcb5SlgyR7DzI,223 +mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi,sha256=izheZTCqKPd-Fl2aZWzhhcFOtdMIY4F_lVqtOmcdtng,250 +mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi,sha256=Ayft1UP88mwxNDsP3KXuyEUfacJ9myhP07vP3lXHL28,223 +mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi,sha256=YIZEizRdrqqcuJwK6XW87OUSUQHo9aSMdkGMJls1nHk,451 +mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi,sha256=p3quhtHggwMg-KDc2dmO8c9oTT6SOZLTG1feVPqXuVw,215 +mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi,sha256=AVUm0QE0OxwwXgZLWITXQBHrp3WFQGyQo1kPN8tF6io,369 +mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi,sha256=RMEF00r8pC3wq6PgHKTg52_Iwo8azKPRs5oGKmKAJAA,556 +mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi,sha256=7WECM-TvzSNknzhW7fy7Q1RAAwLNsncFNP_ujjHKPZA,304 +mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi,sha256=IE05vQKlmMkk9tPbvH-I3FOfSNd-XP1XLvdBX8K0Rb8,726 +mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi,sha256=aXv8cGy3hLrtZerMtHLAiNQaSAQQGke3C6WJR-8A_Ok,228 +mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi,sha256=Qw4i-Jn3A2LoG-jSpHJ8BoUSHk38iegK1FyxtUqngD8,274 +mypy/typeshed/stdlib/lib2to3/main.pyi,sha256=MgUWnovV8WODrjmnR55Xgej8tjBSg3p9gOK1GRbVkJs,1532 +mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi,sha256=J1r7O6-RC55RX9XuIU4QcT8sm-7ySY0eowiibNJz0kE,287 +mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi,sha256=PNvewWFDcgWCmmEwYEKtBrKrHkukMZqkryr6WauQZ1w,1067 +mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi,sha256=dG17yFsbtkiDsvKCyWRZvc0zmaCLF83m_naTZzUziRU,682 +mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi,sha256=TtrXnXJiXUTSBXIP_3hJUoKM2h_rSNg5aTqQcL5tZIc,151 +mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi,sha256=dSjInOriPq4H6YhXCvsW0lUeCZKMV81mYmYc9ZbEh4Y,1133 +mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi,sha256=suHtbvS7x64S7z70EMaFdw-ZJgu8_w7t0WwRvq1AzBo,2273 +mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi,sha256=9kLlQlmffvLgVeS7cQC-OGDuzwKmP92YOOfqmaIDRUM,1418 +mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi,sha256=mdjbHoIgTIFWGaGKpky1FqxpY6Ugih514SvAlNUT-8k,1972 +mypy/typeshed/stdlib/lib2to3/pygram.pyi,sha256=cMDHpJNWgsy0aJVrG2e2uBDq9DbXd30htXQBMjAO_pA,2253 +mypy/typeshed/stdlib/lib2to3/pytree.pyi,sha256=RowzuYJKhSUKX32E6Vrf_SHu9HS8ezr97-vQ-x2MFWY,4185 +mypy/typeshed/stdlib/lib2to3/refactor.pyi,sha256=vhGguYDE5gxdbUxG_LKxVPZ9KhkbryDjRT_hK7FSZ1U,3946 +mypy/typeshed/stdlib/linecache.pyi,sha256=HKDzUJPKyFXBXceGeeoYpMhxXIYapQBj9D2DyQrJ2R8,852 +mypy/typeshed/stdlib/locale.pyi,sha256=fQYiQf-xr8d02FmoEbMECafNv43Hhu0wJK9fZaT9m8s,4934 +mypy/typeshed/stdlib/logging/__init__.pyi,sha256=yTdkVuimp1L1s0C5mVCgfpR96sx1FI0ZCnfM7iw_F2k,21288 +mypy/typeshed/stdlib/logging/config.pyi,sha256=hJxN2Oieqxij9A3m6jYuNJOYlccveJkiynIwhkJVvtA,6323 +mypy/typeshed/stdlib/logging/handlers.pyi,sha256=-tE5aQIqfaG3oNqT8O-bymyKzzMUlI8DFPs8QNueB8k,9192 +mypy/typeshed/stdlib/lzma.pyi,sha256=jW_lZJbwFU3LyHV4jqCm32diG1Qk1G0-2cDFHgJVJdk,4926 +mypy/typeshed/stdlib/mailbox.pyi,sha256=A59sq_iCF1kyKxZhioUeusZkVLfYfTyBnifwvinYGP8,10779 +mypy/typeshed/stdlib/mailcap.pyi,sha256=h3wCqy9SD2DA8-aB5k7vW17ShyhlL-AZV6iYKpRTyP4,388 +mypy/typeshed/stdlib/marshal.pyi,sha256=LqlTQDvNSGJGSKNjSQ832j-3opQFkcaeMVuy2v4RWM0,1605 +mypy/typeshed/stdlib/math.pyi,sha256=pBs28qdJCrqf9GbUFnZpWE3SRQDjnnobRt1z3fXNMS8,6156 +mypy/typeshed/stdlib/mimetypes.pyi,sha256=xW5fMdXLqWZ28W24kOXRvKJFBLtB0Dw_xGrvha4nI7w,2128 +mypy/typeshed/stdlib/mmap.pyi,sha256=O5U2etvBYdYDq1agg3iH2587jMQQkZ4CwLWMK71t1kY,5692 +mypy/typeshed/stdlib/modulefinder.pyi,sha256=IbgQdklMWj-I-DZL4ceI5KzniZ1cNuwdBPLE5ZnD12k,3399 +mypy/typeshed/stdlib/msilib/__init__.pyi,sha256=AMuAaoRE_erzIsqazBOn53UVl2Ss8wIoFX-zgr_YP2Q,5854 +mypy/typeshed/stdlib/msilib/schema.pyi,sha256=2V7cxsSreXKr3UnBQVIgpUEVjXS1gbBGUXsggjFUltM,2173 +mypy/typeshed/stdlib/msilib/sequence.pyi,sha256=6MlkmUtknHyQU535LP_PPXGY5_QCxJo910--XfE0KwM,429 +mypy/typeshed/stdlib/msilib/text.pyi,sha256=1I58yqiApA7hjFdzhrhsw6D8WlVfH8JJtB1b4NkMNL8,216 +mypy/typeshed/stdlib/msvcrt.pyi,sha256=tWT8Hx0Ogy2Fwv_Gt3dVjub0ibtMcXLYoiGPLGiI4MQ,1196 +mypy/typeshed/stdlib/multiprocessing/__init__.pyi,sha256=KafkEHitV2NmXHJS956RawcoMZhXV6_mZ-io0ZpMSv4,3132 +mypy/typeshed/stdlib/multiprocessing/connection.pyi,sha256=QHxUSmeTedOmVlXk_Nn9rvls0rpyZL3XMSujfYuCPtU,3723 +mypy/typeshed/stdlib/multiprocessing/context.pyi,sha256=FCFuO3lfuMSzOeYuBJZJ3K1-PrS9yN5GrPM59i2isWc,8578 +mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi,sha256=RxtDm0qYAruvxpGO-ijjlP_OUNeaTeE0vsb7mlxbKsc,2353 +mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi,sha256=WNsr78HeHz67VG14qLrc6xUkFNQkKt18jw95amhFBQg,1282 +mypy/typeshed/stdlib/multiprocessing/forkserver.pyi,sha256=FDzUWLVRjUsyDrOT1h7mvZD_JIbGf4mPnK6OEN3WwYM,1873 +mypy/typeshed/stdlib/multiprocessing/heap.pyi,sha256=HTI4VlqHvZBggg775D8DsGkkDCTLsda4zbRqHvGCeL0,1084 +mypy/typeshed/stdlib/multiprocessing/managers.pyi,sha256=UaOACGizOaw5DViNPKJ0v9axvYrCQpYD0KKYZeDVdv0,17215 +mypy/typeshed/stdlib/multiprocessing/pool.pyi,sha256=szTwi4UNMQZ37pSC3MMQuHTDs4MLs8AjEOGM5r9wDG0,3938 +mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi,sha256=RHaJE_47OeQykmnXjxeT52Q7FlxznFVaknStQxZJlP8,810 +mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi,sha256=-f851cHQEbM_L9oXaw6PrUHI6bKAVasRR17OirOSd60,353 +mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi,sha256=kuKZmJxw4id8R5dTTp-B7E-5qDWTSexAOkCqStEMoKo,524 +mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi,sha256=ZyXdPF2y4wvcgveiWOouv9Y9P9gnhn7D4XXpD9WF46Q,773 +mypy/typeshed/stdlib/multiprocessing/process.pyi,sha256=k2Zxt_FkjkRG7wFGlGhK6-WDXgDITeF8pIplbaxrRDk,1266 +mypy/typeshed/stdlib/multiprocessing/queues.pyi,sha256=1VGowyM1s1VDJenHK76rdleZfDGAubiic2px79Gqcjw,1949 +mypy/typeshed/stdlib/multiprocessing/reduction.pyi,sha256=y_Iw8A3Tla4xBI233K--zseyG-SsXyVWyjLD2Gvqigw,3270 +mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi,sha256=d9OjiE5L4aC3-u2-WC7csArCtkqs_IMOhhOVMEi6UjY,420 +mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi,sha256=zGYELoHtbABO37k1BWl3_LgSXHnFiBnIUj1fciE8Jb8,695 +mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi,sha256=JRimnBHWs_TwG96aTh2FnuVIGc9gtUjieRe4ZYJeFSA,1500 +mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi,sha256=_srRMuFu7Qgx_T8pCxJnmioDglYGQWoMsIyhd4OFOJk,5254 +mypy/typeshed/stdlib/multiprocessing/spawn.pyi,sha256=oy8FZLtca2ZmZ1OXzvU-kFGSLioeCghBO1iaqLwfy8c,904 +mypy/typeshed/stdlib/multiprocessing/synchronize.pyi,sha256=yxldGzmsmfSGGUYEqalcUUAYKb0U0JHKuaATm87JigE,2525 +mypy/typeshed/stdlib/multiprocessing/util.pyi,sha256=1H7c1aqVS6BpLXB7MCmHxUp53seiuD3O4McMk2Xbq5U,3090 +mypy/typeshed/stdlib/netrc.pyi,sha256=tvfrFw9uqNzt6Xt_fJVlbF2uXIoJy7YXEAOzveB8AEo,745 +mypy/typeshed/stdlib/nis.pyi,sha256=jnKh2Xj3mroOTpZpm-C7BYPVe5M18UAIVeh66AFGyw0,293 +mypy/typeshed/stdlib/nntplib.pyi,sha256=FYFknQ33uku7s3vEFrIPxHlEVA0KY82-a7L66EgPCK0,4279 +mypy/typeshed/stdlib/nt.pyi,sha256=FNIRcLSoTrcRDA2NIYrHiACEr3r3WgkyDwNhSujOlsc,3407 +mypy/typeshed/stdlib/ntpath.pyi,sha256=c_WZ6Pg1gmoyTxjZV5X1HasYC7znrU_9WY5_hYDg5N4,3049 +mypy/typeshed/stdlib/nturl2path.pyi,sha256=MeWnFTlqhvq6m2QsnYDaX_oGiUga6swI7bn_RjP6epE,412 +mypy/typeshed/stdlib/numbers.pyi,sha256=Jhh3FjInAcY76uLHr0aS4zbHOVyydjDR0sGvD8ddnK0,7546 +mypy/typeshed/stdlib/opcode.pyi,sha256=OYD0--bYWa-eZl2IFKBhbwI_nVsz1nmgM9nWzyIJe6k,1119 +mypy/typeshed/stdlib/operator.pyi,sha256=7l31EfbCCMDMwLWVNn7M7Jgt2WYX2IzenDxtAnkgjv8,4927 +mypy/typeshed/stdlib/optparse.pyi,sha256=bpx4WTvY-c8mRkjiF3FgjPzU4T4aoF5zlTtLzf2MwSU,13191 +mypy/typeshed/stdlib/os/__init__.pyi,sha256=rtWD_qwmcyQY8o-oA4K7oOs6Qw3QrYOGiV_GbhybXr8,57934 +mypy/typeshed/stdlib/os/path.pyi,sha256=G76tJbvlG1_kzFd8gnCqS4Mht3gPzlC1ihIBqzurxDM,186 +mypy/typeshed/stdlib/ossaudiodev.pyi,sha256=mjHFd2y8BrdeToNwDIUX3YJtRHBgs9vaGo32sQP9uPI,4409 +mypy/typeshed/stdlib/parser.pyi,sha256=qESTvpCIEl06MJlFOeGt6pVTgqDvrwINj3Haj_g26DE,1100 +mypy/typeshed/stdlib/pathlib/__init__.pyi,sha256=GrZmCnXWQSXVlaBuI24ZRXwTXMnMN0JCyAmtrujfqwU,14683 +mypy/typeshed/stdlib/pathlib/types.pyi,sha256=zNj89KIAok7fdN8Lvm8ujgUnRKS5nZFJsIiSon5LEIY,333 +mypy/typeshed/stdlib/pdb.pyi,sha256=hdT_FYHrX43STqMRgikB79-Z5MT25-IfOjzYODToC7Q,11118 +mypy/typeshed/stdlib/pickle.pyi,sha256=CwfRBnwjHRKgLtvZaxfQ7JW1gROeTM7shtLCfqI6gqM,5306 +mypy/typeshed/stdlib/pickletools.pyi,sha256=Avlw2PygqsaMj4zcx-b2jWXzMFFbz96NC82jefeYsYM,4232 +mypy/typeshed/stdlib/pipes.pyi,sha256=FvE1GTA5YU-JHBIO-mCAIfrAARL7g2Ck0HmgJ765gNc,502 +mypy/typeshed/stdlib/pkgutil.pyi,sha256=ApsHouaT21XnCdXiW4WVG_ck5eDv2vqt8RWS2zpnlGI,2591 +mypy/typeshed/stdlib/platform.pyi,sha256=-YjPVuiCJWNL8W4d1S6ceclr8vW-L04i--1--NqosLs,4109 +mypy/typeshed/stdlib/plistlib.pyi,sha256=YSN2FLch6L7BEJrNR-LpZPlNZQy6qBWBQYmwh-c7I4Y,2746 +mypy/typeshed/stdlib/poplib.pyi,sha256=a-MhQrCHvKvvLACrGalHGM4OTN7dMl8UJJDcjNLjiYo,3122 +mypy/typeshed/stdlib/posix.pyi,sha256=gwKe-gvg6-QOeRCIIpMZmYhmpCybxGGeh54J6qS232I,14052 +mypy/typeshed/stdlib/posixpath.pyi,sha256=dJIklN8TxPNn_5Y-CSL6w5I3IEn5gQXGBXljc_CdhPs,4744 +mypy/typeshed/stdlib/pprint.pyi,sha256=dZlYga82u0YmsP_K_V6INIkqTdZhskEsFBp79l5Qrlk,4835 +mypy/typeshed/stdlib/profile.pyi,sha256=VENI6_XB1JcY18Kn3bY2Sm02efBuCFMG_beiLlpZOQY,1416 +mypy/typeshed/stdlib/pstats.pyi,sha256=cKqAT2Hf7DCOx9b5QKFWZSZ1enS70UdDcHVWWD3SAK8,3074 +mypy/typeshed/stdlib/pty.pyi,sha256=A0mqxGnMi5mqKwFeDbkRUC4bDbga0X9TovCDfbMLZt8,1072 +mypy/typeshed/stdlib/pwd.pyi,sha256=rXA9jXtUOJeQ5D06dv5C8twQxrOatqmQrlg1SZFfxUU,905 +mypy/typeshed/stdlib/py_compile.pyi,sha256=pRlpK44H98D9tnHGi5C0eDgOX68dk_82SizC7voWnH4,894 +mypy/typeshed/stdlib/pyclbr.pyi,sha256=xZ2POHrJZT7xe7eaueO6wxdgpFFkdf1BePdF0PuSbqc,2284 +mypy/typeshed/stdlib/pydoc.pyi,sha256=GuA5LMlVvyseqR5UGQUT0JIUSi6XFcOVN-l7ib26Bfc,14303 +mypy/typeshed/stdlib/pydoc_data/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/pydoc_data/module_docs.pyi,sha256=N40eJTBi8loXiVb-QlmiobAaZQYbDkQEs1WO6rUacks,61 +mypy/typeshed/stdlib/pydoc_data/topics.pyi,sha256=gqCAY10yIjRcrCCE8hqoUVs5o5cE0NgOOft9X-wg3AE,56 +mypy/typeshed/stdlib/pyexpat/__init__.pyi,sha256=uT9PYCwa1oRrxNkdndQoI2tx9MWdcduw8l3faku9STA,3887 +mypy/typeshed/stdlib/pyexpat/errors.pyi,sha256=XA5Ik0oagDYSTmleaMQFSTqkcfMN_1xGwP19va6xeH8,2357 +mypy/typeshed/stdlib/pyexpat/model.pyi,sha256=WLYMeiykYnU6gpN35DItiUEjTPby-vu0DKAZ4afGefU,291 +mypy/typeshed/stdlib/queue.pyi,sha256=_Zq4o820Qh_giAIlnV7hnA9Ox1ws0dRjdGwWVFOUmFE,1910 +mypy/typeshed/stdlib/quopri.pyi,sha256=a-dyP2A0w_xQm3D2KXIZzDA99FPX15Kaq297GJTnK1o,669 +mypy/typeshed/stdlib/random.pyi,sha256=4v-VQZ69AZ8x0vGKKSa82EnIaeyJ5_M2RN6KRSQFdS0,5214 +mypy/typeshed/stdlib/re.pyi,sha256=A3Er_MgsvnAX2T7YTLDGpIrc_bzIxp9P_cR79ThHWhM,12139 +mypy/typeshed/stdlib/readline.pyi,sha256=JoE2nbK4Fv-UIDbo7lgTp_38524hDx8kRRpL5Qhuo5M,1988 +mypy/typeshed/stdlib/reprlib.pyi,sha256=usKrUhRcCNeOVdYy3S6I8njRORXIQ9rXrGme00uGJd4,1986 +mypy/typeshed/stdlib/resource.pyi,sha256=OAlIxkLvLkdxOWk3nmG7kh0GPvPUPgU3HV8wkGx8Fkc,2972 +mypy/typeshed/stdlib/rlcompleter.pyi,sha256=FtTt0Z1sNrWz6EMCyowIRAq8tzAeTpee6rUVJ5b-Tsw,322 +mypy/typeshed/stdlib/runpy.pyi,sha256=hrHtuhkdU-vJb7E6trWXD-ITI33AOQT_HH5CEsURVdQ,811 +mypy/typeshed/stdlib/sched.pyi,sha256=iIT6hC0Nzz47CUBmzSoBlamexV9s5KRD0--vXuumJRk,1521 +mypy/typeshed/stdlib/secrets.pyi,sha256=IrwNYsRo8gkFA4FkqJSPKwYqcAgDnGcgrm3Pu6Y4Yxs,660 +mypy/typeshed/stdlib/select.pyi,sha256=xOhnY8bIZgqUpVX-w4RxXgMpKnNsGCQSDnoiHYLMLWc,5805 +mypy/typeshed/stdlib/selectors.pyi,sha256=2rN66ItZthqaO9SCb6Ix9ImpLfGkdn2-hYk9SexRGt4,2927 +mypy/typeshed/stdlib/shelve.pyi,sha256=iXAfiiZL63IYPfUdIS4g2pMfx6thq4K6NqQ2WfcY6ZE,2343 +mypy/typeshed/stdlib/shlex.pyi,sha256=CNq7RB3jlgSD8lpZVEb42Coh3pfeOpd6tjp3XCVXptQ,2191 +mypy/typeshed/stdlib/shutil.pyi,sha256=TjwVseRzVNWxQgerDoEBwtOWkr5F5nY5GMTPeyovNbU,8362 +mypy/typeshed/stdlib/signal.pyi,sha256=YDVZyjuYVKTZOK7Mvb1LcVyMIqkqDdfyGf_iRPtjED4,6094 +mypy/typeshed/stdlib/site.pyi,sha256=lDIaRFWoJkNeGfPKavcrMtvia4akAMWMR5BIDlDYvx0,1547 +mypy/typeshed/stdlib/smtpd.pyi,sha256=_DHsDMkG8iT4uDal27Ub0-kssEC73bncY-A8f_E_IEE,3082 +mypy/typeshed/stdlib/smtplib.pyi,sha256=OADEHJ4wKdstbcknWtEFw_jaJ0Nmm3aHW8v7nIPaJCY,7523 +mypy/typeshed/stdlib/sndhdr.pyi,sha256=4boTiWWf2o3VW6QhITP8JNEePP734AlxyMeU1cn74CM,353 +mypy/typeshed/stdlib/socket.pyi,sha256=3oEyyJMejbeWsXrfFFI-d_JEmIcpgt2PzLQTnnokh2w,46182 +mypy/typeshed/stdlib/socketserver.pyi,sha256=gPN47U1Kh7UPFxuvK-you8aRwvHbtzgvMVnt9xBQM1A,6991 +mypy/typeshed/stdlib/spwd.pyi,sha256=hyZQp0XfNGpN05cq8qpIenyS2sUm6_H3odOvSyxacKo,1299 +mypy/typeshed/stdlib/sqlite3/__init__.pyi,sha256=gTSYC8b30HiRXBg-yOyB4iySbwpY42lb3ygc-WOWM9E,22071 +mypy/typeshed/stdlib/sqlite3/dbapi2.pyi,sha256=5_auPrbYUGLd6BirR7xmDFUr_Ibdm7ZTAeZ3meU5KEQ,11438 +mypy/typeshed/stdlib/sqlite3/dump.pyi,sha256=kKrQ2CozgG8GoIXMDMNiMJz__B7tzZ0VQb2jzkH6p5g,90 +mypy/typeshed/stdlib/sre_compile.pyi,sha256=WUWnQmaYMB5XB6H9i6VAU-pVrqKb9FqeKYneO99QGak,401 +mypy/typeshed/stdlib/sre_constants.pyi,sha256=XTz8_VeEEAXJSnMdUviQINrLMOXclnaJbzKifN_zjuU,4781 +mypy/typeshed/stdlib/sre_parse.pyi,sha256=AsBSS835EPpGxhpKlo8Ce2Z_t_cwOB7CNwKmR494On0,3906 +mypy/typeshed/stdlib/ssl.pyi,sha256=lRy9m6ekUYu_CRw_S2SgRvdOXO1noZR2T9tVneBjzPQ,22938 +mypy/typeshed/stdlib/stat.pyi,sha256=YbUbmHZzGlieVnKK7uvAjRwv784LjinmOWsnmu05FJM,3354 +mypy/typeshed/stdlib/statistics.pyi,sha256=b40i4KdsQ8NiKI6F4BFqAwuOUsTOdPpy3mdlGzrT6Lo,5916 +mypy/typeshed/stdlib/string/__init__.pyi,sha256=aRIqf-qZi4mc_N7u3HAALMWpXttjU48A6a0bcbPLuoY,3095 +mypy/typeshed/stdlib/string/templatelib.pyi,sha256=b2lwTPVujnkpNrmHIfwe1cz_NFhUJPpaM5UbLPWIAzs,1324 +mypy/typeshed/stdlib/stringprep.pyi,sha256=53l-7SuzjSdXnCCb5lHYSHxNWQNBXLQzbL8DX4usXYs,985 +mypy/typeshed/stdlib/struct.pyi,sha256=7xjDbX-Sh1C_E0rFZ-Z0DnwF6P27v088eMM03kL2R2g,155 +mypy/typeshed/stdlib/subprocess.pyi,sha256=Bysl_cmplt39Hog8xlEquwiYK2Fc6h5j5kShndAqj1Q,73103 +mypy/typeshed/stdlib/sunau.pyi,sha256=qTvLbam1UgmqH9Hr0mLgIFZ3jQqxSvBceIOq5QcnwMU,2991 +mypy/typeshed/stdlib/symbol.pyi,sha256=ADRkN_rhRV_foCYktb0NHR7jm7h_N4XOHo9VPWF1lFM,2144 +mypy/typeshed/stdlib/symtable.pyi,sha256=cisakBNhFUXqj4qVY5DPVHYhCQne9EXG0xvPFMZY0SI,3095 +mypy/typeshed/stdlib/sys/__init__.pyi,sha256=OYe28JBiW5YJNApqSVC_LcCI4KJw0VEJ2jgA3ynxD6c,17286 +mypy/typeshed/stdlib/sys/_monitoring.pyi,sha256=Q1m7PiECYw6GsBMriYApV4ZuNWwzG2az8sW3JptGryM,2116 +mypy/typeshed/stdlib/sysconfig.pyi,sha256=lyZJxIlFWYJ38V_GlzJH5ZZphKd1G89adNl-ryWdMzQ,2075 +mypy/typeshed/stdlib/syslog.pyi,sha256=i76lh_ehgdU2LU7fJ964HDXiDXL64_BSAdR1F7j-rhg,1597 +mypy/typeshed/stdlib/tabnanny.pyi,sha256=qBHW9MY44U92xKdFbYgrSXljglOVtAY0GYTa41BHwbE,514 +mypy/typeshed/stdlib/tarfile.pyi,sha256=ByPxvJLZoWhP025Jq031LgDhwgUUz8WhFIzTo24Zpl0,29540 +mypy/typeshed/stdlib/telnetlib.pyi,sha256=Sh0M5cJCI6WicuEAhDCsDXYxejYsMcZMcLsu0lo0diY,3640 +mypy/typeshed/stdlib/tempfile.pyi,sha256=cbw3xYs5wg6rbl0YvaAfvTzkn3oPsOpbHlWp1f0gHIo,16591 +mypy/typeshed/stdlib/termios.pyi,sha256=z-dQ4Pz1e7IBBVKQx4GraNjNrHC4OI8vAZU4-FYM4TY,8171 +mypy/typeshed/stdlib/textwrap.pyi,sha256=6eEGWUkmDRU_-fA-aOIWWse9-1GIq8T89S4Vaf9aJ7Y,3233 +mypy/typeshed/stdlib/this.pyi,sha256=qeiwAiqbPK8iEcH4W--jUM_ickhZFNnx8cEvTqVPvCY,25 +mypy/typeshed/stdlib/threading.pyi,sha256=W89e0e_bdAeJUfA_MNFK-ICT3j5Rvq_Ob7-wqh3BlBY,6878 +mypy/typeshed/stdlib/time.pyi,sha256=Ngd1mFfkGzY5yPk5C-XWeCoTFttFXpptgpGiyy4yFa8,4317 +mypy/typeshed/stdlib/timeit.pyi,sha256=bF-Gp00o3l1_ccA1EvQoauAJ1lZOLhq8TON2G5-UhBo,1344 +mypy/typeshed/stdlib/tkinter/__init__.pyi,sha256=aGRd3Pe-B1VmomI38V9_0GE_vhv7uAbE2nv2SwFYaMA,163233 +mypy/typeshed/stdlib/tkinter/colorchooser.pyi,sha256=WigYRTIs27oyuwzPwhvndb3z8DkuLuZngd2MsKM3DNA,360 +mypy/typeshed/stdlib/tkinter/commondialog.pyi,sha256=jJRmyjdOxTouujFvS2YtOg0qh1ngKyHQKPc0dnoumhw,468 +mypy/typeshed/stdlib/tkinter/constants.pyi,sha256=sP9hOZSnvBITqJRCmpigGDJqwP_1GoOAOZ2eQH0blkY,1853 +mypy/typeshed/stdlib/tkinter/dialog.pyi,sha256=oEV2mFaVp0ESk_8nFJOuKGlXWG4u5MAYVcRLedjoZik,324 +mypy/typeshed/stdlib/tkinter/dnd.pyi,sha256=hltw1-itHapOgnqlBgcmOgzV1XGMlu6CEsHjwwtqFYE,774 +mypy/typeshed/stdlib/tkinter/filedialog.pyi,sha256=1TUWUWpUtYN7aPDM7ANHPEDIW9tQoTfmY0m9rJhpdI0,5176 +mypy/typeshed/stdlib/tkinter/font.pyi,sha256=raU_THjHyDL6A61VUGyBR1RtojyWuQhhgArYqQ3E-hw,4606 +mypy/typeshed/stdlib/tkinter/messagebox.pyi,sha256=u_s-BST--wes-h8D1d1uSSj-9s-S6hRfJYcwZSHL9Bg,2742 +mypy/typeshed/stdlib/tkinter/scrolledtext.pyi,sha256=Hp_LlFfwVwR3W4iDZKthreGUofPbIbiOkjl1O-HEL9o,302 +mypy/typeshed/stdlib/tkinter/simpledialog.pyi,sha256=ZZxYKT7uNQ7t1FJ4RqlXX5BCJg9Zcs93e3uFRqt-bSU,1596 +mypy/typeshed/stdlib/tkinter/tix.pyi,sha256=c2OTQkpGaZtIUARkX1drGDhFwdl9ffl52ZNiGvkt39Y,14375 +mypy/typeshed/stdlib/tkinter/ttk.pyi,sha256=lkosHUk5zhrJab7NvdZ00qCXP7d3avNg4aXzX5LGkRs,54053 +mypy/typeshed/stdlib/token.pyi,sha256=45u8j2PqFfchSf-9MPcS-Ep7nL_EKb1jSalRa1qr3Mo,3343 +mypy/typeshed/stdlib/tokenize.pyi,sha256=pB0iu_RYKwen5_ZtDW--R7aKiwH8JprdTQsJzKRCAGY,5445 +mypy/typeshed/stdlib/tomllib.pyi,sha256=v4XWpK6XmcXUQ8R3tQSmQBwtbOuBssM0Z5ZDjhYVIcM,937 +mypy/typeshed/stdlib/trace.pyi,sha256=cwRpCtKhsA0IdW7O8OgQJ3l03k-7f7EwrYTj3jQwrko,3605 +mypy/typeshed/stdlib/traceback.pyi,sha256=MSmYqikk5aEGvXjxZEL-9WtQ378lmgmGuRpfiyryf9k,11677 +mypy/typeshed/stdlib/tracemalloc.pyi,sha256=ifAatgAvsKZq2B4JBSCcdhgHy4d22FIVUMEyNO3sN4I,4581 +mypy/typeshed/stdlib/tty.pyi,sha256=fwxTycZe6nGL5DBdXGhiCcgA0yAlqF9hXIUKHmDkTWQ,871 +mypy/typeshed/stdlib/turtle.pyi,sha256=oixZtSAwes43tubfJp3oAF5bmVNebZIhBRhNva1y_tc,25277 +mypy/typeshed/stdlib/types.pyi,sha256=eew2fvipkTE8RmqTx3p2cJGiE8A2UtgXaTevFo7-oQ0,26443 +mypy/typeshed/stdlib/typing.pyi,sha256=AzTvVltVDrEUuHZu2BXS5eLKhnw6QXNuQXGeO97Ixt0,42646 +mypy/typeshed/stdlib/typing_extensions.pyi,sha256=Os4QFp5rNjqa9gt6tieuY0xJq51joHjF86ohGa6OlUE,23359 +mypy/typeshed/stdlib/unicodedata.pyi,sha256=UdeHUdLrKlVMWZ1bttS8npUWtPcpDjt3PzS3y36SAZA,2589 +mypy/typeshed/stdlib/unittest/__init__.pyi,sha256=ARla4cG9E5nWe7hRFzZ82kH10g_awzGp55lY16IU6xA,1848 +mypy/typeshed/stdlib/unittest/_log.pyi,sha256=QnmSKoFS_D1bcRLqFAvfJinXn2-0-DjyBSqH_92vr4g,912 +mypy/typeshed/stdlib/unittest/async_case.pyi,sha256=owQLuLwHxWCY6UDv1wI6eVDGUi9xOKk5l_IWVCvGpXI,850 +mypy/typeshed/stdlib/unittest/case.pyi,sha256=fuVLYJh6s5nsGmSWhiWMWElSsOk3wFc1wl4e2T5hk1A,14468 +mypy/typeshed/stdlib/unittest/loader.pyi,sha256=tr-lR3NHul7QaC61k-MPUJnn5RRfqEbZZXri3qUnxes,3332 +mypy/typeshed/stdlib/unittest/main.pyi,sha256=rd2LDQ54q_gIamVlYfLBT97SE6-IYSknHgEpCcn1Xdw,2767 +mypy/typeshed/stdlib/unittest/mock.pyi,sha256=Wt8aijXORBPX7PyvVceX6JuyH_Jef0qJ8i8QaoF1ung,20327 +mypy/typeshed/stdlib/unittest/result.pyi,sha256=HX5DXqQaIentVCiFufZh-tHpSfliUUGDjb1X8iAnk_8,2050 +mypy/typeshed/stdlib/unittest/runner.pyi,sha256=kKBdpnU1ahX_Uky1uL4C-DnkglLC1QkLUL1Eq6XfslU,3502 +mypy/typeshed/stdlib/unittest/signals.pyi,sha256=6rqsVHXOvSPHSkeF_vYPf5sUaLgqqFSmFihkaDqPhSw,488 +mypy/typeshed/stdlib/unittest/suite.pyi,sha256=FhS30BvL4niz3gI5Acnp2TX449CNPs2avEUEqGt14mo,1047 +mypy/typeshed/stdlib/unittest/util.pyi,sha256=or4A8A8A-AzIJWs-74Ofhm-TaEd29zUYzlnIRhwg-dA,1656 +mypy/typeshed/stdlib/urllib/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/urllib/error.pyi,sha256=UqUqcqbz8FPtlixaJP0Gp3ecUc6MpPJaYOPydkGRQN4,978 +mypy/typeshed/stdlib/urllib/parse.pyi,sha256=Y7xJVpKJHohxE6bPifub48wXO8bJAwYA08lTtNAovzM,6544 +mypy/typeshed/stdlib/urllib/request.pyi,sha256=PYWa5-pItt_y2KWxAAO0HmwqlXjpKk5-aRNiTk_3gcw,20041 +mypy/typeshed/stdlib/urllib/response.pyi,sha256=HTnWMkkVuowLoNdtuZ99Spdymx4NLcJTSG-BdcIrkzk,2002 +mypy/typeshed/stdlib/urllib/robotparser.pyi,sha256=sA7npNj2rB3b_aFOhXqGlQNh-G7kGmyYaZ3wz__N96o,683 +mypy/typeshed/stdlib/uu.pyi,sha256=yMt5ZRAepWSra-qWti133ZGibCtrJXkMZg5kKJe-MdM,431 +mypy/typeshed/stdlib/uuid.pyi,sha256=aqeMSWDDQ0aKOl8Y-cOT7e5OmfSgymoI4gEjy467v8k,3109 +mypy/typeshed/stdlib/venv/__init__.pyi,sha256=GLWFpMESaRETXfoH7IXs67daBAmbJG0aIfDHMU5Nx24,2951 +mypy/typeshed/stdlib/warnings.pyi,sha256=AztB0gbwUylgZH2A-T7FA3X_uOeUWwpjDLaDJOe9cQ0,4238 +mypy/typeshed/stdlib/wave.pyi,sha256=bbbWyMa3ag475svSkm6idBLX6cOdN60IINkp-JSZhww,3492 +mypy/typeshed/stdlib/weakref.pyi,sha256=ic0GBe2EkvHbsXXSgpyCY5Cx339sMv21AejZsOrvNXs,8475 +mypy/typeshed/stdlib/webbrowser.pyi,sha256=CURvTjznP2Tvs8sT8_hFAsEKOBXGsr2IYHki02fSBmE,3040 +mypy/typeshed/stdlib/winreg.pyi,sha256=Iu8TKxlLIEaYP8WJuTS7RZMAgcKUVOhqnv123BsUS7M,5567 +mypy/typeshed/stdlib/winsound.pyi,sha256=I4ogNevxTWqwIqNRIeg5WXvcm_aQDAyI6VKXqMG13xw,1259 +mypy/typeshed/stdlib/wsgiref/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/wsgiref/handlers.pyi,sha256=d4qMJ3ZNLNAnDk1I___l8nIUK9uxDol-bXsjtc9BsX0,3068 +mypy/typeshed/stdlib/wsgiref/headers.pyi,sha256=hwXvKMQQHbjmcdsvFZgJ3LeIdNLcmRUDf7IrT94ZCCo,1050 +mypy/typeshed/stdlib/wsgiref/simple_server.pyi,sha256=CGpqJaFTlao6-hnkzCqHv4sHcDQfpBGT0sIueL5jhMQ,1426 +mypy/typeshed/stdlib/wsgiref/types.pyi,sha256=89NSSgpDnuOWMCuBprU210FsnnMh3V6TPmT26md1aYc,1264 +mypy/typeshed/stdlib/wsgiref/util.pyi,sha256=NxqrfAJ7JBdP4BuWs90xyfdSCfnywSXYi80uCXRt21Q,1060 +mypy/typeshed/stdlib/wsgiref/validate.pyi,sha256=NCpbRPP9fTt21peGNlXLgegq6U1yZaeAxFO-SUfBlng,1737 +mypy/typeshed/stdlib/xdrlib.pyi,sha256=wxJVHCfO5rju29ihBF96XgK3dj5b-LbsVGeotGgp15k,2368 +mypy/typeshed/stdlib/xml/__init__.pyi,sha256=m6b7OtCfk4VfTktwgMovrcUyjhCV0671jAktSJMbdwE,249 +mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi,sha256=W8h9o8Jp1CsxU7O3ciu-6GelYeoJQoVuy8jeUs6xRIs,735 +mypy/typeshed/stdlib/xml/dom/__init__.pyi,sha256=4P-wzCUKUSkybVJieQlmIt338OwpdO0Q_kUnlDDZ4Fc,2548 +mypy/typeshed/stdlib/xml/dom/domreg.pyi,sha256=LNRgIl78O0eH3m7E5GFqG0BKQ0JSsHxTBnwr5KznZvI,418 +mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi,sha256=ClpimZ5otjEESOeunAAT1KoM9d2FvbdJ7a8wCOqWowE,6487 +mypy/typeshed/stdlib/xml/dom/minicompat.pyi,sha256=IgywKLWtKGaXnNA5ZzsAd-VsXUKAgjVIzjPQCpklUFc,716 +mypy/typeshed/stdlib/xml/dom/minidom.pyi,sha256=rxqF7PasZaBH6vugDxx_jR7pEkxhTkWIyUlaV6W7iGs,28674 +mypy/typeshed/stdlib/xml/dom/pulldom.pyi,sha256=nlFB0Lbj0kzV7_F0teVTMTykZ3y_-ZmPQ4dL2cMEWHs,4844 +mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi,sha256=qQK35MzE_YE2hNt90AhQE5jq0jd2bnVTLiGKO0GtEgk,2952 +mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi,sha256=8G_tDfXrvOGm9g3LTVIKnH8JfB1ZzJGcUfVTOA4N-WY,1176 +mypy/typeshed/stdlib/xml/etree/ElementPath.pyi,sha256=TiZrEPQInm35MiIMWr94B77iftOXmBMNvM1WxiwKLYc,2035 +mypy/typeshed/stdlib/xml/etree/ElementTree.pyi,sha256=NWA4O8oUjXfzZfbdEl3J4BMr-9LmSWmWx-eFW5QlVWo,15176 +mypy/typeshed/stdlib/xml/etree/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/xml/etree/cElementTree.pyi,sha256=iYR7ebpdB3g9zfBvICnV1VzvQktMya-Dh6lX4C9u4Uo,36 +mypy/typeshed/stdlib/xml/parsers/__init__.pyi,sha256=PS75lzF6CFuo_xdO83zK-IOQrnoJQ3FkUoMSOMdwWJM,39 +mypy/typeshed/stdlib/xml/parsers/expat/__init__.pyi,sha256=8pm3z3heMEx09A84UjPVQw3lb9cH6X-UK86skDsfEfk,189 +mypy/typeshed/stdlib/xml/parsers/expat/errors.pyi,sha256=mH9YRZuV4quzksDMLEmxiisAFgNhMOhl8p07ZzlS2XE,29 +mypy/typeshed/stdlib/xml/parsers/expat/model.pyi,sha256=M7GVdd-AxOh6oGw6zfONEATLMsxAIYW2y9kROXnn-Zg,28 +mypy/typeshed/stdlib/xml/sax/__init__.pyi,sha256=7TU3Ez8RjqR041xvpGy6eEBajytpO2W8C7L7AxVOwB8,1616 +mypy/typeshed/stdlib/xml/sax/_exceptions.pyi,sha256=Q41LNt4ARdDs5ynBIAGP-YapjU08m5Kah2ZD939fO9c,804 +mypy/typeshed/stdlib/xml/sax/expatreader.pyi,sha256=D77gx2ZCLo4OI11kXiKHUHwidxAv61UfPUI5k3JqFVg,3800 +mypy/typeshed/stdlib/xml/sax/handler.pyi,sha256=rYfSg3SBNou6cpoO7sBwcP6T-kHClkCwzj0QDZW57Zw,4528 +mypy/typeshed/stdlib/xml/sax/saxutils.pyi,sha256=j-yIPACE-yvjnStAguxaR_HLfJN_Hq8KOLVd8DBGJzo,3804 +mypy/typeshed/stdlib/xml/sax/xmlreader.pyi,sha256=cGP-i2OzR9bUSuZct5ijA8bjWUApxdPVopuJ4yerDlU,4348 +mypy/typeshed/stdlib/xmlrpc/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/xmlrpc/client.pyi,sha256=dIN8JqkYO713oZIdUjdPddwe8-M1Na7v54d4zRR0FdQ,12035 +mypy/typeshed/stdlib/xmlrpc/server.pyi,sha256=OF2v_1XAjRYtbMLb_akHJrkXUKHX27cfzmrX7sfgm7E,6231 +mypy/typeshed/stdlib/xxlimited.pyi,sha256=SCWnX8bML0Kky9tWb8sMQSCrafe7gj7ZA_xhltk9Lik,491 +mypy/typeshed/stdlib/zipapp.pyi,sha256=gOkFhcdfGpy6PIboXe45wODMw-94YtC1ypUTCxBxTfU,553 +mypy/typeshed/stdlib/zipfile/__init__.pyi,sha256=0bIQh6JP0UqbBFhcFhP6MlpkVwVYV06yeEUguByZT9A,12968 +mypy/typeshed/stdlib/zipfile/_path/__init__.pyi,sha256=V0KUH4awNAvD4rMNVdhMyGnntWdR8udpDXMp9gkBKrY,3074 +mypy/typeshed/stdlib/zipfile/_path/glob.pyi,sha256=7w_87VMRxyV1KnR7WaXktZtPbi0ZS8ibd9w0qsLxksc,943 +mypy/typeshed/stdlib/zipimport.pyi,sha256=SM9xql-crUor4aP7fFefFvGITxf0MpQPV3dNfTv9hVA,2677 +mypy/typeshed/stdlib/zlib.pyi,sha256=DIoGakJlb3pOGe_aAbSfPpLfaJq1HhdBCL1FbEijqcE,2395 +mypy/typeshed/stdlib/zoneinfo/__init__.pyi,sha256=qM_vgqSETLRL7D6D5upCnmwbnE_Pk_96i0RDnHjWYS8,1326 +mypy/typeshed/stdlib/zoneinfo/_common.pyi,sha256=QdqQFkqe8f-PN05bSbHLW90qfEqgdVLbIsKiPbW4lno,462 +mypy/typeshed/stdlib/zoneinfo/_tzpath.pyi,sha256=C5ve2ashiiq2Jm0EtWEdJDtcdxNc-_Ewff8I56pFfZE,524 +mypy/typeshed/stubs/librt/librt/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stubs/librt/librt/base64.pyi,sha256=eg1QM7rzBPf0M6vRyeufBzPEs5IVIdi0Ibz8ZBI75m8,180 +mypy/typeshed/stubs/librt/librt/internal.pyi,sha256=_PYEoUfpIUrfy9BYwR6E2KeYR5PIasX1J9xjItL8e0s,850 +mypy/typeshed/stubs/librt/librt/strings.pyi,sha256=TZp9sDx-XJ9oCsjRKHtcd6xDm9YslTS9UsnulnZJrXI,1780 +mypy/typeshed/stubs/librt/librt/time.pyi,sha256=cUxvWAIFy4V5dF4bBxljjyBdQDA9dMIEXiEO0kXV2I0,25 +mypy/typeshed/stubs/librt/librt/vecs.pyi,sha256=5bFw_RT-Q7DKxTZGUlPph6qeORj8-DKPozAEOIZWBlU,678 +mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi,sha256=tYCX8TT53K59k-CGWcO0BBH6e04ysgytc6f9LiPDGws,9072 +mypy/typestate.cp314-win_amd64.pyd,sha256=Vh3JvgNy5sAEr_x5OJB8-Uii3HVi9Rv2ojzEJQwqnwQ,10240 +mypy/typestate.py,sha256=8jPWL2ahTWfehNT6WWlVFPC86RFZ152FM7nqq6PeG2A,15958 +mypy/typetraverser.cp314-win_amd64.pyd,sha256=DdmCZpD-mO8J780XsK6yqp3Ksmiw44mW_XxZZwGQDNk,10240 +mypy/typetraverser.py,sha256=eswFxl-86t2d9nukXA00-e8kwWsl8UY4wKudQdCDS3c,4456 +mypy/typevars.cp314-win_amd64.pyd,sha256=9uUqObLGgxAa6CrUH_yA3mGBWwdRBfo0dCH-hsDV7hw,10240 +mypy/typevars.py,sha256=8qw5kAfCaKm5hkk5Ze08HH9yMzsTSZOjBenjydTw5OA,2996 +mypy/typevartuples.cp314-win_amd64.pyd,sha256=t762eW9CLL3V62JaUDP5TujCXbSNa2eW9IRB4mUPTSU,10240 +mypy/typevartuples.py,sha256=jo6F1pu39vcaohI38BbkVhgtmvSy-2aoA3H8WYXzfJI,1058 +mypy/util.cp314-win_amd64.pyd,sha256=uom-_j0SuWCnMOrYCe_FySS6yo8SvKissOi7FRrDg-4,10240 +mypy/util.py,sha256=MjiXTD_BzN02H6xRdx1XhQDMsgdHQ6OhSVEkcFu9zq8,33125 +mypy/version.py,sha256=7WAGL73uwneMeTnPmico6R65EQhKPhmDe0X7Xd0XeqM,24 +mypy/visitor.cp314-win_amd64.pyd,sha256=UDCcL2aGuGeWmbsnMNiZ3KTBO41SxEyHLnS8PE2g7D0,10240 +mypy/visitor.py,sha256=reus_vNJ7I4PNWh1JNRO7-IVxdfbfXbMe4AsGV06C3c,18785 +mypy/xml/mypy-html.css,sha256=-e3IQLmSIuw_RVP8BzyIIsgGg-eOsefWawOg2b3H2KY,1409 +mypy/xml/mypy-html.xslt,sha256=19QUoO3-8HArENuzA1n5sgTiIuUHQEl1YuFy9pJCd3M,3824 +mypy/xml/mypy-txt.xslt,sha256=r94I7UBJQRb-QVytQdPlpRVi4R1AZ49vgf1HN-DPp4k,4686 +mypy/xml/mypy.xsd,sha256=RQw6a6mG9eTaXDT5p2xxLX8rRhfDUyCMCeyDrmLIhdE,2173 +mypyc/__init__.cp314-win_amd64.pyd,sha256=BU-gDnutp4_HiPlZ5W8F6a30K9VnbhGa5cTUlbSwRv8,10240 +mypyc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/__main__.py,sha256=19Zu2Z6FDpgBZU4_L47hAfYuQS9nvmYgiTr9X0m8c4s,1928 +mypyc/__pycache__/__init__.cpython-314.pyc,, +mypyc/__pycache__/__main__.cpython-314.pyc,, +mypyc/__pycache__/annotate.cpython-314.pyc,, +mypyc/__pycache__/build.cpython-314.pyc,, +mypyc/__pycache__/build_setup.cpython-314.pyc,, +mypyc/__pycache__/common.cpython-314.pyc,, +mypyc/__pycache__/crash.cpython-314.pyc,, +mypyc/__pycache__/errors.cpython-314.pyc,, +mypyc/__pycache__/namegen.cpython-314.pyc,, +mypyc/__pycache__/options.cpython-314.pyc,, +mypyc/__pycache__/rt_subtype.cpython-314.pyc,, +mypyc/__pycache__/sametype.cpython-314.pyc,, +mypyc/__pycache__/subtype.cpython-314.pyc,, +mypyc/analysis/__init__.cp314-win_amd64.pyd,sha256=fPb5PWHrxQWSGIMPhYWtwmbTL8KC2qHIXM6hJSZRpos,10240 +mypyc/analysis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/analysis/__pycache__/__init__.cpython-314.pyc,, +mypyc/analysis/__pycache__/attrdefined.cpython-314.pyc,, +mypyc/analysis/__pycache__/blockfreq.cpython-314.pyc,, +mypyc/analysis/__pycache__/capsule_deps.cpython-314.pyc,, +mypyc/analysis/__pycache__/dataflow.cpython-314.pyc,, +mypyc/analysis/__pycache__/ircheck.cpython-314.pyc,, +mypyc/analysis/__pycache__/selfleaks.cpython-314.pyc,, +mypyc/analysis/attrdefined.cp314-win_amd64.pyd,sha256=0-2ZWHu1M13szksWr6TZcyg7O11GmHN3zt2wCQmU_l0,10240 +mypyc/analysis/attrdefined.py,sha256=6GizEEEnsA_pMmDkBQoxEVFd0beZ-WmbO3alJWUmZZo,15419 +mypyc/analysis/blockfreq.cp314-win_amd64.pyd,sha256=DnBmvhBVRAtMOJ2Sim9NvOO8_Ir3_Z_8weWNj7ev43Y,10240 +mypyc/analysis/blockfreq.py,sha256=CjdVRFXgRdsuksk6e11cqbsFdj4e1z_8GHvvnY_Pgb8,1004 +mypyc/analysis/capsule_deps.cp314-win_amd64.pyd,sha256=qPB8iC_L0GUS2ue1y80os7mMgaj-K2OFUBE47AUxlbA,10240 +mypyc/analysis/capsule_deps.py,sha256=yiyc9sR8M9YqxgvPOt2UzyNExID4p4KvV3zj_LDZOXk,3026 +mypyc/analysis/dataflow.cp314-win_amd64.pyd,sha256=6FzbnEC5xjdhe4CVwKi7diRyt1zcLorKDiBQQpJkYZs,10240 +mypyc/analysis/dataflow.py,sha256=knLglTPySxNfObLRMUXrnHP8_jZSPpc4Go1SZVyKYxo,20011 +mypyc/analysis/ircheck.cp314-win_amd64.pyd,sha256=FYM381O9_6hGr9B_bS8-2d7KQTy10xwvNirXn4QJs0Y,10240 +mypyc/analysis/ircheck.py,sha256=vKEnpVGYYQt3ATGhe9Wietm7-XNcHxrFoeJ_S7EWdM8,15810 +mypyc/analysis/selfleaks.cp314-win_amd64.pyd,sha256=Zn4v-VxftPEkooPDqy2r09ONNOixi-X-MAuceIlPN8Q,10240 +mypyc/analysis/selfleaks.py,sha256=GsSBCBl-Fxqg7n7TCV6MTj-rHDZ0cgTn9UzXiX9hArE,6173 +mypyc/annotate.cp314-win_amd64.pyd,sha256=NfvClFoBHQfLHkbSxkNTcOGaA__yCogwaxN3o3WCqvk,10240 +mypyc/annotate.py,sha256=XANWJWaGzXkyUn5J1jlnSj8y4OFucH3PUWwfjtMNfU8,17993 +mypyc/build.cp314-win_amd64.pyd,sha256=7lVbcFlIj4ozJ6tQCBGAXZJSnX6D7UHE7Dz-IIZGKJg,10240 +mypyc/build.py,sha256=L6LH_ryZdwKCbVMmZg0SrIJlOfsF00_AANcl7EIo-SY,31474 +mypyc/build_setup.py,sha256=rbgoioeFLbyK_KNuLYwwd9snN3kDDFv-Qa3QC8NzHgw,2653 +mypyc/codegen/__init__.cp314-win_amd64.pyd,sha256=QRn9nrr86QZqtCf--luVDBNE9I82joo_RLH7jh8-Wdo,10240 +mypyc/codegen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/codegen/__pycache__/__init__.cpython-314.pyc,, +mypyc/codegen/__pycache__/cstring.cpython-314.pyc,, +mypyc/codegen/__pycache__/emit.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitclass.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitfunc.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitmodule.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitwrapper.cpython-314.pyc,, +mypyc/codegen/__pycache__/literals.cpython-314.pyc,, +mypyc/codegen/cstring.cp314-win_amd64.pyd,sha256=RSnZG2Cgk81m0oul1iPPu8bdGo7_kUpSH_72PIlf5Mw,10240 +mypyc/codegen/cstring.py,sha256=yB_SJmahDpTC7Xq3vlCstPZhhyLpRzEy9yHBwdqdIa4,2004 +mypyc/codegen/emit.cp314-win_amd64.pyd,sha256=-MOtIVsXrHLpMUsKJdtvA99hxLzCy4Ah5FgAZ_EeKf8,10240 +mypyc/codegen/emit.py,sha256=jobXvG1e8ilUR80tonwrDISOseM2Og5Y3LzgTfrZTa8,58255 +mypyc/codegen/emitclass.cp314-win_amd64.pyd,sha256=XgM0TApzwdkxYWAR1pD6xfBCX1-Ox6AX9qQ3a3A8Dgo,10240 +mypyc/codegen/emitclass.py,sha256=JMtbxdPbF_JA_7Vi244X_Z_gkshCn07ztuPEy4zMTm8,51670 +mypyc/codegen/emitfunc.cp314-win_amd64.pyd,sha256=JacJeaw2bEwjk7CPLkPCufAIpbo0kgd_ArF36c5Orvo,10240 +mypyc/codegen/emitfunc.py,sha256=rClZn2ddp7_6RbQI9movAXIdCkQmPu2S7twTmiocj1Y,38208 +mypyc/codegen/emitmodule.cp314-win_amd64.pyd,sha256=IURfjSe1YRrGXThjGoFNX2YckzIme4vQ08SkkKvsIUs,10240 +mypyc/codegen/emitmodule.py,sha256=yaWs_S3-diEOprte1muJkxmWKLSh-HHrf7yuuS_P6X4,62790 +mypyc/codegen/emitwrapper.cp314-win_amd64.pyd,sha256=ByAg7rK5V1I9u5fSKdVwLWfGl0mI_cp8c2Ee91wUo9k,10240 +mypyc/codegen/emitwrapper.py,sha256=18d3XwiTPwnc4-Ql68I5JxwLVEI2gfzuFn6MTm8GRME,37886 +mypyc/codegen/literals.cp314-win_amd64.pyd,sha256=5jZ4drEsSxMCq0FOaPf5uJYAbZ6Cs0_yfapEMYF4Mpc,10240 +mypyc/codegen/literals.py,sha256=ZTD77KLDI_B6TfJs1HSatKa5DUMVzbeJs66lXuA8lGY,10602 +mypyc/common.cp314-win_amd64.pyd,sha256=P-0qRRrLqdqN7I19xFASk2O5935sk9Xq1OSi4-FY6RY,10240 +mypyc/common.py,sha256=csTeTjoc3kIjnkbmG1wK29xUHeT2BEJ9ihSMPnuTYvc,5131 +mypyc/crash.cp314-win_amd64.pyd,sha256=8t7h418p2Xuy2aCuBIZo_g-QR9mga-F4FhY9331It7g,10240 +mypyc/crash.py,sha256=ULZHLQqJqSK8oFBsoDvr1eOCLAIoe2lwkVCDi-f9eww,953 +mypyc/errors.cp314-win_amd64.pyd,sha256=eHLPJ1cfIoDXx5fp0WnAeIt4SLU8M3X2sOkOhoha6MA,10240 +mypyc/errors.py,sha256=sUkIPSWQtn4dksR52iCGMwTEmW8CZGiIdggWJzPYNRk,1104 +mypyc/ir/__init__.cp314-win_amd64.pyd,sha256=-3rSxLFCLRkuP_NLjeLckYg6nlWapbBhS5Rkwl5atQc,10240 +mypyc/ir/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/ir/__pycache__/__init__.cpython-314.pyc,, +mypyc/ir/__pycache__/class_ir.cpython-314.pyc,, +mypyc/ir/__pycache__/deps.cpython-314.pyc,, +mypyc/ir/__pycache__/func_ir.cpython-314.pyc,, +mypyc/ir/__pycache__/module_ir.cpython-314.pyc,, +mypyc/ir/__pycache__/ops.cpython-314.pyc,, +mypyc/ir/__pycache__/pprint.cpython-314.pyc,, +mypyc/ir/__pycache__/rtypes.cpython-314.pyc,, +mypyc/ir/class_ir.cp314-win_amd64.pyd,sha256=r5s7MMlYSkCbP8HmG4mU4Gckm36NXHKxxcjDY7meBoM,10240 +mypyc/ir/class_ir.py,sha256=fb0BEd46LQ1-_pECqso1XJbAQfwr4K4xW6YuE1E7zrg,24168 +mypyc/ir/deps.cp314-win_amd64.pyd,sha256=-7b3fc98F3SiVpbVtBEJBWzsj33qBdXfKropnxZIU3w,10240 +mypyc/ir/deps.py,sha256=iAOPw_oD2i5MgmZSZUM7DPGOjv0DvGGnT6bvlSMmLL8,1877 +mypyc/ir/func_ir.cp314-win_amd64.pyd,sha256=tbG38dQsaorsqP_gVbU4J0-kZXAacO6dV1kLzeGcgt0,10240 +mypyc/ir/func_ir.py,sha256=ERRu35X1ZWirhIhqbhswpN9cv1-q7ZgWWU7QkPVPf2g,15944 +mypyc/ir/module_ir.cp314-win_amd64.pyd,sha256=vjsbE6yTNGCTdkyJ637VwvnUwSack8pIe1tpDoFSXac,10240 +mypyc/ir/module_ir.py,sha256=nAr2VjXu5zDPO5189iZTj-DT2aWqei4vHd7y6C4qwTI,4517 +mypyc/ir/ops.cp314-win_amd64.pyd,sha256=bWycUeuI6QugVd0xJXa-msMBJIqYVPiF_0sFnu6Pe7c,10240 +mypyc/ir/ops.py,sha256=na-hk3pCi2eiEvQAt_3aw9_MESbRnpvhjjMQmOYSyi0,62481 +mypyc/ir/pprint.cp314-win_amd64.pyd,sha256=gJsNy7WtnwPAGBLyHgwJALCM_xfjkpGBjxkmveZnrio,10240 +mypyc/ir/pprint.py,sha256=yngmVjQYWb0frc_JdP32i7ZTUph07n6kOQMRMRTf8oo,18668 +mypyc/ir/rtypes.cp314-win_amd64.pyd,sha256=I4dk9IZagNpkMoXzCoVqemj9ULV4kfGceU0acoXzGeU,10240 +mypyc/ir/rtypes.py,sha256=JNRslpTAg2cWUCoBUoTTTY8dQhhIosKJrb0l-x7M7aI,46940 +mypyc/irbuild/__init__.cp314-win_amd64.pyd,sha256=1C-Z4ujM_oVSTvb8jciWzfX-akPEeC0uTFgBdXa6-wM,10240 +mypyc/irbuild/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/irbuild/__pycache__/__init__.cpython-314.pyc,, +mypyc/irbuild/__pycache__/ast_helpers.cpython-314.pyc,, +mypyc/irbuild/__pycache__/builder.cpython-314.pyc,, +mypyc/irbuild/__pycache__/callable_class.cpython-314.pyc,, +mypyc/irbuild/__pycache__/classdef.cpython-314.pyc,, +mypyc/irbuild/__pycache__/constant_fold.cpython-314.pyc,, +mypyc/irbuild/__pycache__/context.cpython-314.pyc,, +mypyc/irbuild/__pycache__/env_class.cpython-314.pyc,, +mypyc/irbuild/__pycache__/expression.cpython-314.pyc,, +mypyc/irbuild/__pycache__/for_helpers.cpython-314.pyc,, +mypyc/irbuild/__pycache__/format_str_tokenizer.cpython-314.pyc,, +mypyc/irbuild/__pycache__/function.cpython-314.pyc,, +mypyc/irbuild/__pycache__/generator.cpython-314.pyc,, +mypyc/irbuild/__pycache__/ll_builder.cpython-314.pyc,, +mypyc/irbuild/__pycache__/main.cpython-314.pyc,, +mypyc/irbuild/__pycache__/mapper.cpython-314.pyc,, +mypyc/irbuild/__pycache__/match.cpython-314.pyc,, +mypyc/irbuild/__pycache__/missingtypevisitor.cpython-314.pyc,, +mypyc/irbuild/__pycache__/nonlocalcontrol.cpython-314.pyc,, +mypyc/irbuild/__pycache__/prebuildvisitor.cpython-314.pyc,, +mypyc/irbuild/__pycache__/prepare.cpython-314.pyc,, +mypyc/irbuild/__pycache__/specialize.cpython-314.pyc,, +mypyc/irbuild/__pycache__/statement.cpython-314.pyc,, +mypyc/irbuild/__pycache__/targets.cpython-314.pyc,, +mypyc/irbuild/__pycache__/util.cpython-314.pyc,, +mypyc/irbuild/__pycache__/vec.cpython-314.pyc,, +mypyc/irbuild/__pycache__/visitor.cpython-314.pyc,, +mypyc/irbuild/__pycache__/vtable.cpython-314.pyc,, +mypyc/irbuild/ast_helpers.cp314-win_amd64.pyd,sha256=SrPZDQiRD9gQikkP8yUuNp37mVWBPa5FQ1Zyv_YXT1Q,10240 +mypyc/irbuild/ast_helpers.py,sha256=aM2zAHB_ZsumV6OWOSnl7StCjhzlLnOUjlXbr63aR4Y,4339 +mypyc/irbuild/builder.cp314-win_amd64.pyd,sha256=l5vVlihVk6mfoI3Oe3JI-vXUZUzGntN8Pt2tqbG7bso,10240 +mypyc/irbuild/builder.py,sha256=jCUDjnnB8Pi_No-RJ9GRqOPAtS4tXNtxBZ2jkj5GWCg,71361 +mypyc/irbuild/callable_class.cp314-win_amd64.pyd,sha256=x7poYGzv5e6KsgiCyNF2Omg5nrbl35qJkrodW5HMPxw,10240 +mypyc/irbuild/callable_class.py,sha256=TLQxOrZL-UR_NaYYUYyiJWqmZLg1kV0TLWCvKxmLatc,10378 +mypyc/irbuild/classdef.cp314-win_amd64.pyd,sha256=gVbV1JUQkYU7-IfYv6SSb0rf6lXS-_OHr0k-aZzkVRI,10240 +mypyc/irbuild/classdef.py,sha256=5JlX4z-0-Rxvrx7EVgiA7jHBqSOxPdG1dwqe6cjVvaQ,38980 +mypyc/irbuild/constant_fold.cp314-win_amd64.pyd,sha256=WXeTaB4vohwlXpzfeJklPyLewkrB_wctZYYuwzVaqxk,10240 +mypyc/irbuild/constant_fold.py,sha256=7qIVEJSgabHIQ37ydZq2wearPFtwn_ztRy3670RhMw0,3335 +mypyc/irbuild/context.cp314-win_amd64.pyd,sha256=bNjd4VYxyJ1G5f71DKhbJ6m6gPlxcjG16qupU0ABStg,10240 +mypyc/irbuild/context.py,sha256=Z1hJYqzIocihndm_rcNZ50uNtFq6GcIdCYh462jT64E,7858 +mypyc/irbuild/env_class.cp314-win_amd64.pyd,sha256=3kql5JxrqXeK-DCwkIpgXzvDqru-jGrh_HcBzKVk7rA,10240 +mypyc/irbuild/env_class.py,sha256=R0i7Fxvzm9zDIK4w_ZBC9V2JOpG-GodPF3fhtt1EJ8I,13034 +mypyc/irbuild/expression.cp314-win_amd64.pyd,sha256=Lc-bC_21gTJauNoz0kNlVovCkH5A1IfC_d2HueulTDg,10240 +mypyc/irbuild/expression.py,sha256=Q-GN14QvP4qzo_UVFASKU07USksQON8hi5B4fJEbvFQ,48353 +mypyc/irbuild/for_helpers.cp314-win_amd64.pyd,sha256=JF3_KRbpgaDxAgRO-qOrQOCX5owG82fnDc_Rxpc0SYE,10240 +mypyc/irbuild/for_helpers.py,sha256=dskqoNgteL_bTIPo6WNOUHkYASLJUv93rF6CdEJol2U,52539 +mypyc/irbuild/format_str_tokenizer.cp314-win_amd64.pyd,sha256=8JGY6s7gM-StuNvfSIGoeDqd8Lf1Kx2-Dh0RkGSJQ64,10240 +mypyc/irbuild/format_str_tokenizer.py,sha256=SI8tBdKISJZ7u8uqr67YCOvv1V05Nz_cGAKvGjka0zc,9491 +mypyc/irbuild/function.cp314-win_amd64.pyd,sha256=NQzxpKb8SL11xTShy7MDj_-u9mbXAHoo2bDW6-x0xXg,10240 +mypyc/irbuild/function.py,sha256=Li5AnagBqBXLX-E9wPXwNEynmG-pXB1qlER7G7Sm8q0,50088 +mypyc/irbuild/generator.cp314-win_amd64.pyd,sha256=-TG4r3nmnPlG2XBkdzv6kBdTC4IJdWqAU2I6jezsEoc,10240 +mypyc/irbuild/generator.py,sha256=srx_C-ZyzHKa_7PHM-qE5NNsVAo15SvYbJfQ265tyb0,17139 +mypyc/irbuild/ll_builder.cp314-win_amd64.pyd,sha256=pIHCMKBRxpOdxcuBiY_QUPNIYdjBxy_WAUDlGdpX4zc,10240 +mypyc/irbuild/ll_builder.py,sha256=rtLMVRMf1Oil5yA-1QTqpeFRuSGANs_KG77gN3tt0CE,126260 +mypyc/irbuild/main.cp314-win_amd64.pyd,sha256=oEKcdwXCjyH7_kugipP3pBB02bokcLeOBxaY4IOuG2Y,10240 +mypyc/irbuild/main.py,sha256=AXVfML8txMS7qavazawaIJq2RrLD_8PLrMScItonBXY,5438 +mypyc/irbuild/mapper.cp314-win_amd64.pyd,sha256=ruVN7_HZQF6BMzs5ZOThERUC2K5mIJuV12TBH-ImAhI,10240 +mypyc/irbuild/mapper.py,sha256=KFLyJxngqkaPpeGE-TBGt1RxRr_htcONi-bSI5NQeto,9861 +mypyc/irbuild/match.cp314-win_amd64.pyd,sha256=xjFlRSkDN01cxgjUZCkcHCXFSzlE2LoGQzyMscait20,10240 +mypyc/irbuild/match.py,sha256=c-HbpkpZUgVS-ULCgVHRlCkp9efSzAfOEMCwayn8beA,12420 +mypyc/irbuild/missingtypevisitor.cp314-win_amd64.pyd,sha256=SYDroe68XuDK8PNsmRyXZzMURuoBmm69BUpCWEyg1oY,10240 +mypyc/irbuild/missingtypevisitor.py,sha256=awXMMkRhXZq0AnbSGKfUzs9Lx526gFvDuiYaKjeqAq4,699 +mypyc/irbuild/nonlocalcontrol.cp314-win_amd64.pyd,sha256=zCU7D72fBmUgf2Vta9z1au1PlywO8xp-RG3wKJ4isrY,10240 +mypyc/irbuild/nonlocalcontrol.py,sha256=3Afxmw21hnY2EeOdDCgSmVElV4qNGM1o8b5FGO6FVck,8035 +mypyc/irbuild/prebuildvisitor.cp314-win_amd64.pyd,sha256=2gj_NTgHMTFP_lYwbY4uulE_T_kXNUur5d_1l_6Wcjk,10240 +mypyc/irbuild/prebuildvisitor.py,sha256=JCbt7jv8_vR5LRtkhixhtA0KKbXKuS4fG02pvvBXeCM,12085 +mypyc/irbuild/prepare.cp314-win_amd64.pyd,sha256=QNlQupX0EaZWAMhGNeUwIr8lJJSeiQ0LLfF5BE1Vj2w,10240 +mypyc/irbuild/prepare.py,sha256=oOl9GsYAklOXG6dTAIu8g1afdHfvrYSbsos5p5-ozWs,35992 +mypyc/irbuild/specialize.cp314-win_amd64.pyd,sha256=xTWI3wUO28I6vLCZ_9xZEXB0p1KQYQYRkEDanEl6qKQ,10240 +mypyc/irbuild/specialize.py,sha256=j11nSFUlcCvTUU7gFt0-xQpNJxsweDcHrGnKoOR7rfg,56112 +mypyc/irbuild/statement.cp314-win_amd64.pyd,sha256=qAA4MerD5Nhzd1ZpkD7nPrCuBbBM0u_-wXJQr0_eTI8,10240 +mypyc/irbuild/statement.py,sha256=CoWJYC7extK7SZXUZERMaOb5vcc11dLDw7BFUrqGrm0,53212 +mypyc/irbuild/targets.cp314-win_amd64.pyd,sha256=mNKqI13--GrJGY7NLne5qcx5jMykHlHLqHVHJMCe7Xs,10240 +mypyc/irbuild/targets.py,sha256=r12ynPhUaTmIgnmV5c5eNbWJbqf2_L12RtW_PIQXhq8,2313 +mypyc/irbuild/util.cp314-win_amd64.pyd,sha256=P5QKbMK6G_4FfZ_AZYqcATPM863Q1hSVJf4TJEgrqn4,10240 +mypyc/irbuild/util.py,sha256=PF1wZAzRKo8eF1rSNR-zwefph-6TPf-HTx8z03i-MDE,10094 +mypyc/irbuild/vec.cp314-win_amd64.pyd,sha256=nnYCqOPDYnV0wV7RKRTsbR-3GRZ_-0RJCltHvVc61vo,10240 +mypyc/irbuild/vec.py,sha256=tNbM_s23ZVx9RxiyVboKbjhJa7Qytd_uzHDCVAKvgmM,17774 +mypyc/irbuild/visitor.cp314-win_amd64.pyd,sha256=mGPN1jxjolTLwNcfb9MGhCFuv6Fcnz1t_OXtRH0VLIk,10240 +mypyc/irbuild/visitor.py,sha256=u9q8PNSuoltkukmZkhegjCqIfQ2XIsst-Q72hd8uTOY,13305 +mypyc/irbuild/vtable.cp314-win_amd64.pyd,sha256=yG5Hd0HussrlS5388y6opYAIgt0MjDkEJXmJQaC0zcs,10240 +mypyc/irbuild/vtable.py,sha256=7OZtwAaX90up3daQb793uVlqA3q2l6WUgTAeKwrbfAI,3333 +mypyc/lib-rt/CPy.h,sha256=LwzpGVowkZSEpoScf8mtsTA71-Jx68TtWlK8v3sFSU8,37907 +mypyc/lib-rt/__pycache__/build_setup.cpython-314.pyc,, +mypyc/lib-rt/base64/arch/avx/codec.c,sha256=urTWLTPI5DOFUKQEM1eptpEgACXA0PK9oXCNZMzd0o4,1691 +mypyc/lib-rt/base64/arch/avx/enc_loop_asm.c,sha256=5x7KgCny9gCuv0Oo50lNCo2LDt-tPOYg3t5vyTaW-kY,9314 +mypyc/lib-rt/base64/arch/avx2/codec.c,sha256=3HbccwvMmDoP_QS-B6YzXIOgY51vp7FDe9m838Kv5tk,1398 +mypyc/lib-rt/base64/arch/avx2/dec_loop.c,sha256=hq_yeFr9wrlOXrU4lPUQ--xpW1D0_m6FJkenA1Yt-fE,3229 +mypyc/lib-rt/base64/arch/avx2/dec_reshuffle.c,sha256=_qr6r3_QSicmOgl8tNMjoSX9UAR0tLY2QTk6dpwDt3Q,1304 +mypyc/lib-rt/base64/arch/avx2/enc_loop.c,sha256=-dydoBxKt1X_sTVpSYKZJlR8sfIeYLUJOzv_6HD60XM,2293 +mypyc/lib-rt/base64/arch/avx2/enc_loop_asm.c,sha256=LseS09A_syLXv0C4n5C_loPIGg3B0sjOZZ5UVZ3D-po,10453 +mypyc/lib-rt/base64/arch/avx2/enc_reshuffle.c,sha256=CWOGlvQQEsOXzCjkA5KV5EYlgAyXqyMthfD09qQbJ8w,2714 +mypyc/lib-rt/base64/arch/avx2/enc_translate.c,sha256=ZbxW4tT0V5uZEOqiium6CtRnXaYK1gd-JdG-P77RRSM,1251 +mypyc/lib-rt/base64/arch/avx512/codec.c,sha256=8244HSPoAsilcDbpbI2pvPJMuqO746VNUb5wGsAbUI8,1139 +mypyc/lib-rt/base64/arch/avx512/enc_loop.c,sha256=c264nxVYfl3m72ArgsHGol9-FQW4e4yipzTm1yoSMW8,1506 +mypyc/lib-rt/base64/arch/avx512/enc_reshuffle_translate.c,sha256=lESfOAK6yVviMyCwAQrnpWQJdxds0m109czGSbxeuRw,2277 +mypyc/lib-rt/base64/arch/generic/32/dec_loop.c,sha256=XCo00web4l5L98dDc_4ZPjdwRhwJYJJyv6zTg2ia3kM,2218 +mypyc/lib-rt/base64/arch/generic/32/enc_loop.c,sha256=8WMMHEf-xmo5f6Z7DY5JVaSvAaf80pziA9vm--GvYj0,1932 +mypyc/lib-rt/base64/arch/generic/64/enc_loop.c,sha256=6jBEKBphrKK0f3a4ZUg4pY1YXvEnVW5yvJcXtoMAOyE,2128 +mypyc/lib-rt/base64/arch/generic/codec.c,sha256=7yiK4he-nAvRAMS3RF2bkL3Q0k19OusjyAjcuLniSAM,790 +mypyc/lib-rt/base64/arch/generic/dec_head.c,sha256=XG7_4Z7O5zIWkYbyhiCuyGz8kQOT1P3hd73WJDuGSsk,791 +mypyc/lib-rt/base64/arch/generic/dec_tail.c,sha256=l4QXLn3bJYYhPJzTz2Hi1OuISw0svJAsgLkMllTCX6s,1774 +mypyc/lib-rt/base64/arch/generic/enc_head.c,sha256=gY1NrRIVDBKz1krrqbmBFQCXvW7TsISu6SP2h0Ty1W4,585 +mypyc/lib-rt/base64/arch/generic/enc_tail.c,sha256=oIaNxx1iv54RB_sjfCt9y3iwcKeYVDrXmQdj28RT6sc,637 +mypyc/lib-rt/base64/arch/neon32/codec.c,sha256=OSnQicSBOazJecWFtqLAJswxO4XFQ_6zXUEyYyDzlwo,1984 +mypyc/lib-rt/base64/arch/neon32/dec_loop.c,sha256=RP9UALT25-0h9y0ZZT-UfcUPGPnRAdrCY7DFT_qQwtY,2906 +mypyc/lib-rt/base64/arch/neon32/enc_loop.c,sha256=9OFz_fJlYxFHOEWSqftSE7D1lrK2wYXW0XswNcZ1K1U,4655 +mypyc/lib-rt/base64/arch/neon32/enc_reshuffle.c,sha256=1KiwN8mbkMlHGt1Vdh9ZqFCxmPSGbFeirZF1r_KNr6o,982 +mypyc/lib-rt/base64/arch/neon32/enc_translate.c,sha256=6p36hJofziya1lgosMW2X7Q8Hp6pU01-DJmWsj_iNQw,2116 +mypyc/lib-rt/base64/arch/neon64/codec.c,sha256=iPS0ePONE6VHjSAPcna41Dy3adhNnbp_tOhv78fJfx0,2190 +mypyc/lib-rt/base64/arch/neon64/dec_loop.c,sha256=QDwhq_CvCMo6p1JMjNW5S8-Z5woMVDxMeExeZXxO_qA,5263 +mypyc/lib-rt/base64/arch/neon64/enc_loop.c,sha256=blYyAtfGMaOj1jhqaeHbBxRvyXRbJEzXsmv2S5aIL-4,1857 +mypyc/lib-rt/base64/arch/neon64/enc_loop_asm.c,sha256=1EyqW3h__LuKAXbvQjSL7JZolvzoiEVdcgDXwDMalwU,5617 +mypyc/lib-rt/base64/arch/neon64/enc_reshuffle.c,sha256=re6811Zr3Tzd98VPMWfeTD6gi4LTznykA9QIqTxoEpc,988 +mypyc/lib-rt/base64/arch/sse41/codec.c,sha256=FZ5gJbgm_89_eK10ELRqskzCDerJDjlxoegiu2zb-kk,1456 +mypyc/lib-rt/base64/arch/sse42/codec.c,sha256=OkPETkcPsuWC3uqz3aNJ3dIrnlOSlwaucfJUe8Mkzng,1456 +mypyc/lib-rt/base64/arch/ssse3/codec.c,sha256=p6vpLANpGMSQriymltKOkGOBQwoeuCDJCpymNSs1MR8,1540 +mypyc/lib-rt/base64/arch/ssse3/dec_loop.c,sha256=ijGEu4Sqie-yqQe6SBIsJUCYht___loZE-QWh97LOJk,6891 +mypyc/lib-rt/base64/arch/ssse3/dec_reshuffle.c,sha256=1he_eNgNRnjYzq8ggN_UQhm3iu6EMrfWEILfJ_PVDII,1118 +mypyc/lib-rt/base64/arch/ssse3/enc_loop.c,sha256=j04w3bGmfUhJfG1lfa5Q7L_R2NztzS96A-r_veHeTLg,1549 +mypyc/lib-rt/base64/arch/ssse3/enc_loop_asm.c,sha256=x8xD-nt8hZbrL40GvwAZHTchbCfBENgW_sBZ_AB3New,9310 +mypyc/lib-rt/base64/arch/ssse3/enc_reshuffle.c,sha256=PmfzUCjYt32d6GfeI-Y7yhISywFON1k63kT34PqRZAI,1514 +mypyc/lib-rt/base64/arch/ssse3/enc_translate.c,sha256=MubLb6H3NQxyBjDnqFednwREHp9BSpGr_uk_riGL62k,1171 +mypyc/lib-rt/base64/codec_choose.c,sha256=bc_oLC_HVv4jNnXKuJ3clxJZHpa8uCDxR_gnri7zg3w,7590 +mypyc/lib-rt/base64/codecs.h,sha256=UJ-aFppCj4u4NoCv9WJtqeBWXYMF_JY8Jg8p1PoerUo,1188 +mypyc/lib-rt/base64/config.h,sha256=1ObCnDkVHLBW8jezBLG-VEtKuxMrnp4RmE3HxTD7Ej8,600 +mypyc/lib-rt/base64/env.h,sha256=7BFrEAjO7eymj4U3t-GHkDb3CgDlRTvFOqQLl_ERWvQ,2453 +mypyc/lib-rt/base64/lib.c,sha256=Wsr16GjZknZVF19smY382ZXxbZb94JcL28jkFB0G_Wo,3270 +mypyc/lib-rt/base64/lib_openmp.c,sha256=5UyZ_yWMjmyY3Lgr8CTAPnSNB7BgJDq-SowgsWKFaxo,4457 +mypyc/lib-rt/base64/libbase64.h,sha256=NTBKkl1S6J7OGEqOAQiHIwEuNcS9CFC8HM7t4y7YRnY,4789 +mypyc/lib-rt/base64/librt_base64.c,sha256=QNMU-YdCSPGSj99tZgm7iFhtSPil9polk5c8yfUgJKY,11681 +mypyc/lib-rt/base64/librt_base64.h,sha256=UsANYtfzM__3EwnZPaHPCCsYQ4RoZj71brWXH8tCQS8,1754 +mypyc/lib-rt/base64/tables/table_dec_32bit.h,sha256=huHBM0bQhO-qaY4VKQXZd_sPGr-hGuLoCQAsBYULbo0,25258 +mypyc/lib-rt/base64/tables/table_enc_12bit.h,sha256=d5pGp6iJjmRvuy53oS9QDQ_om9Ra4Y9BqnKTyRDA8mE,74858 +mypyc/lib-rt/base64/tables/tables.c,sha256=8EMu3og65__OzaHO_lbIk8ZMtdXyHqe4j7VpLRfPggY,2051 +mypyc/lib-rt/base64/tables/tables.h,sha256=Vnp9YLfiaFlKzM3JWSi3FJFG53rdzrMluwz1XqSRSvI,704 +mypyc/lib-rt/build_setup.py,sha256=rbgoioeFLbyK_KNuLYwwd9snN3kDDFv-Qa3QC8NzHgw,2653 +mypyc/lib-rt/bytearray_extra_ops.c,sha256=8psEK_k3gCa8MOdhYBEw9PN2AET8AiFvf9Ay9wxdOFc,122 +mypyc/lib-rt/bytearray_extra_ops.h,sha256=FaaMRumr8tfrFry10gy-4sI58KmzPYrOHAwL2D8PcJA,182 +mypyc/lib-rt/bytes_extra_ops.c,sha256=C4QRQH0hoXdwIrr5sY9CRWZmt07nTldOvXwmXNfpszg,1531 +mypyc/lib-rt/bytes_extra_ops.h,sha256=reksqOE75L9aGqtAucfUh7E2eRmxdSX_DGLlLTvCBQ4,896 +mypyc/lib-rt/bytes_ops.c,sha256=O7F_GJUvJe0MW2KSI9Ogc5YpadNzkFCP8qVdnlQsVIc,7018 +mypyc/lib-rt/byteswriter_extra_ops.c,sha256=Fgg3mVx8IbvYZKCyiAibCQkORPxh8pwtB3xtNIVN9ms,1377 +mypyc/lib-rt/byteswriter_extra_ops.h,sha256=q8SYxozwj2D83ECkiiHm7awEd2UkZqZX-lMJ58KhsDc,9460 +mypyc/lib-rt/dict_ops.c,sha256=C9xc53PPthOZzu9ZlrbHk72zLrmOt1WQe50pQUscx1g,12310 +mypyc/lib-rt/exc_ops.c,sha256=4Uw3Yf99IsGhUa7lFREBokqVUxUd49qqpIXd54DLrU0,8337 +mypyc/lib-rt/float_ops.c,sha256=MdcyrPHS44ct8ELfLnGEuUXveD7Kiy4onTYSSHwKCiU,6326 +mypyc/lib-rt/function_wrapper.c,sha256=gmi5h5HuzscLXUumCa7BlGvolbebYth3uy46AqS5QU4,8723 +mypyc/lib-rt/generic_ops.c,sha256=yTHiCG4diW9B5a407M-5wQlIEqiCFs_eKVCMavHC1Zs,2419 +mypyc/lib-rt/getargs.c,sha256=EAGGVcJKuNWvZ4r_Lfy5hUviqZKObokXADyuRR-R8lU,15769 +mypyc/lib-rt/getargsfast.c,sha256=NEVdecCZduWjuBZlQK30d4jO-_a8kxPFFmzTIIwOxrs,18808 +mypyc/lib-rt/init.c,sha256=R6y6CoucAaMijQfTftiD5cqfjJWNT-VqKsg89GM7-Ko,807 +mypyc/lib-rt/int_ops.c,sha256=ijRFnrtdhgV1czE3b8vNiAkDPbRAunQP2FUdRZMmr6k,21587 +mypyc/lib-rt/internal/librt_internal.c,sha256=VgfyevQ0a2AIVbX5pjd_YR50ySRw7FC4Poepu4mQbQU,31116 +mypyc/lib-rt/internal/librt_internal.h,sha256=3z33EzjYalaS_AURAlLcDrKJkn56nnHunGMwfcBx5CA,5202 +mypyc/lib-rt/list_ops.c,sha256=Aso05zNE2Pb1LhhZ2rJh96fncH9ov2FznugXemPKPyc,11625 +mypyc/lib-rt/misc_ops.c,sha256=-lVvAh7zgwWXlrBgAXsC95tjXvdi22k5bH5Bjg-dXRc,52384 +mypyc/lib-rt/module_shim.tmpl,sha256=HciO4-fZWZ4de_Xjb1P3n20ajJuab5tt5INgt5Pab7g,670 +mypyc/lib-rt/module_shim_no_gil_multiphase.tmpl,sha256=dEyyzaG6xmIgCOyWNX7qC4YjhgSHc_5_6yNG-WbUKUo,1205 +mypyc/lib-rt/mypyc_util.h,sha256=PN32V6x4hpip7ifMWoUc6zC0eVzcmeBuLv2Eg5KqgDc,6103 +mypyc/lib-rt/pythoncapi_compat.h,sha256=TF6SIFdR6KYE_FlWc-2JL8GcZGpsdf_LoQSEj0ua0_o,70628 +mypyc/lib-rt/pythonsupport.c,sha256=xPeVp4cOPw3zd60Gh1xLFSIb7CILMCWb8pZVtsoNa0c,5252 +mypyc/lib-rt/pythonsupport.h,sha256=Au9MSk0mfPBOkOr3hQ1kyfmmqAU2Tq45jv_SEPWVcuI,10320 +mypyc/lib-rt/set_ops.c,sha256=-fImDML6Aobq7-NCbb28O19g6C2YyHkGJ6NF1gueHJM,351 +mypyc/lib-rt/static_data.c,sha256=VFK_GRXuRIiBWO4sqcazKITjoAESHnKwhToNrFa-yqM,2651 +mypyc/lib-rt/static_data.h,sha256=ih4pBQlopFRhUdj8R8TUGAKrS7ckNNZtcX7wxa9cKw4,1569 +mypyc/lib-rt/str_extra_ops.c,sha256=CSxw5KMIPiDLWaz1Ezbr2AqNQiszTKtwHDiyO5nMXSw,147 +mypyc/lib-rt/str_extra_ops.h,sha256=lfWF7LgHyvDKlUJszbjiGPDIpEHUVWum6QFXZXyxM5k,865 +mypyc/lib-rt/str_ops.c,sha256=4eVj_n35JzuhQBx3q2gM2IcNkKOOw2YFycEmmm7VfrU,26284 +mypyc/lib-rt/strings/librt_strings.c,sha256=66K-kzGHU2zrBivNGRmeszABl4TikQ0mlsVVO1eu7-8,39842 +mypyc/lib-rt/strings/librt_strings.h,sha256=XkeeqKEWIY_WbAR6DC_7UQVqgY1jq727iLGj_v3MgQ0,4285 +mypyc/lib-rt/strings/librt_strings_common.h,sha256=Bp6pxoZlfKTOjSyQXtC6tioyQJDVdG-Z_Rfg66_jkcQ,11644 +mypyc/lib-rt/stringwriter_extra_ops.c,sha256=AcMzbrJWbGOs9-u0LFePXV0b6g4lBTTi5ukjc3uYmhg,390 +mypyc/lib-rt/stringwriter_extra_ops.h,sha256=TrpFPWYrSwG6rL2Q9UADsDF16ywrgKE0U887Utiq7eE,2200 +mypyc/lib-rt/time/librt_time.c,sha256=pCgP5XfC2JYGFfNDZLMNnhYgN4HMnJpIDwlmhDm-CFs,3843 +mypyc/lib-rt/time/librt_time.h,sha256=IlttzlxyKB4WnkyXPQky-BS4kClS83cPAKgZOLirxHs,1773 +mypyc/lib-rt/tuple_ops.c,sha256=Fe7Tj8ZVF6HTVrflq9um-rDCduF-M846sJ1TYbpX4p0,1956 +mypyc/lib-rt/vecs/librt_vecs.c,sha256=pAm4ZSRHKWx85rhH3F8JC1cGBNj6YizWXoSiQsF3Ngk,32578 +mypyc/lib-rt/vecs/librt_vecs.h,sha256=31OXD3qo8Lxy9CJROH7Fg5WO63jw3HqI1gTyioipuhc,25801 +mypyc/lib-rt/vecs/vec_bool.c,sha256=ehJc_Bqr9aPe4HTodZvLFCEjGUnh8CgF8c6Fv1AOmlo,550 +mypyc/lib-rt/vecs/vec_float.c,sha256=lsEZVaESGcqW0TdPBxm24_0h6NTMqrpZ8KCePh2QpRk,565 +mypyc/lib-rt/vecs/vec_i16.c,sha256=tUgRuDiETfx728SHvDOs_9LM3fWfhXPrvfToP4Pt2iw,540 +mypyc/lib-rt/vecs/vec_i32.c,sha256=87yOpNOs7-lWl1CKkHWTqUiMIqUGXp_3vEHBAjZt6AY,540 +mypyc/lib-rt/vecs/vec_i64.c,sha256=ycHcMxNCU-fLtyKG0yh5xkRIMVz_89rka0hK7XmEETQ,540 +mypyc/lib-rt/vecs/vec_nested.c,sha256=RyCfLHRsyW6jAb2QH1mz3EolRJmqwVfEbHxuVodmruI,15911 +mypyc/lib-rt/vecs/vec_t.c,sha256=g8Ox19H9M323Oss-KbXMvrpMvkIxwmy124IEO0Hc8qQ,14945 +mypyc/lib-rt/vecs/vec_template.c,sha256=2y-5VB5hd46tiQ2t_O_2LGlop9nbqfOWvtbAYAqY5uU,12055 +mypyc/lib-rt/vecs/vec_u8.c,sha256=OVzKEpLmEj7Nn4QVMKtbh3mPhLbUb5TB0QAGimqYa8k,527 +mypyc/lib-rt/vecs/vecs_internal.h,sha256=92eiZe_4rq00xg00kl-MDL2d4PE7oktsgL403uZCrRg,220 +mypyc/lib-rt/vecs_extra_ops.c,sha256=O0j9Lfs_7q5_S51O35Y3bx1s0dEHzzsKd6qAQoDYcGE,299 +mypyc/lib-rt/vecs_extra_ops.h,sha256=iWowopsv3jvqZNqXvnwLtvvNXyvFog5fmvHik0yawAU,323 +mypyc/lower/__init__.cp314-win_amd64.pyd,sha256=Hzcux7o3rseOFUrT2DXVmtT55hOC7rnrzn8oBhV9B3Y,10240 +mypyc/lower/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/lower/__pycache__/__init__.cpython-314.pyc,, +mypyc/lower/__pycache__/int_ops.cpython-314.pyc,, +mypyc/lower/__pycache__/list_ops.cpython-314.pyc,, +mypyc/lower/__pycache__/misc_ops.cpython-314.pyc,, +mypyc/lower/__pycache__/registry.cpython-314.pyc,, +mypyc/lower/int_ops.cp314-win_amd64.pyd,sha256=bc1lQkNlLBC-JWsENSWsYhZiCXpe_wXfWeGFoIXJr2w,10240 +mypyc/lower/int_ops.py,sha256=3YiQ1qc5cjNJwp_Xm_8tztYcBcKvxr1_1YPmCqACOnY,4777 +mypyc/lower/list_ops.cp314-win_amd64.pyd,sha256=Rfpa20NOIvALWabLmJtB2q3fNRuO_sbHqNtFuZQg8_c,10240 +mypyc/lower/list_ops.py,sha256=OZP8EEVq-IpEUm8lBnQqKNB3BvJDu3ILJtbm5_dgJyc,2522 +mypyc/lower/misc_ops.cp314-win_amd64.pyd,sha256=RxNUdhvG2DYtJHmmoUHE2G7vdALkhzIGzy0-363xjzw,10240 +mypyc/lower/misc_ops.py,sha256=Nw5HXBjMmaCePpDQ54xiN9xlr8Tl5VsXl-Yo6znAeag,920 +mypyc/lower/registry.cp314-win_amd64.pyd,sha256=D0UTjc0lIoY-REeu4LBrEp5q5kCW4gkRZE1xuKLPPx4,10240 +mypyc/lower/registry.py,sha256=wbO1g9rZ0XldFPjNTVln6gxcZbH1fMcXLX03JftNEOE,844 +mypyc/namegen.cp314-win_amd64.pyd,sha256=d_z6-zgMoIuDlxG7rrP-zc0_DsX49DJfrBBYMjzzx_0,10240 +mypyc/namegen.py,sha256=c5p7yxxUyWqJRNqKmkVCR1xW0u45LbIrqTPnR0n-I64,4934 +mypyc/options.cp314-win_amd64.pyd,sha256=4_MCkuV7UXQntPTDQxdUpRDqRmQlHiFMu30HsnxD_j0,10240 +mypyc/options.py,sha256=nK8E1Ze1C8r8a0m9349UOWWhQxGPrJXgcUJWvjSl-Rc,3890 +mypyc/primitives/__init__.cp314-win_amd64.pyd,sha256=Co8Ih2Nlg5XOHhrYdnuXgqKbDVbGijGJk72o4RZvyyI,10240 +mypyc/primitives/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/primitives/__pycache__/__init__.cpython-314.pyc,, +mypyc/primitives/__pycache__/bytearray_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/bytes_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/dict_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/exc_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/float_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/generic_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/int_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/librt_strings_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/librt_time_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/librt_vecs_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/list_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/misc_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/registry.cpython-314.pyc,, +mypyc/primitives/__pycache__/set_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/str_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/tuple_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/weakref_ops.cpython-314.pyc,, +mypyc/primitives/bytearray_ops.cp314-win_amd64.pyd,sha256=Pw6eiz2yqzjy0euNX35y7PBHjYUdsiht39O_aCAJNDM,10240 +mypyc/primitives/bytearray_ops.py,sha256=_OZZkKJzFZHHYbn2A2muMrCc3vzRvVDcMXdVfxQWvBs,1387 +mypyc/primitives/bytes_ops.cp314-win_amd64.pyd,sha256=hDrFNK7LKC3hqc7dh8SRiLVsWQRGs29hql_TgN_CPng,10240 +mypyc/primitives/bytes_ops.py,sha256=Z08QDrqLaZS8F0uFrlAOGTX3QP8widaODeB4PUnauFw,4936 +mypyc/primitives/dict_ops.cp314-win_amd64.pyd,sha256=AmlaSn-SX1KmRKvNZJ5GjEDQyMvtYaRORgzOLuY4ODw,10240 +mypyc/primitives/dict_ops.py,sha256=PWEAZVXfGavfGGGA8kyVCwkD3-vR7Qrks13NACVF4wI,8825 +mypyc/primitives/exc_ops.cp314-win_amd64.pyd,sha256=Cnps-3p65GrvpHTdocZJJDQqhtWEPz5Zqee9WYIf0Gg,10240 +mypyc/primitives/exc_ops.py,sha256=JMmg41FKPOwGFxNWwIhSFDCqwD7GaItxPmWeDajNMQE,3650 +mypyc/primitives/float_ops.cp314-win_amd64.pyd,sha256=eVOkQZPinEC-ApfCXnseHXXnaZUPDSr8hRcgbbNY7YU,10240 +mypyc/primitives/float_ops.py,sha256=uWZfhN6ixM46o-Ryu9nRSLN-zopol8cnudIrnSRRf7I,4090 +mypyc/primitives/generic_ops.cp314-win_amd64.pyd,sha256=ik1U0g2-1QPsVd9c1fTtdYg2JMNfm2a56-fnRQprRRU,10240 +mypyc/primitives/generic_ops.py,sha256=PkAUT1YlfpwbeDkMNNLTwc01eCqmLPv3-kU0ZtwwWsA,11749 +mypyc/primitives/int_ops.cp314-win_amd64.pyd,sha256=Fcbvzy_0F4qREZWunwY41bK7espxoAjNgEPOCpsck88,10240 +mypyc/primitives/int_ops.py,sha256=53jqguUtyvAECGdm45ZZw4CvbJNh9XS8SS3s34LyRoA,10566 +mypyc/primitives/librt_strings_ops.cp314-win_amd64.pyd,sha256=ZKCCfvkdH1X5URRUeOtqD7Fb6xAAiqEyabMMVPgORkA,10240 +mypyc/primitives/librt_strings_ops.py,sha256=kwQlcx84KbQ9DarEGMoZY8gziaxnwgZYnmmLGnfsrAA,12903 +mypyc/primitives/librt_time_ops.cp314-win_amd64.pyd,sha256=rxmU7UvpeIG2V-LC2qmqLEivxqKviG1IQ9TW13aGOlU,10240 +mypyc/primitives/librt_time_ops.py,sha256=sywnuBEdxQRaf7_5WKdSapQa5re7BeJlUfttxnyQL4k,405 +mypyc/primitives/librt_vecs_ops.cp314-win_amd64.pyd,sha256=aIDpCyQqvlhk8Bxr_A91qa1GZNnSOVIuJy46-Cg7f90,10240 +mypyc/primitives/librt_vecs_ops.py,sha256=n67p6dP3ct6iovw-VFG2RMnbsBFCMp7MQ9h2K1OoA6c,487 +mypyc/primitives/list_ops.cp314-win_amd64.pyd,sha256=gii7FxxFu6LbuHp9_kygRuTmLsylMm6nouc9lT0zkYE,10240 +mypyc/primitives/list_ops.py,sha256=auDy4fR5yf-wGRpho0elbaZ5WPQMe9S-s6sxRcM3XVs,9121 +mypyc/primitives/misc_ops.cp314-win_amd64.pyd,sha256=Mm9JnEUoarI_B-1z76hOCDlg8C9DyeBlL3st6ch67tM,10240 +mypyc/primitives/misc_ops.py,sha256=Y3vXitX4T4e77X3pOoSueWJ6F6BjEk6x7S4s3IB3tqo,17949 +mypyc/primitives/registry.cp314-win_amd64.pyd,sha256=VdmF1MmHIlgR6PNc9B3Xaz21GOmt1wPnxiyNfCf5Huc,10240 +mypyc/primitives/registry.py,sha256=VkAhMsGIDbq8K_9Sf_PRh9prLlIW2BmeCIKBIoXT4KA,13239 +mypyc/primitives/set_ops.cp314-win_amd64.pyd,sha256=6zyB01NVtHwpPicdgGJrtJ3NIfkMSvjpFls2cL-kM-s,10240 +mypyc/primitives/set_ops.py,sha256=dgy_6M2ZuQglEYlf-AX1YNQPgaYK9uKQ9Vr3svMf768,3795 +mypyc/primitives/str_ops.cp314-win_amd64.pyd,sha256=O9iocu7MMIvBthwCPgZSr1yW3q7nrBN0EzVAVkw-yss,10240 +mypyc/primitives/str_ops.py,sha256=vDI3h9OB7KQZ0mNOSt1oFhRx-T7fqxwYZwTlS2RY6II,15715 +mypyc/primitives/tuple_ops.cp314-win_amd64.pyd,sha256=XBFt7sKWw1dIJVkBv2QcZFvbOcBpttmLYhAjvLpDe0M,10240 +mypyc/primitives/tuple_ops.py,sha256=PeDVdwZkvOxvnnOP_iUi4c-rzPiF4LqaUqv5yu98-lQ,3752 +mypyc/primitives/weakref_ops.cp314-win_amd64.pyd,sha256=gvWt6oWDxoxuSvzgW6J0Sn0AzcHrfZezBGCSAYmIuLE,10240 +mypyc/primitives/weakref_ops.py,sha256=jfh4j2yO5OAFKXsSQeJKPIKWl3j3mYnyDpjwgj9mUHI,1160 +mypyc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/rt_subtype.cp314-win_amd64.pyd,sha256=MSc0Vq6iRktK3X-w3_P7EQjpfe7V6khptCu7hC_xyi0,10240 +mypyc/rt_subtype.py,sha256=G1fE7PptSRl4z3AoifqNmmVCKthir2z3dw4EtDy1SVw,2743 +mypyc/sametype.cp314-win_amd64.pyd,sha256=nEwG0XElHkMUKzK-ny0hEPEDMWS0UQuyBSN1XOsSWzU,10240 +mypyc/sametype.py,sha256=CpcY2ck5NYPOM6pjyg73LxrgWOcYqgIRiLP0W78efpM,2608 +mypyc/subtype.cp314-win_amd64.pyd,sha256=0dUXjD1r-_KZbcUv5_3yMtVa0FHhU1zfLdiA1q3IUzU,10240 +mypyc/subtype.py,sha256=Aa_w1kbRWYCb8rxUwwVfWp7UCs40uMNpWliDUsD_frY,3354 +mypyc/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/test/__pycache__/__init__.cpython-314.pyc,, +mypyc/test/__pycache__/config.cpython-314.pyc,, +mypyc/test/__pycache__/librt_cache.cpython-314.pyc,, +mypyc/test/__pycache__/test_alwaysdefined.cpython-314.pyc,, +mypyc/test/__pycache__/test_analysis.cpython-314.pyc,, +mypyc/test/__pycache__/test_annotate.cpython-314.pyc,, +mypyc/test/__pycache__/test_capsule_deps.cpython-314.pyc,, +mypyc/test/__pycache__/test_cheader.cpython-314.pyc,, +mypyc/test/__pycache__/test_commandline.cpython-314.pyc,, +mypyc/test/__pycache__/test_emit.cpython-314.pyc,, +mypyc/test/__pycache__/test_emitclass.cpython-314.pyc,, +mypyc/test/__pycache__/test_emitfunc.cpython-314.pyc,, +mypyc/test/__pycache__/test_emitwrapper.cpython-314.pyc,, +mypyc/test/__pycache__/test_exceptions.cpython-314.pyc,, +mypyc/test/__pycache__/test_external.cpython-314.pyc,, +mypyc/test/__pycache__/test_irbuild.cpython-314.pyc,, +mypyc/test/__pycache__/test_ircheck.cpython-314.pyc,, +mypyc/test/__pycache__/test_literals.cpython-314.pyc,, +mypyc/test/__pycache__/test_lowering.cpython-314.pyc,, +mypyc/test/__pycache__/test_misc.cpython-314.pyc,, +mypyc/test/__pycache__/test_namegen.cpython-314.pyc,, +mypyc/test/__pycache__/test_optimizations.cpython-314.pyc,, +mypyc/test/__pycache__/test_pprint.cpython-314.pyc,, +mypyc/test/__pycache__/test_rarray.cpython-314.pyc,, +mypyc/test/__pycache__/test_refcount.cpython-314.pyc,, +mypyc/test/__pycache__/test_run.cpython-314.pyc,, +mypyc/test/__pycache__/test_serialization.cpython-314.pyc,, +mypyc/test/__pycache__/test_statement.cpython-314.pyc,, +mypyc/test/__pycache__/test_struct.cpython-314.pyc,, +mypyc/test/__pycache__/test_tuplename.cpython-314.pyc,, +mypyc/test/__pycache__/test_typeops.cpython-314.pyc,, +mypyc/test/__pycache__/testutil.cpython-314.pyc,, +mypyc/test/config.py,sha256=ZnruYrojiT_ZG4RrYzoESoNTiZY1bWuk0SQ2CFZHTQA,406 +mypyc/test/librt_cache.py,sha256=nvsUhe0_g5zZowzv7ELrIQH3oto1Z4SE6KRZsdDdThM,8596 +mypyc/test/test_alwaysdefined.py,sha256=NtJx8cYeU9wblyglViCc1Ww0yRyoEhElW1HV9-7i_ok,1528 +mypyc/test/test_analysis.py,sha256=8TetLNYto3iO3KCjEhYKOMvPkOc6Hr5tVbEqdo8G8zk,3265 +mypyc/test/test_annotate.py,sha256=WgWtYrPHQHu8PVhbHkk4GuG9Xf_r63Vu5adBkkzRPfo,2600 +mypyc/test/test_capsule_deps.py,sha256=FWkA3NPXT8xrJil8hZQgXzgQVqsWgfaAwfbuDZMarSs,2002 +mypyc/test/test_cheader.py,sha256=65ScI-JGu_v6HlKZsFbesJYmW4Wh3p1ltfp_zmteEi4,2974 +mypyc/test/test_commandline.py,sha256=ULYaN9gmgBXwnGUVYIui_x8Ybny3Wy5KKHpuJaeXxFs,2823 +mypyc/test/test_emit.py,sha256=XHCqiTDTt3KTQiSLMdF8DtjDo_7CLQodwOHlN5GhZvo,6519 +mypyc/test/test_emitclass.py,sha256=DE9sG9K-05LjbDvT6CWidDJB-onab7O0t8l2GVhjYlM,1228 +mypyc/test/test_emitfunc.py,sha256=35g_frZXo6Ps7oQqRiUTj2qTzbC0dm2hlRoMPaVQf-Q,39997 +mypyc/test/test_emitwrapper.py,sha256=C2cI4tJlpv-S4XOE1NIGG5-hUsm0YLVngNBzIN9yZL8,2219 +mypyc/test/test_exceptions.py,sha256=xKKMry9EcV6Msjnv3x_BIaXOoD1Y0VCZFqHKtCHxXcY,2145 +mypyc/test/test_external.py,sha256=KcgwW_a7L8btyPmo88YaFNQ8v_ODcpr4OtiS2aLaleA,4029 +mypyc/test/test_irbuild.py,sha256=wUI10odXsb-6HFxyUNG1XOphRQehtr5xUPrxiucq8Vo,3074 +mypyc/test/test_ircheck.py,sha256=OS5yZipy-bOCW9zCePk-b8x-xn2eK5yle_aoH6CrSiI,6891 +mypyc/test/test_literals.py,sha256=VospqX81-sNRhInwnnwC81Kzk9z1hr7UsnIDjC1NXhs,3325 +mypyc/test/test_lowering.py,sha256=8jllO0-mIwbdcJXxFgpj4XUsy8XiZgfeYJddkya5f5U,2473 +mypyc/test/test_misc.py,sha256=ncl-npJh2z8deAaNK30lq7LH3R7FCabiEhD_VwClwfI,740 +mypyc/test/test_namegen.py,sha256=GZaE_OGUApOf-RzJKe-5XlVHL5-rwoINEhPotCuwx5Q,2720 +mypyc/test/test_optimizations.py,sha256=lutkoLAqF3K_prJoXByFGHVykB8VhY1SQcyiYRuXmgg,2318 +mypyc/test/test_pprint.py,sha256=6kfSLDyEvNXPGmdbvDojM4wEdWFoi-6Oh23AHOjx-v4,1281 +mypyc/test/test_rarray.py,sha256=eVIfBeR2t6F-16QXznpycEN5DkRGYAvR-hNbkIkaRPw,1488 +mypyc/test/test_refcount.py,sha256=PSfI4Nsetl6O5uw9JnjAfyHMDcD9U3qtLnsoHJgrnZY,2058 +mypyc/test/test_run.py,sha256=qhaPJu7Jq_NXCqdjZcfWeWKaG3uJFBDEEPYtqqXRPVg,19669 +mypyc/test/test_serialization.py,sha256=DEEW4smq3Exp_4yJnfldsFcGEWmVq-uGH3oCEOx0GU0,3881 +mypyc/test/test_statement.py,sha256=27jPSZCbXVWLZKv7WwrPpaqTkDhF2bR7potVW7vrT2M,5515 +mypyc/test/test_struct.py,sha256=EEfu868uSm1wJmwowq1S_g1wInUaURX8tIhoPqGzs8w,3903 +mypyc/test/test_tuplename.py,sha256=P03_NcIw1n-g4vFOig_aKX5RgLqoBkO3xh7M2Zzerkg,1044 +mypyc/test/test_typeops.py,sha256=FQvUfsjTKL_eIPbBxcchG6zrsVJvgWpb5U316NrvFCw,3935 +mypyc/test/testutil.py,sha256=1PAHAhDQYg9npFSxLHRcbsB1zJembWsDwRdXfwZDrLQ,10252 +mypyc/transform/__init__.cp314-win_amd64.pyd,sha256=NtvJjilP3-CJTG9J3drcdBLtaSOQ3bjSSpH-ogC47rE,10240 +mypyc/transform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/transform/__pycache__/__init__.cpython-314.pyc,, +mypyc/transform/__pycache__/copy_propagation.cpython-314.pyc,, +mypyc/transform/__pycache__/exceptions.cpython-314.pyc,, +mypyc/transform/__pycache__/flag_elimination.cpython-314.pyc,, +mypyc/transform/__pycache__/ir_transform.cpython-314.pyc,, +mypyc/transform/__pycache__/log_trace.cpython-314.pyc,, +mypyc/transform/__pycache__/lower.cpython-314.pyc,, +mypyc/transform/__pycache__/refcount.cpython-314.pyc,, +mypyc/transform/__pycache__/spill.cpython-314.pyc,, +mypyc/transform/__pycache__/uninit.cpython-314.pyc,, +mypyc/transform/copy_propagation.cp314-win_amd64.pyd,sha256=HdbnJ71DwETSSzoRtuus2p4xNMQB8AJsTGXQcw7wdC0,10240 +mypyc/transform/copy_propagation.py,sha256=JrbL3Y-qPlcSGyWI2_jBO-UezHDrMf2pIII9wRu6fJI,3435 +mypyc/transform/exceptions.cp314-win_amd64.pyd,sha256=S3GRI6umtTitXw1RXoFuVsgIFm9xAz41MSk-nDRNJHk,10240 +mypyc/transform/exceptions.py,sha256=-62uaOPEZBlXbtJNVxI_bnRY3G9HmhR5Rjlx52XT3Wo,6797 +mypyc/transform/flag_elimination.cp314-win_amd64.pyd,sha256=oYicPSvvCrxUpnGDSCOvbOFYy-O7a9rj2N3wjFvLknM,10240 +mypyc/transform/flag_elimination.py,sha256=84M5VUt57iEj-yJR02XVeJsV-nviYO5YoqiDuOK0kxI,3531 +mypyc/transform/ir_transform.cp314-win_amd64.pyd,sha256=ZO0mi4dgJuz6L7WUD8JpgfQtuOtzkaQJATRTunEtWoY,10240 +mypyc/transform/ir_transform.py,sha256=WXHXZgKacp3ujajD0jlgps-WeVG36fEeY5O9gFVjKUU,11693 +mypyc/transform/log_trace.cp314-win_amd64.pyd,sha256=dxH6Dkt9Pdw0Du0FuX3bXcMjJoYlCrZ0AwgqG0LccCY,10240 +mypyc/transform/log_trace.py,sha256=_vLi9moWRpRqi5w85dLZt7Olg0n0HCPwh_NJMu0gX_E,5374 +mypyc/transform/lower.cp314-win_amd64.pyd,sha256=9DyJbWRJNUREmr--4BhMq06lg7TUJ53zAhlSvnfybEI,10240 +mypyc/transform/lower.py,sha256=LfFFCqN5_XoISoHoAHDggVTo9E45eeBiRnIQzJWWHAg,1344 +mypyc/transform/refcount.cp314-win_amd64.pyd,sha256=V1mGQBokl4SQ3wlPI7qJvTtjESSCGOW56WQp0mvCS0c,10240 +mypyc/transform/refcount.py,sha256=iW00ioXptnZe_CK9yBXe1dIajeHqweo3LNlKqHVMobQ,10109 +mypyc/transform/spill.cp314-win_amd64.pyd,sha256=8I7qyADwHo1IvHeQ-KhmELh05Fzlzr9h0ETTmoP7ij4,10240 +mypyc/transform/spill.py,sha256=dO7W2tChyzpb3E_Ut4RD510SIrvAu-mVM45_kR13JLk,4185 +mypyc/transform/uninit.cp314-win_amd64.pyd,sha256=iS8XT8wgsGNMJXboHcPAidaqj4vFBK0egc_ZhewKsBo,10240 +mypyc/transform/uninit.py,sha256=oY72iJXKDkWwYT4NsEHMZH_u1TpcFKp2EhsmkTwFje0,7307 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/REQUESTED b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/WHEEL b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..a2596f35678bd8c16829de6f09aac682f013ad1f --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp314-cp314-win_amd64 + diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/direct_url.json b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..b0b565014f974fc49d412aced7f2288e3f8544fe --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///D:/bld/mypy-split_1776801208905/work"} \ No newline at end of file diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/entry_points.txt b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..0ece8370b20afd5c124c69bf2a956da90f7e4573 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/entry_points.txt @@ -0,0 +1,6 @@ +[console_scripts] +dmypy = mypy.dmypy.client:console_entry +mypy = mypy.__main__:console_entry +mypyc = mypyc.__main__:main +stubgen = mypy.stubgen:main +stubtest = mypy.stubtest:main diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/top_level.txt b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..50589689b1823f95fe723f5b4f9c53de79063c03 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy-1.20.2.dist-info/top_level.txt @@ -0,0 +1,3 @@ +0aca9ce3d91742c5b361__mypyc +mypy +mypyc diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0f6dd08aefafcc9a9bd989c681c9e779ad135b2c Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4000266849d05c68ee9559bbe1126a8493c4f9 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.py @@ -0,0 +1 @@ +# This page intentionally left blank diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__main__.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4d61f44658cc78424c440efb5e03a600e1aa08 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__main__.py @@ -0,0 +1,50 @@ +"""Mypy type checker command line tool.""" + +from __future__ import annotations + +import os +import sys +import traceback + +from mypy.main import main, process_options +from mypy.util import FancyFormatter + + +def console_entry() -> None: + try: + main() + sys.stdout.flush() + sys.stderr.flush() + except BrokenPipeError: + # Python flushes standard streams on exit; redirect remaining output + # to devnull to avoid another BrokenPipeError at shutdown + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, sys.stdout.fileno()) + sys.exit(2) + except KeyboardInterrupt: + _, options = process_options(args=sys.argv[1:]) + if options.show_traceback: + sys.stdout.write(traceback.format_exc()) + formatter = FancyFormatter(sys.stdout, sys.stderr, False) + msg = "Interrupted\n" + sys.stdout.write(formatter.style(msg, color="red", bold=True)) + sys.stdout.flush() + sys.stderr.flush() + sys.exit(2) + except Exception as e: + # Try reporting any uncaught error canonically, otherwise just flush the traceback. + try: + import mypy.errors + + _, options = process_options(args=sys.argv[1:]) + mypy.errors.report_internal_error(e, None, 0, None, options) + except Exception: + pass + sys.stdout.write(traceback.format_exc()) + sys.stdout.flush() + sys.stderr.flush() + sys.exit(2) + + +if __name__ == "__main__": + console_entry() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..7034aed0466621cbbd45f79e6410deb6fe380eb7 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.py new file mode 100644 index 0000000000000000000000000000000000000000..90ef985491da5350bad0735c6807836c29edc410 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.py @@ -0,0 +1,95 @@ +"""This module makes it possible to use mypy as part of a Python application. + +Since mypy still changes, the API was kept utterly simple and non-intrusive. +It just mimics command line activation without starting a new interpreter. +So the normal docs about the mypy command line apply. +Changes in the command line version of mypy will be immediately usable. + +Just import this module and then call the 'run' function with a parameter of +type List[str], containing what normally would have been the command line +arguments to mypy. + +Function 'run' returns a Tuple[str, str, int], namely +(, , ), +in which is what mypy normally writes to sys.stdout, + is what mypy normally writes to sys.stderr and exit_status is +the exit status mypy normally returns to the operating system. + +Any pretty formatting is left to the caller. + +The 'run_dmypy' function is similar, but instead mimics invocation of +dmypy. Note that run_dmypy is not thread-safe and modifies sys.stdout +and sys.stderr during its invocation. + +Note that these APIs don't support incremental generation of error +messages. + +Trivial example of code using this module: + +import sys +from mypy import api + +result = api.run(sys.argv[1:]) + +if result[0]: + print('\nType checking report:\n') + print(result[0]) # stdout + +if result[1]: + print('\nError report:\n') + print(result[1]) # stderr + +print('\nExit status:', result[2]) + +""" + +from __future__ import annotations + +import sys +from collections.abc import Callable +from io import StringIO +from typing import TextIO + + +def _run(main_wrapper: Callable[[TextIO, TextIO], None]) -> tuple[str, str, int]: + stdout = StringIO() + stderr = StringIO() + + try: + main_wrapper(stdout, stderr) + exit_status = 0 + except SystemExit as system_exit: + assert isinstance(system_exit.code, int) + exit_status = system_exit.code + + return stdout.getvalue(), stderr.getvalue(), exit_status + + +def run(args: list[str]) -> tuple[str, str, int]: + # Lazy import to avoid needing to import all of mypy to call run_dmypy + from mypy.main import main + + return _run( + lambda stdout, stderr: main(args=args, stdout=stdout, stderr=stderr, clean_exit=True) + ) + + +def run_dmypy(args: list[str]) -> tuple[str, str, int]: + from mypy.dmypy.client import main + + # A bunch of effort has been put into threading stdout and stderr + # through the main API to avoid the threadsafety problems of + # modifying sys.stdout/sys.stderr, but that hasn't been done for + # the dmypy client, so we just do the non-threadsafe thing. + def f(stdout: TextIO, stderr: TextIO) -> None: + old_stdout = sys.stdout + old_stderr = sys.stderr + try: + sys.stdout = stdout + sys.stderr = stderr + main(args) + finally: + sys.stdout = old_stdout + sys.stderr = old_stderr + + return _run(f) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..6791199321fe0e7469ab17f6f3a1984843ff8ccc Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.py new file mode 100644 index 0000000000000000000000000000000000000000..c8003795ba0b1fd0197406cb7d72591e59cb3236 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.py @@ -0,0 +1,303 @@ +from __future__ import annotations + +from collections.abc import Callable, Iterable, Sequence + +import mypy.subtypes +from mypy.erasetype import erase_typevars +from mypy.expandtype import expand_type +from mypy.nodes import Context, TypeInfo +from mypy.type_visitor import TypeTranslator +from mypy.typeops import get_all_type_vars +from mypy.types import ( + AnyType, + CallableType, + Instance, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PartialType, + ProperType, + Type, + TypeAliasType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UninhabitedType, + UnpackType, + get_proper_type, + remove_dups, +) + + +def get_target_type( + tvar: TypeVarLikeType, + type: Type, + callable: CallableType, + report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None], + context: Context, + skip_unsatisfied: bool, +) -> Type | None: + p_type = get_proper_type(type) + if isinstance(p_type, UninhabitedType) and tvar.has_default(): + return tvar.default + if isinstance(tvar, ParamSpecType): + return type + if isinstance(tvar, TypeVarTupleType): + return type + assert isinstance(tvar, TypeVarType) + values = tvar.values + if values: + if isinstance(p_type, AnyType): + return type + if isinstance(p_type, TypeVarType) and p_type.values: + # Allow substituting T1 for T if every allowed value of T1 + # is also a legal value of T. + if all(any(mypy.subtypes.is_same_type(v, v1) for v in values) for v1 in p_type.values): + return type + matching = [] + for value in values: + if mypy.subtypes.is_subtype(type, value): + matching.append(value) + if matching: + best = matching[0] + # If there are more than one matching value, we select the narrowest + for match in matching[1:]: + if mypy.subtypes.is_subtype(match, best): + best = match + return best + if skip_unsatisfied: + return None + report_incompatible_typevar_value(callable, type, tvar.name, context) + else: + upper_bound = tvar.upper_bound + if tvar.name == "Self": + # Internally constructed Self-types contain class type variables in upper bound, + # so we need to erase them to avoid false positives. This is safe because we do + # not support type variables in upper bounds of user defined types. + upper_bound = erase_typevars(upper_bound) + if not mypy.subtypes.is_subtype(type, upper_bound): + if skip_unsatisfied: + return None + report_incompatible_typevar_value(callable, type, tvar.name, context) + return type + + +def apply_generic_arguments( + callable: CallableType, + orig_types: Sequence[Type | None], + report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None], + context: Context, + skip_unsatisfied: bool = False, +) -> CallableType: + """Apply generic type arguments to a callable type. + + For example, applying [int] to 'def [T] (T) -> T' results in + 'def (int) -> int'. + + Note that each type can be None; in this case, it will not be applied. + + If `skip_unsatisfied` is True, then just skip the types that don't satisfy type variable + bound or constraints, instead of giving an error. + """ + tvars = callable.variables + assert len(orig_types) <= len(tvars) + # Check that inferred type variable values are compatible with allowed + # values and bounds. Also, promote subtype values to allowed values. + # Create a map from type variable id to target type. + id_to_type: dict[TypeVarId, Type] = {} + + for tvar, type in zip(tvars, orig_types): + assert not isinstance(type, PartialType), "Internal error: must never apply partial type" + if type is None: + continue + + target_type = get_target_type( + tvar, type, callable, report_incompatible_typevar_value, context, skip_unsatisfied + ) + if target_type is not None: + id_to_type[tvar.id] = target_type + + # TODO: validate arg_kinds/arg_names for ParamSpec and TypeVarTuple replacements, + # not just type variable bounds above. + param_spec = callable.param_spec() + if param_spec is not None: + nt = id_to_type.get(param_spec.id) + if nt is not None: + # ParamSpec expansion is special-cased, so we need to always expand callable + # as a whole, not expanding arguments individually. + callable = expand_type(callable, id_to_type) + assert isinstance(callable, CallableType) + return callable.copy_modified( + variables=[tv for tv in tvars if tv.id not in id_to_type] + ) + + # Apply arguments to argument types. + var_arg = callable.var_arg() + if var_arg is not None and isinstance(var_arg.typ, UnpackType): + # Same as for ParamSpec, callable with variadic types needs to be expanded as a whole. + callable = expand_type(callable, id_to_type) + assert isinstance(callable, CallableType) + return callable.copy_modified(variables=[tv for tv in tvars if tv.id not in id_to_type]) + else: + callable = callable.copy_modified( + arg_types=[expand_type(at, id_to_type) for at in callable.arg_types] + ) + + # Apply arguments to TypeGuard and TypeIs if any. + if callable.type_guard is not None: + type_guard = expand_type(callable.type_guard, id_to_type) + else: + type_guard = None + if callable.type_is is not None: + type_is = expand_type(callable.type_is, id_to_type) + else: + type_is = None + + # The callable may retain some type vars if only some were applied. + # TODO: move apply_poly() logic here when new inference + # becomes universally used (i.e. in all passes + in unification). + # With this new logic we can actually *add* some new free variables. + remaining_tvars: list[TypeVarLikeType] = [] + for tv in tvars: + if tv.id in id_to_type: + continue + if not tv.has_default(): + remaining_tvars.append(tv) + continue + # TypeVarLike isn't in id_to_type mapping. + # Only expand the TypeVar default here. + typ = expand_type(tv, id_to_type) + assert isinstance(typ, TypeVarLikeType) + remaining_tvars.append(typ) + + return callable.copy_modified( + ret_type=expand_type(callable.ret_type, id_to_type), + variables=remaining_tvars, + type_guard=type_guard, + type_is=type_is, + ) + + +def apply_poly(tp: CallableType, poly_tvars: Sequence[TypeVarLikeType]) -> CallableType | None: + """Make free type variables generic in the type if possible. + + This will translate the type `tp` while trying to create valid bindings for + type variables `poly_tvars` while traversing the type. This follows the same rules + as we do during semantic analysis phase, examples: + * Callable[Callable[[T], T], T] -> def [T] (def (T) -> T) -> T + * Callable[[], Callable[[T], T]] -> def () -> def [T] (T -> T) + * List[T] -> None (not possible) + """ + try: + return tp.copy_modified( + arg_types=[t.accept(PolyTranslator(poly_tvars)) for t in tp.arg_types], + ret_type=tp.ret_type.accept(PolyTranslator(poly_tvars)), + variables=[], + ) + except PolyTranslationError: + return None + + +class PolyTranslationError(Exception): + pass + + +class PolyTranslator(TypeTranslator): + """Make free type variables generic in the type if possible. + + See docstring for apply_poly() for details. + """ + + def __init__( + self, + poly_tvars: Iterable[TypeVarLikeType], + bound_tvars: frozenset[TypeVarLikeType] = frozenset(), + seen_aliases: frozenset[TypeInfo] = frozenset(), + ) -> None: + super().__init__() + self.poly_tvars = set(poly_tvars) + # This is a simplified version of TypeVarScope used during semantic analysis. + self.bound_tvars = bound_tvars + self.seen_aliases = seen_aliases + + def collect_vars(self, t: CallableType | Parameters) -> list[TypeVarLikeType]: + found_vars = [] + for arg in t.arg_types: + for tv in get_all_type_vars(arg): + if isinstance(tv, ParamSpecType): + normalized: TypeVarLikeType = tv.copy_modified( + flavor=ParamSpecFlavor.BARE, prefix=Parameters([], [], []) + ) + else: + normalized = tv + if normalized in self.poly_tvars and normalized not in self.bound_tvars: + found_vars.append(normalized) + return remove_dups(found_vars) + + def visit_callable_type(self, t: CallableType) -> Type: + found_vars = self.collect_vars(t) + self.bound_tvars |= set(found_vars) + result = super().visit_callable_type(t) + self.bound_tvars -= set(found_vars) + + assert isinstance(result, ProperType) and isinstance(result, CallableType) + result.variables = result.variables + tuple(found_vars) + return result + + def visit_type_var(self, t: TypeVarType) -> Type: + if t in self.poly_tvars and t not in self.bound_tvars: + raise PolyTranslationError() + return super().visit_type_var(t) + + def visit_param_spec(self, t: ParamSpecType) -> Type: + if t in self.poly_tvars and t not in self.bound_tvars: + raise PolyTranslationError() + return super().visit_param_spec(t) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + if t in self.poly_tvars and t not in self.bound_tvars: + raise PolyTranslationError() + return super().visit_type_var_tuple(t) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + if not t.args: + return t.copy_modified() + if not t.is_recursive: + return get_proper_type(t).accept(self) + # We can't handle polymorphic application for recursive generic aliases + # without risking an infinite recursion, just give up for now. + raise PolyTranslationError() + + def visit_instance(self, t: Instance) -> Type: + if t.type.has_param_spec_type: + # We need this special-casing to preserve the possibility to store a + # generic function in an instance type. Things like + # forall T . Foo[[x: T], T] + # are not really expressible in current type system, but this looks like + # a useful feature, so let's keep it. + param_spec_index = next( + i for (i, tv) in enumerate(t.type.defn.type_vars) if isinstance(tv, ParamSpecType) + ) + p = get_proper_type(t.args[param_spec_index]) + if isinstance(p, Parameters): + found_vars = self.collect_vars(p) + self.bound_tvars |= set(found_vars) + new_args = [a.accept(self) for a in t.args] + self.bound_tvars -= set(found_vars) + + repl = new_args[param_spec_index] + assert isinstance(repl, ProperType) and isinstance(repl, Parameters) + repl.variables = list(repl.variables) + list(found_vars) + return t.copy_modified(args=new_args) + # There is the same problem with callback protocols as with aliases + # (callback protocols are essentially more flexible aliases to callables). + if t.args and t.type.is_protocol and t.type.protocol_members == ["__call__"]: + if t.type in self.seen_aliases: + raise PolyTranslationError() + call = mypy.subtypes.find_member("__call__", t, t, is_operator=True) + assert call is not None + return call.accept( + PolyTranslator(self.poly_tvars, self.bound_tvars, self.seen_aliases | {t.type}) + ) + return super().visit_instance(t) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..7b3448b6ecb62ada60d93968efb688e0b8c6dcb3 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.py new file mode 100644 index 0000000000000000000000000000000000000000..c30f6bd43f13fce35148c320fba0ca6f040ba4d1 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.py @@ -0,0 +1,269 @@ +"""Utilities for mapping between actual and formal arguments (and their types).""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING + +from mypy import nodes +from mypy.maptype import map_instance_to_supertype +from mypy.types import ( + AnyType, + Instance, + ParamSpecType, + TupleType, + Type, + TypedDictType, + TypeOfAny, + TypeVarTupleType, + UnpackType, + get_proper_type, +) + +if TYPE_CHECKING: + from mypy.infer import ArgumentInferContext + + +def map_actuals_to_formals( + actual_kinds: list[nodes.ArgKind], + actual_names: Sequence[str | None] | None, + formal_kinds: list[nodes.ArgKind], + formal_names: Sequence[str | None], + actual_arg_type: Callable[[int], Type], +) -> list[list[int]]: + """Calculate mapping between actual (caller) args and formals. + + The result contains a list of caller argument indexes mapping to each + callee argument index, indexed by callee index. + + The actual_arg_type argument should evaluate to the type of the actual + argument with the given index. + """ + nformals = len(formal_kinds) + formal_to_actual: list[list[int]] = [[] for i in range(nformals)] + ambiguous_actual_kwargs: list[int] = [] + fi = 0 + for ai, actual_kind in enumerate(actual_kinds): + if actual_kind == nodes.ARG_POS: + if fi < nformals: + if not formal_kinds[fi].is_star(): + formal_to_actual[fi].append(ai) + fi += 1 + elif formal_kinds[fi] == nodes.ARG_STAR: + formal_to_actual[fi].append(ai) + elif actual_kind == nodes.ARG_STAR: + # We need to know the actual type to map varargs. + actualt = get_proper_type(actual_arg_type(ai)) + if isinstance(actualt, TupleType): + # A tuple actual maps to a fixed number of formals. + for _ in range(len(actualt.items)): + if fi < nformals: + if formal_kinds[fi] != nodes.ARG_STAR2: + formal_to_actual[fi].append(ai) + else: + break + if formal_kinds[fi] != nodes.ARG_STAR: + fi += 1 + else: + # Assume that it is an iterable (if it isn't, there will be + # an error later). + while fi < nformals: + if formal_kinds[fi].is_named(star=True): + break + else: + formal_to_actual[fi].append(ai) + if formal_kinds[fi] == nodes.ARG_STAR: + break + fi += 1 + elif actual_kind.is_named(): + assert actual_names is not None, "Internal error: named kinds without names given" + name = actual_names[ai] + if name in formal_names and formal_kinds[formal_names.index(name)] != nodes.ARG_STAR: + formal_to_actual[formal_names.index(name)].append(ai) + elif nodes.ARG_STAR2 in formal_kinds: + formal_to_actual[formal_kinds.index(nodes.ARG_STAR2)].append(ai) + else: + assert actual_kind == nodes.ARG_STAR2 + actualt = get_proper_type(actual_arg_type(ai)) + if isinstance(actualt, TypedDictType): + for name in actualt.items: + if name in formal_names: + formal_to_actual[formal_names.index(name)].append(ai) + elif nodes.ARG_STAR2 in formal_kinds: + formal_to_actual[formal_kinds.index(nodes.ARG_STAR2)].append(ai) + else: + # We don't exactly know which **kwargs are provided by the + # caller, so we'll defer until all the other unambiguous + # actuals have been processed + ambiguous_actual_kwargs.append(ai) + + if ambiguous_actual_kwargs: + # Assume the ambiguous kwargs will fill the remaining arguments. + # + # TODO: If there are also tuple varargs, we might be missing some potential + # matches if the tuple was short enough to not match everything. + unmatched_formals = [ + fi + for fi in range(nformals) + if ( + formal_names[fi] + and ( + not formal_to_actual[fi] + or actual_kinds[formal_to_actual[fi][0]] == nodes.ARG_STAR + ) + and formal_kinds[fi] != nodes.ARG_STAR + ) + or formal_kinds[fi] == nodes.ARG_STAR2 + ] + for ai in ambiguous_actual_kwargs: + for fi in unmatched_formals: + formal_to_actual[fi].append(ai) + + return formal_to_actual + + +def map_formals_to_actuals( + actual_kinds: list[nodes.ArgKind], + actual_names: Sequence[str | None] | None, + formal_kinds: list[nodes.ArgKind], + formal_names: list[str | None], + actual_arg_type: Callable[[int], Type], +) -> list[list[int]]: + """Calculate the reverse mapping of map_actuals_to_formals.""" + formal_to_actual = map_actuals_to_formals( + actual_kinds, actual_names, formal_kinds, formal_names, actual_arg_type + ) + # Now reverse the mapping. + actual_to_formal: list[list[int]] = [[] for _ in actual_kinds] + for formal, actuals in enumerate(formal_to_actual): + for actual in actuals: + actual_to_formal[actual].append(formal) + return actual_to_formal + + +class ArgTypeExpander: + """Utility class for mapping actual argument types to formal arguments. + + One of the main responsibilities is to expand caller tuple *args and TypedDict + **kwargs, and to keep track of which tuple/TypedDict items have already been + consumed. + + Example: + + def f(x: int, *args: str) -> None: ... + f(*(1, 'x', 1.1)) + + We'd call expand_actual_type three times: + + 1. The first call would provide 'int' as the actual type of 'x' (from '1'). + 2. The second call would provide 'str' as one of the actual types for '*args'. + 2. The third call would provide 'float' as one of the actual types for '*args'. + + A single instance can process all the arguments for a single call. Each call + needs a separate instance since instances have per-call state. + """ + + def __init__(self, context: ArgumentInferContext) -> None: + # Next tuple *args index to use. + self.tuple_index = 0 + # Keyword arguments in TypedDict **kwargs used. + self.kwargs_used: set[str] | None = None + # Type context for `*` and `**` arg kinds. + self.context = context + + def expand_actual_type( + self, + actual_type: Type, + actual_kind: nodes.ArgKind, + formal_name: str | None, + formal_kind: nodes.ArgKind, + allow_unpack: bool = False, + ) -> Type: + """Return the actual (caller) type(s) of a formal argument with the given kinds. + + If the actual argument is a tuple *args, return the next individual tuple item that + maps to the formal arg. + + If the actual argument is a TypedDict **kwargs, return the next matching typed dict + value type based on formal argument name and kind. + + This is supposed to be called for each formal, in order. Call multiple times per + formal if multiple actuals map to a formal. + """ + original_actual = actual_type + actual_type = get_proper_type(actual_type) + if actual_kind == nodes.ARG_STAR: + if isinstance(actual_type, TypeVarTupleType): + # This code path is hit when *Ts is passed to a callable and various + # special-handling didn't catch this. The best thing we can do is to use + # the upper bound. + actual_type = get_proper_type(actual_type.upper_bound) + if isinstance(actual_type, Instance) and actual_type.args: + from mypy.subtypes import is_subtype + + if is_subtype(actual_type, self.context.iterable_type): + return map_instance_to_supertype( + actual_type, self.context.iterable_type.type + ).args[0] + else: + # We cannot properly unpack anything other + # than `Iterable` type with `*`. + # Just return `Any`, other parts of code would raise + # a different error for improper use. + return AnyType(TypeOfAny.from_error) + elif isinstance(actual_type, TupleType): + # Get the next tuple item of a tuple *arg. + if self.tuple_index >= len(actual_type.items): + # Exhausted a tuple -- continue to the next *args. + self.tuple_index = 1 + else: + self.tuple_index += 1 + item = actual_type.items[self.tuple_index - 1] + if isinstance(item, UnpackType) and not allow_unpack: + # An unpack item that doesn't have special handling, use upper bound as above. + unpacked = get_proper_type(item.type) + if isinstance(unpacked, TypeVarTupleType): + fallback = get_proper_type(unpacked.upper_bound) + else: + fallback = unpacked + assert ( + isinstance(fallback, Instance) + and fallback.type.fullname == "builtins.tuple" + ) + item = fallback.args[0] + return item + elif isinstance(actual_type, ParamSpecType): + # ParamSpec is valid in *args but it can't be unpacked. + return actual_type + else: + return AnyType(TypeOfAny.from_error) + elif actual_kind == nodes.ARG_STAR2: + from mypy.subtypes import is_subtype + + if isinstance(actual_type, TypedDictType): + if self.kwargs_used is None: + self.kwargs_used = set() + if formal_kind != nodes.ARG_STAR2 and formal_name in actual_type.items: + # Lookup type based on keyword argument name. + assert formal_name is not None + else: + # Pick an arbitrary item if no specified keyword is expected. + formal_name = (set(actual_type.items.keys()) - self.kwargs_used).pop() + self.kwargs_used.add(formal_name) + return actual_type.items[formal_name] + elif isinstance(actual_type, Instance) and is_subtype( + actual_type, self.context.mapping_type + ): + # Only `Mapping` type can be unpacked with `**`. + # Other types will produce an error somewhere else. + return map_instance_to_supertype(actual_type, self.context.mapping_type.type).args[ + 1 + ] + elif isinstance(actual_type, ParamSpecType): + # ParamSpec is valid in **kwargs but it can't be unpacked. + return actual_type + else: + return AnyType(TypeOfAny.from_error) + else: + # No translation for other kinds -- 1:1 mapping. + return original_actual diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ae812e46c6eb8c62e34b624bca5b0d4ab780899c Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.py new file mode 100644 index 0000000000000000000000000000000000000000..adcc812badc914c6fb91adfff28a4fd6e4143b3e --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.py @@ -0,0 +1,709 @@ +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Literal, NamedTuple, TypeAlias as _TypeAlias + +from mypy.erasetype import remove_instance_last_known_values +from mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash, subkeys +from mypy.nodes import ( + LITERAL_NO, + Expression, + IndexExpr, + MemberExpr, + NameExpr, + RefExpr, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.subtypes import is_same_type, is_subtype +from mypy.typeops import make_simplified_union +from mypy.types import ( + AnyType, + Instance, + NoneType, + PartialType, + ProperType, + TupleType, + Type, + TypeOfAny, + TypeType, + TypeVarType, + UnionType, + UnpackType, + find_unpack_in_list, + flatten_nested_unions, + get_proper_type, +) +from mypy.typevars import fill_typevars_with_any + +BindableExpression: _TypeAlias = IndexExpr | MemberExpr | NameExpr + + +class CurrentType(NamedTuple): + type: Type + from_assignment: bool + + +class Frame: + """A Frame represents a specific point in the execution of a program. + + It carries information about the current types of expressions at + that point, arising either from assignments to those expressions + or the result of isinstance checks and other type narrowing + operations. It also records whether it is possible to reach that + point at all. + + We add a new frame wherenever there is a new scope or control flow + branching. + + This information is not copied into a new Frame when it is pushed + onto the stack, so a given Frame only has information about types + that were assigned in that frame. + + Expressions are stored in dicts using 'literal hashes' as keys (type + "Key"). These are hashable values derived from expression AST nodes + (only those that can be narrowed). literal_hash(expr) is used to + calculate the hashes. Note that this isn't directly related to literal + types -- the concept predates literal types. + """ + + def __init__(self, id: int, conditional_frame: bool = False) -> None: + self.id = id + self.types: dict[Key, CurrentType] = {} + self.unreachable = False + self.conditional_frame = conditional_frame + self.suppress_unreachable_warnings = False + + def __repr__(self) -> str: + return f"Frame({self.id}, {self.types}, {self.unreachable}, {self.conditional_frame})" + + +Assigns = defaultdict[Expression, list[tuple[Type, Type | None]]] + + +class FrameContext: + """Context manager pushing a Frame to ConditionalTypeBinder. + + See frame_context() below for documentation on parameters. We use this class + instead of @contextmanager as a mypyc-specific performance optimization. + """ + + def __init__( + self, + binder: ConditionalTypeBinder, + can_skip: bool, + fall_through: int, + break_frame: int, + continue_frame: int, + conditional_frame: bool, + try_frame: bool, + discard: bool, + ) -> None: + self.binder = binder + self.can_skip = can_skip + self.fall_through = fall_through + self.break_frame = break_frame + self.continue_frame = continue_frame + self.conditional_frame = conditional_frame + self.try_frame = try_frame + self.discard = discard + + def __enter__(self) -> Frame: + assert len(self.binder.frames) > 1 + + if self.break_frame: + self.binder.break_frames.append(len(self.binder.frames) - self.break_frame) + if self.continue_frame: + self.binder.continue_frames.append(len(self.binder.frames) - self.continue_frame) + if self.try_frame: + self.binder.try_frames.add(len(self.binder.frames) - 1) + + new_frame = self.binder.push_frame(self.conditional_frame) + if self.try_frame: + # An exception may occur immediately + self.binder.allow_jump(-1) + return new_frame + + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]: + self.binder.pop_frame(self.can_skip, self.fall_through, discard=self.discard) + + if self.break_frame: + self.binder.break_frames.pop() + if self.continue_frame: + self.binder.continue_frames.pop() + if self.try_frame: + self.binder.try_frames.remove(len(self.binder.frames) - 1) + return False + + +class ConditionalTypeBinder: + """Keep track of conditional types of variables. + + NB: Variables are tracked by literal hashes of expressions, so it is + possible to confuse the binder when there is aliasing. Example: + + class A: + a: int | str + + x = A() + lst = [x] + reveal_type(x.a) # int | str + x.a = 1 + reveal_type(x.a) # int + reveal_type(lst[0].a) # int | str + lst[0].a = 'a' + reveal_type(x.a) # int + reveal_type(lst[0].a) # str + """ + + # Stored assignments for situations with tuple/list lvalue and rvalue of union type. + # This maps an expression to a list of bound types for every item in the union type. + type_assignments: Assigns | None = None + + def __init__(self, options: Options) -> None: + # Each frame gets an increasing, distinct id. + self.next_id = 1 + + # The stack of frames currently used. These map + # literal_hash(expr) -- literals like 'foo.bar' -- + # to types. The last element of this list is the + # top-most, current frame. Each earlier element + # records the state as of when that frame was last + # on top of the stack. + self.frames = [Frame(self._get_id())] + + # For frames higher in the stack, we record the set of + # Frames that can escape there, either by falling off + # the end of the frame or by a loop control construct + # or raised exception. The last element of self.frames + # has no corresponding element in this list. + self.options_on_return: list[list[Frame]] = [] + + # Maps literal_hash(expr) to get_declaration(expr) + # for every expr stored in the binder + self.declarations: dict[Key, Type | None] = {} + # Set of other keys to invalidate if a key is changed, e.g. x -> {x.a, x[0]} + # Whenever a new key (e.g. x.a.b) is added, we update this + self.dependencies: dict[Key, set[Key]] = {} + + # Whether the last pop changed the newly top frame on exit + self.last_pop_changed = False + + # These are used to track control flow in try statements and loops. + self.try_frames: set[int] = set() + self.break_frames: list[int] = [] + self.continue_frames: list[int] = [] + + # If True, initial assignment to a simple variable (e.g. "x", but not "x.y") + # is added to the binder. This allows more precise narrowing and more + # flexible inference of variable types (--allow-redefinition-new). + self.bind_all = options.allow_redefinition_new + + # This tracks any externally visible changes in binder to invalidate + # expression caches when needed. + self.version = 0 + + def _get_id(self) -> int: + self.next_id += 1 + return self.next_id + + def _add_dependencies(self, key: Key, value: Key | None = None) -> None: + if value is None: + value = key + else: + self.dependencies.setdefault(key, set()).add(value) + for elt in subkeys(key): + self._add_dependencies(elt, value) + + def push_frame(self, conditional_frame: bool = False) -> Frame: + """Push a new frame into the binder.""" + f = Frame(self._get_id(), conditional_frame) + self.frames.append(f) + self.options_on_return.append([]) + return f + + def _put(self, key: Key, type: Type, from_assignment: bool, index: int = -1) -> None: + self.version += 1 + self.frames[index].types[key] = CurrentType(type, from_assignment) + + def _get(self, key: Key, index: int = -1) -> CurrentType | None: + if index < 0: + index += len(self.frames) + for i in range(index, -1, -1): + if key in self.frames[i].types: + return self.frames[i].types[key] + return None + + @classmethod + def can_put_directly(cls, expr: Expression) -> bool: + """Will `.put()` on this expression be successful? + + This is inlined in `.put()` because the logic is rather hot and must be kept + in sync. + """ + return isinstance(expr, (IndexExpr, MemberExpr, NameExpr)) and literal(expr) > LITERAL_NO + + def put(self, expr: Expression, typ: Type, *, from_assignment: bool = True) -> None: + """Directly set the narrowed type of expression (if it supports it). + + This is used for isinstance() etc. Assignments should go through assign_type(). + """ + if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)): + return + if not literal(expr): + return + key = literal_hash(expr) + assert key is not None, "Internal error: binder tried to put non-literal" + if key not in self.declarations: + self.declarations[key] = get_declaration(expr) + self._add_dependencies(key) + self._put(key, typ, from_assignment) + + def unreachable(self) -> None: + self.version += 1 + self.frames[-1].unreachable = True + + def suppress_unreachable_warnings(self) -> None: + self.frames[-1].suppress_unreachable_warnings = True + + def get(self, expr: Expression) -> Type | None: + key = literal_hash(expr) + assert key is not None, "Internal error: binder tried to get non-literal" + found = self._get(key) + if found is None: + return None + return found.type + + def is_unreachable(self) -> bool: + # TODO: Copy the value of unreachable into new frames to avoid + # this traversal on every statement? + return any(f.unreachable for f in self.frames) + + def is_unreachable_warning_suppressed(self) -> bool: + return any(f.suppress_unreachable_warnings for f in self.frames) + + def cleanse(self, expr: Expression) -> None: + """Remove all references to a Node from the binder.""" + key = literal_hash(expr) + assert key is not None, "Internal error: binder tried cleanse non-literal" + self._cleanse_key(key) + + def _cleanse_key(self, key: Key) -> None: + """Remove all references to a key from the binder.""" + for frame in self.frames: + if key in frame.types: + del frame.types[key] + + def update_from_options(self, frames: list[Frame]) -> bool: + """Update the frame to reflect that each key will be updated + as in one of the frames. Return whether any item changes. + + If a key is declared as AnyType, only update it if all the + options are the same. + """ + all_reachable = all(not f.unreachable for f in frames) + if not all_reachable: + frames = [f for f in frames if not f.unreachable] + changed = False + keys = [key for f in frames for key in f.types] + if len(keys) > 1: + keys = list(set(keys)) + for key in keys: + current_value = self._get(key) + resulting_values = [f.types.get(key, current_value) for f in frames] + # Keys can be narrowed using two different semantics. The new semantics + # is enabled for inferred variables when bind_all is true, and it allows + # variable types to be widened using subsequent assignments. This is + # not allowed for instance attributes and annotated variables. + var = extract_var_from_literal_hash(key) + old_semantics = ( + not self.bind_all or var is None or not var.is_inferred and not var.is_argument + ) + if old_semantics and any(x is None for x in resulting_values): + # We didn't know anything about key before + # (current_value must be None), and we still don't + # know anything about key in at least one possible frame. + continue + + resulting_values = [x for x in resulting_values if x is not None] + + if all_reachable and all(not x.from_assignment for x in resulting_values): + # Do not synthesize a new type if we encountered a conditional block + # (if, while or match-case) without assignments. + # See check-isinstance.test::testNoneCheckDoesNotMakeTypeVarOptional + # This is a safe assumption: the fact that we checked something with `is` + # or `isinstance` does not change the type of the value. + continue + + # Remove exact duplicates to save pointless work later, this is + # a micro-optimization for --allow-redefinition-new. + seen_types = set() + resulting_types = [] + for rv in resulting_values: + assert rv is not None + if rv.type in seen_types: + continue + resulting_types.append(rv.type) + seen_types.add(rv.type) + + type = resulting_types[0] + declaration_type = get_proper_type(self.declarations.get(key)) + if isinstance(declaration_type, AnyType): + # At this point resulting values can't contain None, see continue above + if not all(is_same_type(type, t) for t in resulting_types[1:]): + type = AnyType(TypeOfAny.from_another_any, source_any=declaration_type) + else: + possible_types = [] + for t in resulting_types: + assert t is not None + possible_types.append(t) + if len(possible_types) == 1: + # This is to avoid calling get_proper_type() unless needed, as this may + # interfere with our (hacky) TypeGuard support. + type = possible_types[0] + else: + type = make_simplified_union(possible_types) + # Legacy guard for corner case when the original type is TypeVarType. + if isinstance(declaration_type, TypeVarType) and not is_subtype( + type, declaration_type + ): + type = declaration_type + # Try simplifying resulting type for unions involving variadic tuples. + # Technically, everything is still valid without this step, but if we do + # not do this, this may create long unions after exiting an if check like: + # x: tuple[int, ...] + # if len(x) < 10: + # ... + # We want the type of x to be tuple[int, ...] after this block (if it is + # still equivalent to such type). + if isinstance(type, UnionType): + type = collapse_variadic_union(type) + if ( + old_semantics + and isinstance(type, ProperType) + and isinstance(type, UnionType) + ): + # Simplify away any extra Any's that were added to the declared + # type when popping a frame. + simplified = UnionType.make_union( + [t for t in type.items if not isinstance(get_proper_type(t), AnyType)] + ) + if simplified == self.declarations[key]: + type = simplified + if ( + current_value is None + or not is_same_type(type, current_value.type) + # Manually carry over any narrowing from hasattr() from inner frames. This is + # a bit ad-hoc, but our handling of hasattr() is on best effort basis anyway. + or isinstance(p_type := get_proper_type(type), Instance) + and p_type.extra_attrs + ): + self._put(key, type, from_assignment=True) + if current_value is not None or extract_var_from_literal_hash(key) is None: + # We definitely learned something new + changed = True + elif not changed: + # If there is no current value compare with the declaration. This prevents + # reporting false changes in cases like this: + # x: int + # if foo(): + # x = 1 + # else: + # x = 2 + # We check partial types and widening in accept_loop() separately, so + # this should be safe. + changed = declaration_type is not None and not is_same_type( + type, declaration_type + ) + + self.frames[-1].unreachable = not frames + + return changed + + def pop_frame(self, can_skip: bool, fall_through: int, *, discard: bool = False) -> Frame: + """Pop a frame and return it. + + See frame_context() for documentation of fall_through and discard. + """ + + if fall_through > 0: + self.allow_jump(-fall_through) + + result = self.frames.pop() + options = self.options_on_return.pop() + + if discard: + self.last_pop_changed = False + return result + + if can_skip: + options.insert(0, self.frames[-1]) + + self.last_pop_changed = self.update_from_options(options) + + return result + + @contextmanager + def accumulate_type_assignments(self) -> Iterator[Assigns]: + """Push a new map to collect assigned types in multiassign from union. + + If this map is not None, actual binding is deferred until all items in + the union are processed (a union of collected items is later bound + manually by the caller). + """ + old_assignments = None + if self.type_assignments is not None: + old_assignments = self.type_assignments + self.type_assignments = defaultdict(list) + yield self.type_assignments + self.type_assignments = old_assignments + + def assign_type(self, expr: Expression, type: Type, declared_type: Type | None) -> None: + """Narrow type of expression through an assignment. + + Do nothing if the expression doesn't support narrowing. + + When not narrowing though an assignment (isinstance() etc.), use put() + directly. This omits some special-casing logic for assignments. + """ + # We should erase last known value in binder, because if we are using it, + # it means that the target is not final, and therefore can't hold a literal. + type = remove_instance_last_known_values(type) + + if self.type_assignments is not None: + # We are in a multiassign from union, defer the actual binding, + # just collect the types. + self.type_assignments[expr].append((type, declared_type)) + return + if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)): + return + if not literal(expr): + return + self.invalidate_dependencies(expr) + + if declared_type is None: + # Not sure why this happens. It seems to mainly happen in + # member initialization. + return + if not is_subtype(type, declared_type): + # Pretty sure this is only happens when there's a type error. + + # Ideally this function wouldn't be called if the + # expression has a type error, though -- do other kinds of + # errors cause this function to get called at invalid + # times? + return + + p_declared = get_proper_type(declared_type) + p_type = get_proper_type(type) + if isinstance(p_type, AnyType): + # Any type requires some special casing, for both historical reasons, + # and to optimise user experience without sacrificing correctness too much. + if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred: + # First case: a local/global variable without explicit annotation, + # in this case we just assign Any (essentially following the SSA logic). + self.put(expr, type) + elif isinstance(p_declared, UnionType): + all_items = flatten_nested_unions(p_declared.items) + if any(isinstance(get_proper_type(item), NoneType) for item in all_items): + # Second case: explicit optional type, in this case we optimize for + # a common pattern when an untyped value used as a fallback replacing None. + new_items = [ + type if isinstance(get_proper_type(item), NoneType) else item + for item in all_items + ] + self.put(expr, UnionType(new_items)) + elif any(isinstance(get_proper_type(item), AnyType) for item in all_items): + # Third case: a union already containing Any (most likely from + # an un-imported name), in this case we allow assigning Any as well. + self.put(expr, type) + else: + # In all other cases we don't narrow to Any to minimize false negatives. + self.put(expr, declared_type) + else: + self.put(expr, declared_type) + elif isinstance(p_declared, AnyType): + # Mirroring the first case above, we don't narrow to a precise type if the variable + # has an explicit `Any` type annotation. + if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred: + self.put(expr, type) + else: + self.put(expr, declared_type) + else: + self.put(expr, type) + + for i in self.try_frames: + # XXX This should probably not copy the entire frame, but + # just copy this variable into a single stored frame. + self.allow_jump(i) + + def invalidate_dependencies(self, expr: BindableExpression) -> None: + """Invalidate knowledge of types that include expr, but not expr itself. + + For example, when expr is foo.bar, invalidate foo.bar.baz. + + It is overly conservative: it invalidates globally, including + in code paths unreachable from here. + """ + key = literal_hash(expr) + assert key is not None + for dep in self.dependencies.get(key, set()): + self._cleanse_key(dep) + + def allow_jump(self, index: int) -> None: + # self.frames and self.options_on_return have different lengths + # so make sure the index is positive + if index < 0: + index += len(self.options_on_return) + frame = Frame(self._get_id()) + for f in self.frames[index + 1 :]: + frame.types.update(f.types) + if f.unreachable: + frame.unreachable = True + self.options_on_return[index].append(frame) + + def handle_break(self) -> None: + self.allow_jump(self.break_frames[-1]) + self.unreachable() + + def handle_continue(self) -> None: + self.allow_jump(self.continue_frames[-1]) + self.unreachable() + + def frame_context( + self, + *, + can_skip: bool, + fall_through: int = 1, + break_frame: int = 0, + continue_frame: int = 0, + conditional_frame: bool = False, + try_frame: bool = False, + discard: bool = False, + ) -> FrameContext: + """Return a context manager that pushes/pops frames on enter/exit. + + If can_skip is True, control flow is allowed to bypass the + newly-created frame. + + If fall_through > 0, then it will allow control flow that + falls off the end of the frame to escape to its ancestor + `fall_through` levels higher. Otherwise, control flow ends + at the end of the frame. + + If break_frame > 0, then 'break' statements within this frame + will jump out to the frame break_frame levels higher than the + frame created by this call to frame_context. Similarly, for + continue_frame and 'continue' statements. + + If try_frame is true, then execution is allowed to jump at any + point within the newly created frame (or its descendants) to + its parent (i.e., to the frame that was on top before this + call to frame_context). + + If discard is True, then this is a temporary throw-away frame + (used e.g. for isolation) and its effect will be discarded on pop. + + After the context manager exits, self.last_pop_changed indicates + whether any types changed in the newly-topmost frame as a result + of popping this frame. + """ + return FrameContext( + self, + can_skip=can_skip, + fall_through=fall_through, + break_frame=break_frame, + continue_frame=continue_frame, + conditional_frame=conditional_frame, + try_frame=try_frame, + discard=discard, + ) + + @contextmanager + def top_frame_context(self) -> Iterator[Frame]: + """A variant of frame_context for use at the top level of + a namespace (module, function, or class). + """ + assert len(self.frames) == 1 + yield self.push_frame() + self.pop_frame(True, 0) + assert len(self.frames) == 1 + + +def get_declaration(expr: BindableExpression) -> Type | None: + """Get the declared or inferred type of a RefExpr expression. + + Return None if there is no type or the expression is not a RefExpr. + This can return None if the type hasn't been inferred yet. + """ + if isinstance(expr, RefExpr): + if isinstance(expr.node, Var): + type = expr.node.type + if not isinstance(get_proper_type(type), PartialType): + return type + elif isinstance(expr.node, TypeInfo): + return TypeType(fill_typevars_with_any(expr.node)) + return None + + +def collapse_variadic_union(typ: UnionType) -> Type: + """Simplify a union involving variadic tuple if possible. + + This will collapse a type like e.g. + tuple[X, Z] | tuple[X, Y, Z] | tuple[X, Y, Y, *tuple[Y, ...], Z] + back to + tuple[X, *tuple[Y, ...], Z] + which is equivalent, but much simpler form of the same type. + """ + tuple_items = [] + other_items = [] + for t in typ.items: + p_t = get_proper_type(t) + if isinstance(p_t, TupleType): + tuple_items.append(p_t) + else: + other_items.append(t) + if len(tuple_items) <= 1: + # This type cannot be simplified further. + return typ + tuple_items = sorted(tuple_items, key=lambda t: len(t.items)) + first = tuple_items[0] + last = tuple_items[-1] + unpack_index = find_unpack_in_list(last.items) + if unpack_index is None: + return typ + unpack = last.items[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + if not isinstance(unpacked, Instance): + return typ + assert unpacked.type.fullname == "builtins.tuple" + suffix = last.items[unpack_index + 1 :] + + # Check that first item matches the expected pattern and infer prefix. + if len(first.items) < len(suffix): + return typ + if suffix and first.items[-len(suffix) :] != suffix: + return typ + if suffix: + prefix = first.items[: -len(suffix)] + else: + prefix = first.items + + # Check that all middle types match the expected pattern as well. + arg = unpacked.args[0] + for i, it in enumerate(tuple_items[1:-1]): + if it.items != prefix + [arg] * (i + 1) + suffix: + return typ + + # Check the last item (the one with unpack), and choose an appropriate simplified type. + if last.items != prefix + [arg] * (len(typ.items) - 1) + [unpack] + suffix: + return typ + if len(first.items) == 0: + simplified: Type = unpacked.copy_modified() + else: + simplified = TupleType(prefix + [unpack] + suffix, fallback=last.partial_fallback) + return UnionType.make_union([simplified] + other_items) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/bogus_type.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/bogus_type.py new file mode 100644 index 0000000000000000000000000000000000000000..1a61abac9732d1eab673061c10d8118c34281b28 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/bogus_type.py @@ -0,0 +1,27 @@ +"""A Bogus[T] type alias for marking when we subvert the type system + +We need this for compiling with mypyc, which inserts runtime +typechecks that cause problems when we subvert the type system. So +when compiling with mypyc, we turn those places into Any, while +keeping the types around for normal typechecks. + +Since this causes the runtime types to be Any, this is best used +in places where efficient access to properties is not important. +For those cases some other technique should be used. +""" + +from __future__ import annotations + +from typing import Any, TypeVar + +from mypy_extensions import FlexibleAlias + +T = TypeVar("T") + +# This won't ever be true at runtime, but we consider it true during +# mypyc compilations. +MYPYC = False +if MYPYC: + Bogus = FlexibleAlias[T, Any] +else: + Bogus = FlexibleAlias[T, T] diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/build.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/build.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b9acee1c34027af0a86ca9ae78b944623b632002 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/build.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/build.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/build.py new file mode 100644 index 0000000000000000000000000000000000000000..1f83cee536e827c69bcf0378d65ded049548cb10 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/build.py @@ -0,0 +1,4796 @@ +"""Facilities to analyze entire programs, including imported modules. + +Parse and analyze the source files of a program in the correct order +(based on file dependencies), and collect the results. + +This module only directs a build, which is performed in multiple passes per +file. The individual passes are implemented in separate modules. + +The function build() is the main interface to this module. +""" + +# TODO: More consistent terminology, e.g. path/fnam, module/id, state/file + +from __future__ import annotations + +import collections +import contextlib +import gc +import json +import os +import pickle +import platform +import re +import stat +import subprocess +import sys +import time +import types +from collections.abc import Callable, Iterator, Mapping, Sequence, Set as AbstractSet +from heapq import heappop, heappush +from textwrap import dedent +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Final, + NoReturn, + TextIO, + TypeAlias as _TypeAlias, + TypedDict, + cast, + final, +) + +from librt.base64 import b64encode +from librt.internal import ( + cache_version, + read_bool, + read_int as read_int_bare, + read_str as read_str_bare, + read_tag, + write_bool, + write_bytes as write_bytes_bare, + write_int as write_int_bare, + write_str as write_str_bare, + write_tag, +) + +import mypy.semanal_main +from mypy.cache import ( + CACHE_VERSION, + DICT_STR_GEN, + LIST_GEN, + LITERAL_NONE, + CacheMeta, + ErrorTuple, + JsonValue, + ReadBuffer, + Tag, + WriteBuffer, + read_bytes, + read_errors, + read_int, + read_int_list, + read_int_opt, + read_str, + read_str_list, + read_str_opt, + write_bytes, + write_errors, + write_int, + write_int_list, + write_int_opt, + write_json_value, + write_str, + write_str_list, + write_str_opt, +) +from mypy.checker import TypeChecker +from mypy.defaults import ( + WORKER_CONNECTION_TIMEOUT, + WORKER_DONE_TIMEOUT, + WORKER_START_INTERVAL, + WORKER_START_TIMEOUT, +) +from mypy.error_formatter import OUTPUT_CHOICES, ErrorFormatter +from mypy.errorcodes import ErrorCode +from mypy.errors import CompileError, ErrorInfo, Errors, report_internal_error +from mypy.graph_utils import prepare_sccs, strongly_connected_components, topsort +from mypy.indirection import TypeIndirectionVisitor +from mypy.ipc import ( + BadStatus, + IPCClient, + IPCException, + IPCMessage, + read_status, + ready_to_read, + receive, + send, +) +from mypy.messages import MessageBuilder +from mypy.nodes import ( + FileRawData, + Import, + ImportAll, + ImportBase, + ImportFrom, + MypyFile, + SymbolTable, +) +from mypy.options import OPTIONS_AFFECTING_CACHE_NO_PLATFORM +from mypy.partially_defined import PossiblyUndefinedVariableVisitor +from mypy.semanal import SemanticAnalyzer +from mypy.semanal_pass1 import SemanticAnalyzerPreAnalysis +from mypy.util import ( + DecodeError, + decode_python_encoding, + get_mypy_comments, + hash_digest, + hash_digest_bytes, + is_stub_package_file, + is_sub_path_normabs, + is_typeshed_file, + module_prefix, + os_path_join, + read_py_file, + time_ref, + time_spent_us, +) + +if TYPE_CHECKING: + from mypy.report import Reports # Avoid unconditional slow import + +from mypy import errorcodes as codes +from mypy.config_parser import get_config_module_names, parse_mypy_comments +from mypy.fixup import fixup_module +from mypy.freetree import free_tree +from mypy.fscache import FileSystemCache +from mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore +from mypy.modulefinder import ( + BuildSource as BuildSource, + BuildSourceSet as BuildSourceSet, + FindModuleCache, + ModuleNotFoundReason, + ModuleSearchResult, + SearchPaths, + compute_search_paths, +) +from mypy.nodes import Expression +from mypy.options import Options +from mypy.parse import load_from_raw, parse +from mypy.plugin import ChainedPlugin, Plugin, ReportConfigContext +from mypy.plugins.default import DefaultPlugin +from mypy.renaming import LimitedVariableRenameVisitor, VariableRenameVisitor +from mypy.stats import dump_type_stats +from mypy.stubinfo import is_module_from_legacy_bundled_package, stub_distribution_name +from mypy.types import Type, instance_cache +from mypy.typestate import reset_global_state, type_state +from mypy.util import json_dumps, json_loads +from mypy.version import __version__ + +# Switch to True to produce debug output related to fine-grained incremental +# mode only that is useful during development. This produces only a subset of +# output compared to --verbose output. We use a global flag to enable this so +# that it's easy to enable this when running tests. +DEBUG_FINE_GRAINED: Final = False + +# These modules are special and should always come from typeshed. +CORE_BUILTIN_MODULES: Final = { + "builtins", + "typing", + "types", + "typing_extensions", + "mypy_extensions", + "_typeshed", + "_collections_abc", + "collections", + "collections.abc", + "sys", + "abc", +} + +# We are careful now, we can increase this in future if safe/useful. +MAX_GC_FREEZE_CYCLES: Final = 1 + +# We store status of initial GC freeze as a global variable to avoid memory +# leaks in tests, where we keep creating new BuildManagers in the same process. +initial_gc_freeze_done = False + +Graph: _TypeAlias = dict[str, "State"] + +MODULE_RESOLUTION_URL: Final = ( + "https://mypy.readthedocs.io/en/stable/running_mypy.html#mapping-file-paths-to-modules" +) + + +class SCC: + """A simple class that represents a strongly connected component (import cycle).""" + + id_counter: ClassVar[int] = 0 + + def __init__( + self, ids: set[str], scc_id: int | None = None, deps: list[int] | None = None + ) -> None: + if scc_id is None: + self.id = SCC.id_counter + SCC.id_counter += 1 + else: + self.id = scc_id + # Ids of modules in this cycle. + self.mod_ids = ids + # Direct dependencies, should be populated by the caller. + self.deps: set[int] = set(deps) if deps is not None else set() + # Direct dependencies that have not been processed yet. + # Should be populated by the caller. This set may change during graph + # processing, while the above stays constant. + self.not_ready_deps: set[int] = set() + # SCCs that (directly) depend on this SCC. Note this is a list to + # make processing order more predictable. Dependents will be notified + # that they may be ready in the order in this list. + self.direct_dependents: list[int] = [] + # Rough estimate of how much time processing this SCC will take, this + # is used for more efficient scheduling across multiple build workers. + self.size_hint: int = 0 + + +# TODO: Get rid of BuildResult. We might as well return a BuildManager. +class BuildResult: + """The result of a successful build. + + Attributes: + manager: The build manager. + files: Dictionary from module name to related AST node. + types: Dictionary from parse tree node to its inferred type. + used_cache: Whether the build took advantage of a pre-existing cache + errors: List of error messages. + """ + + def __init__(self, manager: BuildManager, graph: Graph) -> None: + self.manager = manager + self.graph = graph + self.files = manager.modules + self.types = manager.all_types # Non-empty if export_types True in options + self.used_cache = manager.cache_enabled + self.errors: list[str] = [] # Filled in by build if desired + + +class WorkerClient: + """A simple class that represents a mypy build worker.""" + + conn: IPCClient + + def __init__(self, status_file: str, options_data: str, env: Mapping[str, str]) -> None: + self.status_file = status_file + if os.path.isfile(status_file): + os.unlink(status_file) + + command = [ + sys.executable, + "-m", + "mypy.build_worker", + f"--status-file={status_file}", + f'--options-data="{options_data}"', + ] + # Return early without waiting, caller must call connect() before using the client. + self.proc = subprocess.Popen(command, env=env) + + def connect(self) -> None: + end_time = time.time() + WORKER_START_TIMEOUT + last_exception: Exception | None = None + while time.time() < end_time: + try: + data = read_status(self.status_file) + except BadStatus as exc: + last_exception = exc + time.sleep(WORKER_START_INTERVAL) + continue + try: + pid, connection_name = data["pid"], data["connection_name"] + assert isinstance(pid, int), f"Bad PID: {pid}" + assert isinstance(connection_name, str), f"Bad connection name: {connection_name}" + if sys.platform != "win32": + # Windows uses "wrapper processes" to run Python, so we cannot + # verify PIDs reliably. + assert pid == self.proc.pid, f"PID mismatch: {pid} vs {self.proc.pid}" + self.conn = IPCClient(connection_name, WORKER_CONNECTION_TIMEOUT) + return + except Exception as exc: + last_exception = exc + break + print("Failed to establish connection with worker:", last_exception) + sys.exit(2) + + def close(self) -> None: + self.conn.close() + # Technically we don't need to wait, but otherwise we will get ResourceWarnings. + try: + self.proc.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + if os.path.isfile(self.status_file): + os.unlink(self.status_file) + + +def build_error(msg: str) -> NoReturn: + raise CompileError([f"mypy: error: {msg}"]) + + +def build( + sources: list[BuildSource], + options: Options, + alt_lib_path: str | None = None, + flush_errors: Callable[[str | None, list[str], bool], None] | None = None, + fscache: FileSystemCache | None = None, + stdout: TextIO | None = None, + stderr: TextIO | None = None, + extra_plugins: Sequence[Plugin] | None = None, + worker_env: Mapping[str, str] | None = None, +) -> BuildResult: + """Analyze a program. + + A single call to build performs parsing, semantic analysis and optionally + type checking for the program *and* all imported modules, recursively. + + Return BuildResult if successful or only non-blocking errors were found; + otherwise raise CompileError. + + If a flush_errors callback is provided, all error messages will be + passed to it and the errors and messages fields of BuildResult and + CompileError (respectively) will be empty. Otherwise those fields will + report any error messages. + + Args: + sources: list of sources to build + options: build options + alt_lib_path: an additional directory for looking up library modules + (takes precedence over other directories) + flush_errors: optional function to flush errors after a file is processed + fscache: optionally a file-system cacher + worker_env: An environment to start parallel build workers (used for tests) + """ + # If we were not given a flush_errors, we use one that will populate those + # fields for callers that want the traditional API. + messages = [] + + # This is mostly for the benefit of tests that use builtins fixtures. + instance_cache.reset() + + def default_flush_errors( + filename: str | None, new_messages: list[str], is_serious: bool + ) -> None: + messages.extend(new_messages) + + flush_errors = flush_errors or default_flush_errors + stdout = stdout or sys.stdout + stderr = stderr or sys.stderr + extra_plugins = extra_plugins or [] + + workers = [] + if options.num_workers > 0: + # TODO: switch to something more efficient than pickle (also in the daemon). + pickled_options = pickle.dumps(options.snapshot()) + options_data = b64encode(pickled_options).decode() + workers = [ + WorkerClient(f".mypy_worker.{idx}.json", options_data, worker_env or os.environ) + for idx in range(options.num_workers) + ] + sources_message = SourcesDataMessage(sources=sources) + buf = WriteBuffer() + sources_message.write(buf) + sources_data = buf.getvalue() + for worker in workers: + # Start loading graph in each worker as soon as it is up. + worker.connect() + worker.conn.write_bytes(sources_data) + + try: + result = build_inner( + sources, + options, + alt_lib_path, + flush_errors, + fscache, + stdout, + stderr, + extra_plugins, + workers, + ) + result.errors = messages + return result + except CompileError as e: + # CompileErrors raised from an errors object carry all the + # messages that have not been reported out by error streaming. + # Patch it up to contain either none or all none of the messages, + # depending on whether we are flushing errors. + serious = not e.use_stdout + flush_errors(None, e.messages, serious) + e.messages = messages + raise + finally: + for worker in workers: + try: + send(worker.conn, SccRequestMessage(scc_id=None, import_errors={}, mod_data={})) + except (OSError, IPCException): + pass + for worker in workers: + worker.close() + + +def build_inner( + sources: list[BuildSource], + options: Options, + alt_lib_path: str | None, + flush_errors: Callable[[str | None, list[str], bool], None], + fscache: FileSystemCache | None, + stdout: TextIO, + stderr: TextIO, + extra_plugins: Sequence[Plugin], + workers: list[WorkerClient], +) -> BuildResult: + if platform.python_implementation() == "CPython": + # Run gc less frequently, as otherwise we can spend a large fraction of + # cpu in gc. This seems the most reasonable place to tune garbage collection. + gc.set_threshold(200 * 1000, 30, 30) + + data_dir = default_data_dir() + fscache = fscache or FileSystemCache() + + search_paths = compute_search_paths(sources, options, data_dir, alt_lib_path) + + reports = None + if options.report_dirs: + # Import lazily to avoid slowing down startup. + from mypy.report import Reports + + reports = Reports(data_dir, options.report_dirs) + + source_set = BuildSourceSet(sources) + cached_read = fscache.read + errors = Errors(options, read_source=lambda path: read_py_file(path, cached_read)) + # Record import errors so that they can be replayed by the workers. + if workers: + errors.global_watcher = True + plugin, snapshot = load_plugins(options, errors, stdout, extra_plugins) + + # Validate error codes after plugins are loaded. + options.process_error_codes(error_callback=build_error) + + # Construct a build manager object to hold state during the build. + # + # Ignore current directory prefix in error messages. + manager = BuildManager( + data_dir, + search_paths, + ignore_prefix=os.getcwd(), + source_set=source_set, + reports=reports, + options=options, + version_id=__version__, + plugin=plugin, + plugins_snapshot=snapshot, + errors=errors, + error_formatter=None if options.output is None else OUTPUT_CHOICES.get(options.output), + flush_errors=flush_errors, + fscache=fscache, + stdout=stdout, + stderr=stderr, + ) + manager.workers = workers + if manager.verbosity() >= 2: + manager.trace(repr(options)) + + reset_global_state() + try: + graph = dispatch(sources, manager, stdout) + if not options.fine_grained_incremental: + type_state.reset_all_subtype_caches() + if options.timing_stats is not None: + dump_timing_stats(options.timing_stats, graph) + if options.line_checking_stats is not None: + dump_line_checking_stats(options.line_checking_stats, graph) + warn_unused_configs(options, flush_errors) + return BuildResult(manager, graph) + finally: + t0 = time.time() + manager.metastore.commit() + manager.add_stats(cache_commit_time=time.time() - t0) + manager.log( + "Build finished in %.3f seconds with %d modules, and %d errors" + % ( + time.time() - manager.start_time, + len(manager.modules), + manager.errors.num_messages(), + ) + ) + manager.dump_stats() + if reports is not None: + # Finish the HTML or XML reports even if CompileError was raised. + reports.finish() + if os.path.isdir(options.cache_dir): + add_catch_all_gitignore(options.cache_dir) + exclude_from_backups(options.cache_dir) + if os.path.isdir(options.cache_dir): + record_missing_stub_packages(options.cache_dir, manager.missing_stub_packages) + + +def warn_unused_configs( + options: Options, flush_errors: Callable[[str | None, list[str], bool], None] +) -> None: + if options.warn_unused_configs and options.unused_configs and not options.non_interactive: + unused = get_config_module_names( + options.config_file, + [glob for glob in options.per_module_options.keys() if glob in options.unused_configs], + ) + flush_errors( + None, ["{}: note: unused section(s): {}".format(options.config_file, unused)], False + ) + + +def default_data_dir() -> str: + """Returns directory containing typeshed directory.""" + return os.path.dirname(__file__) + + +def normpath(path: str, options: Options) -> str: + """Convert path to absolute; but to relative in bazel mode. + + (Bazel's distributed cache doesn't like filesystem metadata to + end up in output files.) + """ + # TODO: Could we always use relpath? (A worry in non-bazel + # mode would be that a moved file may change its full module + # name without changing its size, mtime or hash.) + if options.bazel: + return os.path.relpath(path) + else: + return os.path.abspath(path) + + +# NOTE: dependencies + suppressed == all reachable imports; +# suppressed contains those reachable imports that were prevented by +# silent mode or simply not found. + + +# Metadata for the fine-grained dependencies file associated with a module. +class FgDepMeta(TypedDict): + path: str + mtime: int + + +# Priorities used for imports. (Here, top-level includes inside a class.) +# These are used to determine a more predictable order in which the +# nodes in an import cycle are processed. +PRI_HIGH: Final = 5 # top-level "from X import blah" +PRI_MED: Final = 10 # top-level "import X" +PRI_LOW: Final = 20 # either form inside a function +PRI_MYPY: Final = 25 # inside "if MYPY" or "if TYPE_CHECKING" +PRI_INDIRECT: Final = 30 # an indirect dependency +PRI_ALL: Final = 99 # include all priorities + + +def import_priority(imp: ImportBase, toplevel_priority: int) -> int: + """Compute import priority from an import node.""" + if not imp.is_top_level: + # Inside a function + return PRI_LOW + if imp.is_mypy_only: + # Inside "if MYPY" or "if typing.TYPE_CHECKING" + return max(PRI_MYPY, toplevel_priority) + # A regular import; priority determined by argument. + return toplevel_priority + + +def load_plugins_from_config( + options: Options, errors: Errors, stdout: TextIO +) -> tuple[list[Plugin], dict[str, str]]: + """Load all configured plugins. + + Return a list of all the loaded plugins from the config file. + The second return value is a snapshot of versions/hashes of loaded user + plugins (for cache validation). + """ + import importlib + + snapshot: dict[str, str] = {} + + if not options.config_file: + return [], snapshot + + line = find_config_file_line_number(options.config_file, "mypy", "plugins") + if line == -1: + line = 1 # We need to pick some line number that doesn't look too confusing + + def plugin_error(message: str) -> NoReturn: + errors.report(line, 0, message) + errors.raise_error(use_stdout=False) + + custom_plugins: list[Plugin] = [] + errors.set_file(options.config_file, None, options) + for plugin_path in options.plugins: + func_name = "plugin" + plugin_dir: str | None = None + if ":" in os.path.basename(plugin_path): + plugin_path, func_name = plugin_path.rsplit(":", 1) + if plugin_path.endswith(".py"): + # Plugin paths can be relative to the config file location. + plugin_path = os_path_join(os.path.dirname(options.config_file), plugin_path) + if not os.path.isfile(plugin_path): + plugin_error(f'Can\'t find plugin "{plugin_path}"') + # Use an absolute path to avoid populating the cache entry + # for 'tmp' during tests, since it will be different in + # different tests. + plugin_dir = os.path.abspath(os.path.dirname(plugin_path)) + fnam = os.path.basename(plugin_path) + module_name = fnam[:-3] + sys.path.insert(0, plugin_dir) + elif re.search(r"[\\/]", plugin_path): + fnam = os.path.basename(plugin_path) + plugin_error(f'Plugin "{fnam}" does not have a .py extension') + else: + module_name = plugin_path + + try: + module = importlib.import_module(module_name) + except Exception as exc: + plugin_error(f'Error importing plugin "{plugin_path}": {exc}') + finally: + if plugin_dir is not None: + assert sys.path[0] == plugin_dir + del sys.path[0] + + if not hasattr(module, func_name): + plugin_error( + 'Plugin "{}" does not define entry point function "{}"'.format( + plugin_path, func_name + ) + ) + + try: + plugin_type = getattr(module, func_name)(__version__) + except Exception: + print(f"Error calling the plugin(version) entry point of {plugin_path}\n", file=stdout) + raise # Propagate to display traceback + + if not isinstance(plugin_type, type): + plugin_error( + 'Type object expected as the return value of "plugin"; got {!r} (in {})'.format( + plugin_type, plugin_path + ) + ) + if not issubclass(plugin_type, Plugin): + plugin_error( + 'Return value of "plugin" must be a subclass of "mypy.plugin.Plugin" ' + "(in {})".format(plugin_path) + ) + try: + custom_plugins.append(plugin_type(options)) + snapshot[module_name] = take_module_snapshot(module) + except Exception: + print(f"Error constructing plugin instance of {plugin_type.__name__}\n", file=stdout) + raise # Propagate to display traceback + + return custom_plugins, snapshot + + +def load_plugins( + options: Options, errors: Errors, stdout: TextIO, extra_plugins: Sequence[Plugin] +) -> tuple[Plugin, dict[str, str]]: + """Load all configured plugins. + + Return a plugin that encapsulates all plugins chained together. Always + at least include the default plugin (it's last in the chain). + The second return value is a snapshot of versions/hashes of loaded user + plugins (for cache validation). + """ + custom_plugins, snapshot = load_plugins_from_config(options, errors, stdout) + + custom_plugins += extra_plugins + + default_plugin: Plugin = DefaultPlugin(options) + if not custom_plugins: + return default_plugin, snapshot + + # Custom plugins take precedence over the default plugin. + return ChainedPlugin(options, custom_plugins + [default_plugin]), snapshot + + +def take_module_snapshot(module: types.ModuleType) -> str: + """Take plugin module snapshot by recording its version and hash. + + We record _both_ hash and the version to detect more possible changes + (e.g. if there is a change in modules imported by a plugin). + """ + if hasattr(module, "__file__"): + assert module.__file__ is not None + with open(module.__file__, "rb") as f: + digest = hash_digest(f.read()) + else: + digest = "unknown" + ver = getattr(module, "__version__", "none") + return f"{ver}:{digest}" + + +def find_config_file_line_number(path: str, section: str, setting_name: str) -> int: + """Return the approximate location of setting_name within mypy config file. + + Return -1 if can't determine the line unambiguously. + """ + in_desired_section = False + try: + results = [] + with open(path, encoding="UTF-8") as f: + for i, line in enumerate(f): + line = line.strip() + if line.startswith("[") and line.endswith("]"): + current_section = line[1:-1].strip() + in_desired_section = current_section == section + elif in_desired_section and re.match(rf"{setting_name}\s*=", line): + results.append(i + 1) + if len(results) == 1: + return results[0] + except OSError: + pass + return -1 + + +class BuildManager: + """This class holds shared state for building a mypy program. + + It is used to coordinate parsing, import processing, semantic + analysis and type checking. The actual build steps are carried + out by dispatch(). + + Attributes: + data_dir: Mypy data directory (contains stubs) + search_paths: SearchPaths instance indicating where to look for modules + modules: Mapping of module ID to MypyFile (shared by the passes) + semantic_analyzer: + Semantic analyzer, pass 2 + all_types: Map {Expression: Type} from all modules (enabled by export_types) + options: Build options + missing_modules: Modules that could not be imported (or intentionally skipped) + stale_modules: Set of modules that needed to be rechecked (only used by tests) + fg_deps_meta: Metadata for fine-grained dependencies caches associated with modules + fg_deps: A fine-grained dependency map + version_id: The current mypy version (based on commit id when possible) + plugin: Active mypy plugin(s) + plugins_snapshot: + Snapshot of currently active user plugins (versions and hashes) + old_plugins_snapshot: + Plugins snapshot from previous incremental run (or None in + non-incremental mode and if cache was not found) + errors: Used for reporting all errors + flush_errors: A function for processing errors after each SCC + cache_enabled: Whether cache is being read. This is set based on options, + but is disabled if fine-grained cache loading fails + and after an initial fine-grained load. This doesn't + determine whether we write cache files or not. + quickstart_state: + A cache of filename -> mtime/size/hash info used to avoid + needing to hash source files when using a cache with mismatching mtimes + stats: Dict with various instrumentation numbers, it is used + not only for debugging, but also required for correctness, + in particular to check consistency of the fine-grained dependency cache. + fscache: A file system cacher + ast_cache: AST cache to speed up mypy daemon + """ + + def __init__( + self, + data_dir: str, + search_paths: SearchPaths, + ignore_prefix: str, + source_set: BuildSourceSet, + reports: Reports | None, + options: Options, + version_id: str, + plugin: Plugin, + plugins_snapshot: dict[str, str], + errors: Errors, + flush_errors: Callable[[str | None, list[str], bool], None], + fscache: FileSystemCache, + stdout: TextIO, + stderr: TextIO, + error_formatter: ErrorFormatter | None = None, + parallel_worker: bool = False, + ) -> None: + self.stats: dict[str, Any] = {} # Values are ints or floats + self.stdout = stdout + self.stderr = stderr + self.start_time = time.time() + self.data_dir = data_dir + self.errors = errors + self.errors.set_ignore_prefix(ignore_prefix) + self.error_formatter = error_formatter + self.search_paths = search_paths + self.source_set = source_set + self.reports = reports + self.options = options + self.version_id = version_id + self.modules: dict[str, MypyFile] = {} + self.import_map: dict[str, set[str]] = {} + self.missing_modules: dict[str, int] = {} + self.fg_deps_meta: dict[str, FgDepMeta] = {} + # fg_deps holds the dependencies of every module that has been + # processed. We store this in BuildManager so that we can compute + # dependencies as we go, which allows us to free ASTs and type information, + # saving a ton of memory on net. + self.fg_deps: dict[str, set[str]] = {} + # Always convert the plugin to a ChainedPlugin so that it can be manipulated if needed + if not isinstance(plugin, ChainedPlugin): + plugin = ChainedPlugin(options, [plugin]) + self.plugin = plugin + # These allow quickly skipping logging and stats collection calls. Note + # that some stats impact mypy behavior, so be careful when skipping stats + # collection calls. + self.stats_enabled = self.options.dump_build_stats + self.logging_enabled = self.options.verbosity >= 1 + self.tracing_enabled = self.options.verbosity >= 2 + # Set of namespaces (module or class) that are being populated during semantic + # analysis and may have missing definitions. + self.incomplete_namespaces: set[str] = set() + self.semantic_analyzer = SemanticAnalyzer( + self.modules, + self.missing_modules, + self.incomplete_namespaces, + self.errors, + self.plugin, + self.import_map, + ) + self.all_types: dict[Expression, Type] = {} # Enabled by export_types + self.indirection_detector = TypeIndirectionVisitor() + self.stale_modules: set[str] = set() + self.rechecked_modules: set[str] = set() + self.flush_errors = flush_errors + has_reporters = reports is not None and reports.reporters + self.cache_enabled = ( + options.incremental + and (not options.fine_grained_incremental or options.use_fine_grained_cache) + and not has_reporters + ) + self.fscache = fscache + self.cwd = os.getcwd() + self.find_module_cache = FindModuleCache( + self.search_paths, self.fscache, self.options, source_set=self.source_set + ) + for module in CORE_BUILTIN_MODULES: + if options.use_builtins_fixtures: + continue + path = self.find_module_cache.find_module(module, fast_path=True) + if not isinstance(path, str): + raise CompileError( + [f"Failed to find builtin module {module}, perhaps typeshed is broken?"] + ) + if is_typeshed_file(options.abs_custom_typeshed_dir, path) or is_stub_package_file( + path + ): + continue + + raise CompileError( + [ + f'mypy: "{os.path.relpath(path)}" shadows library module "{module}"', + f'note: A user-defined top-level module with name "{module}" is not supported', + ] + ) + + self.metastore = create_metastore(options, parallel_worker=parallel_worker) + + # a mapping from source files to their corresponding shadow files + # for efficient lookup + self.shadow_map: dict[str, str] = {} + if self.options.shadow_file is not None: + self.shadow_map = dict(self.options.shadow_file) + # a mapping from each file being typechecked to its possible shadow file + self.shadow_equivalence_map: dict[str, str | None] = {} + self.plugin = plugin + self.plugins_snapshot = plugins_snapshot + self.old_plugins_snapshot = read_plugins_snapshot(self) + if self.verbosity() >= 2: + self.trace(f"Plugins snapshot (fresh) {json.dumps(self.plugins_snapshot)}") + self.quickstart_state = read_quickstart_file(options, self.stdout) + # Fine grained targets (module top levels and top level functions) processed by + # the semantic analyzer, used only for testing. Currently used only by the new + # semantic analyzer. Tuple of module and target name. + self.processed_targets: list[tuple[str, str]] = [] + # Missing stub packages encountered. + self.missing_stub_packages: set[str] = set() + # Cache for mypy ASTs that have completed semantic analysis + # pass 1. When multiple files are added to the build in a + # single daemon increment, only one of the files gets added + # per step and the others are discarded. This gets repeated + # until all the files have been added. This means that a + # new file can be processed O(n**2) times. This cache + # avoids most of this redundant work. + self.ast_cache: dict[str, tuple[MypyFile, list[ErrorInfo]]] = {} + # Number of times we used GC optimization hack for fresh SCCs. + self.gc_freeze_cycles = 0 + # Mapping from SCC id to corresponding SCC instance. This is populated + # in process_graph(). + self.scc_by_id: dict[int, SCC] = {} + # Mapping from module id to the SCC it belongs to. This is populated + # in process_graph(). + self.scc_by_mod_id: dict[str, SCC] = {} + # Global topological order for SCCs. This exists to make order of processing + # SCCs more predictable. + self.top_order: list[int] = [] + # Stale SCCs that are queued for processing. Each tuple contains SCC size hint, + # SCC adding order (tie-breaker), and the SCC itself. + self.scc_queue: list[tuple[int, int, SCC]] = [] + # SCCs that have been fully processed. + self.done_sccs: set[int] = set() + # Parallel build workers, list is empty for in-process type-checking. + self.workers: list[WorkerClient] = [] + # We track which workers are currently free in the coordinator process. + # This is a tiny bit faster and conceptually simpler than check which ones + # are writeable each time we want to submit an SCC for processing. + self.free_workers: set[int] = set() + # A global adding order for SCC queue, see comment above. + self.queue_order: int = 0 + # Is this an instance used by a parallel worker? + self.parallel_worker = parallel_worker + # Snapshot of import-related options per module. We record these even for + # suppressed imports, since they can affect errors in the callers. Bytes + # value is opaque but can be compared to detect changes in options. + self.import_options: dict[str, bytes] = {} + # Cache for transitive dependency check (expensive). + self.transitive_deps_cache: dict[tuple[int, int], bool] = {} + # Packages for which we know presence or absence of __getattr__(). + self.known_partial_packages: dict[str, bool] = {} + + def dump_stats(self) -> None: + if self.stats_enabled: + print("Stats:") + for key, value in sorted(self.stats_summary().items()): + print(f"{key + ':':24}{value}") + + def use_fine_grained_cache(self) -> bool: + return self.cache_enabled and self.options.use_fine_grained_cache + + def maybe_swap_for_shadow_path(self, path: str) -> str: + if not self.shadow_map: + return path + + path = normpath(path, self.options) + + previously_checked = path in self.shadow_equivalence_map + if not previously_checked: + for source, shadow in self.shadow_map.items(): + if self.fscache.samefile(path, source): + self.shadow_equivalence_map[path] = shadow + break + else: + self.shadow_equivalence_map[path] = None + + shadow_file = self.shadow_equivalence_map.get(path) + return shadow_file if shadow_file else path + + def get_stat(self, path: str) -> os.stat_result | None: + return self.fscache.stat_or_none(self.maybe_swap_for_shadow_path(path)) + + def getmtime(self, path: str) -> int: + """Return a file's mtime; but 0 in bazel mode. + + (Bazel's distributed cache doesn't like filesystem metadata to + end up in output files.) + """ + if self.options.bazel: + return 0 + else: + return int(self.metastore.getmtime(path)) + + def correct_rel_imp(self, file: MypyFile, imp: ImportFrom | ImportAll) -> str: + """Function to correct for relative imports.""" + file_id = file.fullname + rel = imp.relative + if rel == 0: + return imp.id + if os.path.basename(file.path).startswith("__init__."): + rel -= 1 + if rel != 0: + file_id = ".".join(file_id.split(".")[:-rel]) + new_id = file_id + "." + imp.id if imp.id else file_id + + if not new_id: + self.errors.set_file(file.path, file.name, self.options) + self.error( + imp.line, "No parent module -- cannot perform relative import", blocker=True + ) + + return new_id + + def all_imported_modules_in_file(self, file: MypyFile) -> list[tuple[int, str, int]]: + """Find all reachable import statements in a file. + + Return list of tuples (priority, module id, import line number) + for all modules imported in file; lower numbers == higher priority. + + Can generate blocking errors on bogus relative imports. + """ + res: list[tuple[int, str, int]] = [] + for imp in file.imports: + if not imp.is_unreachable: + if isinstance(imp, Import): + pri = import_priority(imp, PRI_MED) + ancestor_pri = import_priority(imp, PRI_LOW) + for id, _ in imp.ids: + res.append((pri, id, imp.line)) + ancestor_parts = id.split(".")[:-1] + ancestors = [] + for part in ancestor_parts: + ancestors.append(part) + res.append((ancestor_pri, ".".join(ancestors), imp.line)) + elif isinstance(imp, ImportFrom): + cur_id = self.correct_rel_imp(file, imp) + all_are_submodules = True + # Also add any imported names that are submodules. + pri = import_priority(imp, PRI_MED) + for name, __ in imp.names: + sub_id = cur_id + "." + name + if self.is_module(sub_id): + res.append((pri, sub_id, imp.line)) + else: + all_are_submodules = False + # Add cur_id as a dependency, even if all the + # imports are submodules. Processing import from will try + # to look through cur_id, so we should depend on it. + # As a workaround for some bugs in cycle handling (#4498), + # if all the imports are submodules, do the import at a lower + # priority. + pri = import_priority(imp, PRI_HIGH if not all_are_submodules else PRI_LOW) + res.append((pri, cur_id, imp.line)) + elif isinstance(imp, ImportAll): + pri = import_priority(imp, PRI_HIGH) + res.append((pri, self.correct_rel_imp(file, imp), imp.line)) + + # Sort such that module (e.g. foo.bar.baz) comes before its ancestors (e.g. foo + # and foo.bar) so that, if FindModuleCache finds the target module in a + # package marked with py.typed underneath a namespace package installed in + # site-packages, (gasp), that cache's knowledge of the ancestors + # (aka FindModuleCache.ns_ancestors) can be primed when it is asked to find + # the parent. + res.sort(key=lambda x: -x[1].count(".")) + return res + + def is_module(self, id: str) -> bool: + """Is there a file in the file system corresponding to module id?""" + return find_module_simple(id, self) is not None + + def parse_file( + self, + id: str, + path: str, + source: str, + ignore_errors: bool, + options: Options, + raw_data: FileRawData | None = None, + ) -> MypyFile: + """Parse the source of a file with the given name. + + Raise CompileError if there is a parse error. + """ + imports_only = False + if self.workers and self.fscache.exists(path): + # Currently, we can use the native parser only for actual files. + imports_only = True + t0 = time.time() + if ignore_errors: + self.errors.ignored_files.add(path) + if raw_data: + # If possible, deserialize from known binary data instead of parsing from scratch. + tree = load_from_raw(path, id, raw_data, self.errors, options) + else: + tree = parse(source, path, id, self.errors, options=options, imports_only=imports_only) + tree._fullname = id + self.add_stats( + files_parsed=1, + modules_parsed=int(not tree.is_stub), + stubs_parsed=int(tree.is_stub), + parse_time=time.time() - t0, + ) + + if self.errors.is_blockers(): + self.log("Bailing due to parse errors") + self.errors.raise_error() + return tree + + def load_fine_grained_deps(self, id: str) -> dict[str, set[str]]: + t0 = time.time() + if id in self.fg_deps_meta: + # TODO: Assert deps file wasn't changed. + deps = json_loads(self.metastore.read(self.fg_deps_meta[id]["path"])) + else: + deps = {} + val = {k: set(v) for k, v in deps.items()} + self.add_stats(load_fg_deps_time=time.time() - t0) + return val + + def report_file( + self, file: MypyFile, type_map: dict[Expression, Type], options: Options + ) -> None: + if self.reports is not None and self.source_set.is_source(file): + self.reports.file(file, self.modules, type_map, options) + + def verbosity(self) -> int: + return self.options.verbosity + + def log(self, *message: str) -> None: + if self.verbosity() >= 1: + if message: + print("LOG: ", *message, file=self.stderr) + else: + print(file=self.stderr) + self.stderr.flush() + + def log_fine_grained(self, *message: str) -> None: + if self.verbosity() >= 1: + self.log("fine-grained:", *message) + elif mypy.build.DEBUG_FINE_GRAINED: + # Output log in a simplified format that is quick to browse. + if message: + print(*message, file=self.stderr) + else: + print(file=self.stderr) + self.stderr.flush() + + def trace(self, *message: str) -> None: + if self.verbosity() >= 2: + print("TRACE:", *message, file=self.stderr) + self.stderr.flush() + + def add_stats(self, **kwds: Any) -> None: + for key, value in kwds.items(): + if key in self.stats: + self.stats[key] += value + else: + self.stats[key] = value + + def stats_summary(self) -> Mapping[str, object]: + return self.stats + + def submit(self, graph: Graph, sccs: list[SCC]) -> None: + """Submit a stale SCC for processing in current process or parallel workers.""" + if self.workers: + self.submit_to_workers(graph, sccs) + else: + self.scc_queue.extend([(0, 0, scc) for scc in sccs]) + + def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None: + if sccs is not None: + for scc in sccs: + heappush(self.scc_queue, (-scc.size_hint, self.queue_order, scc)) + self.queue_order += 1 + while self.scc_queue and self.free_workers: + idx = self.free_workers.pop() + _, _, scc = heappop(self.scc_queue) + import_errors = { + mod_id: self.errors.recorded[path] + for mod_id in scc.mod_ids + if (path := graph[mod_id].xpath) in self.errors.recorded + } + send( + self.workers[idx].conn, + SccRequestMessage( + scc_id=scc.id, + import_errors=import_errors, + mod_data={ + mod_id: ( + # Although workers don't really need to know about details + # of dependencies, they will write cache, so we need to pass + # suppressed_deps_opts() as part of module data. + graph[mod_id].suppressed_deps_opts(), + tree.raw_data if (tree := graph[mod_id].tree) else None, + ) + for mod_id in scc.mod_ids + }, + ), + ) + + def wait_for_done( + self, graph: Graph + ) -> tuple[list[SCC], bool, dict[str, tuple[str, list[str]]]]: + """Wait for a stale SCC processing to finish. + + Return a tuple three items: + * processed SCCs + * whether we have more in the queue + * new interface hash and list of errors for each module + The last item is only used for parallel processing. + """ + if self.workers: + return self.wait_for_done_workers(graph) + if not self.scc_queue: + return [], False, {} + _, _, next_scc = self.scc_queue.pop(0) + process_stale_scc(graph, next_scc, self) + return [next_scc], bool(self.scc_queue), {} + + def wait_for_done_workers( + self, graph: Graph + ) -> tuple[list[SCC], bool, dict[str, tuple[str, list[str]]]]: + if not self.scc_queue and len(self.free_workers) == len(self.workers): + return [], False, {} + + done_sccs = [] + results = {} + for idx in ready_to_read([w.conn for w in self.workers], WORKER_DONE_TIMEOUT): + data = SccResponseMessage.read(receive(self.workers[idx].conn)) + self.free_workers.add(idx) + scc_id = data.scc_id + if data.blocker is not None: + raise data.blocker + assert data.result is not None + results.update(data.result) + done_sccs.append(self.scc_by_id[scc_id]) + self.submit_to_workers(graph) # advance after some workers are free. + return ( + done_sccs, + bool(self.scc_queue) or len(self.free_workers) < len(self.workers), + results, + ) + + def is_transitive_scc_dep(self, from_scc_id: int, to_scc_id: int) -> bool: + """Check if one SCC is a (transitive) dependency of another.""" + edge = (from_scc_id, to_scc_id) + if (cached := self.transitive_deps_cache.get(edge)) is not None: + return cached + todo = self.scc_by_id[from_scc_id].deps + seen = set() + while todo: + more = set() + # Breadth-first search seems to be better here, because all + # "lower-level" SCCs are processed and some may be cached. + for dep in todo: + seen.add(dep) + if dep == to_scc_id: + self.transitive_deps_cache[edge] = True + return True + if cached := self.transitive_deps_cache.get((dep, to_scc_id)): + self.transitive_deps_cache[edge] = True + return True + elif cached is None: + more |= self.scc_by_id[dep].deps + todo = more + self.transitive_deps_cache[edge] = False + for dep in seen: + # We negative-cache all intermediate lookups, thus + # trading time for space. + self.transitive_deps_cache[(dep, to_scc_id)] = False + return False + + def error( + self, + line: int | None, + msg: str, + code: ErrorCode | None = None, + *, + blocker: bool = False, + only_once: bool = False, + ) -> None: + if line is None: + line = column = -1 + else: + column = 0 + self.errors.report(line, column, msg, code, blocker=blocker, only_once=only_once) + + def note( + self, line: int | None, msg: str, code: ErrorCode | None = None, *, only_once: bool = False + ) -> None: + if line is None: + line = column = -1 + else: + column = 0 + self.errors.report(line, column, msg, code, severity="note", only_once=only_once) + + def note_multiline( + self, line: int | None, msg: str, code: ErrorCode | None = None, *, only_once: bool = False + ) -> None: + for msg_line in dedent(msg.lstrip("\n")).splitlines(): + self.note(line, msg_line, code, only_once=only_once) + + +def deps_to_json(x: dict[str, set[str]]) -> bytes: + return json_dumps({k: list(v) for k, v in x.items()}) + + +# File for storing metadata about all the fine-grained dependency caches +DEPS_META_FILE: Final = "@deps.meta.json" +# File for storing fine-grained dependencies that didn't a parent in the build +DEPS_ROOT_FILE: Final = "@root.deps.json" + +# The name of the fake module used to store fine-grained dependencies that +# have no other place to go. +FAKE_ROOT_MODULE: Final = "@root" + + +def write_deps_cache( + rdeps: dict[str, dict[str, set[str]]], manager: BuildManager, graph: Graph +) -> None: + """Write cache files for fine-grained dependencies. + + Serialize fine-grained dependencies map for fine-grained mode. + + Dependencies on some module 'm' is stored in the dependency cache + file m.deps.json. This entails some spooky action at a distance: + if module 'n' depends on 'm', that produces entries in m.deps.json. + When there is a dependency on a module that does not exist in the + build, it is stored with its first existing parent module. If no + such module exists, it is stored with the fake module FAKE_ROOT_MODULE. + + This means that the validity of the fine-grained dependency caches + are a global property, so we store validity checking information for + fine-grained dependencies in a global cache file: + * We take a snapshot of current sources to later check consistency + between the fine-grained dependency cache and module cache metadata + * We store the mtime of all the dependency files to verify they + haven't changed + """ + metastore = manager.metastore + + error = False + + fg_deps_meta = manager.fg_deps_meta.copy() + + for id in rdeps: + if id != FAKE_ROOT_MODULE: + _, _, deps_json = get_cache_names(id, graph[id].xpath, manager.options) + else: + deps_json = DEPS_ROOT_FILE + assert deps_json + manager.log("Writing deps cache", deps_json) + if not manager.metastore.write(deps_json, deps_to_json(rdeps[id])): + manager.log(f"Error writing fine-grained deps JSON file {deps_json}") + error = True + else: + fg_deps_meta[id] = {"path": deps_json, "mtime": manager.getmtime(deps_json)} + + meta_snapshot: dict[str, str] = {} + for id, st in graph.items(): + # If we didn't parse a file (so it doesn't have a + # source_hash), then it must be a module with a fresh cache, + # so use the hash from that. + if st.source_hash: + hash = st.source_hash + else: + if st.meta: + hash = st.meta.hash + else: + hash = "" + meta_snapshot[id] = hash + + meta = {"snapshot": meta_snapshot, "deps_meta": fg_deps_meta} + + if not metastore.write(DEPS_META_FILE, json_dumps(meta)): + manager.log(f"Error writing fine-grained deps meta JSON file {DEPS_META_FILE}") + error = True + + if error: + manager.errors.set_file(_cache_dir_prefix(manager.options), None, manager.options) + manager.error(None, "Error writing fine-grained dependencies cache", blocker=True) + + +def invert_deps(deps: dict[str, set[str]], graph: Graph) -> dict[str, dict[str, set[str]]]: + """Splits fine-grained dependencies based on the module of the trigger. + + Returns a dictionary from module ids to all dependencies on that + module. Dependencies not associated with a module in the build will be + associated with the nearest parent module that is in the build, or the + fake module FAKE_ROOT_MODULE if none are. + """ + # Lazy import to speed up startup + from mypy.server.target import trigger_to_target + + # Prepopulate the map for all the modules that have been processed, + # so that we always generate files for processed modules (even if + # there aren't any dependencies to them.) + rdeps: dict[str, dict[str, set[str]]] = {id: {} for id, st in graph.items() if st.tree} + for trigger, targets in deps.items(): + module = module_prefix(graph, trigger_to_target(trigger)) + if not module or not graph[module].tree: + module = FAKE_ROOT_MODULE + + mod_rdeps = rdeps.setdefault(module, {}) + mod_rdeps.setdefault(trigger, set()).update(targets) + + return rdeps + + +def generate_deps_for_cache(manager: BuildManager, graph: Graph) -> dict[str, dict[str, set[str]]]: + """Generate fine-grained dependencies into a form suitable for serializing. + + This does a couple things: + 1. Splits fine-grained deps based on the module of the trigger + 2. For each module we generated fine-grained deps for, load any previous + deps and merge them in. + + Returns a dictionary from module ids to all dependencies on that + module. Dependencies not associated with a module in the build will be + associated with the nearest parent module that is in the build, or the + fake module FAKE_ROOT_MODULE if none are. + """ + from mypy.server.deps import merge_dependencies # Lazy import to speed up startup + + # Split the dependencies out into based on the module that is depended on. + rdeps = invert_deps(manager.fg_deps, graph) + + # We can't just clobber existing dependency information, so we + # load the deps for every module we've generated new dependencies + # to and merge the new deps into them. + for module, mdeps in rdeps.items(): + old_deps = manager.load_fine_grained_deps(module) + merge_dependencies(old_deps, mdeps) + + return rdeps + + +PLUGIN_SNAPSHOT_FILE: Final = "@plugins_snapshot.json" + + +def write_plugins_snapshot(manager: BuildManager) -> None: + """Write snapshot of versions and hashes of currently active plugins.""" + snapshot = json_dumps(manager.plugins_snapshot) + if ( + not manager.metastore.write(PLUGIN_SNAPSHOT_FILE, snapshot) + and manager.options.cache_dir != os.devnull + ): + manager.errors.set_file(_cache_dir_prefix(manager.options), None, manager.options) + manager.error(None, "Error writing plugins snapshot", blocker=True) + + +def read_plugins_snapshot(manager: BuildManager) -> dict[str, str] | None: + """Read cached snapshot of versions and hashes of plugins from previous run.""" + snapshot = _load_json_file( + PLUGIN_SNAPSHOT_FILE, + manager, + log_success="Plugins snapshot (cached) ", + log_error="Could not load plugins snapshot: ", + ) + if snapshot is None: + return None + if not isinstance(snapshot, dict): + manager.log(f"Could not load plugins snapshot: cache is not a dict: {type(snapshot)}") # type: ignore[unreachable] + return None + return snapshot + + +def read_quickstart_file( + options: Options, stdout: TextIO +) -> dict[str, tuple[float, int, str]] | None: + quickstart: dict[str, tuple[float, int, str]] | None = None + if options.quickstart_file: + # This is very "best effort". If the file is missing or malformed, + # just ignore it. + raw_quickstart: dict[str, Any] = {} + try: + with open(options.quickstart_file, "rb") as f: + raw_quickstart = json_loads(f.read()) + + quickstart = {} + for file, (x, y, z) in raw_quickstart.items(): + quickstart[file] = (x, y, z) + except Exception as e: + print(f"Warning: Failed to load quickstart file: {str(e)}\n", file=stdout) + return quickstart + + +def read_deps_cache(manager: BuildManager, graph: Graph) -> dict[str, FgDepMeta] | None: + """Read and validate the fine-grained dependencies cache. + + See the write_deps_cache documentation for more information on + the details of the cache. + + Returns None if the cache was invalid in some way. + """ + deps_meta = _load_json_file( + DEPS_META_FILE, + manager, + log_success="Deps meta ", + log_error="Could not load fine-grained dependency metadata: ", + ) + if deps_meta is None: + return None + meta_snapshot = deps_meta["snapshot"] + # Take a snapshot of the source hashes from all the metas we found. + # (Including the ones we rejected because they were out of date.) + # We use this to verify that they match up with the proto_deps. + current_meta_snapshot = { + id: st.meta_source_hash for id, st in graph.items() if st.meta_source_hash is not None + } + + common = set(meta_snapshot.keys()) & set(current_meta_snapshot.keys()) + if any(meta_snapshot[id] != current_meta_snapshot[id] for id in common): + # TODO: invalidate also if options changed (like --strict-optional)? + manager.log("Fine-grained dependencies cache inconsistent, ignoring") + return None + + module_deps_metas = deps_meta["deps_meta"] + assert isinstance(module_deps_metas, dict) + if not manager.options.skip_cache_mtime_checks: + for meta in module_deps_metas.values(): + try: + matched = manager.getmtime(meta["path"]) == meta["mtime"] + except FileNotFoundError: + matched = False + if not matched: + manager.log(f"Invalid or missing fine-grained deps cache: {meta['path']}") + return None + + return module_deps_metas + + +def _load_ff_file( + file: str, manager: BuildManager, log_error_fmt: str, id: str | None +) -> bytes | None: + if manager.stats_enabled: + t0 = time.time() + try: + data = manager.metastore.read(file) + except OSError: + if manager.logging_enabled: + if id: + message = log_error_fmt.format(id) + file + else: + message = log_error_fmt + file + manager.log(message) + return None + if manager.stats_enabled: + manager.add_stats(metastore_read_time=time.time() - t0) + return data + + +def _load_json_file( + file: str, manager: BuildManager, log_success: str, log_error: str +) -> dict[str, Any] | None: + """A simple helper to read a JSON file with logging.""" + t0 = time.time() + try: + data = manager.metastore.read(file) + except OSError: + manager.log(log_error + file) + return None + manager.add_stats(metastore_read_time=time.time() - t0) + # Only bother to compute the log message if we are logging it, since it could be big + if manager.verbosity() >= 2: + manager.trace(log_success + data.rstrip().decode()) + try: + t1 = time.time() + result = json_loads(data) + manager.add_stats(data_file_load_time=time.time() - t1) + except json.JSONDecodeError: + manager.errors.set_file(file, None, manager.options) + manager.error( + None, + "Error reading JSON file;" + " you likely have a bad cache.\n" + "Try removing the {cache_dir} directory" + " and run mypy again.".format(cache_dir=manager.options.cache_dir), + blocker=True, + ) + return None + else: + assert isinstance(result, dict) + return result + + +def _cache_dir_prefix(options: Options) -> str: + """Get current cache directory (or file if id is given).""" + if options.bazel: + # This is needed so the cache map works. + return os.curdir + cache_dir = options.cache_dir + pyversion = options.python_version + base = os_path_join(cache_dir, "%d.%d" % pyversion) + return base + + +def add_catch_all_gitignore(target_dir: str) -> None: + """Add catch-all .gitignore to an existing directory. + + No-op if the .gitignore already exists. + """ + gitignore = os_path_join(target_dir, ".gitignore") + try: + with open(gitignore, "x") as f: + print("# Automatically created by mypy", file=f) + print("*", file=f) + except FileExistsError: + pass + + +def exclude_from_backups(target_dir: str) -> None: + """Exclude the directory from various archives and backups supporting CACHEDIR.TAG. + + If the CACHEDIR.TAG file exists the function is a no-op. + """ + cachedir_tag = os_path_join(target_dir, "CACHEDIR.TAG") + try: + with open(cachedir_tag, "x") as f: + f.write("""Signature: 8a477f597d28d172789f06886806bc55 +# This file is a cache directory tag automatically created by mypy. +# For information about cache directory tags see https://bford.info/cachedir/ +""") + except FileExistsError: + pass + + +def create_metastore(options: Options, parallel_worker: bool) -> MetadataStore: + """Create the appropriate metadata store.""" + if options.sqlite_cache: + mds: MetadataStore = SqliteMetadataStore( + _cache_dir_prefix(options), set_journal_mode=not parallel_worker + ) + else: + mds = FilesystemMetadataStore(_cache_dir_prefix(options)) + return mds + + +def get_errors_name(meta_name: str) -> str: + # Convert e.g. foo.bar.meta.ff to foo.bar.err.ff + parts = meta_name.rsplit(".", maxsplit=2) + parts[1] = "err" + return ".".join(parts) + + +def get_cache_names(id: str, path: str, options: Options) -> tuple[str, str, str | None]: + """Return the file names for the cache files. + + Args: + id: module ID + path: module path + options: build options + + Returns: + A tuple with the file names to be used for the meta file, the + data file, and the fine-grained deps JSON, respectively. + """ + if options.cache_map: + pair = options.cache_map.get(normpath(path, options)) + else: + pair = None + if pair is not None: + # The cache map paths were specified relative to the base directory, + # but the filesystem metastore APIs operates relative to the cache + # prefix directory. + # Solve this by rewriting the paths as relative to the root dir. + # This only makes sense when using the filesystem backed cache. + root = _cache_dir_prefix(options) + return os.path.relpath(pair[0], root), os.path.relpath(pair[1], root), None + prefix = os.path.join(*id.split(".")) + is_package = os.path.basename(path).startswith("__init__.py") + if is_package: + prefix = os_path_join(prefix, "__init__") + + deps_json = None + if options.cache_fine_grained: + deps_json = prefix + ".deps.json" + if options.fixed_format_cache: + data_suffix = ".data.ff" + meta_suffix = ".meta.ff" + else: + data_suffix = ".data.json" + meta_suffix = ".meta.json" + return prefix + meta_suffix, prefix + data_suffix, deps_json + + +def options_snapshot(id: str, manager: BuildManager) -> dict[str, object]: + """Make compact snapshot of options for a module. + + Separately store only the options we may compare individually, and take a hash + of everything else. If --debug-cache is specified, fall back to full snapshot. + """ + platform_opt, values = manager.options.clone_for_module(id).select_options_affecting_cache() + if manager.options.debug_cache: + # Build full options snapshot for debugging purposes. + result: dict[str, object] = {"platform": platform_opt} + for key, val in zip(OPTIONS_AFFECTING_CACHE_NO_PLATFORM, values): + result[key] = val + return result + # Process most options quickly, since this is performance critical. + buf = WriteBuffer() + write_json_value(buf, cast(JsonValue, values)) + return {"platform": platform_opt, "other_options": hash_digest(buf.getvalue())} + + +def find_cache_meta( + id: str, path: str, manager: BuildManager, skip_validation: bool = False +) -> tuple[CacheMeta | None, list[ErrorTuple]]: + """Find cache data for a module. + + Args: + id: module ID + path: module path + manager: the build manager (for pyversion, log/trace, and build options) + skip_validation: if True skip any validation steps (used for parallel checking) + + Returns: + A CacheMeta instance if the cache data was found and appears + valid; otherwise None. + """ + # TODO: May need to take more build options into account + meta_file, data_file, _ = get_cache_names(id, path, manager.options) + if manager.tracing_enabled: + manager.trace(f"Looking for {id} at {meta_file}") + if manager.stats_enabled: + t0 = time.time() + if manager.options.fixed_format_cache: + meta = _load_ff_file( + meta_file, manager, log_error_fmt="Could not load cache for {}: ", id=id + ) + else: + meta = _load_json_file( + meta_file, + manager, + log_success=f"Meta {id} ", + log_error=f"Could not load cache for {id}: ", + ) + if meta is None: + return None, [] + if manager.stats_enabled: + t1 = time.time() + if isinstance(meta, bytes): + # If either low-level buffer format or high-level cache layout changed, we + # cannot use the cache files, even with --skip-version-check. + # TODO: switch to something like librt.internal.read_byte() if this is slow. + if meta[0] != cache_version() or meta[1] != CACHE_VERSION: + manager.log(f"Metadata abandoned for {id}: incompatible cache format") + return None, [] + data_io = ReadBuffer(meta[2:]) + m = CacheMeta.read(data_io, data_file) + else: + m = CacheMeta.deserialize(meta, data_file) + if m is None: + manager.log(f"Metadata abandoned for {id}: cannot deserialize data") + return None, [] + if manager.stats_enabled: + t2 = time.time() + manager.add_stats( + load_meta_time=t2 - t0, load_meta_load_time=t1 - t0, load_meta_from_dict_time=t2 - t1 + ) + if skip_validation: + return m, [] + + # Ignore cache if generated by an older mypy version. + if m.version_id != manager.version_id and not manager.options.skip_version_check: + manager.log(f"Metadata abandoned for {id}: different mypy version") + return None, [] + + total_deps = len(m.dependencies) + len(m.suppressed) + if len(m.dep_prios) != total_deps or len(m.dep_lines) != total_deps: + manager.log(f"Metadata abandoned for {id}: broken dependencies") + return None, [] + + # Ignore cache if (relevant) options aren't the same. + # Note that it's fine to mutilate cached_options since it's only used here. + cached_options = m.options + current_options = options_snapshot(id, manager) + if manager.options.skip_version_check: + # When we're lax about version we're also lax about platform. + cached_options["platform"] = current_options["platform"] + if "debug_cache" in cached_options: + # Older versions included debug_cache, but it's silly to compare it. + del cached_options["debug_cache"] + if cached_options != current_options: + manager.log(f"Metadata abandoned for {id}: options differ") + if manager.options.verbosity >= 2: + for key in sorted(set(cached_options) | set(current_options)): + if cached_options.get(key) != current_options.get(key): + manager.trace( + " {}: {} != {}".format( + key, cached_options.get(key), current_options.get(key) + ) + ) + return None, [] + if manager.old_plugins_snapshot and manager.plugins_snapshot: + # Check if plugins are still the same. + if manager.plugins_snapshot != manager.old_plugins_snapshot: + manager.log(f"Metadata abandoned for {id}: plugins differ") + return None, [] + plugin_data = manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=True)) + if not manager.options.fixed_format_cache: + # So that plugins can return data with tuples in it without + # things silently always invalidating modules, we round-trip + # the config data. This isn't beautiful. + plugin_data = json_loads(json_dumps(plugin_data)) + if m.plugin_data != plugin_data: + manager.log(f"Metadata abandoned for {id}: plugin configuration differs") + return None, [] + + # Load cached errors for this file, even if empty. This is needed to avoid + # invalid cache state after a crash/blocker/Ctrl+C etc. + errors_file = get_errors_name(meta_file) + if manager.options.fixed_format_cache: + errors = _load_ff_file( + errors_file, manager, log_error_fmt="Could not load errors for {}: ", id=id + ) + else: + errors = _load_json_file( + errors_file, + manager, + log_success=f"Errors {id} ", + log_error=f"Could not load errors for {id}: ", + ) + if errors is None: + return None, [] + if isinstance(errors, bytes): + data_io = ReadBuffer(errors) + e = read_errors(data_io) + else: + e = [tuple(err) for err in errors["error_lines"]] + manager.add_stats(fresh_metas=1) + return m, e + + +def validate_meta( + meta: CacheMeta | None, id: str, path: str | None, ignore_all: bool, manager: BuildManager +) -> CacheMeta | None: + """Checks whether the cached AST of this module can be used. + + Returns: + None, if the cached AST is unusable. + Original meta, if mtime/size matched. + Meta with mtime updated to match source file, if hash/size matched but mtime/path didn't. + """ + # This requires two steps. The first one is obvious: we check that the module source file + # contents is the same as it was when the cache data file was created. The second one is not + # too obvious: we check that the cache data file mtime has not changed; it is needed because + # we use cache data file mtime to propagate information about changes in the dependencies. + + if meta is None: + manager.log(f"Metadata not found for {id}") + return None + + if meta.ignore_all and not ignore_all: + manager.log(f"Metadata abandoned for {id}: errors were previously ignored") + return None + + if manager.stats_enabled: + t0 = time.time() + bazel = manager.options.bazel + assert path is not None, "Internal error: meta was provided without a path" + if not manager.options.skip_cache_mtime_checks: + # Check data_file; assume if its mtime matches it's good. + try: + data_mtime = manager.getmtime(meta.data_file) + except OSError: + manager.log(f"Metadata abandoned for {id}: failed to stat data_file") + return None + if data_mtime != meta.data_mtime: + manager.log(f"Metadata abandoned for {id}: data cache is modified") + return None + + if bazel: + # Normalize path under bazel to make sure it isn't absolute + path = normpath(path, manager.options) + + st = manager.get_stat(path) + if st is None: + return None + if not stat.S_ISDIR(st.st_mode) and not stat.S_ISREG(st.st_mode): + manager.log(f"Metadata abandoned for {id}: file or directory {path} does not exist") + return None + + if manager.stats_enabled: + manager.add_stats(validate_stat_time=time.time() - t0) + + # When we are using a fine-grained cache, we want our initial + # build() to load all of the cache information and then do a + # fine-grained incremental update to catch anything that has + # changed since the cache was generated. We *don't* want to do a + # coarse-grained incremental rebuild, so we accept the cache + # metadata even if it doesn't match the source file. + # + # We still *do* the mtime/hash checks, however, to enable + # fine-grained mode to take advantage of the mtime-updating + # optimization when mtimes differ but hashes match. There is + # essentially no extra time cost to computing the hash here, since + # it will be cached and will be needed for finding changed files + # later anyways. + fine_grained_cache = manager.use_fine_grained_cache() + + size = st.st_size + # Bazel ensures the cache is valid. + if size != meta.size and not bazel and not fine_grained_cache: + manager.log(f"Metadata abandoned for {id}: file {path} has different size") + return None + + # Bazel ensures the cache is valid. + mtime = 0 if bazel else int(st.st_mtime) + if not bazel and (mtime != meta.mtime or path != meta.path): + if manager.quickstart_state and path in manager.quickstart_state: + # If the mtime and the size of the file recorded in the quickstart dump matches + # what we see on disk, we know (assume) that the hash matches the quickstart + # data as well. If that hash matches the hash in the metadata, then we know + # the file is up to date even though the mtime is wrong, without needing to hash it. + qmtime, qsize, qhash = manager.quickstart_state[path] + if int(qmtime) == mtime and qsize == size and qhash == meta.hash: + manager.log(f"Metadata fresh (by quickstart) for {id}: file {path}") + meta.mtime = mtime + meta.path = path + return meta + + t0 = time.time() + try: + # dir means it is a namespace package + if stat.S_ISDIR(st.st_mode): + source_hash = "" + else: + source_hash = manager.fscache.hash_digest(path) + except (OSError, UnicodeDecodeError, DecodeError): + return None + manager.add_stats(validate_hash_time=time.time() - t0) + if source_hash != meta.hash: + if fine_grained_cache: + manager.log(f"Using stale metadata for {id}: file {path}") + return meta + else: + manager.log(f"Metadata abandoned for {id}: file {path} has different hash") + return None + else: + if manager.stats_enabled: + t0 = time.time() + # Optimization: update mtime and path (otherwise, this mismatch will reappear). + meta.mtime = mtime + meta.path = path + meta.size = size + meta.options = options_snapshot(id, manager) + meta_file, _, _ = get_cache_names(id, path, manager.options) + if manager.logging_enabled: + manager.log( + "Updating mtime for {}: file {}, meta {}, mtime {}".format( + id, path, meta_file, meta.mtime + ) + ) + write_cache_meta(meta, manager, meta_file) + if manager.stats_enabled: + t1 = time.time() + manager.add_stats( + validate_update_time=time.time() - t1, validate_munging_time=t1 - t0 + ) + return meta + + # It's a match on (id, path, size, hash, mtime). + if manager.logging_enabled: + manager.log(f"Metadata fresh for {id}: file {path}") + return meta + + +def compute_hash(text: str) -> str: + # We use a crypto hash instead of the builtin hash(...) function + # because the output of hash(...) can differ between runs due to + # hash randomization (enabled by default in Python 3.3). See the + # note in + # https://docs.python.org/3/reference/datamodel.html#object.__hash__. + return hash_digest(text.encode("utf-8")) + + +def write_cache( + id: str, + path: str, + tree: MypyFile, + dependencies: list[str], + suppressed: list[str], + suppressed_deps_opts: bytes, + imports_ignored: dict[int, list[str]], + dep_prios: list[int], + dep_lines: list[int], + old_interface_hash: bytes, + trans_dep_hash: bytes, + source_hash: str, + ignore_all: bool, + manager: BuildManager, +) -> tuple[bytes, tuple[CacheMeta, str] | None]: + """Write cache files for a module. + + Note that this mypy's behavior is still correct when any given + write_cache() call is replaced with a no-op, so error handling + code that bails without writing anything is okay. + + Args: + id: module ID + path: module path + tree: the fully checked module data + dependencies: module IDs on which this module depends + suppressed: module IDs which were suppressed as dependencies + dep_prios: priorities (parallel array to dependencies) + dep_lines: import line locations (parallel array to dependencies) + old_interface_hash: the hash from the previous version of the data cache file + source_hash: the hash of the source code + ignore_all: the ignore_all flag for this module + manager: the build manager (for pyversion, log/trace) + + Returns: + A tuple containing the interface hash and inner tuple with CacheMeta + that should be written and path to cache file (inner tuple may be None, + if the cache data could not be written). + """ + metastore = manager.metastore + # For Bazel we use relative paths and zero mtimes. + bazel = manager.options.bazel + + # Obtain file paths. + meta_file, data_file, _ = get_cache_names(id, path, manager.options) + manager.log(f"Writing {id} {path} {meta_file} {data_file}") + + # Update tree.path so that in bazel mode it's made relative (since + # sometimes paths leak out). + if bazel: + tree.path = path + + plugin_data = manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=False)) + + # Serialize data and analyze interface + if manager.options.fixed_format_cache: + data_io = WriteBuffer() + tree.write(data_io) + data_bytes = data_io.getvalue() + else: + data = tree.serialize() + data_bytes = json_dumps(data, manager.options.debug_cache) + interface_hash = hash_digest_bytes(data_bytes + json_dumps(plugin_data)) + + # Obtain and set up metadata + st = manager.get_stat(path) + if st is None: + manager.log(f"Cannot get stat for {path}") + # Remove apparently-invalid cache files. + # (This is purely an optimization.) + for filename in [data_file, meta_file]: + try: + os.remove(filename) + except OSError: + pass + # Still return the interface hash we computed. + return interface_hash, None + + # Write data cache file, if applicable + # Note that for Bazel we don't record the data file's mtime. + if old_interface_hash == interface_hash: + manager.trace(f"Interface for {id} is unchanged") + else: + manager.trace(f"Interface for {id} has changed") + if not metastore.write(data_file, data_bytes): + # Most likely the error is the replace() call + # (see https://github.com/python/mypy/issues/3215). + manager.log(f"Error writing cache data file {data_file}") + # Let's continue without writing the meta file. Analysis: + # If the replace failed, we've changed nothing except left + # behind an extraneous temporary file; if the replace + # worked but the getmtime() call failed, the meta file + # will be considered invalid on the next run because the + # data_mtime field won't match the data file's mtime. + # Both have the effect of slowing down the next run a + # little bit due to an out-of-date cache file. + return interface_hash, None + + try: + data_mtime = manager.getmtime(data_file) + except OSError: + manager.log(f"Error in os.stat({data_file!r}), skipping cache write") + return interface_hash, None + + mtime = 0 if bazel else int(st.st_mtime) + size = st.st_size + # Note that the options we store in the cache are the options as + # specified by the command line/config file and *don't* reflect + # updates made by inline config directives in the file. This is + # important, or otherwise the options would never match when + # verifying the cache. + assert source_hash is not None + meta = CacheMeta( + id=id, + path=path, + mtime=mtime, + size=size, + hash=source_hash, + dependencies=dependencies, + data_mtime=data_mtime, + data_file=data_file, + suppressed=suppressed, + imports_ignored=imports_ignored, + options=options_snapshot(id, manager), + suppressed_deps_opts=suppressed_deps_opts, + dep_prios=dep_prios, + dep_lines=dep_lines, + interface_hash=interface_hash, + trans_dep_hash=trans_dep_hash, + version_id=manager.version_id, + ignore_all=ignore_all, + plugin_data=plugin_data, + # This one will be filled by the caller. + dep_hashes=[], + ) + return interface_hash, (meta, meta_file) + + +def write_cache_meta(meta: CacheMeta, manager: BuildManager, meta_file: str) -> None: + # Write meta cache file + metastore = manager.metastore + if manager.options.fixed_format_cache: + data_io = WriteBuffer() + meta.write(data_io) + # Prefix with both low- and high-level cache format versions for future validation. + # TODO: switch to something like librt.internal.write_byte() if this is slow. + meta_bytes = bytes([cache_version(), CACHE_VERSION]) + data_io.getvalue() + else: + meta_dict = meta.serialize() + meta_bytes = json_dumps(meta_dict, manager.options.debug_cache) + if not metastore.write(meta_file, meta_bytes): + # Most likely the error is the replace() call + # (see https://github.com/python/mypy/issues/3215). + # The next run will simply find the cache entry out of date. + manager.log(f"Error writing cache meta file {meta_file}") + + +def write_errors_file( + meta_file: str, error_lines: list[ErrorTuple], manager: BuildManager +) -> None: + # Write errors cache file + errors_file = get_errors_name(meta_file) + metastore = manager.metastore + if manager.options.fixed_format_cache: + data_io = WriteBuffer() + write_errors(data_io, error_lines) + meta_bytes = data_io.getvalue() + else: + # Some generic JSON helpers require top-level to be a dict. + meta_bytes = json_dumps({"error_lines": error_lines}, manager.options.debug_cache) + if not metastore.write(errors_file, meta_bytes): + manager.log(f"Error writing errors file {errors_file}") + + +"""Dependency manager. + +Design +====== + +Ideally +------- + +A. Collapse cycles (each SCC -- strongly connected component -- + becomes one "supernode"). + +B. Topologically sort nodes based on dependencies. + +C. Process from leaves towards roots. + +Wrinkles +-------- + +a. Need to parse source modules to determine dependencies. + +b. Processing order for modules within an SCC. + +c. Must order mtimes of files to decide whether to re-process; depends + on clock never resetting. + +d. from P import M; checks filesystem whether module P.M exists in + filesystem. + +e. Race conditions, where somebody modifies a file while we're + processing. Solved by using a FileSystemCache. + + +Steps +----- + +1. For each explicitly given module find the source file location. + +2. For each such module load and check the cache metadata, and decide + whether it's valid. + +3. Now recursively (or iteratively) find dependencies and add those to + the graph: + + - for cached nodes use the list of dependencies from the cache + metadata (this will be valid even if we later end up re-parsing + the same source); + + - for uncached nodes parse the file and process all imports found, + taking care of (a) above. + +Step 3 should also address (d) above. + +Once step 3 terminates we have the entire dependency graph, and for +each module we've either loaded the cache metadata or parsed the +source code. (However, we may still need to parse those modules for +which we have cache metadata but that depend, directly or indirectly, +on at least one module for which the cache metadata is stale.) + +Now we can execute steps A-C from the first section. Finding SCCs for +step A shouldn't be hard; there's a recipe here: +https://code.activestate.com/recipes/578507/. There's also a plethora +of topsort recipes, e.g. https://code.activestate.com/recipes/577413/. + +For single nodes, processing is simple. If the node was cached, we +deserialize the cache data and fix up cross-references. Otherwise, we +do semantic analysis followed by type checking. Once we (re-)processed +an SCC we check whether its interface (symbol table) is still fresh +(matches previous cached value). If it is not, we consider dependent SCCs +stale so that they need to be re-parsed as well. + +Note on indirect dependencies: normally dependencies are determined from +imports, but since our interfaces are "opaque" (i.e. symbol tables can +contain cross-references as well as types identified by name), these are not +enough. We *must* also add "indirect" dependencies from symbols and types to +their definitions. For this purpose, we record all accessed symbols during +semantic analysis, and after we finished processing a module, we traverse its +type map, and for each type we find (transitively) on which named types it +depends. + +Import cycles +------------- + +Finally we have to decide how to handle (b), import cycles. Here +we'll need a modified version of the original state machine +(build.py), but we only need to do this per SCC, and we won't have to +deal with changes to the list of nodes while we're processing it. + +If all nodes in the SCC have valid cache metadata and all dependencies +outside the SCC are still valid, we can proceed as follows: + + 1. Load cache data for all nodes in the SCC. + + 2. Fix up cross-references for all nodes in the SCC. + +Otherwise, the simplest (but potentially slow) way to proceed is to +invalidate all cache data in the SCC and re-parse all nodes in the SCC +from source. We can do this as follows: + + 1. Parse source for all nodes in the SCC. + + 2. Semantic analysis for all nodes in the SCC. + + 3. Type check all nodes in the SCC. + +(If there are more passes the process is the same -- each pass should +be done for all nodes before starting the next pass for any nodes in +the SCC.) + +We could process the nodes in the SCC in any order. For sentimental +reasons, I've decided to process them in the reverse order in which we +encountered them when originally constructing the graph. That's how +the old build.py deals with cycles, and at least this reproduces the +previous implementation more accurately. + +Can we do better than re-parsing all nodes in the SCC when any of its +dependencies are out of date? It's doubtful. The optimization +mentioned at the end of the previous section would require re-parsing +and type-checking a node and then comparing its symbol table to the +cached data; but because the node is part of a cycle we can't +technically type-check it until the semantic analysis of all other +nodes in the cycle has completed. (This is an important issue because +Dropbox has a very large cycle in production code. But I'd like to +deal with it later.) + +Additional wrinkles +------------------- + +During implementation more wrinkles were found. + +- When a submodule of a package (e.g. x.y) is encountered, the parent + package (e.g. x) must also be loaded, but it is not strictly a + dependency. See State.add_ancestors() below. +""" + + +class SuppressionReason: + NOT_FOUND: Final = 1 + SKIPPED: Final = 2 + + +class ModuleNotFound(Exception): + """Control flow exception to signal that a module was not found.""" + + def __init__(self, reason: int = SuppressionReason.NOT_FOUND) -> None: + self.reason = reason + + +@final +class State: + """The state for a module. + + The source is only used for the -c command line option; in that + case path is None. Otherwise, source is None and path isn't. + """ + + manager: BuildManager + order_counter: ClassVar[int] = 0 + order: int # Order in which modules were encountered + id: str # Fully qualified module name + path: str | None = None # Path to module source + abspath: str | None = None # Absolute path to module source + xpath: str # Path or '' + source: str | None = None # Module source code + source_hash: str | None = None # Hash calculated based on the source code + meta_source_hash: str | None = None # Hash of the source given in the meta, if any + meta: CacheMeta | None = None + tree: MypyFile | None = None + # We keep both a list and set of dependencies. A set because it makes it efficient to + # prevent duplicates and the list because I am afraid of changing the order of + # iteration over dependencies. + # They should be managed with add_dependency and suppress_dependency. + dependencies: list[str] # Modules directly imported by the module + dependencies_set: set[str] # The same but as a set for deduplication purposes + suppressed: list[str] # Suppressed/missing dependencies + suppressed_set: set[str] # Suppressed/missing dependencies + priorities: dict[str, int] + + # Map each dependency to the line number where it is first imported + dep_line_map: dict[str, int] + + # Map from dependency id to its last observed interface hash + dep_hashes: dict[str, bytes] + + # List of errors reported for this file last time. + error_lines: list[ErrorTuple] + + # Parent package, its parent, etc. + ancestors: list[str] | None = None + + # List of (path, line number) tuples giving context for import + import_context: list[tuple[str, int]] + + # If caller_state is set, the line number in the caller where the import occurred + caller_line = 0 + + # Contains a hash of the public interface in incremental mode + interface_hash: bytes = b"" + + # Hash of import structure that this module depends on. It is not 1:1 with + # transitive dependencies set, but if two hashes are equal, transitive + # dependencies are guaranteed to be identical. Some expensive checks can be + # skipped if this value is unchanged for a module. + trans_dep_hash: bytes = b"" + + # Options, specialized for this file + options: Options + + # Whether to ignore all errors + ignore_all = False + + # Errors reported before semantic analysis, to allow fine-grained + # mode to keep reporting them. + early_errors: list[ErrorInfo] + + # Type checker used for checking this file. Use type_checker() for + # access and to construct this on demand. + _type_checker: TypeChecker | None = None + + fine_grained_deps_loaded = False + + # Cumulative time spent on this file, in microseconds (for profiling stats) + time_spent_us: int = 0 + + # Per-line type-checking time (cumulative time spent type-checking expressions + # on a given source code line). + per_line_checking_time_ns: dict[int, int] + + # Rough estimate of how much time it would take to process this file. Currently, + # we use file size as a proxy for complexity. + size_hint: int + + # Mapping from line number to type ignore codes on this line (for imports only). + imports_ignored: dict[int, list[str]] + + @staticmethod + def new_state( + id: str | None, + path: str | None, + source: str | None, + manager: BuildManager, + caller_state: State | None = None, + caller_line: int = 0, + ancestor_for: State | None = None, + root_source: bool = False, + # If `temporary` is True, this State is being created to just + # quickly parse/load the tree, without an intention to further + # process it. With this flag, any changes to external state as well + # as error reporting should be avoided. + temporary: bool = False, + ) -> State: + if not temporary: + assert id or path or source is not None, "Neither id, path nor source given" + State.order_counter += 1 + if caller_state: + import_context = caller_state.import_context.copy() + import_context.append((caller_state.xpath, caller_line)) + else: + import_context = [] + id = id or "__main__" + options = manager.options.clone_for_module(id) + manager.import_options[id] = options.dep_import_options() + + ignore_all = False + if not path and source is None: + assert id is not None + try: + path, follow_imports = find_module_and_diagnose( + manager, + id, + options, + caller_state, + caller_line, + ancestor_for, + root_source, + skip_diagnose=temporary, + ) + except ModuleNotFound as exc: + if not temporary: + manager.missing_modules[id] = exc.reason + raise + if follow_imports == "silent": + ignore_all = True + elif path and is_silent_import_module(manager, path) and not root_source: + ignore_all = True + + meta = None + interface_hash = b"" + meta_source_hash = None + if path and source is None and manager.cache_enabled: + meta, error_lines = find_cache_meta(id, path, manager) + # TODO: Get mtime if not cached. + if meta is not None: + interface_hash = meta.interface_hash + meta_source_hash = meta.hash + if path and source is None and manager.fscache.isdir(path): + source = "" + + if manager.stats_enabled: + t0 = time.time() + meta = validate_meta(meta, id, path, ignore_all, manager) + if manager.stats_enabled: + manager.add_stats(validate_meta_time=time.time() - t0) + + if meta: + # Make copies, since we may modify these and want to + # compare them to the originals later. + dependencies = list(meta.dependencies) + suppressed = list(meta.suppressed) + all_deps = dependencies + suppressed + assert len(all_deps) == len(meta.dep_prios) + priorities = {id: pri for id, pri in zip(all_deps, meta.dep_prios)} + assert len(all_deps) == len(meta.dep_lines) + dep_line_map = {id: line for id, line in zip(all_deps, meta.dep_lines)} + assert len(meta.dep_hashes) == len(meta.dependencies) + dep_hashes = {k: v for (k, v) in zip(meta.dependencies, meta.dep_hashes)} + # Only copy `error_lines` if the module is not silently imported. + error_lines = [] if ignore_all else error_lines + imports_ignored = meta.imports_ignored + else: + dependencies = [] + suppressed = [] + priorities = {} + dep_line_map = {} + dep_hashes = {} + error_lines = [] + imports_ignored = {} + + state = State( + manager=manager, + order=State.order_counter, + id=id, + path=path, + source=source, + options=options, + ignore_all=ignore_all, + caller_line=caller_line, + import_context=import_context, + meta=meta, + interface_hash=interface_hash, + meta_source_hash=meta_source_hash, + dependencies=dependencies, + suppressed=suppressed, + priorities=priorities, + dep_line_map=dep_line_map, + dep_hashes=dep_hashes, + error_lines=error_lines, + imports_ignored=imports_ignored, + ) + + if meta: + if temporary: + state.load_tree(temporary=True) + if not manager.use_fine_grained_cache(): + # Special case: if there were a previously missing package imported here, + # and it is not present, then we need to re-calculate dependencies. + # This is to support patterns like this: + # from missing_package import missing_module # type: ignore + # At first mypy doesn't know that `missing_module` is a module + # (it may be a variable, a class, or a function), so it is not added to + # suppressed dependencies. Therefore, when the package with module is added, + # we need to re-calculate dependencies. + # NOTE: see comment below for why we skip this in fine-grained mode. + if exist_added_packages(suppressed, manager): + state.parse_file() # This is safe because the cache is anyway stale. + state.compute_dependencies() + # This is an inverse to the situation above. If we had an import like this: + # from pkg import mod + # and then mod was deleted, we need to force recompute dependencies, to + # decide whether we should still depend on a missing pkg.mod. Otherwise, + # the above import is indistinguishable from something like this: + # import pkg + # import pkg.mod + if exist_removed_submodules(dependencies, manager): + state.parse_file() # Same as above, the current state is stale anyway. + state.compute_dependencies() + state.size_hint = meta.size + else: + # When doing a fine-grained cache load, pretend we only + # know about modules that have cache information and defer + # handling new modules until the fine-grained update. + if manager.use_fine_grained_cache(): + manager.log(f"Deferring module to fine-grained update {path} ({id})") + raise ModuleNotFound + + # Parse the file (and then some) to get the dependencies. + state.parse_file(temporary=temporary) + state.compute_dependencies() + if manager.workers and state.tree: + # We don't need imports in coordinator process anymore, we parse only to + # compute dependencies. + state.tree.imports = [] + del manager.ast_cache[id] + + return state + + def __init__( + self, + manager: BuildManager, + order: int, + id: str, + path: str | None, + source: str | None, + options: Options, + ignore_all: bool, + caller_line: int, + import_context: list[tuple[str, int]], + meta: CacheMeta | None, + interface_hash: bytes, + meta_source_hash: str | None, + dependencies: list[str], + suppressed: list[str], + priorities: dict[str, int], + dep_line_map: dict[str, int], + dep_hashes: dict[str, bytes], + error_lines: list[ErrorTuple], + imports_ignored: dict[int, list[str]], + size_hint: int = 0, + ) -> None: + self.manager = manager + self.order = order + self.id = id + self.path = path + if path: + # Avoid calling os.abspath, since it makes a getcwd() syscall, which is slow + if os.path.isabs(path): + self.abspath = path + else: + self.abspath = os.path.normpath(os_path_join(manager.cwd, path)) + self.xpath = path or "" + self.source = source + self.options = options + self.ignore_all = ignore_all + self.caller_line = caller_line + self.import_context = import_context + self.meta = meta + self.interface_hash = interface_hash + self.meta_source_hash = meta_source_hash + self.dependencies = dependencies + self.suppressed = suppressed + self.dependencies_set = set(dependencies) + self.suppressed_set = set(suppressed) + self.priorities = priorities + self.dep_line_map = dep_line_map + self.dep_hashes = dep_hashes + self.error_lines = error_lines + self.per_line_checking_time_ns = collections.defaultdict(int) + self.early_errors = [] + self._type_checker = None + self.add_ancestors() + self.imports_ignored = imports_ignored + self.size_hint = size_hint + # Pre-computed opaque value of suppressed_deps_opts() used + # to minimize amount of data sent to parallel workers. + self.known_suppressed_deps_opts: bytes | None = None + + def write(self, buf: WriteBuffer) -> None: + """Serialize State for sending to build worker. + + Note that unlike write() methods for most other classes, this one is + not idempotent. We erase some bulky values that should either be not needed + for processing by the worker, or can be re-created from other data relatively + quickly. These are: + * self.meta: workers will call self.reload_meta() anyway. + * self.options: can be restored with Options.clone_for_module(). + * self.error_lines: fresh errors are handled by the coordinator. + """ + write_int(buf, self.order) + write_str(buf, self.id) + write_str_opt(buf, self.path) + write_str_opt(buf, self.source) # mostly for mypy -c '' + write_bool(buf, self.ignore_all) + write_int(buf, self.caller_line) + write_tag(buf, LIST_GEN) + write_int_bare(buf, len(self.import_context)) + for path, line in self.import_context: + write_str(buf, path) + write_int(buf, line) + write_bytes(buf, self.interface_hash) + write_str_opt(buf, self.meta_source_hash) + write_str_list(buf, self.dependencies) + write_str_list(buf, self.suppressed) + # TODO: we can possibly serialize these dictionaries in a more compact way. + # Most keys in the dictionaries should be the same, so we can write them once. + write_tag(buf, DICT_STR_GEN) + write_int_bare(buf, len(self.priorities)) + for mod_id, prio in self.priorities.items(): + write_str_bare(buf, mod_id) + write_int(buf, prio) + write_tag(buf, DICT_STR_GEN) + write_int_bare(buf, len(self.dep_line_map)) + for mod_id, line in self.dep_line_map.items(): + write_str_bare(buf, mod_id) + write_int(buf, line) + write_tag(buf, DICT_STR_GEN) + write_int_bare(buf, len(self.dep_hashes)) + for mod_id, dep_hash in self.dep_hashes.items(): + write_str_bare(buf, mod_id) + write_bytes(buf, dep_hash) + write_int(buf, self.size_hint) + + @classmethod + def read(cls, buf: ReadBuffer, manager: BuildManager) -> State: + order = read_int(buf) + id = read_str(buf) + path = read_str_opt(buf) + source = read_str_opt(buf) + ignore_all = read_bool(buf) + caller_line = read_int(buf) + assert read_tag(buf) == LIST_GEN + import_context = [(read_str(buf), read_int(buf)) for _ in range(read_int_bare(buf))] + interface_hash = read_bytes(buf) + meta_source_hash = read_str_opt(buf) + dependencies = read_str_list(buf) + suppressed = read_str_list(buf) + assert read_tag(buf) == DICT_STR_GEN + priorities = {read_str_bare(buf): read_int(buf) for _ in range(read_int_bare(buf))} + assert read_tag(buf) == DICT_STR_GEN + dep_line_map = {read_str_bare(buf): read_int(buf) for _ in range(read_int_bare(buf))} + assert read_tag(buf) == DICT_STR_GEN + dep_hashes = {read_str_bare(buf): read_bytes(buf) for _ in range(read_int_bare(buf))} + return cls( + manager=manager, + order=order, + id=id, + path=path, + source=source, + # The caller must call clone_for_module(). + options=manager.options, + ignore_all=ignore_all, + caller_line=caller_line, + import_context=import_context, + meta=None, + interface_hash=interface_hash, + meta_source_hash=meta_source_hash, + dependencies=dependencies, + suppressed=suppressed, + priorities=priorities, + dep_line_map=dep_line_map, + dep_hashes=dep_hashes, + error_lines=[], + imports_ignored={}, + size_hint=read_int(buf), + ) + + def reload_meta(self) -> None: + """Force reload of cache meta. + + This is used by parallel checking workers to update shared information + that may have changed after initial graph loading. Currently, this is only + the interface hash. + """ + assert self.path is not None + self.meta, _ = find_cache_meta(self.id, self.path, self.manager, skip_validation=True) + assert self.meta is not None + self.interface_hash = self.meta.interface_hash + + def add_ancestors(self) -> None: + if self.path is not None: + _, name = os.path.split(self.path) + base, _ = os.path.splitext(name) + if "." in base: + # This is just a weird filename, don't add anything + self.ancestors = [] + return + # All parent packages are new ancestors. + ancestors = [] + parent = self.id + while "." in parent: + parent, _ = parent.rsplit(".", 1) + ancestors.append(parent) + self.ancestors = ancestors + + def is_fresh(self) -> bool: + """Return whether the cache data for this file is fresh.""" + # NOTE: self.dependencies may differ from + # self.meta.dependencies when a dependency is dropped due to + # suppression by silent mode. However, when a suppressed + # dependency is added back we find out later in the process. + # Additionally, we need to verify that import following options are + # same for suppressed dependencies, even if the first check is OK. + return ( + self.meta is not None + and self.dependencies == self.meta.dependencies + and ( + self.options.fine_grained_incremental + or self.meta.suppressed_deps_opts == self.suppressed_deps_opts() + ) + ) + + def mark_as_rechecked(self) -> None: + """Marks this module as having been fully re-analyzed by the type-checker.""" + self.manager.rechecked_modules.add(self.id) + + def mark_interface_stale(self) -> None: + """Marks this module as having a stale public interface, and discards the cache data.""" + self.manager.stale_modules.add(self.id) + + def check_blockers(self) -> None: + """Raise CompileError if a blocking error is detected.""" + if self.manager.errors.is_blockers(): + self.manager.log("Bailing due to blocking errors") + self.manager.errors.raise_error() + + @contextlib.contextmanager + def wrap_context(self, check_blockers: bool = True) -> Iterator[None]: + """Temporarily change the error import context to match this state. + + Also report an internal error if an unexpected exception was raised + and raise an exception on a blocking error, unless + check_blockers is False. Skipping blocking error reporting is used + in the semantic analyzer so that we can report all blocking errors + for a file (across multiple targets) to maintain backward + compatibility. + """ + save_import_context = self.manager.errors.import_context() + self.manager.errors.set_import_context(self.import_context) + try: + yield + except CompileError: + raise + except Exception as err: + report_internal_error( + err, + self.path, + 0, + self.manager.errors, + self.options, + self.manager.stdout, + self.manager.stderr, + ) + self.manager.errors.set_import_context(save_import_context) + # TODO: Move this away once we've removed the old semantic analyzer? + if check_blockers: + self.check_blockers() + + def load_fine_grained_deps(self) -> dict[str, set[str]]: + return self.manager.load_fine_grained_deps(self.id) + + def load_tree(self, temporary: bool = False) -> None: + if self.manager.parallel_worker: + assert self.path is not None + _, data_file, _ = get_cache_names(self.id, self.path, self.manager.options) + else: + assert ( + self.meta is not None + ), "Internal error: this method must be called only for cached modules" + data_file = self.meta.data_file + + data: bytes | dict[str, Any] | None + if self.options.fixed_format_cache: + data = _load_ff_file(data_file, self.manager, "Could not load tree: ", None) + else: + data = _load_json_file(data_file, self.manager, "Load tree ", "Could not load tree: ") + if data is None: + return + + t0 = time.time() + # TODO: Assert data file wasn't changed. + if isinstance(data, bytes): + data_io = ReadBuffer(data) + self.tree = MypyFile.read(data_io) + else: + self.tree = MypyFile.deserialize(data) + t1 = time.time() + self.manager.add_stats(deserialize_time=t1 - t0) + if not temporary: + self.manager.modules[self.id] = self.tree + self.manager.add_stats(fresh_trees=1) + + def fix_cross_refs(self) -> None: + assert self.tree is not None, "Internal error: method must be called on parsed file only" + # We need to set allow_missing when doing a fine-grained cache + # load because we need to gracefully handle missing modules. + fixup_module(self.tree, self.manager.modules, self.options.use_fine_grained_cache) + + # Methods for processing modules from source code. + + def parse_file(self, *, temporary: bool = False, raw_data: FileRawData | None = None) -> None: + """Parse file and run first pass of semantic analysis. + + Everything done here is local to the file. Don't depend on imported + modules in any way. Also record module dependencies based on imports. + """ + if self.tree is not None: + # The file was already parsed (in __init__()). + return + + manager = self.manager + + # Can we reuse a previously parsed AST? This avoids redundant work in daemon. + cached = self.id in manager.ast_cache + modules = manager.modules + if not cached: + manager.log(f"Parsing {self.xpath} ({self.id})") + else: + manager.log(f"Using cached AST for {self.xpath} ({self.id})") + + t0 = time_ref() + + with self.wrap_context(): + source = self.source + if self.path and source is None: + try: + path = manager.maybe_swap_for_shadow_path(self.path) + source = decode_python_encoding(manager.fscache.read(path)) + self.source_hash = manager.fscache.hash_digest(path) + except OSError as ioerr: + # ioerr.strerror differs for os.stat failures between Windows and + # other systems, but os.strerror(ioerr.errno) does not, so we use that. + # (We want the error messages to be platform-independent so that the + # tests have predictable output.) + assert ioerr.errno is not None + raise CompileError( + [ + "mypy: error: cannot read file '{}': {}".format( + self.path.replace(os.getcwd() + os.sep, ""), + os.strerror(ioerr.errno), + ) + ], + module_with_blocker=self.id, + ) from ioerr + except (UnicodeDecodeError, DecodeError) as decodeerr: + if self.path.endswith(".pyd"): + err = f"{self.path}: error: stubgen does not support .pyd files" + else: + err = f"{self.path}: error: cannot decode file: {str(decodeerr)}" + raise CompileError([err], module_with_blocker=self.id) from decodeerr + elif self.path and self.manager.fscache.isdir(self.path): + source = "" + self.source_hash = "" + else: + assert source is not None + self.source_hash = compute_hash(source) + + self.parse_inline_configuration(source) + self.check_for_invalid_options() + + self.size_hint = len(source) + if not cached: + ignore_errors = self.ignore_all or self.options.ignore_errors + self.tree = manager.parse_file( + self.id, + self.xpath, + source, + ignore_errors=ignore_errors, + options=self.options, + raw_data=raw_data, + ) + else: + # Reuse a cached AST + self.tree = manager.ast_cache[self.id][0] + + self.time_spent_us += time_spent_us(t0) + + if not cached: + # Make a copy of any errors produced during parse time so that + # fine-grained mode can repeat them when the module is + # reprocessed. + self.early_errors = list(manager.errors.error_info_map.get(self.xpath, [])) + self.semantic_analysis_pass1() + else: + self.early_errors = manager.ast_cache[self.id][1] + + if not temporary: + modules[self.id] = self.tree + self.check_blockers() + + manager.ast_cache[self.id] = (self.tree, self.early_errors) + self.setup_errors() + + def setup_errors(self) -> None: + assert self.tree is not None + self.manager.errors.set_file_ignored_lines( + self.xpath, self.tree.ignored_lines, self.ignore_all or self.options.ignore_errors + ) + self.manager.errors.set_skipped_lines(self.xpath, self.tree.skipped_lines) + + def parse_inline_configuration(self, source: str) -> None: + """Check for inline mypy: options directive and parse them.""" + flags = get_mypy_comments(source) + if flags: + changes, config_errors = parse_mypy_comments(flags, self.options) + self.options = self.options.apply_changes(changes) + self.manager.errors.set_file(self.xpath, self.id, self.options) + for lineno, error in config_errors: + self.manager.error(lineno, error) + + def check_for_invalid_options(self) -> None: + if self.options.mypyc and not self.options.strict_bytes: + self.manager.errors.set_file(self.xpath, self.id, options=self.options) + self.manager.error( + None, "Option --strict-bytes cannot be disabled when using mypyc", blocker=True + ) + + def semantic_analysis_pass1(self) -> None: + """Perform pass 1 of semantic analysis, which happens immediately after parsing. + + This pass can't assume that any other modules have been processed yet. + """ + options = self.options + assert self.tree is not None + + t0 = time_ref() + + # Do the first pass of semantic analysis: analyze the reachability + # of blocks and import statements. We must do this before + # processing imports, since this may mark some import statements as + # unreachable. + # + # TODO: This should not be considered as a semantic analysis + # pass -- it's an independent pass. + if not options.native_parser: + analyzer = SemanticAnalyzerPreAnalysis() + with self.wrap_context(): + analyzer.visit_file(self.tree, self.xpath, self.id, options) + # TODO: Do this while constructing the AST? + self.tree.names = SymbolTable() + if not self.tree.is_stub: + if not self.options.allow_redefinition_new: + # Perform some low-key variable renaming when assignments can't + # widen inferred types + self.tree.accept(LimitedVariableRenameVisitor()) + if options.allow_redefinition_old: + # Perform more renaming across the AST to allow variable redefinitions + self.tree.accept(VariableRenameVisitor()) + self.time_spent_us += time_spent_us(t0) + + def add_dependency(self, dep: str) -> None: + if dep not in self.dependencies_set: + self.dependencies.append(dep) + self.dependencies_set.add(dep) + if dep in self.suppressed_set: + self.suppressed.remove(dep) + self.suppressed_set.remove(dep) + + def suppress_dependency(self, dep: str) -> None: + if dep in self.dependencies_set: + self.dependencies.remove(dep) + self.dependencies_set.remove(dep) + if dep not in self.suppressed_set: + self.suppressed.append(dep) + self.suppressed_set.add(dep) + + def compute_dependencies(self) -> None: + """Compute a module's dependencies after parsing it. + + This is used when we parse a file that we didn't have + up-to-date cache information for. When we have an up-to-date + cache, we just use the cached info. + """ + manager = self.manager + assert self.tree is not None + + # Compute (direct) dependencies. + # Add all direct imports (this is why we needed the first pass). + # Also keep track of each dependency's source line. + # Missing dependencies will be moved from dependencies to + # suppressed when they fail to be loaded in load_graph. + + self.dependencies = [] + self.dependencies_set = set() + self.suppressed = [] + self.suppressed_set = set() + self.priorities = {} # id -> priority + self.dep_line_map = {} # id -> line + self.dep_hashes = {} + dep_entries = manager.all_imported_modules_in_file( + self.tree + ) + self.manager.plugin.get_additional_deps(self.tree) + for pri, id, line in dep_entries: + self.priorities[id] = min(pri, self.priorities.get(id, PRI_ALL)) + if id == self.id: + continue + self.add_dependency(id) + if id not in self.dep_line_map: + self.dep_line_map[id] = line + import_lines = self.dep_line_map.values() + self.imports_ignored = { + line: codes for line, codes in self.tree.ignored_lines.items() if line in import_lines + } + # Every module implicitly depends on builtins. + if self.id != "builtins": + self.add_dependency("builtins") + if self.tree.uses_template_strings: + self.add_dependency("string.templatelib") + + self.check_blockers() # Can fail due to bogus relative imports + + def type_check_first_pass(self) -> None: + if self.options.semantic_analysis_only: + return + t0 = time_ref() + with self.wrap_context(): + self.type_checker().check_first_pass() + self.time_spent_us += time_spent_us(t0) + + def type_checker(self) -> TypeChecker: + if not self._type_checker: + assert self.tree is not None, "Internal error: must be called on parsed file only" + manager = self.manager + self._type_checker = TypeChecker( + manager.errors, + manager.modules, + self.options, + self.tree, + self.xpath, + manager.plugin, + self.per_line_checking_time_ns, + ) + return self._type_checker + + def type_map(self) -> dict[Expression, Type]: + # We can extract the master type map directly since at this + # point no temporary type maps can be active. + assert len(self.type_checker()._type_maps) == 1 + return self.type_checker()._type_maps[0] + + def type_check_second_pass(self) -> bool: + if self.options.semantic_analysis_only: + return False + t0 = time_ref() + with self.wrap_context(): + result = self.type_checker().check_second_pass() + self.time_spent_us += time_spent_us(t0) + return result + + def detect_possibly_undefined_vars(self) -> None: + assert self.tree is not None, "Internal error: method must be called on parsed file only" + if self.tree.is_stub: + # We skip stub files because they aren't actually executed. + return + manager = self.manager + manager.errors.set_file(self.xpath, self.tree.fullname, options=self.options) + if manager.errors.is_error_code_enabled( + codes.POSSIBLY_UNDEFINED + ) or manager.errors.is_error_code_enabled(codes.USED_BEFORE_DEF): + self.tree.accept( + PossiblyUndefinedVariableVisitor( + MessageBuilder(manager.errors, manager.modules), + self.type_map(), + self.options, + self.tree.names, + ) + ) + + def finish_passes(self) -> None: + assert self.tree is not None, "Internal error: method must be called on parsed file only" + manager = self.manager + if self.options.semantic_analysis_only: + return + t0 = time_ref() + with self.wrap_context(): + # Some tests (and tools) want to look at the set of all types. + options = manager.options + if options.export_types: + manager.all_types.update(self.type_map()) + + # We should always patch indirect dependencies, even in full (non-incremental) builds, + # because the cache still may be written, and it must be correct. + self.patch_indirect_dependencies( + # Two possible sources of indirect dependencies: + # * Symbols not directly imported in this module but accessed via an attribute + # or via a re-export (vast majority of these recorded in semantic analysis). + # * For each expression type we need to record definitions of type components + # since "meaning" of the type may be updated when definitions are updated. + self.tree.module_refs | self.type_checker().module_refs, + set(self.type_map().values()), + ) + + if self.options.dump_inference_stats: + dump_type_stats( + self.tree, + self.xpath, + modules=self.manager.modules, + inferred=True, + typemap=self.type_map(), + ) + manager.report_file(self.tree, self.type_map(), self.options) + + self.update_fine_grained_deps(self.manager.fg_deps) + + if manager.options.export_ref_info: + write_undocumented_ref_info( + self, manager.metastore, manager.options, self.type_map() + ) + + self.free_state() + if not manager.options.fine_grained_incremental and not manager.options.preserve_asts: + free_tree(self.tree) + self.tree.defs.clear() + self.time_spent_us += time_spent_us(t0) + + def free_state(self) -> None: + if self._type_checker: + self._type_checker.reset() + self._type_checker = None + + def patch_indirect_dependencies(self, module_refs: set[str], types: set[Type]) -> None: + assert self.ancestors is not None + existing_deps = set(self.dependencies + self.suppressed + self.ancestors) + existing_deps.add(self.id) + + encountered = self.manager.indirection_detector.find_modules(types) | module_refs + for dep in sorted(encountered - existing_deps): + if dep not in self.manager.modules: + continue + self.add_dependency(dep) + self.priorities[dep] = PRI_INDIRECT + + def compute_fine_grained_deps(self) -> dict[str, set[str]]: + assert self.tree is not None + if self.id in ("builtins", "typing", "types", "sys", "_typeshed"): + # We don't track changes to core parts of typeshed -- the + # assumption is that they are only changed as part of mypy + # updates, which will invalidate everything anyway. These + # will always be processed in the initial non-fine-grained + # build. Other modules may be brought in as a result of an + # fine-grained increment, and we may need these + # dependencies then to handle cyclic imports. + return {} + from mypy.server.deps import get_dependencies # Lazy import to speed up startup + + return get_dependencies( + target=self.tree, + type_map=self.type_map(), + python_version=self.options.python_version, + options=self.manager.options, + ) + + def update_fine_grained_deps(self, deps: dict[str, set[str]]) -> None: + options = self.manager.options + if options.cache_fine_grained or options.fine_grained_incremental: + from mypy.server.deps import merge_dependencies # Lazy import to speed up startup + + merge_dependencies(self.compute_fine_grained_deps(), deps) + type_state.update_protocol_deps(deps) + + def suppressed_deps_opts(self) -> bytes: + if not self.suppressed: + return b"" + if self.known_suppressed_deps_opts: + return self.known_suppressed_deps_opts + buf = WriteBuffer() + import_options = self.manager.import_options + for dep in sorted(self.suppressed): + # Using .get() is a bit defensive, but just in case we have a bug elsewhere + # (e.g. in the daemon), it is better to get a stale cache than a crash. + reason = self.manager.missing_modules.get(dep, SuppressionReason.NOT_FOUND) + if self.priorities.get(dep) != PRI_INDIRECT: + write_str_bare(buf, dep) + write_bytes_bare(buf, import_options[dep]) + write_int_bare(buf, reason) + return buf.getvalue() + + def write_cache(self) -> tuple[CacheMeta, str] | None: + assert self.tree is not None, "Internal error: method must be called on parsed file only" + # We don't support writing cache files in fine-grained incremental mode. + if ( + not self.path + or self.options.cache_dir == os.devnull + or self.options.fine_grained_incremental + ): + if self.options.debug_serialize: + try: + if self.manager.options.fixed_format_cache: + data = WriteBuffer() + self.tree.write(data) + else: + self.tree.serialize() + except Exception: + print(f"Error serializing {self.id}", file=self.manager.stdout) + raise # Propagate to display traceback + return None + dep_prios = self.dependency_priorities() + dep_lines = self.dependency_lines() + assert self.source_hash is not None + assert len(set(self.dependencies)) == len( + self.dependencies + ), f"Duplicates in dependencies list for {self.id} ({self.dependencies})" + new_interface_hash, meta_tuple = write_cache( + self.id, + self.path, + self.tree, + list(self.dependencies), + list(self.suppressed), + self.suppressed_deps_opts(), + self.imports_ignored, + dep_prios, + dep_lines, + self.interface_hash, + self.trans_dep_hash, + self.source_hash, + self.ignore_all, + self.manager, + ) + if new_interface_hash == self.interface_hash: + self.manager.log(f"Cached module {self.id} has same interface") + else: + self.manager.log(f"Cached module {self.id} has changed interface") + self.mark_interface_stale() + self.interface_hash = new_interface_hash + return meta_tuple + + def verify_dependencies(self, suppressed_only: bool = False) -> None: + """Report errors for import targets in modules that don't exist. + + If suppressed_only is set, only check suppressed dependencies. + """ + manager = self.manager + assert self.ancestors is not None + # Strip out indirect dependencies. See comment in build.load_graph(). + if suppressed_only: + all_deps = [dep for dep in self.suppressed if self.priorities.get(dep) != PRI_INDIRECT] + else: + dependencies = [ + dep + for dep in self.dependencies + self.suppressed + if self.priorities.get(dep) != PRI_INDIRECT + ] + all_deps = dependencies + self.ancestors + for dep in all_deps: + if dep in manager.modules: + continue + options = manager.options.clone_for_module(dep) + if options.ignore_missing_imports: + continue + line = self.dep_line_map.get(dep, 1) + try: + if dep in self.ancestors: + state: State | None = None + ancestor: State | None = self + else: + state, ancestor = self, None + # Called just for its side effects of producing diagnostics. + find_module_and_diagnose( + manager, + dep, + options, + caller_state=state, + caller_line=line, + ancestor_for=ancestor, + ) + except (ModuleNotFound, CompileError): + # Swallow up any ModuleNotFounds or CompilerErrors while generating + # a diagnostic. CompileErrors may get generated in + # fine-grained mode when an __init__.py is deleted, if a module + # that was in that package has targets reprocessed before + # it is renamed. + pass + + def dependency_priorities(self) -> list[int]: + return [self.priorities.get(dep, PRI_HIGH) for dep in self.dependencies + self.suppressed] + + def dependency_lines(self) -> list[int]: + return [self.dep_line_map.get(dep, 1) for dep in self.dependencies + self.suppressed] + + def generate_unused_ignore_notes(self) -> None: + if ( + self.options.warn_unused_ignores + or codes.UNUSED_IGNORE in self.options.enabled_error_codes + ) and codes.UNUSED_IGNORE not in self.options.disabled_error_codes: + # We only need this for the daemon, regular incremental does this unconditionally. + if self.meta and self.options.fine_grained_incremental: + self.verify_dependencies(suppressed_only=True) + is_typeshed = self.tree is not None and self.tree.is_typeshed_file(self.options) + self.manager.errors.generate_unused_ignore_errors(self.xpath, is_typeshed) + + def generate_ignore_without_code_notes(self) -> None: + if self.manager.errors.is_error_code_enabled(codes.IGNORE_WITHOUT_CODE): + is_typeshed = self.tree is not None and self.tree.is_typeshed_file(self.options) + self.manager.errors.generate_ignore_without_code_errors( + self.xpath, self.options.warn_unused_ignores, is_typeshed + ) + + +# Module import and diagnostic glue + + +def find_module_and_diagnose( + manager: BuildManager, + id: str, + options: Options, + caller_state: State | None = None, + caller_line: int = 0, + ancestor_for: State | None = None, + root_source: bool = False, + skip_diagnose: bool = False, +) -> tuple[str, str]: + """Find a module by name, respecting follow_imports and producing diagnostics. + + If the module is not found, then the ModuleNotFound exception is raised. + + Args: + id: module to find + options: the options for the module being loaded + caller_state: the state of the importing module, if applicable + caller_line: the line number of the import + ancestor_for: the child module this is an ancestor of, if applicable + root_source: whether this source was specified on the command line + skip_diagnose: skip any error diagnosis and reporting (but ModuleNotFound is + still raised if the module is missing) + + The specified value of follow_imports for a module can be overridden + if the module is specified on the command line or if it is a stub, + so we compute and return the "effective" follow_imports of the module. + + Returns a tuple containing (file path, target's effective follow_imports setting) + """ + result = find_module_with_reason(id, manager) + if isinstance(result, str): + # For non-stubs, look at options.follow_imports: + # - normal (default) -> fully analyze + # - silent -> analyze but silence errors + # - skip -> don't analyze, make the type Any + follow_imports = options.follow_imports + if ( + root_source # Honor top-level modules + or ( + result.endswith(".pyi") # Stubs are always normal + and not options.follow_imports_for_stubs # except when they aren't + ) + or id in CORE_BUILTIN_MODULES # core is always normal + ): + follow_imports = "normal" + if skip_diagnose: + pass + elif follow_imports == "silent": + # Still import it, but silence non-blocker errors. + manager.log(f"Silencing {result} ({id})") + elif follow_imports == "skip" or follow_imports == "error": + # In 'error' mode, produce special error messages. + if id not in manager.missing_modules: + manager.log(f"Skipping {result} ({id})") + if follow_imports == "error": + if ancestor_for: + skipping_ancestor(manager, id, result, ancestor_for) + else: + skipping_module(manager, caller_line, caller_state, id, result) + reason = SuppressionReason.SKIPPED + if options.ignore_missing_imports: + # Performance optimization: when we are ignoring imports, there is no + # difference for the caller between skipped import and actually missing one. + reason = SuppressionReason.NOT_FOUND + raise ModuleNotFound(reason=reason) + if is_silent_import_module(manager, result) and not root_source: + follow_imports = "silent" + return result, follow_imports + else: + # Could not find a module. Typically, the reason is a + # misspelled module name, missing stub, module not in + # search path or the module has not been installed. + + ignore_missing_imports = options.ignore_missing_imports + + # Don't honor a global (not per-module) ignore_missing_imports + # setting for modules that used to have bundled stubs, as + # otherwise updating mypy can silently result in new false + # negatives. (Unless there are stubs, but they are incomplete.) + global_ignore_missing_imports = manager.options.ignore_missing_imports + if ( + is_module_from_legacy_bundled_package(id) + and global_ignore_missing_imports + and not options.ignore_missing_imports_per_module + and result is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED + ): + ignore_missing_imports = False + + if skip_diagnose: + raise ModuleNotFound + if caller_state: + if not (ignore_missing_imports or in_partial_package(id, manager)): + module_not_found(manager, caller_line, caller_state, id, result) + raise ModuleNotFound + elif root_source: + # If we can't find a root source it's always fatal. + # TODO: This might hide non-fatal errors from + # root sources processed earlier. + raise CompileError([f"mypy: can't find module '{id}'"]) + else: + raise ModuleNotFound + + +def exist_added_packages(suppressed: list[str], manager: BuildManager) -> bool: + """Find if there are any newly added packages that were previously suppressed. + + Exclude everything not in build for follow-imports=skip. + """ + for dep in suppressed: + if dep in manager.source_set.source_modules: + # We don't need to add any special logic for this. If a module + # is added to build, importers will be invalidated by normal mechanism. + continue + path = find_module_simple(dep, manager) + if not path: + continue + options = manager.options.clone_for_module(dep) + # Technically this is not 100% correct, since we can have: + # from pkg import mod + # with + # [mypy-pkg] + # follow-import = silent + # [mypy-pkg.mod] + # follow-imports = normal + # But such cases are extremely rare, and this allows us to avoid + # massive performance impact in much more common situations. + if options.follow_imports in ("skip", "error") and ( + not path.endswith(".pyi") or options.follow_imports_for_stubs + ): + continue + if os.path.basename(path) in ("__init__.py", "__init__.pyi"): + return True + return False + + +def exist_removed_submodules(dependencies: list[str], manager: BuildManager) -> bool: + """Find if there are any submodules of packages that are now missing. + + This is conceptually an inverse of exist_added_packages(). + """ + dependencies_set = set(dependencies) + for dep in dependencies: + if "." not in dep: + continue + if dep in manager.source_set.source_modules: + # We still know it is definitely a module. + continue + direct_ancestor, _ = dep.rsplit(".", maxsplit=1) + if direct_ancestor not in dependencies_set: + continue + if find_module_simple(dep, manager) is None: + return True + return False + + +def find_module_simple(id: str, manager: BuildManager) -> str | None: + """Find a filesystem path for module `id` or `None` if not found.""" + if manager.stats_enabled: + t0 = time.time() + x = manager.find_module_cache.find_module(id, fast_path=True) + if manager.stats_enabled: + manager.add_stats(find_module_time=time.time() - t0, find_module_calls=1) + if isinstance(x, ModuleNotFoundReason): + return None + return x + + +def find_module_with_reason(id: str, manager: BuildManager) -> ModuleSearchResult: + """Find a filesystem path for module `id` or the reason it can't be found.""" + if manager.stats_enabled: + t0 = time.time() + x = manager.find_module_cache.find_module(id, fast_path=False) + if manager.stats_enabled: + manager.add_stats(find_module_time=time.time() - t0, find_module_calls=1) + return x + + +def in_partial_package(id: str, manager: BuildManager) -> bool: + """Check if a missing module can potentially be a part of a package. + + This checks if there is any existing parent __init__.pyi stub that + defines a module-level __getattr__ (a.k.a. partial stub package). + """ + while "." in id: + ancestor, _ = id.rsplit(".", 1) + if ancestor in manager.known_partial_packages: + return manager.known_partial_packages[ancestor] + if ancestor in manager.modules: + ancestor_mod: MypyFile | None = manager.modules[ancestor] + else: + # Ancestor is not in build, try quickly if we can find it. + try: + ancestor_st = State.new_state( + id=ancestor, path=None, source=None, manager=manager, temporary=True + ) + except (ModuleNotFound, CompileError): + ancestor_mod = None + else: + ancestor_mod = ancestor_st.tree + # We will not need this anymore. + ancestor_st.tree = None + if ancestor_mod is not None: + # Bail out soon, complete subpackage found + manager.known_partial_packages[ancestor] = ancestor_mod.is_partial_stub_package + return ancestor_mod.is_partial_stub_package + id = ancestor + return False + + +def module_not_found( + manager: BuildManager, + line: int, + caller_state: State, + target: str, + reason: ModuleNotFoundReason, +) -> None: + errors = manager.errors + save_import_context = errors.import_context() + errors.set_import_context(caller_state.import_context) + errors.set_file(caller_state.xpath, caller_state.id, caller_state.options) + errors.set_file_ignored_lines( + caller_state.xpath, + caller_state.tree.ignored_lines if caller_state.tree else caller_state.imports_ignored, + caller_state.ignore_all or caller_state.options.ignore_errors, + ) + if target == "builtins": + manager.error( + line, "Cannot find 'builtins' module. Typeshed appears broken!", blocker=True + ) + errors.raise_error() + else: + daemon = manager.options.fine_grained_incremental + msg, notes = reason.error_message_templates(daemon) + if reason == ModuleNotFoundReason.NOT_FOUND: + code = codes.IMPORT_NOT_FOUND + elif ( + reason == ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS + or reason == ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED + ): + code = codes.IMPORT_UNTYPED + else: + code = codes.IMPORT + manager.error(line, msg.format(module=target), code=code) + + dist = stub_distribution_name(target) + for note in notes: + if "{stub_dist}" in note: + assert dist is not None + note = note.format(stub_dist=dist) + manager.note(line, note, only_once=True, code=code) + if reason is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED: + assert dist is not None + manager.missing_stub_packages.add(dist) + errors.set_import_context(save_import_context) + + +def skipping_module( + manager: BuildManager, line: int, caller_state: State | None, id: str, path: str +) -> None: + """Produce an error for an import ignored due to --follow_imports=error""" + assert caller_state, (id, path) + save_import_context = manager.errors.import_context() + manager.errors.set_import_context(caller_state.import_context) + manager.errors.set_file(caller_state.xpath, caller_state.id, manager.options) + manager.error(line, f'Import of "{id}" ignored') + manager.note( + line, "(Using --follow-imports=error, module not passed on command line)", only_once=True + ) + manager.errors.set_import_context(save_import_context) + + +def skipping_ancestor(manager: BuildManager, id: str, path: str, ancestor_for: State) -> None: + """Produce an error for an ancestor ignored due to --follow_imports=error""" + # TODO: Read the path (the __init__.py file) and return + # immediately if it's empty or only contains comments. + # But beware, some package may be the ancestor of many modules, + # so we'd need to cache the decision. + manager.errors.set_import_context([]) + manager.errors.set_file(ancestor_for.xpath, ancestor_for.id, manager.options) + manager.error(None, f'Ancestor package "{id}" ignored', only_once=True) + manager.note( + None, "(Using --follow-imports=error, submodule passed on command line)", only_once=True + ) + + +def log_configuration(manager: BuildManager, sources: list[BuildSource]) -> None: + """Output useful configuration information to LOG and TRACE""" + + if not manager.logging_enabled: + return + + config_file = manager.options.config_file + if config_file: + config_file = os.path.abspath(config_file) + + manager.log() + configuration_vars = [ + ("Mypy Version", __version__), + ("Config File", (config_file or "Default")), + ("Configured Executable", manager.options.python_executable or "None"), + ("Current Executable", sys.executable), + ("Cache Dir", manager.options.cache_dir), + ("Compiled", str(not __file__.endswith(".py"))), + ("Exclude", manager.options.exclude), + ] + + for conf_name, conf_value in configuration_vars: + manager.log(f"{conf_name + ':':24}{conf_value}") + + for source in sources: + manager.log(f"{'Found source:':24}{source}") + + # Complete list of searched paths can get very long, put them under TRACE + for path_type, paths in manager.search_paths.asdict().items(): + if not paths: + manager.trace(f"No {path_type}") + continue + + manager.trace(f"{path_type}:") + + for pth in paths: + manager.trace(f" {pth}") + + +# The driver + + +def dispatch(sources: list[BuildSource], manager: BuildManager, stdout: TextIO) -> Graph: + log_configuration(manager, sources) + + t0 = time.time() + + # We disable GC while loading the graph as a performance optimization for + # cold-cache runs. The parsed ASTs are trees, and therefore should not have any + # reference cycles. This is an important optimization, since we create a lot of + # new objects while parsing files. + global initial_gc_freeze_done + if ( + not manager.options.test_env + and platform.python_implementation() == "CPython" + and not initial_gc_freeze_done + ): + gc.disable() + graph = load_graph(sources, manager) + + # This is a kind of unfortunate hack to work around some of fine-grained's + # fragility: if we have loaded less than 50% of the specified files from + # cache in fine-grained cache mode, load the graph again honestly. + # In this case, we just turn the cache off entirely, so we don't need + # to worry about some files being loaded and some from cache and so + # that fine-grained mode never *writes* to the cache. + if manager.use_fine_grained_cache() and len(graph) < 0.50 * len(sources): + manager.log("Redoing load_graph without cache because too much was missing") + manager.cache_enabled = False + graph = load_graph(sources, manager) + + if ( + not manager.options.test_env + and platform.python_implementation() == "CPython" + and not initial_gc_freeze_done + ): + gc.freeze() + gc.unfreeze() + gc.enable() + initial_gc_freeze_done = True + + for id in graph: + manager.import_map[id] = graph[id].dependencies_set + + t1 = time.time() + manager.add_stats( + graph_size=len(graph), + stubs_found=sum(g.path is not None and g.path.endswith(".pyi") for g in graph.values()), + graph_load_time=(t1 - t0), + fm_cache_size=len(manager.find_module_cache.results), + ) + if not graph: + print("Nothing to do?!", file=stdout) + return graph + manager.log(f"Loaded graph with {len(graph)} nodes ({t1 - t0:.3f} sec)") + if manager.options.dump_graph: + dump_graph(graph, stdout) + return graph + + # Fine grained dependencies that didn't have an associated module in the build + # are serialized separately, so we read them after we load the graph. + # We need to read them both for running in daemon mode and if we are generating + # a fine-grained cache (so that we can properly update them incrementally). + # The `read_deps_cache` will also validate + # the deps cache against the loaded individual cache files. + if manager.options.cache_fine_grained or manager.use_fine_grained_cache(): + t2 = time.time() + fg_deps_meta = read_deps_cache(manager, graph) + manager.add_stats(load_fg_deps_time=time.time() - t2) + if fg_deps_meta is not None: + manager.fg_deps_meta = fg_deps_meta + elif manager.stats.get("fresh_metas", 0) > 0: + # Clear the stats so we don't infinite loop because of positive fresh_metas + manager.stats.clear() + # There were some cache files read, but no fine-grained dependencies loaded. + manager.log("Error reading fine-grained dependencies cache -- aborting cache load") + manager.cache_enabled = False + manager.log("Falling back to full run -- reloading graph...") + return dispatch(sources, manager, stdout) + + # If we are loading a fine-grained incremental mode cache, we + # don't want to do a real incremental reprocess of the + # graph---we'll handle it all later. + if not manager.use_fine_grained_cache(): + process_graph(graph, manager) + # Update plugins snapshot. + write_plugins_snapshot(manager) + manager.old_plugins_snapshot = manager.plugins_snapshot + if manager.options.cache_fine_grained or manager.options.fine_grained_incremental: + # If we are running a daemon or are going to write cache for further fine grained use, + # then we need to collect fine grained protocol dependencies. + # Since these are a global property of the program, they are calculated after we + # processed the whole graph. + type_state.add_all_protocol_deps(manager.fg_deps) + if not manager.options.fine_grained_incremental: + rdeps = generate_deps_for_cache(manager, graph) + write_deps_cache(rdeps, manager, graph) + + if manager.options.dump_deps: + # This speeds up startup a little when not using the daemon mode. + from mypy.server.deps import dump_all_dependencies + + dump_all_dependencies( + manager.modules, manager.all_types, manager.options.python_version, manager.options + ) + + return graph + + +class NodeInfo: + """Some info about a node in the graph of SCCs.""" + + def __init__(self, index: int, scc: list[str]) -> None: + self.node_id = "n%d" % index + self.scc = scc + self.sizes: dict[str, int] = {} # mod -> size in bytes + self.deps: dict[str, int] = {} # node_id -> pri + + def dumps(self) -> str: + """Convert to JSON string.""" + total_size = sum(self.sizes.values()) + return "[{}, {}, {},\n {},\n {}]".format( + json.dumps(self.node_id), + json.dumps(total_size), + json.dumps(self.scc), + json.dumps(self.sizes), + json.dumps(self.deps), + ) + + +def dump_timing_stats(path: str, graph: Graph) -> None: + """Dump timing stats for each file in the given graph.""" + with open(path, "w") as f: + for id in sorted(graph): + f.write(f"{id} {graph[id].time_spent_us}\n") + + +def dump_line_checking_stats(path: str, graph: Graph) -> None: + """Dump per-line expression type checking stats.""" + with open(path, "w") as f: + for id in sorted(graph): + if not graph[id].per_line_checking_time_ns: + continue + f.write(f"{id}:\n") + for line in sorted(graph[id].per_line_checking_time_ns): + line_time = graph[id].per_line_checking_time_ns[line] + f.write(f"{line:>5} {line_time/1000:8.1f}\n") + + +def dump_graph(graph: Graph, stdout: TextIO | None = None) -> None: + """Dump the graph as a JSON string to stdout. + + This copies some of the work by process_graph() + (sorted_components() and order_ascc()). + """ + stdout = stdout or sys.stdout + nodes = [] + sccs = sorted_components(graph) + for i, ascc in enumerate(sccs): + scc = order_ascc(graph, ascc.mod_ids) + node = NodeInfo(i, scc) + nodes.append(node) + inv_nodes = {} # module -> node_id + for node in nodes: + for mod in node.scc: + inv_nodes[mod] = node.node_id + for node in nodes: + for mod in node.scc: + state = graph[mod] + size = 0 + if state.path: + try: + size = os.path.getsize(state.path) + except OSError: + pass + node.sizes[mod] = size + for dep in state.dependencies: + if dep in state.priorities: + pri = state.priorities[dep] + if dep in inv_nodes: + dep_id = inv_nodes[dep] + if dep_id != node.node_id and ( + dep_id not in node.deps or pri < node.deps[dep_id] + ): + node.deps[dep_id] = pri + print("[" + ",\n ".join(node.dumps() for node in nodes) + "\n]", file=stdout) + + +def load_graph( + sources: list[BuildSource], + manager: BuildManager, + old_graph: Graph | None = None, + new_modules: list[State] | None = None, +) -> Graph: + """Given some source files, load the full dependency graph. + + If an old_graph is passed in, it is used as the starting point and + modified during graph loading. + + If a new_modules is passed in, any modules that are loaded are + added to the list. This is an argument and not a return value + so that the caller can access it even if load_graph fails. + + As this may need to parse files, this can raise CompileError in case + there are syntax errors. + """ + + graph: Graph = old_graph if old_graph is not None else {} + + # The deque is used to implement breadth-first traversal. + # TODO: Consider whether to go depth-first instead. This may + # affect the order in which we process files within import cycles. + new = new_modules if new_modules is not None else [] + entry_points: set[str] = set() + # Seed the graph with the initial root sources. + for bs in sources: + try: + st = State.new_state( + id=bs.module, + path=bs.path, + source=bs.text, + manager=manager, + root_source=not bs.followed, + ) + except ModuleNotFound: + continue + if st.id in graph: + manager.errors.set_file(st.xpath, st.id, manager.options) + manager.error( + None, + f'Duplicate module named "{st.id}" (also at "{graph[st.id].xpath}")', + blocker=True, + ) + resolution_note = f""" + See {MODULE_RESOLUTION_URL} for more info + Common resolutions include: + a) using `--exclude` to avoid checking one of them, + b) adding `__init__.py` somewhere, + c) using `--explicit-package-bases` or adjusting `MYPYPATH` + """ + manager.note_multiline(None, resolution_note) + manager.errors.raise_error() + graph[st.id] = st + new.append(st) + entry_points.add(bs.module) + + # Note: Running this each time could be slow in the daemon. If it's a problem, we + # can do more work to maintain this incrementally. + seen_files = {st.abspath: st for st in graph.values() if st.path} + + # Collect dependencies. We go breadth-first. + # More nodes might get added to new as we go, but that's fine. + for st in new: + assert st.ancestors is not None + # Strip out indirect dependencies. These will be dealt with + # when they show up as direct dependencies, and there's a + # scenario where they hurt: + # - Suppose A imports B and B imports C. + # - Suppose on the next round: + # - C is deleted; + # - B is updated to remove the dependency on C; + # - A is unchanged. + # - In this case A's cached *direct* dependencies are still valid + # (since direct dependencies reflect the imports found in the source) + # but A's cached *indirect* dependency on C is wrong. + dependencies = [dep for dep in st.dependencies if st.priorities.get(dep) != PRI_INDIRECT] + if not manager.use_fine_grained_cache(): + added = [dep for dep in st.suppressed if find_module_simple(dep, manager)] + else: + # During initial loading we don't care about newly added modules, + # they will be taken care of during fine-grained update. See also + # comment about this in `State.new_state()`. + added = [] + for dep in st.ancestors + dependencies + st.suppressed: + ignored = dep in st.suppressed_set and dep not in entry_points + if ignored and dep not in added: + manager.missing_modules[dep] = SuppressionReason.NOT_FOUND + # TODO: for now we skip this in the daemon as a performance optimization. + # This however creates a correctness issue, see #7777 and State.is_fresh(). + if not manager.use_fine_grained_cache() or manager.options.warn_unused_configs: + manager.import_options[dep] = manager.options.clone_for_module( + dep + ).dep_import_options() + elif dep not in graph: + try: + if dep in st.ancestors: + # TODO: Why not 'if dep not in st.dependencies' ? + # Ancestors don't have import context. + newst = State.new_state( + id=dep, path=None, source=None, manager=manager, ancestor_for=st + ) + else: + newst = State.new_state( + id=dep, + path=None, + source=None, + manager=manager, + caller_state=st, + caller_line=st.dep_line_map.get(dep, 1), + ) + except ModuleNotFound: + if dep in st.dependencies_set: + st.suppress_dependency(dep) + else: + if newst.path: + newst_path = newst.abspath + + if newst_path in seen_files: + manager.error( + None, + "Source file found twice under different module names: " + f'"{seen_files[newst_path].id}" and "{newst.id}"', + blocker=True, + ) + resolution_note = f""" + See {MODULE_RESOLUTION_URL} for more info + Common resolutions include: + a) adding `__init__.py` somewhere, + b) using `--explicit-package-bases` or adjusting `MYPYPATH` + """ + manager.note_multiline(None, resolution_note) + manager.errors.raise_error() + + seen_files[newst_path] = newst + + assert newst.id not in graph, newst.id + graph[newst.id] = newst + new.append(newst) + # There are two things we need to do after the initial load loop. One is up-suppress + # modules that are back in graph. We need to do this after the loop to cover edge cases + # like where a namespace package ancestor is shared by a typed and an untyped package. + for st in graph.values(): + for dep in st.suppressed.copy(): + if dep in graph: + st.add_dependency(dep) + manager.missing_modules.pop(dep, None) + # Second, in the initial loop we skip indirect dependencies, so to make indirect dependencies + # behave more consistently with regular ones, we suppress them manually here (when needed). + for st in graph.values(): + indirect = [dep for dep in st.dependencies if st.priorities.get(dep) == PRI_INDIRECT] + for dep in indirect: + if dep not in graph: + st.suppress_dependency(dep) + manager.plugin.set_modules(manager.modules) + manager.errors.global_watcher = False + return graph + + +def order_ascc_ex(graph: Graph, ascc: SCC) -> list[str]: + """Apply extra heuristics on top of order_ascc(). + + This should be used only for actual SCCs, not for "inner" SCCs + we create recursively during ordering of the SCC. Currently, this + has only some special handling for builtin SCC. + """ + scc = order_ascc(graph, ascc.mod_ids) + # Make the order of the SCC that includes 'builtins' and 'typing', + # among other things, predictable. Various things may break if + # the order changes. + if "builtins" in ascc.mod_ids: + scc = sorted(scc, reverse=True) + # If builtins is in the list, move it last. (This is a bit of + # a hack, but it's necessary because the builtins module is + # part of a small cycle involving at least {builtins, abc, + # typing}. Of these, builtins must be processed last or else + # some builtin objects will be incompletely processed.) + scc.remove("builtins") + scc.append("builtins") + return scc + + +def verify_transitive_deps(ascc: SCC, graph: Graph, manager: BuildManager) -> str | None: + """Verify all indirect dependencies of this SCC are still reachable via direct ones. + + Return first unreachable dependency id, or None. + """ + for id in ascc.mod_ids: + st = graph[id] + assert st.meta is not None, "Must be called on fresh SCCs only" + if st.trans_dep_hash == st.meta.trans_dep_hash: + # Import graph unchanged, skip this module. + continue + for dep in st.dependencies: + if st.priorities.get(dep) == PRI_INDIRECT: + dep_scc_id = manager.scc_by_mod_id[dep].id + if dep_scc_id == ascc.id: + continue + if not manager.is_transitive_scc_dep(ascc.id, dep_scc_id): + return dep + return None + + +def find_stale_sccs( + sccs: list[SCC], graph: Graph, manager: BuildManager +) -> tuple[list[SCC], list[SCC]]: + """Split a list of ready SCCs into stale and fresh. + + Fresh SCCs are those where: + * We have valid cache files for all modules in the SCC. + * There are no changes in dependencies (files removed from/added to the build). + * The interface hashes of dependencies matches those recorded in the cache. + * All indirect dependencies are still reachable via direct ones. + The first and second conditions are verified by is_fresh(). + """ + stale_sccs = [] + fresh_sccs = [] + for ascc in sccs: + stale_scc = {id for id in ascc.mod_ids if not graph[id].is_fresh()} + fresh = not stale_scc + + # Verify that interfaces of dependencies still present in graph are up-to-date (fresh). + stale_deps = set() + for id in ascc.mod_ids: + for dep in graph[id].dep_hashes: + if dep in graph and graph[dep].interface_hash != graph[id].dep_hashes[dep]: + stale_deps.add(dep) + fresh = fresh and not stale_deps + + # Verify the invariant that indirect dependencies are a subset of transitive direct + # dependencies. Note: the case where indirect dependency is removed from the graph + # completely is already handled above. + stale_indirect = None + if fresh: + stale_indirect = verify_transitive_deps(ascc, graph, manager) + if stale_indirect is not None: + fresh = False + + if manager.logging_enabled: + if fresh: + fresh_msg = "fresh" + elif stale_scc: + fresh_msg = "inherently stale" + if stale_scc != ascc.mod_ids: + fresh_msg += f" ({' '.join(sorted(stale_scc))})" + if stale_deps: + fresh_msg += f" with stale deps ({' '.join(sorted(stale_deps))})" + elif stale_deps: + fresh_msg = f"stale due to deps ({' '.join(sorted(stale_deps))})" + else: + assert stale_indirect is not None + fresh_msg = f"stale due to stale indirect dep(s): first {stale_indirect}" + scc_str = " ".join(ascc.mod_ids) + + if fresh: + if manager.tracing_enabled: + manager.trace(f"Found {fresh_msg} SCC ({scc_str})") + # If there is at most one file with errors we can skip the ordering to save time. + mods_with_errors = [id for id in ascc.mod_ids if graph[id].error_lines] + if len(mods_with_errors) <= 1: + scc = mods_with_errors + else: + # Use exactly the same order as for stale SCCs for stability. + scc = order_ascc_ex(graph, ascc) + for id in scc: + if graph[id].error_lines: + path = manager.errors.simplify_path(graph[id].xpath) + formatted = manager.errors.format_messages( + path, graph[id].error_lines, formatter=manager.error_formatter + ) + manager.flush_errors(path, formatted, False) + fresh_sccs.append(ascc) + else: + if manager.logging_enabled: + size = len(ascc.mod_ids) + if size == 1: + manager.log(f"Scheduling SCC singleton ({scc_str}) as {fresh_msg}") + else: + manager.log( + "Scheduling SCC of size %d (%s) as %s" % (size, scc_str, fresh_msg) + ) + stale_sccs.append(ascc) + return stale_sccs, fresh_sccs + + +def process_graph(graph: Graph, manager: BuildManager) -> None: + """Process everything in dependency order.""" + # Broadcast graph to workers before computing SCCs to save a bit of time. + # TODO: check if we can optimize by sending only part of the graph needed for given SCC. + # For example only send modules in the SCC and their dependencies. + graph_message = GraphMessage(graph=graph, missing_modules=manager.missing_modules) + buf = WriteBuffer() + graph_message.write(buf) + graph_data = buf.getvalue() + for worker in manager.workers: + AckMessage.read(receive(worker.conn)) + worker.conn.write_bytes(graph_data) + + sccs = sorted_components(graph) + manager.log( + "Found %d SCCs; largest has %d nodes" % (len(sccs), max(len(scc.mod_ids) for scc in sccs)) + ) + scc_by_id = {scc.id: scc for scc in sccs} + manager.scc_by_id = scc_by_id + manager.top_order = [scc.id for scc in sccs] + for scc in sccs: + for mod_id in scc.mod_ids: + manager.scc_by_mod_id[mod_id] = scc + + # Broadcast SCC structure to the parallel workers, since they don't compute it. + sccs_message = SccsDataMessage(sccs=sccs) + buf = WriteBuffer() + sccs_message.write(buf) + sccs_data = buf.getvalue() + for worker in manager.workers: + AckMessage.read(receive(worker.conn)) + worker.conn.write_bytes(sccs_data) + for worker in manager.workers: + AckMessage.read(receive(worker.conn)) + + manager.free_workers = set(range(manager.options.num_workers)) + + # Prime the ready list with leaf SCCs (that have no dependencies). + ready = [] + not_ready = set() + for scc in sccs: + if not scc.deps: + ready.append(scc) + else: + not_ready.add(scc) + + still_working = False + while ready or not_ready or still_working: + stale, fresh = find_stale_sccs(ready, graph, manager) + if stale: + for scc in stale: + for id in scc.mod_ids: + graph[id].mark_as_rechecked() + manager.submit(graph, stale) + still_working = True + # We eagerly walk over fresh SCCs to reach as many stale SCCs as soon + # as possible. Only when there are no fresh SCCs, we wait on scheduled stale ones. + # This strategy, similar to a naive strategy in minesweeper game, will allow us + # to leverage parallelism as much as possible. + if fresh: + done = fresh + else: + done, still_working, results = manager.wait_for_done(graph) + # Expose the results of type-checking by workers. For in-process + # type-checking this is already done and results should be empty here. + if not manager.workers: + assert not results + for id, (interface_hash, errors) in results.items(): + new_hash = bytes.fromhex(interface_hash) + if new_hash != graph[id].interface_hash: + graph[id].mark_interface_stale() + graph[id].interface_hash = new_hash + manager.flush_errors(manager.errors.simplify_path(graph[id].xpath), errors, False) + ready = [] + for done_scc in done: + for dependent in done_scc.direct_dependents: + scc_by_id[dependent].not_ready_deps.discard(done_scc.id) + if not scc_by_id[dependent].not_ready_deps: + not_ready.remove(scc_by_id[dependent]) + ready.append(scc_by_id[dependent]) + manager.trace(f"Transitive deps cache size: {sys.getsizeof(manager.transitive_deps_cache)}") + + +def order_ascc(graph: Graph, ascc: AbstractSet[str], pri_max: int = PRI_INDIRECT) -> list[str]: + """Come up with the ideal processing order within an SCC. + + Using the priorities assigned by all_imported_modules_in_file(), + try to reduce the cycle to a DAG, by omitting arcs representing + dependencies of lower priority. + + In the simplest case, if we have A <--> B where A has a top-level + "import B" (medium priority) but B only has the reverse "import A" + inside a function (low priority), we turn the cycle into a DAG by + dropping the B --> A arc, which leaves only A --> B. + + If all arcs have the same priority, we fall back to sorting by + reverse global order (the order in which modules were first + encountered). + + The algorithm is recursive, as follows: when as arcs of different + priorities are present, drop all arcs of the lowest priority, + identify SCCs in the resulting graph, and apply the algorithm to + each SCC thus found. The recursion is bounded because at each + recursion the spread in priorities is (at least) one less. + + In practice there are only a few priority levels (less than a + dozen) and in the worst case we just carry out the same algorithm + for finding SCCs N times. Thus, the complexity is no worse than + the complexity of the original SCC-finding algorithm -- see + strongly_connected_components() below for a reference. + """ + if len(ascc) == 1: + return list(ascc) + pri_spread = set() + for id in ascc: + state = graph[id] + for dep in state.dependencies: + if dep in ascc: + pri = state.priorities.get(dep, PRI_HIGH) + if pri < pri_max: + pri_spread.add(pri) + if len(pri_spread) == 1: + # Filtered dependencies are uniform -- order by global order. + return sorted(ascc, key=lambda id: -graph[id].order) + pri_max = max(pri_spread) + sccs = sorted_components_inner(graph, ascc, pri_max) + # The recursion is bounded by the len(pri_spread) check above. + return [s for ss in sccs for s in order_ascc(graph, ss, pri_max)] + + +def process_fresh_modules(graph: Graph, modules: list[str], manager: BuildManager) -> None: + """Process the modules in one group of modules from their cached data. + + This can be used to process an SCC of modules. This involves loading the tree (i.e. + module symbol tables) from cache file and then fixing cross-references in the symbols. + """ + t0 = time.time() + for id in modules: + graph[id].load_tree() + t1 = time.time() + for id in modules: + graph[id].fix_cross_refs() + t2 = time.time() + manager.add_stats(process_fresh_time=t2 - t0, load_tree_time=t1 - t0) + + +def process_stale_scc( + graph: Graph, ascc: SCC, manager: BuildManager, from_cache: set[str] | None = None +) -> dict[str, tuple[str, list[str]]]: + """Process the modules in one SCC from source code.""" + # First verify if all transitive dependencies are loaded in the current process. + t0 = time.time() + missing_sccs = set() + sccs_to_find = ascc.deps.copy() + while sccs_to_find: + dep_scc = sccs_to_find.pop() + if dep_scc in manager.done_sccs or dep_scc in missing_sccs: + continue + missing_sccs.add(dep_scc) + sccs_to_find.update(manager.scc_by_id[dep_scc].deps) + + if missing_sccs: + # Load missing SCCs from cache. + # TODO: speed-up ordering if this causes problems for large builds. + fresh_sccs_to_load = [ + manager.scc_by_id[sid] for sid in manager.top_order if sid in missing_sccs + ] + + if manager.parallel_worker: + # Update cache metas as well, cache data is loaded below + # in process_fresh_modules(). + for prev_scc in fresh_sccs_to_load: + for mod_id in prev_scc.mod_ids: + graph[mod_id].reload_meta() + + manager.log(f"Processing {len(fresh_sccs_to_load)} fresh SCCs") + if ( + not manager.options.test_env + and platform.python_implementation() == "CPython" + # Parallel workers perform loading in many smaller "pieces", so we + # should repeat the GC hack multiple times to actually benefit from it. + and (manager.gc_freeze_cycles < MAX_GC_FREEZE_CYCLES or manager.parallel_worker) + ): + # When deserializing cache we create huge amount of new objects, so even + # with our generous GC thresholds, GC is still doing a lot of pointless + # work searching for garbage. So, we temporarily disable it when + # processing fresh SCCs, and then move all the new objects to the oldest + # generation with the freeze()/unfreeze() trick below. This is arguably + # a hack, but it gives huge performance wins for large third-party + # libraries, like torch. + gc.collect(generation=1) + gc.collect(generation=0) + gc.disable() + for prev_scc in fresh_sccs_to_load: + manager.done_sccs.add(prev_scc.id) + process_fresh_modules(graph, sorted(prev_scc.mod_ids), manager) + if ( + not manager.options.test_env + and platform.python_implementation() == "CPython" + and (manager.gc_freeze_cycles < MAX_GC_FREEZE_CYCLES or manager.parallel_worker) + ): + manager.gc_freeze_cycles += 1 + gc.freeze() + gc.unfreeze() + gc.enable() + + t1 = time.time() + # Process the SCC in stable order. + scc = order_ascc_ex(graph, ascc) + + t2 = time.time() + stale = scc + for id in stale: + # Re-generate import errors in case this module was loaded from the cache. + # Deserialized states all have meta=None, so the caller should specify + # explicitly which of them are from cache. + if graph[id].meta or from_cache and id in from_cache: + graph[id].verify_dependencies(suppressed_only=True) + # We may already have parsed the module, or not. + # If the former, parse_file() is a no-op. + graph[id].parse_file() + if "typing" in scc: + # For historical reasons we need to manually add typing aliases + # for built-in generic collections, see docstring of + # SemanticAnalyzerPass2.add_builtin_aliases for details. + typing_mod = graph["typing"].tree + assert typing_mod, "The typing module was not parsed" + mypy.semanal_main.semantic_analysis_for_scc(graph, scc, manager.errors) + + t3 = time.time() + # Track what modules aren't yet done, so we can finish them as soon + # as possible, saving memory. + unfinished_modules = set(stale) + for id in stale: + graph[id].type_check_first_pass() + if not graph[id].type_checker().deferred_nodes: + unfinished_modules.discard(id) + graph[id].detect_possibly_undefined_vars() + graph[id].finish_passes() + + while unfinished_modules: + for id in stale: + if id not in unfinished_modules: + continue + if not graph[id].type_check_second_pass(): + unfinished_modules.discard(id) + graph[id].detect_possibly_undefined_vars() + graph[id].finish_passes() + for id in stale: + graph[id].generate_unused_ignore_notes() + graph[id].generate_ignore_without_code_notes() + + t4 = time.time() + # Flush errors, and write cache in two phases: first data files, then meta files. + meta_tuples = {} + errors_by_id = {} + formatted_by_id = {} + for id in stale: + if graph[id].xpath not in manager.errors.ignored_files: + errors = manager.errors.file_messages(graph[id].xpath) + formatted = manager.errors.format_messages( + graph[id].xpath, errors, formatter=manager.error_formatter + ) + manager.flush_errors(manager.errors.simplify_path(graph[id].xpath), formatted, False) + errors_by_id[id] = errors + formatted_by_id[id] = formatted + meta_tuples[id] = graph[id].write_cache() + for id in stale: + meta_tuple = meta_tuples[id] + if meta_tuple is None: + continue + meta, meta_file = meta_tuple + meta.dep_hashes = [graph[dep].interface_hash for dep in graph[id].dependencies] + write_cache_meta(meta, manager, meta_file) + write_errors_file(meta_file, errors_by_id.get(id, []), manager) + manager.done_sccs.add(ascc.id) + manager.add_stats( + load_missing_time=t1 - t0, + order_scc_time=t2 - t1, + semanal_time=t3 - t2, + type_check_time=t4 - t3, + flush_and_cache_time=time.time() - t4, + ) + scc_result = {} + for id in scc: + scc_result[id] = graph[id].interface_hash.hex(), formatted_by_id.get(id, []) + return scc_result + + +def prepare_sccs_full( + raw_sccs: Iterator[set[str]], edges: dict[str, list[str]] +) -> dict[SCC, set[SCC]]: + """Turn raw SCC sets into SCC objects and build dependency graph for SCCs.""" + sccs = [SCC(raw_scc) for raw_scc in raw_sccs] + scc_map = {} + for scc in sccs: + for id in scc.mod_ids: + scc_map[id] = scc + scc_deps_map: dict[SCC, set[SCC]] = {} + for scc in sccs: + for id in scc.mod_ids: + scc_deps_map.setdefault(scc, set()).update(scc_map[dep] for dep in edges[id]) + for scc in sccs: + # Remove trivial dependency on itself. + scc_deps_map[scc].discard(scc) + for dep_scc in scc_deps_map[scc]: + scc.deps.add(dep_scc.id) + scc.not_ready_deps.add(dep_scc.id) + return scc_deps_map + + +def sorted_components(graph: Graph) -> list[SCC]: + """Return the graph's SCCs, topologically sorted by dependencies. + + The sort order is from leaves (nodes without dependencies) to + roots (nodes on which no other nodes depend). + """ + # Compute SCCs. + vertices = set(graph) + edges = {id: deps_filtered(graph, vertices, id, PRI_INDIRECT) for id in vertices} + scc_dep_map = prepare_sccs_full(strongly_connected_components(vertices, edges), edges) + # Topsort. + res = [] + for ready in topsort(scc_dep_map): + # Sort the sets in ready by reversed smallest State.order. Examples: + # + # - If ready is [{x}, {y}], x.order == 1, y.order == 2, we get + # [{y}, {x}]. + # + # - If ready is [{a, b}, {c, d}], a.order == 1, b.order == 3, + # c.order == 2, d.order == 4, the sort keys become [1, 2] + # and the result is [{c, d}, {a, b}]. + sorted_ready = sorted(ready, key=lambda scc: -min(graph[id].order for id in scc.mod_ids)) + for scc in sorted_ready: + scc.size_hint = sum(graph[mid].size_hint for mid in scc.mod_ids) + for dep in scc_dep_map[scc]: + dep.direct_dependents.append(scc.id) + # We compute dependencies hash here since we know no direct + # dependencies will be added or suppressed after this point. + trans_dep_hash = transitive_dep_hash(scc, graph) + for id in scc.mod_ids: + graph[id].trans_dep_hash = trans_dep_hash + res.extend(sorted_ready) + return res + + +def sorted_components_inner( + graph: Graph, vertices: AbstractSet[str], pri_max: int +) -> list[AbstractSet[str]]: + """Simplified version of sorted_components() to work with sub-graphs. + + This doesn't create SCC objects, and operates with raw sets. This function + also allows filtering dependencies to take into account when building SCCs. + This is used for heuristic ordering of modules within actual SCCs. + """ + edges = {id: deps_filtered(graph, vertices, id, pri_max) for id in vertices} + sccs = list(strongly_connected_components(vertices, edges)) + res = [] + for ready in topsort(prepare_sccs(sccs, edges)): + res.extend(sorted(ready, key=lambda scc: -min(graph[id].order for id in scc))) + return res + + +def deps_filtered(graph: Graph, vertices: AbstractSet[str], id: str, pri_max: int) -> list[str]: + """Filter dependencies for id with pri < pri_max.""" + if id not in vertices: + return [] + state = graph[id] + return [ + dep + for dep in state.dependencies + if dep in vertices and state.priorities.get(dep, PRI_HIGH) < pri_max + ] + + +def transitive_dep_hash(scc: SCC, graph: Graph) -> bytes: + """Compute stable snapshot of transitive import structure for given SCC.""" + all_direct_deps = sorted( + { + dep + for id in scc.mod_ids + for dep in graph[id].dependencies + if graph[id].priorities.get(dep) != PRI_INDIRECT + } + ) + buf = WriteBuffer() + for dep_id in all_direct_deps: + write_str_bare(buf, dep_id) + if dep_id not in scc.mod_ids: + write_bytes_bare(buf, graph[dep_id].trans_dep_hash) + return hash_digest_bytes(buf.getvalue()) + + +def missing_stubs_file(cache_dir: str) -> str: + return os_path_join(cache_dir, "missing_stubs") + + +def record_missing_stub_packages(cache_dir: str, missing_stub_packages: set[str]) -> None: + """Write a file containing missing stub packages. + + This allows a subsequent "mypy --install-types" run (without other arguments) + to install missing stub packages. + """ + fnam = missing_stubs_file(cache_dir) + if missing_stub_packages: + with open(fnam, "w") as f: + for pkg in sorted(missing_stub_packages): + f.write(f"{pkg}\n") + else: + if os.path.isfile(fnam): + os.remove(fnam) + + +def is_silent_import_module(manager: BuildManager, path: str) -> bool: + if manager.options.no_silence_site_packages: + return False + # Silence errors in site-package dirs and typeshed + if any(is_sub_path_normabs(path, dir) for dir in manager.search_paths.package_path): + return True + return any(is_sub_path_normabs(path, dir) for dir in manager.search_paths.typeshed_path) + + +def write_undocumented_ref_info( + state: State, metastore: MetadataStore, options: Options, type_map: dict[Expression, Type] +) -> None: + # This exports some dependency information in a rather ad-hoc fashion, which + # can be helpful for some tools. This is all highly experimental and could be + # removed at any time. + + from mypy.refinfo import get_undocumented_ref_info_json + + if not state.tree: + # We need a full AST for this. + return + + _, data_file, _ = get_cache_names(state.id, state.xpath, options) + ref_info_file = ".".join(data_file.split(".")[:-2]) + ".refs.json" + assert not ref_info_file.startswith(".") + + deps_json = get_undocumented_ref_info_json(state.tree, type_map) + metastore.write(ref_info_file, json_dumps(deps_json)) + + +# The IPC message classes and tags for communication with build workers are +# in this file to avoid import cycles. +# Note that we use a more compact fixed serialization format than in cache.py. +# This is because the messages don't need to read by a generic tool, nor there +# is any need for backwards compatibility. We still reuse some elements from +# cache.py for convenience, and also some conventions (like using bare ints +# to specify object size). +# Note that we can use tags overlapping with cache.py, since they should never +# appear on the same context. +ACK_MESSAGE: Final[Tag] = 101 +SCC_REQUEST_MESSAGE: Final[Tag] = 102 +SCC_RESPONSE_MESSAGE: Final[Tag] = 103 +SOURCES_DATA_MESSAGE: Final[Tag] = 104 +SCCS_DATA_MESSAGE: Final[Tag] = 105 +GRAPH_MESSAGE: Final[Tag] = 106 + + +class AckMessage(IPCMessage): + """An empty message used primarily for synchronization.""" + + @classmethod + def read(cls, buf: ReadBuffer) -> AckMessage: + assert read_tag(buf) == ACK_MESSAGE + return AckMessage() + + def write(self, buf: WriteBuffer) -> None: + write_tag(buf, ACK_MESSAGE) + + +class SccRequestMessage(IPCMessage): + """ + A message representing a request to type check an SCC. + + If scc_id is None, then it means that the coordinator requested a shutdown. + """ + + def __init__( + self, + *, + scc_id: int | None, + import_errors: dict[str, list[ErrorInfo]], + mod_data: dict[str, tuple[bytes, FileRawData | None]], + ) -> None: + self.scc_id = scc_id + self.import_errors = import_errors + self.mod_data = mod_data + + @classmethod + def read(cls, buf: ReadBuffer) -> SccRequestMessage: + assert read_tag(buf) == SCC_REQUEST_MESSAGE + return SccRequestMessage( + scc_id=read_int_opt(buf), + import_errors={ + read_str(buf): [ErrorInfo.read(buf) for _ in range(read_int_bare(buf))] + for _ in range(read_int_bare(buf)) + }, + mod_data={ + read_str_bare(buf): ( + read_bytes(buf), + FileRawData.read(buf) if read_bool(buf) else None, + ) + for _ in range(read_int_bare(buf)) + }, + ) + + def write(self, buf: WriteBuffer) -> None: + write_tag(buf, SCC_REQUEST_MESSAGE) + write_int_opt(buf, self.scc_id) + write_int_bare(buf, len(self.import_errors)) + for path, errors in self.import_errors.items(): + write_str(buf, path) + write_int_bare(buf, len(errors)) + for error in errors: + error.write(buf) + write_int_bare(buf, len(self.mod_data)) + for mod, (suppressed_deps_opts, raw_data) in self.mod_data.items(): + write_str_bare(buf, mod) + write_bytes(buf, suppressed_deps_opts) + if raw_data is None: + write_bool(buf, False) + else: + write_bool(buf, True) + raw_data.write(buf) + + +class SccResponseMessage(IPCMessage): + """ + A message representing a result of type checking an SCC. + + Only one of `result` or `blocker` can be non-None. The latter means there was + a blocking error while type checking the SCC. + """ + + def __init__( + self, + *, + scc_id: int, + result: dict[str, tuple[str, list[str]]] | None = None, + blocker: CompileError | None = None, + ) -> None: + if result is not None: + assert blocker is None + if blocker is not None: + assert result is None + self.scc_id = scc_id + self.result = result + self.blocker = blocker + + @classmethod + def read(cls, buf: ReadBuffer) -> SccResponseMessage: + assert read_tag(buf) == SCC_RESPONSE_MESSAGE + scc_id = read_int(buf) + tag = read_tag(buf) + if tag == LITERAL_NONE: + return SccResponseMessage( + scc_id=scc_id, + blocker=CompileError(read_str_list(buf), read_bool(buf), read_str_opt(buf)), + ) + else: + assert tag == DICT_STR_GEN + return SccResponseMessage( + scc_id=scc_id, + result={ + read_str_bare(buf): (read_str(buf), read_str_list(buf)) + for _ in range(read_int_bare(buf)) + }, + ) + + def write(self, buf: WriteBuffer) -> None: + write_tag(buf, SCC_RESPONSE_MESSAGE) + write_int(buf, self.scc_id) + if self.result is None: + assert self.blocker is not None + write_tag(buf, LITERAL_NONE) + write_str_list(buf, self.blocker.messages) + write_bool(buf, self.blocker.use_stdout) + write_str_opt(buf, self.blocker.module_with_blocker) + else: + write_tag(buf, DICT_STR_GEN) + write_int_bare(buf, len(self.result)) + for mod_id in sorted(self.result): + write_str_bare(buf, mod_id) + hex_hash, errs = self.result[mod_id] + write_str(buf, hex_hash) + write_str_list(buf, errs) + + +class SourcesDataMessage(IPCMessage): + """A message wrapping a list of build sources.""" + + def __init__(self, *, sources: list[BuildSource]) -> None: + self.sources = sources + + @classmethod + def read(cls, buf: ReadBuffer) -> SourcesDataMessage: + assert read_tag(buf) == SOURCES_DATA_MESSAGE + sources = [ + BuildSource( + read_str_opt(buf), + read_str_opt(buf), + read_str_opt(buf), + read_str_opt(buf), + read_bool(buf), + ) + for _ in range(read_int_bare(buf)) + ] + return SourcesDataMessage(sources=sources) + + def write(self, buf: WriteBuffer) -> None: + write_tag(buf, SOURCES_DATA_MESSAGE) + write_int_bare(buf, len(self.sources)) + for bs in self.sources: + write_str_opt(buf, bs.path) + write_str_opt(buf, bs.module) + write_str_opt(buf, bs.text) + write_str_opt(buf, bs.base_dir) + write_bool(buf, bs.followed) + + +class SccsDataMessage(IPCMessage): + """A message wrapping the SCC structure computed by the coordinator.""" + + def __init__(self, *, sccs: list[SCC]) -> None: + self.sccs = sccs + + @classmethod + def read(cls, buf: ReadBuffer) -> SccsDataMessage: + assert read_tag(buf) == SCCS_DATA_MESSAGE + sccs = [ + SCC(set(read_str_list(buf)), read_int(buf), read_int_list(buf)) + for _ in range(read_int_bare(buf)) + ] + return SccsDataMessage(sccs=sccs) + + def write(self, buf: WriteBuffer) -> None: + write_tag(buf, SCCS_DATA_MESSAGE) + write_int_bare(buf, len(self.sccs)) + for scc in self.sccs: + write_str_list(buf, sorted(scc.mod_ids)) + write_int(buf, scc.id) + write_int_list(buf, sorted(scc.deps)) + + +class GraphMessage(IPCMessage): + """A message wrapping the build graph computed by the coordinator.""" + + def __init__(self, *, graph: Graph, missing_modules: dict[str, int]) -> None: + self.graph = graph + self.missing_modules = missing_modules + # Send this data separately as it will be lost during state serialization. + self.from_cache = {mod_id for mod_id in graph if graph[mod_id].meta} + + @classmethod + def read(cls, buf: ReadBuffer, manager: BuildManager | None = None) -> GraphMessage: + assert manager is not None + assert read_tag(buf) == GRAPH_MESSAGE + graph = {read_str_bare(buf): State.read(buf, manager) for _ in range(read_int_bare(buf))} + missing_modules = {read_str_bare(buf): read_int(buf) for _ in range(read_int_bare(buf))} + message = GraphMessage(graph=graph, missing_modules=missing_modules) + message.from_cache = {read_str_bare(buf) for _ in range(read_int_bare(buf))} + return message + + def write(self, buf: WriteBuffer) -> None: + write_tag(buf, GRAPH_MESSAGE) + write_int_bare(buf, len(self.graph)) + for mod_id, state in self.graph.items(): + write_str_bare(buf, mod_id) + state.write(buf) + write_int_bare(buf, len(self.missing_modules)) + for module, reason in self.missing_modules.items(): + write_str_bare(buf, module) + write_int(buf, reason) + write_int_bare(buf, len(self.from_cache)) + for module in self.from_cache: + write_str_bare(buf, module) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..60a4ceb3bbcc8dbda5b8a5f7de17e193ba8cecc9 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0adc7affb8cb416b6f35523907c36b6190f76c72 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.py @@ -0,0 +1,532 @@ +""" +This module contains high-level logic for fixed format serialization. + +Lower-level parts are implemented in C in mypyc/lib-rt/internal/librt_internal.c +Short summary of low-level functionality: +* integers are automatically serialized as 1, 2, or 4 bytes, or arbitrary length. +* str/bytes are serialized as size (1, 2, or 4 bytes) followed by bytes buffer. +* floats are serialized as C doubles. + +At high-level we add type tags as needed so that our format is self-descriptive. +More precisely: +* False, True, and None are stored as just a tag: 0, 1, 2 correspondingly. +* builtin primitives like int/str/bytes/float are stored as their type tag followed + by bare (low-level) representation of the value. Reserved tag range for primitives is + 3 ... 19. +* generic (heterogeneous) list are stored as tag, followed by bare size, followed by + sequence of tagged values. +* homogeneous lists of primitives are stored as tag, followed by bare size, followed + by sequence of bare values. +* reserved tag range for sequence-like builtins is 20 ... 29 +* currently we have only one mapping-like format: string-keyed dictionary with heterogeneous + values. It is stored as tag, followed by bare size, followed by sequence of pairs: bare + string key followed by tagged value. +* reserved tag range for mapping-like builtins is 30 ... 39 +* there is an additional reserved tag range 40 ... 49 for any other builtin collections. +* custom classes (like types, symbols etc.) are stored as tag, followed by a sequence of + tagged field values, followed by a special end tag 255. Names of class fields are + *not* stored, the caller should know the field names and order for the given class tag. +* reserved tag range for symbols (TypeInfo, Var, etc) is 50 ... 79. +* class Instance is the only exception from the above format (since it is the most common one). + It has two extra formats: few most common instances like "builtins.object" are stored as + instance tag followed by a secondary tag, other plain non-generic instances are stored as + instance tag followed by secondary tag followed by fullname as bare string. All generic + readers must handle these. +* reserved tag range for Instance type formats is 80 ... 99, for other types it is 100 ... 149. +* tag 254 is reserved for if we would ever need to extend the tag range to indicated second tag + page. Tags 150 ... 253 are free for everything else (e.g. AST nodes etc). + +General convention is that custom classes implement write() and read() methods for FF +serialization. The write method should write both class tag and end tag. The read method +conventionally *does not* read the start tag (to simplify logic for unions). Known exceptions +are MypyFile.read() and SymbolTableNode.read(), since those two never appear in a union. + +If any of these details change, or if the structure of CacheMeta changes please +bump CACHE_VERSION below. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, Final, TypeAlias as _TypeAlias + +from librt.internal import ( + ReadBuffer as ReadBuffer, + WriteBuffer as WriteBuffer, + read_bool as read_bool, + read_bytes as read_bytes_bare, + read_float as read_float_bare, + read_int as read_int_bare, + read_str as read_str_bare, + read_tag as read_tag, + write_bool as write_bool, + write_bytes as write_bytes_bare, + write_float as write_float_bare, + write_int as write_int_bare, + write_str as write_str_bare, + write_tag as write_tag, +) +from mypy_extensions import u8 + +# High-level cache layout format +CACHE_VERSION: Final = 7 + +# Type used internally to represent errors: +# (path, line, column, end_line, end_column, severity, message, code) +ErrorTuple: _TypeAlias = tuple[str | None, int, int, int, int, str, str, str | None] + + +class CacheMeta: + """Class representing cache metadata for a module.""" + + def __init__( + self, + *, + id: str, + path: str, + mtime: int, + size: int, + hash: str, + dependencies: list[str], + data_mtime: int, + data_file: str, + suppressed: list[str], + imports_ignored: dict[int, list[str]], + options: dict[str, object], + suppressed_deps_opts: bytes, + dep_prios: list[int], + dep_lines: list[int], + dep_hashes: list[bytes], + interface_hash: bytes, + trans_dep_hash: bytes, + version_id: str, + ignore_all: bool, + plugin_data: Any, + ) -> None: + self.id = id + self.path = path + self.mtime = mtime # source file mtime + self.size = size # source file size + self.hash = hash # source file hash (as a hex string for historical reasons) + self.dependencies = dependencies # names of imported modules + self.data_mtime = data_mtime # mtime of data_file + self.data_file = data_file # path of .data.json or .data.ff + self.suppressed = suppressed # dependencies that weren't imported + self.imports_ignored = imports_ignored # type ignore codes by line + self.options = options # build options snapshot + self.suppressed_deps_opts = suppressed_deps_opts # hash of import-related options + # dep_prios and dep_lines are both aligned with dependencies + suppressed + self.dep_prios = dep_prios + self.dep_lines = dep_lines + # dep_hashes list is aligned with dependencies only + self.dep_hashes = dep_hashes # list of interface_hash for dependencies + self.interface_hash = interface_hash # hash representing the public interface + self.trans_dep_hash = trans_dep_hash # hash of import structure (transitive) + self.version_id = version_id # mypy version for cache invalidation + self.ignore_all = ignore_all # if errors were ignored + self.plugin_data = plugin_data # config data from plugins + + def serialize(self) -> dict[str, Any]: + return { + "id": self.id, + "path": self.path, + "mtime": self.mtime, + "size": self.size, + "hash": self.hash, + "data_mtime": self.data_mtime, + "dependencies": self.dependencies, + "suppressed": self.suppressed, + "imports_ignored": {str(line): codes for line, codes in self.imports_ignored.items()}, + "options": self.options, + "suppressed_deps_opts": self.suppressed_deps_opts.hex(), + "dep_prios": self.dep_prios, + "dep_lines": self.dep_lines, + "dep_hashes": [dep.hex() for dep in self.dep_hashes], + "interface_hash": self.interface_hash.hex(), + "trans_dep_hash": self.trans_dep_hash.hex(), + "version_id": self.version_id, + "ignore_all": self.ignore_all, + "plugin_data": self.plugin_data, + } + + @classmethod + def deserialize(cls, meta: dict[str, Any], data_file: str) -> CacheMeta | None: + try: + return CacheMeta( + id=meta["id"], + path=meta["path"], + mtime=meta["mtime"], + size=meta["size"], + hash=meta["hash"], + dependencies=meta["dependencies"], + data_mtime=meta["data_mtime"], + data_file=data_file, + suppressed=meta["suppressed"], + imports_ignored={ + int(line): codes for line, codes in meta["imports_ignored"].items() + }, + options=meta["options"], + suppressed_deps_opts=bytes.fromhex(meta["suppressed_deps_opts"]), + dep_prios=meta["dep_prios"], + dep_lines=meta["dep_lines"], + dep_hashes=[bytes.fromhex(dep) for dep in meta["dep_hashes"]], + interface_hash=bytes.fromhex(meta["interface_hash"]), + trans_dep_hash=bytes.fromhex(meta["trans_dep_hash"]), + version_id=meta["version_id"], + ignore_all=meta["ignore_all"], + plugin_data=meta["plugin_data"], + ) + except (KeyError, ValueError): + return None + + def write(self, data: WriteBuffer) -> None: + write_str(data, self.id) + write_str(data, self.path) + write_int(data, self.mtime) + write_int(data, self.size) + write_str(data, self.hash) + write_str_list(data, self.dependencies) + write_int(data, self.data_mtime) + write_str_list(data, self.suppressed) + write_int_bare(data, len(self.imports_ignored)) + for line, codes in self.imports_ignored.items(): + write_int(data, line) + write_str_list(data, codes) + write_json(data, self.options) + write_bytes(data, self.suppressed_deps_opts) + write_int_list(data, self.dep_prios) + write_int_list(data, self.dep_lines) + write_bytes_list(data, self.dep_hashes) + write_bytes(data, self.interface_hash) + write_bytes(data, self.trans_dep_hash) + write_str(data, self.version_id) + write_bool(data, self.ignore_all) + # Plugin data may be not a dictionary, so we use + # a more generic write_json_value() here. + write_json_value(data, self.plugin_data) + + @classmethod + def read(cls, data: ReadBuffer, data_file: str) -> CacheMeta | None: + try: + return CacheMeta( + id=read_str(data), + path=read_str(data), + mtime=read_int(data), + size=read_int(data), + hash=read_str(data), + dependencies=read_str_list(data), + data_mtime=read_int(data), + data_file=data_file, + suppressed=read_str_list(data), + imports_ignored={ + read_int(data): read_str_list(data) for _ in range(read_int_bare(data)) + }, + options=read_json(data), + suppressed_deps_opts=read_bytes(data), + dep_prios=read_int_list(data), + dep_lines=read_int_list(data), + dep_hashes=read_bytes_list(data), + interface_hash=read_bytes(data), + trans_dep_hash=read_bytes(data), + version_id=read_str(data), + ignore_all=read_bool(data), + plugin_data=read_json_value(data), + ) + except (ValueError, AssertionError): + return None + + +# Always use this type alias to refer to type tags. +Tag = u8 + +# Primitives. +LITERAL_FALSE: Final[Tag] = 0 +LITERAL_TRUE: Final[Tag] = 1 +LITERAL_NONE: Final[Tag] = 2 +LITERAL_INT: Final[Tag] = 3 +LITERAL_STR: Final[Tag] = 4 +LITERAL_BYTES: Final[Tag] = 5 +LITERAL_FLOAT: Final[Tag] = 6 +LITERAL_COMPLEX: Final[Tag] = 7 + +# Collections. +LIST_GEN: Final[Tag] = 20 +LIST_INT: Final[Tag] = 21 +LIST_STR: Final[Tag] = 22 +LIST_BYTES: Final[Tag] = 23 +TUPLE_GEN: Final[Tag] = 24 +DICT_STR_GEN: Final[Tag] = 30 +DICT_INT_GEN: Final[Tag] = 31 + +# Misc classes. +EXTRA_ATTRS: Final[Tag] = 150 +DT_SPEC: Final[Tag] = 151 +# Four integers representing source file (line, column) range. +LOCATION: Final[Tag] = 152 + +END_TAG: Final[Tag] = 255 + + +def read_literal(data: ReadBuffer, tag: Tag) -> int | str | bool | float: + if tag == LITERAL_INT: + return read_int_bare(data) + elif tag == LITERAL_STR: + return read_str_bare(data) + elif tag == LITERAL_FALSE: + return False + elif tag == LITERAL_TRUE: + return True + elif tag == LITERAL_FLOAT: + return read_float_bare(data) + assert False, f"Unknown literal tag {tag}" + + +# There is an intentional asymmetry between read and write for literals because +# None and/or complex values are only allowed in some contexts but not in others. +def write_literal(data: WriteBuffer, value: int | str | bool | float | complex | None) -> None: + if isinstance(value, bool): + write_bool(data, value) + elif isinstance(value, int): + write_tag(data, LITERAL_INT) + write_int_bare(data, value) + elif isinstance(value, str): + write_tag(data, LITERAL_STR) + write_str_bare(data, value) + elif isinstance(value, float): + write_tag(data, LITERAL_FLOAT) + write_float_bare(data, value) + elif isinstance(value, complex): + write_tag(data, LITERAL_COMPLEX) + write_float_bare(data, value.real) + write_float_bare(data, value.imag) + else: + write_tag(data, LITERAL_NONE) + + +def read_int(data: ReadBuffer) -> int: + assert read_tag(data) == LITERAL_INT + return read_int_bare(data) + + +def write_int(data: WriteBuffer, value: int) -> None: + write_tag(data, LITERAL_INT) + write_int_bare(data, value) + + +def read_str(data: ReadBuffer) -> str: + assert read_tag(data) == LITERAL_STR + return read_str_bare(data) + + +def write_str(data: WriteBuffer, value: str) -> None: + write_tag(data, LITERAL_STR) + write_str_bare(data, value) + + +def read_bytes(data: ReadBuffer) -> bytes: + assert read_tag(data) == LITERAL_BYTES + return read_bytes_bare(data) + + +def write_bytes(data: WriteBuffer, value: bytes) -> None: + write_tag(data, LITERAL_BYTES) + write_bytes_bare(data, value) + + +def read_int_opt(data: ReadBuffer) -> int | None: + tag = read_tag(data) + if tag == LITERAL_NONE: + return None + assert tag == LITERAL_INT + return read_int_bare(data) + + +def write_int_opt(data: WriteBuffer, value: int | None) -> None: + if value is not None: + write_tag(data, LITERAL_INT) + write_int_bare(data, value) + else: + write_tag(data, LITERAL_NONE) + + +def read_str_opt(data: ReadBuffer) -> str | None: + tag = read_tag(data) + if tag == LITERAL_NONE: + return None + assert tag == LITERAL_STR + return read_str_bare(data) + + +def write_str_opt(data: WriteBuffer, value: str | None) -> None: + if value is not None: + write_tag(data, LITERAL_STR) + write_str_bare(data, value) + else: + write_tag(data, LITERAL_NONE) + + +def read_int_list(data: ReadBuffer) -> list[int]: + assert read_tag(data) == LIST_INT + size = read_int_bare(data) + return [read_int_bare(data) for _ in range(size)] + + +def write_int_list(data: WriteBuffer, value: list[int]) -> None: + write_tag(data, LIST_INT) + write_int_bare(data, len(value)) + for item in value: + write_int_bare(data, item) + + +def read_str_list(data: ReadBuffer) -> list[str]: + assert read_tag(data) == LIST_STR + size = read_int_bare(data) + return [read_str_bare(data) for _ in range(size)] + + +def write_str_list(data: WriteBuffer, value: Sequence[str]) -> None: + write_tag(data, LIST_STR) + write_int_bare(data, len(value)) + for item in value: + write_str_bare(data, item) + + +def read_bytes_list(data: ReadBuffer) -> list[bytes]: + assert read_tag(data) == LIST_BYTES + size = read_int_bare(data) + return [read_bytes_bare(data) for _ in range(size)] + + +def write_bytes_list(data: WriteBuffer, value: Sequence[bytes]) -> None: + write_tag(data, LIST_BYTES) + write_int_bare(data, len(value)) + for item in value: + write_bytes_bare(data, item) + + +def read_str_opt_list(data: ReadBuffer) -> list[str | None]: + assert read_tag(data) == LIST_GEN + size = read_int_bare(data) + return [read_str_opt(data) for _ in range(size)] + + +def write_str_opt_list(data: WriteBuffer, value: list[str | None]) -> None: + write_tag(data, LIST_GEN) + write_int_bare(data, len(value)) + for item in value: + write_str_opt(data, item) + + +Value: _TypeAlias = None | int | str | bool + +# Our JSON format is somewhat non-standard as we distinguish lists and tuples. +# This is convenient for some internal things, like mypyc plugin and error serialization. +JsonValue: _TypeAlias = ( + Value | list["JsonValue"] | dict[str, "JsonValue"] | tuple["JsonValue", ...] +) + + +def read_json_value(data: ReadBuffer) -> JsonValue: + tag = read_tag(data) + if tag == LITERAL_NONE: + return None + if tag == LITERAL_FALSE: + return False + if tag == LITERAL_TRUE: + return True + if tag == LITERAL_INT: + return read_int_bare(data) + if tag == LITERAL_STR: + return read_str_bare(data) + if tag == LIST_GEN: + size = read_int_bare(data) + return [read_json_value(data) for _ in range(size)] + if tag == TUPLE_GEN: + size = read_int_bare(data) + return tuple(read_json_value(data) for _ in range(size)) + if tag == DICT_STR_GEN: + size = read_int_bare(data) + return {read_str_bare(data): read_json_value(data) for _ in range(size)} + assert False, f"Invalid JSON tag: {tag}" + + +def write_json_value(data: WriteBuffer, value: JsonValue) -> None: + if value is None: + write_tag(data, LITERAL_NONE) + elif isinstance(value, bool): + write_bool(data, value) + elif isinstance(value, int): + write_tag(data, LITERAL_INT) + write_int_bare(data, value) + elif isinstance(value, str): + write_tag(data, LITERAL_STR) + write_str_bare(data, value) + elif isinstance(value, list): + write_tag(data, LIST_GEN) + write_int_bare(data, len(value)) + for val in value: + write_json_value(data, val) + elif isinstance(value, tuple): + write_tag(data, TUPLE_GEN) + write_int_bare(data, len(value)) + for val in value: + write_json_value(data, val) + elif isinstance(value, dict): + write_tag(data, DICT_STR_GEN) + write_int_bare(data, len(value)) + for key in sorted(value): + write_str_bare(data, key) + write_json_value(data, value[key]) + else: + assert False, f"Invalid JSON value: {value}" + + +# These are functions for JSON *dictionaries* specifically. Unfortunately, we +# must use imprecise types here, because the callers use imprecise types. +def read_json(data: ReadBuffer) -> dict[str, Any]: + assert read_tag(data) == DICT_STR_GEN + size = read_int_bare(data) + return {read_str_bare(data): read_json_value(data) for _ in range(size)} + + +def write_json(data: WriteBuffer, value: dict[str, Any]) -> None: + write_tag(data, DICT_STR_GEN) + write_int_bare(data, len(value)) + for key in sorted(value): + write_str_bare(data, key) + write_json_value(data, value[key]) + + +def write_errors(data: WriteBuffer, errs: list[ErrorTuple]) -> None: + write_tag(data, LIST_GEN) + write_int_bare(data, len(errs)) + for path, line, column, end_line, end_column, severity, message, code in errs: + write_tag(data, TUPLE_GEN) + write_str_opt(data, path) + write_int(data, line) + write_int(data, column) + write_int(data, end_line) + write_int(data, end_column) + write_str(data, severity) + write_str(data, message) + write_str_opt(data, code) + + +def read_errors(data: ReadBuffer) -> list[ErrorTuple]: + assert read_tag(data) == LIST_GEN + result = [] + for _ in range(read_int_bare(data)): + assert read_tag(data) == TUPLE_GEN + result.append( + ( + read_str_opt(data), + read_int(data), + read_int(data), + read_int(data), + read_int(data), + read_str(data), + read_str(data), + read_str_opt(data), + ) + ) + return result diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..9c564b612c5daf2227afca4cc23e63b44bf54bde Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker.py new file mode 100644 index 0000000000000000000000000000000000000000..717733dd412468a25bcbe2aad7253466128fd992 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker.py @@ -0,0 +1,9590 @@ +"""Mypy type checker.""" + +from __future__ import annotations + +import itertools +from collections import defaultdict +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Set as AbstractSet +from contextlib import ExitStack, contextmanager +from typing import ( + Final, + Generic, + Literal, + NamedTuple, + TypeAlias as _TypeAlias, + TypeGuard, + TypeVar, + cast, + overload, +) + +import mypy.checkexpr +from mypy import errorcodes as codes, join, message_registry, nodes, operators +from mypy.binder import ConditionalTypeBinder, Frame, get_declaration +from mypy.checker_shared import CheckerScope, TypeCheckerSharedApi, TypeRange +from mypy.checker_state import checker_state +from mypy.checkmember import ( + MemberContext, + analyze_class_attribute_access, + analyze_instance_member_access, + analyze_member_access, + is_instance_var, +) +from mypy.checkpattern import PatternChecker +from mypy.constraints import SUPERTYPE_OF +from mypy.erasetype import ( + erase_type, + erase_typevars, + remove_instance_last_known_values, + shallow_erase_type_for_equality, +) +from mypy.errorcodes import TYPE_VAR, UNUSED_AWAITABLE, UNUSED_COROUTINE, ErrorCode +from mypy.errors import ( + ErrorInfo, + Errors, + ErrorWatcher, + IterationDependentErrors, + IterationErrorWatcher, + report_internal_error, +) +from mypy.expandtype import expand_type +from mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash +from mypy.maptype import map_instance_to_supertype +from mypy.meet import is_overlapping_erased_types, is_overlapping_types, meet_types +from mypy.message_registry import ErrorMessage +from mypy.messages import ( + SUGGESTED_TEST_FIXTURES, + MessageBuilder, + append_invariance_notes, + append_union_note, + format_type, + format_type_bare, + format_type_distinctly, + make_inferred_type_note, + pretty_seq, +) +from mypy.mro import MroError, calculate_mro +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + ARG_STAR, + CONTRAVARIANT, + COVARIANT, + FUNC_NO_INFO, + GDEF, + IMPLICITLY_ABSTRACT, + INVARIANT, + IS_ABSTRACT, + LDEF, + LITERAL_TYPE, + MDEF, + NOT_ABSTRACT, + SYMBOL_FUNCBASE_TYPES, + AssertStmt, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + ClassDef, + ComparisonExpr, + Context, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + EllipsisExpr, + Expression, + ExpressionStmt, + FloatExpr, + ForStmt, + FuncBase, + FuncDef, + FuncItem, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportBase, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListExpr, + Lvalue, + MatchStmt, + MemberExpr, + MypyFile, + NameExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + PassStmt, + PromoteExpr, + RaiseStmt, + RefExpr, + ReturnStmt, + SetExpr, + SplittingVisitor, + StarExpr, + Statement, + StrExpr, + SymbolNode, + SymbolTable, + SymbolTableNode, + TempNode, + TryStmt, + TupleExpr, + TypeAlias, + TypeAliasStmt, + TypeInfo, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + get_func_def, + is_final_node, +) +from mypy.operators import flip_ops, int_op_to_method, neg_ops +from mypy.options import PRECISE_TUPLE_TYPES, Options +from mypy.patterns import AsPattern, StarredPattern +from mypy.plugin import Plugin +from mypy.plugins import dataclasses as dataclasses_plugin +from mypy.scope import Scope +from mypy.semanal import is_trivial_body, refers_to_fullname, set_callable_name +from mypy.semanal_enum import ENUM_BASES, ENUM_SPECIAL_PROPS +from mypy.semanal_shared import SemanticAnalyzerCoreInterface +from mypy.sharedparse import BINARY_MAGIC_METHODS +from mypy.state import state +from mypy.subtypes import ( + find_member, + infer_class_variances, + is_callable_compatible, + is_equivalent, + is_more_precise, + is_proper_subtype, + is_same_type, + is_subtype, + restrict_subtype_away, + unify_generic_callable, +) +from mypy.traverser import TraverserVisitor, all_return_statements, has_return_statement +from mypy.treetransform import TransformVisitor +from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type, make_optional_type +from mypy.typeops import ( + bind_self, + can_have_shared_disjoint_base, + coerce_to_literal, + custom_special_method, + erase_def_to_union_or_bound, + erase_to_bound, + erase_to_union_or_bound, + false_only, + fixup_partial_type, + function_type, + is_literal_type_like, + is_singleton_equality_type, + is_singleton_identity_type, + make_simplified_union, + true_only, + try_expanding_sum_type_to_union, + try_getting_int_literals_from_type, + try_getting_str_literals, + try_getting_str_literals_from_type, + tuple_fallback, + type_object_type, +) +from mypy.types import ( + ANY_STRATEGY, + MYPYC_NATIVE_INT_NAMES, + NOT_IMPLEMENTED_TYPE_NAMES, + OVERLOAD_NAMES, + AnyType, + BoolTypeQuery, + CallableType, + DeletedType, + ErasedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeGuardedType, + TypeOfAny, + TypeTranslator, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + flatten_nested_unions, + get_proper_type, + get_proper_types, + instance_cache, + is_literal_type, + is_named_instance, +) +from mypy.types_utils import is_overlapping_none, remove_optional, store_argument_type, strip_type +from mypy.typetraverser import TypeTraverserVisitor +from mypy.typevars import fill_typevars, fill_typevars_with_any, has_no_typevars +from mypy.util import is_dunder, is_sunder +from mypy.visitor import NodeVisitor + +T = TypeVar("T") + +DEFAULT_LAST_PASS: Final = 2 # Pass numbers start at 0 + +# Maximum length of fixed tuple types inferred when narrowing from variadic tuples. +MAX_PRECISE_TUPLE_SIZE: Final = 8 + +DeferredNodeType: _TypeAlias = FuncDef | OverloadedFuncDef | Decorator +FineGrainedDeferredNodeType: _TypeAlias = FuncDef | MypyFile | OverloadedFuncDef + + +# A node which is postponed to be processed during the next pass. +# In normal mode one can defer functions and methods (also decorated and/or overloaded) +# but not lambda expressions. Nested functions can't be deferred -- only top-level functions +# and methods of classes not defined within a function can be deferred. +class DeferredNode(NamedTuple): + node: DeferredNodeType + # And its TypeInfo (for semantic analysis self type handling) + active_typeinfo: TypeInfo | None + + +# Same as above, but for fine-grained mode targets. Only top-level functions/methods +# and module top levels are allowed as such. +class FineGrainedDeferredNode(NamedTuple): + node: FineGrainedDeferredNodeType + active_typeinfo: TypeInfo | None + + +# Data structure returned by find_isinstance_check representing +# information learned from the truth or falsehood of a condition. The +# dict maps nodes representing expressions like 'a[0].x' to their +# refined types under the assumption that the condition has a +# particular truth value. A value of None means that the condition can +# never have that truth value. + +# NB: The keys of this dict are nodes in the original source program, +# which are compared by reference equality--effectively, being *the +# same* expression of the program, not just two identical expressions +# (such as two references to the same variable). TODO: it would +# probably be better to have the dict keyed by the nodes' literal_hash +# field instead. +TypeMap: _TypeAlias = dict[Expression, Type] + + +# Keeps track of partial types in a single scope. In fine-grained incremental +# mode partial types initially defined at the top level cannot be completed in +# a function, and we use the 'is_function' attribute to enforce this. +class PartialTypeScope(NamedTuple): + map: dict[Var, Context] + is_function: bool + is_local: bool + + +class LocalTypeMap: + """Store inferred types into a temporary type map (returned). + + This can be used to perform type checking "experiments" without + affecting exported types (which are used by mypyc). + """ + + def __init__(self, chk: TypeChecker) -> None: + self.chk = chk + + def __enter__(self) -> dict[Expression, Type]: + temp_type_map: dict[Expression, Type] = {} + self.chk._type_maps.append(temp_type_map) + return temp_type_map + + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]: + self.chk._type_maps.pop() + return False + + +class TypeChecker(NodeVisitor[None], TypeCheckerSharedApi, SplittingVisitor): + """Mypy type checker. + + Type check mypy source files that have been semantically analyzed. + + You must create a separate instance for each source file. + """ + + # Are we type checking a stub? + is_stub = False + # Error message reporter + errors: Errors + # Utility for generating messages + msg: MessageBuilder + # Types of type checked nodes. The first item is the "master" type + # map that will store the final, exported types. Additional items + # are temporary type maps used during type inference, and these + # will be eventually popped and either discarded or merged into + # the master type map. + # + # Avoid accessing this directly, but prefer the lookup_type(), + # has_type() etc. helpers instead. + _type_maps: list[dict[Expression, Type]] + + # Helper for managing conditional types + binder: ConditionalTypeBinder + # Helper for type checking expressions + _expr_checker: mypy.checkexpr.ExpressionChecker + + pattern_checker: PatternChecker + + tscope: Scope + scope: CheckerScope + # Innermost enclosing type + type: TypeInfo | None + # Stack of function return types + return_types: list[Type] + # Flags; true for dynamically typed functions + dynamic_funcs: list[bool] + # Stack of collections of variables with partial types + partial_types: list[PartialTypeScope] + # Vars for which partial type errors are already reported + # (to avoid logically duplicate errors with different error context). + partial_reported: set[Var] + # Short names of Var nodes whose previous inferred type has been widened via assignment. + # NOTE: The names might not be unique, they are only for debugging purposes. + widened_vars: list[str] + globals: SymbolTable + modules: dict[str, MypyFile] + # Nodes that couldn't be checked because some types weren't available. We'll run + # another pass and try these again. + deferred_nodes: list[DeferredNode] + # Type checking pass number (0 = first pass) + pass_num = 0 + # Last pass number to take + last_pass = DEFAULT_LAST_PASS + # Have we deferred the current function? If yes, don't infer additional + # types during this pass within the function. + current_node_deferred = False + # Is this file a typeshed stub? + is_typeshed_stub = False + options: Options + # Used for collecting inferred attribute types so that they can be checked + # for consistency. + inferred_attribute_types: dict[Var, Type] | None = None + # Don't infer partial None types if we are processing assignment from Union + no_partial_types: bool = False + # Extra module references not detected during semantic analysis (these are rare cases + # e.g. access to class-level import via instance). + module_refs: set[str] + # A map from variable nodes to a snapshot of the frame ids of the + # frames that were active when the variable was declared. This can + # be used to determine nearest common ancestor frame of a variable's + # declaration and the current frame, which lets us determine if it + # was declared in a different branch of the same `if` statement + # (if that frame is a conditional_frame). + var_decl_frames: dict[Var, set[int]] + + # Plugin that provides special type checking rules for specific library + # functions such as open(), etc. + plugin: Plugin + + # A helper state to produce unique temporary names on demand. + _unique_id: int + # Fake concrete type used when checking variance + _variance_dummy_type: Instance | None + + def __init__( + self, + errors: Errors, + modules: dict[str, MypyFile], + options: Options, + tree: MypyFile, + path: str, + plugin: Plugin, + per_line_checking_time_ns: dict[int, int], + ) -> None: + """Construct a type checker. + + Use errors to report type check errors. + """ + self.errors = errors + self.modules = modules + self.options = options + self.tree = tree + self.path = path + self.msg = MessageBuilder(errors, modules) + self.plugin = plugin + self.tscope = Scope() + self.scope = CheckerScope(tree) + self.binder = ConditionalTypeBinder(options) + self.globals = tree.names + self.type = None + self.return_types = [] + self.dynamic_funcs = [] + self.partial_types = [] + self.partial_reported = set() + self.var_decl_frames = {} + self.deferred_nodes = [] + self.widened_vars = [] + self._type_maps = [{}] + self.module_refs = set() + self.pass_num = 0 + self.current_node_deferred = False + self.is_stub = tree.is_stub + self.is_typeshed_stub = tree.is_typeshed_file(options) + self.inferred_attribute_types = None + self.allow_constructor_cache = True + self.local_type_map = LocalTypeMap(self) + + self.can_skip_diagnostics: Final = ( + self.options.ignore_errors + or self.path in self.msg.errors.ignored_files + or (self.options.test_env and self.is_typeshed_stub) + ) + self.recurse_into_functions = True + # This internal flag is used to track whether we a currently type-checking + # a final declaration (assignment), so that some errors should be suppressed. + # Should not be set manually, use get_final_context/enter_final_context instead. + # NOTE: we use the context manager to avoid "threading" an additional `is_final_def` + # argument through various `checker` and `checkmember` functions. + self._is_final_def = False + + # Track when we enter an overload implementation. Some checks should not be applied + # to the implementation signature when specific overloads are available. + # Use `enter_overload_impl` to modify. + self.overload_impl_stack: list[OverloadPart] = [] + + # This flag is set when we run type-check or attribute access check for the purpose + # of giving a note on possibly missing "await". It is used to avoid infinite recursion. + self.checking_missing_await = False + + # While this is True, allow passing an abstract class where Type[T] is expected. + # although this is technically unsafe, this is desirable in some context, for + # example when type-checking class decorators. + self.allow_abstract_call = False + + # Child checker objects for specific AST node types + self._expr_checker = mypy.checkexpr.ExpressionChecker( + self, self.msg, self.plugin, per_line_checking_time_ns + ) + + self.pattern_checker = PatternChecker(self, self.msg, self.plugin, options) + self._unique_id = 0 + self._variance_dummy_type = None + + @property + def expr_checker(self) -> mypy.checkexpr.ExpressionChecker: + return self._expr_checker + + @property + def type_context(self) -> list[Type | None]: + return self._expr_checker.type_context + + def reset(self) -> None: + """Cleanup stale state that might be left over from a typechecking run. + + This allows us to reuse TypeChecker objects in fine-grained + incremental mode. + """ + # TODO: verify this is still actually worth it over creating new checkers + self.partial_reported.clear() + self.module_refs.clear() + self.binder = ConditionalTypeBinder(self.options) + self._type_maps[1:] = [] + self._type_maps[0].clear() + self.expr_checker.reset() + self.deferred_nodes = [] + self.partial_types = [] + self.inferred_attribute_types = None + self.scope = CheckerScope(self.tree) + + def check_first_pass(self) -> None: + """Type check the entire file, but defer functions with unresolved references. + + Unresolved references are forward references to variables + whose types haven't been inferred yet. They may occur later + in the same file or in a different file that's being processed + later (usually due to an import cycle). + + Deferred functions will be processed by check_second_pass(). + """ + self.recurse_into_functions = True + with state.strict_optional_set(self.options.strict_optional), checker_state.set(self): + self.errors.set_file( + self.path, self.tree.fullname, scope=self.tscope, options=self.options + ) + with self.tscope.module_scope(self.tree.fullname): + with self.enter_partial_types(), self.binder.top_frame_context(): + for d in self.tree.defs: + if self.binder.is_unreachable(): + if not self.should_report_unreachable_issues(): + break + if not self.is_noop_for_reachability(d): + self.msg.unreachable_statement(d) + break + else: + self.accept(d) + + assert not self.current_node_deferred + + all_ = self.globals.get("__all__") + if all_ is not None and all_.type is not None: + all_node = all_.node + assert all_node is not None + seq_str = self.named_generic_type( + "typing.Sequence", [self.named_type("builtins.str")] + ) + if not is_subtype(all_.type, seq_str): + str_seq_s, all_s = format_type_distinctly( + seq_str, all_.type, options=self.options + ) + self.fail( + message_registry.ALL_MUST_BE_SEQ_STR.format(str_seq_s, all_s), all_node + ) + + def check_second_pass( + self, + todo: Sequence[DeferredNode | FineGrainedDeferredNode] | None = None, + *, + allow_constructor_cache: bool = True, + ) -> bool: + """Run second or following pass of type checking. + + This goes through deferred nodes, returning True if there were any. + """ + self.allow_constructor_cache = allow_constructor_cache + self.recurse_into_functions = True + with state.strict_optional_set(self.options.strict_optional), checker_state.set(self): + if not todo and not self.deferred_nodes: + return False + self.errors.set_file( + self.path, self.tree.fullname, scope=self.tscope, options=self.options + ) + with self.tscope.module_scope(self.tree.fullname): + self.pass_num += 1 + if not todo: + todo = self.deferred_nodes + else: + assert not self.deferred_nodes + self.deferred_nodes = [] + done: set[DeferredNodeType | FineGrainedDeferredNodeType] = set() + for node, active_typeinfo in todo: + if node in done: + continue + # This is useful for debugging: + # print("XXX in pass %d, class %s, function %s" % + # (self.pass_num, type_name, node.fullname or node.name)) + done.add(node) + with ExitStack() as stack: + if active_typeinfo: + stack.enter_context(self.tscope.class_scope(active_typeinfo)) + stack.enter_context(self.scope.push_class(active_typeinfo)) + self.check_partial(node) + return True + + def check_partial(self, node: DeferredNodeType | FineGrainedDeferredNodeType) -> None: + self.widened_vars = [] + if isinstance(node, MypyFile): + self.check_top_level(node) + else: + self.recurse_into_functions = True + with self.binder.top_frame_context(): + self.accept(node) + + def check_top_level(self, node: MypyFile) -> None: + """Check only the top-level of a module, skipping function definitions.""" + self.recurse_into_functions = False + with self.enter_partial_types(): + with self.binder.top_frame_context(): + for d in node.defs: + d.accept(self) + + assert not self.current_node_deferred + # TODO: Handle __all__ + + def defer_node(self, node: DeferredNodeType, enclosing_class: TypeInfo | None) -> None: + """Defer a node for processing during next type-checking pass. + + Args: + node: function/method being deferred + enclosing_class: for methods, the class where the method is defined + NOTE: this can't handle nested functions/methods. + """ + # We don't freeze the entire scope since only top-level functions and methods + # can be deferred. Only module/class level scope information is needed. + # Module-level scope information is preserved in the TypeChecker instance. + self.deferred_nodes.append(DeferredNode(node, enclosing_class)) + + def handle_cannot_determine_type(self, name: str, context: Context) -> None: + node = self.scope.top_level_function() + if self.pass_num < self.last_pass and isinstance(node, FuncDef): + # Don't report an error yet. Just defer. Note that we don't defer + # lambdas because they are coupled to the surrounding function + # through the binder and the inferred type of the lambda, so it + # would get messy. + enclosing_class = self.scope.enclosing_class(node) + self.defer_node(node, enclosing_class) + # Set a marker so that we won't infer additional types in this + # function. Any inferred types could be bogus, because there's at + # least one type that we don't know. + self.current_node_deferred = True + else: + self.msg.cannot_determine_type(name, context) + + def accept(self, stmt: Statement) -> None: + """Type check a node in the given type context.""" + try: + stmt.accept(self) + except Exception as err: + report_internal_error(err, self.errors.file, stmt.line, self.errors, self.options) + + def accept_loop( + self, + body: Statement, + else_body: Statement | None = None, + *, + exit_condition: Expression | None = None, + on_enter_body: Callable[[], None] | None = None, + ) -> None: + """Repeatedly type check a loop body until the frame doesn't change.""" + + # The outer frame accumulates the results of all iterations: + with self.binder.frame_context(can_skip=False, conditional_frame=True): + # Check for potential decreases in the number of partial types so as not to stop the + # iteration too early: + partials_old = sum(len(pts.map) for pts in self.partial_types) + # Check if assignment widened the inferred type of a variable; in this case we + # need to iterate again (we only do one extra iteration, since this could go + # on without bound otherwise) + widened_old = len(self.widened_vars) + + iter_errors = IterationDependentErrors() + iter = 1 + while True: + with self.binder.frame_context(can_skip=True, break_frame=2, continue_frame=1): + if on_enter_body is not None: + on_enter_body() + + with IterationErrorWatcher(self.msg.errors, iter_errors): + self.accept(body) + + partials_new = sum(len(pts.map) for pts in self.partial_types) + widened_new = len(self.widened_vars) + # Perform multiple iterations if something changed that might affect + # inferred types. Also limit the number of iterations. The limits are + # somewhat arbitrary, but they were chosen to 1) avoid slowdown from + # multiple iterations in common cases and 2) support common, valid use + # cases. Limits are needed since otherwise we could infer infinitely + # complex types. + if ( + (partials_new == partials_old) + and (not self.binder.last_pop_changed or iter > 3) + and (widened_new == widened_old or iter > 1) + ): + break + partials_old = partials_new + widened_old = widened_new + iter += 1 + if iter == 20: + raise RuntimeError("Too many iterations when checking a loop") + + self.msg.iteration_dependent_errors(iter_errors) + + # If exit_condition is set, assume it must be False on exit from the loop: + if exit_condition: + _, else_map = self.find_isinstance_check(exit_condition) + self.push_type_map(else_map) + + # Check the else body: + if else_body: + self.accept(else_body) + + # + # Definitions + # + + def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: + # If a function/method can infer variable types, it should be processed as part + # of the module top level (i.e. module interface). + if not self.recurse_into_functions and not defn.def_or_infer_vars: + return + with self.tscope.function_scope(defn), self.set_recurse_into_functions(): + self._visit_overloaded_func_def(defn) + + def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: + num_abstract = 0 + if not defn.items: + # In this case we have already complained about none of these being + # valid overloads. + return + if len(defn.items) == 1: + self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, defn) + + if defn.is_property: + # HACK: Infer the type of the property. + assert isinstance(defn.items[0], Decorator) + self.visit_decorator(defn.items[0]) + if defn.items[0].var.is_settable_property: + # Perform a reduced visit just to infer the actual setter type. + self.visit_decorator_inner(defn.setter, skip_first_item=True) + setter_type = defn.setter.var.type + # Check if the setter can accept two positional arguments. + any_type = AnyType(TypeOfAny.special_form) + fallback_setter_type = CallableType( + arg_types=[any_type, any_type], + arg_kinds=[ARG_POS, ARG_POS], + arg_names=[None, None], + ret_type=any_type, + fallback=self.named_type("builtins.function"), + ) + if setter_type and not is_subtype(setter_type, fallback_setter_type): + self.fail("Invalid property setter signature", defn.setter.func) + setter_type = self.extract_callable_type(setter_type, defn) + if not isinstance(setter_type, CallableType) or len(setter_type.arg_types) != 2: + # TODO: keep precise type for callables with tricky but valid signatures. + setter_type = fallback_setter_type + defn.items[0].var.setter_type = setter_type + if isinstance(defn.type, Overloaded): + # Update legacy property type for decorated properties. + getter_type = self.extract_callable_type(defn.items[0].var.type, defn) + if getter_type is not None: + getter_type.definition = defn.items[0] + defn.type.items[0] = getter_type + for i, fdef in enumerate(defn.items): + assert isinstance(fdef, Decorator) + if defn.is_property: + assert isinstance(defn.items[0], Decorator) + settable = defn.items[0].var.is_settable_property + # Do not visit the second time the items we checked above. + if (settable and i > 1) or (not settable and i > 0): + self.check_func_item(fdef.func, name=fdef.func.name, allow_empty=True) + else: + # Perform full check for real overloads to infer type of all decorated + # overload variants. + self.visit_decorator_inner(fdef, allow_empty=True) + if fdef.func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT): + num_abstract += 1 + if num_abstract not in (0, len(defn.items)): + self.fail(message_registry.INCONSISTENT_ABSTRACT_OVERLOAD, defn) + if defn.impl: + with self.enter_overload_impl(defn.impl): + defn.impl.accept(self) + if not defn.is_property: + self.check_overlapping_overloads(defn) + if defn.type is None: + item_types = [] + for item in defn.items: + assert isinstance(item, Decorator) + item_type = self.extract_callable_type(item.var.type, item) + if item_type is not None: + item_type.definition = item + item_types.append(item_type) + if item_types: + defn.type = Overloaded(item_types) + elif defn.type is None: + # We store the getter type as an overall overload type, as some + # code paths are getting property type this way. + assert isinstance(defn.items[0], Decorator) + var_type = self.extract_callable_type(defn.items[0].var.type, defn) + if not isinstance(var_type, CallableType): + # Construct a fallback type, invalid types should be already reported. + any_type = AnyType(TypeOfAny.special_form) + var_type = CallableType( + arg_types=[any_type], + arg_kinds=[ARG_POS], + arg_names=[None], + ret_type=any_type, + fallback=self.named_type("builtins.function"), + ) + defn.type = Overloaded([var_type]) + # Check override validity after we analyzed current definition. + if not self.can_skip_diagnostics and defn.info: + found_method_base_classes = self.check_method_override(defn) + if ( + defn.is_explicit_override + and not found_method_base_classes + and found_method_base_classes is not None + # If the class has Any fallback, we can't be certain that a method + # is really missing - it might come from unfollowed import. + and not defn.info.fallback_to_any + ): + self.msg.no_overridable_method(defn.name, defn) + self.check_explicit_override_decorator(defn, found_method_base_classes, defn.impl) + self.check_inplace_operator_method(defn) + + @contextmanager + def enter_overload_impl(self, impl: OverloadPart) -> Iterator[None]: + self.overload_impl_stack.append(impl) + try: + yield + finally: + assert self.overload_impl_stack.pop() == impl + + def extract_callable_type(self, inner_type: Type | None, ctx: Context) -> CallableType | None: + """Get type as seen by an overload item caller.""" + inner_type = get_proper_type(inner_type) + outer_type: FunctionLike | None = None + if inner_type is None or isinstance(inner_type, AnyType): + return None + if isinstance(inner_type, TypeVarLikeType): + inner_type = get_proper_type(inner_type.upper_bound) + if isinstance(inner_type, TypeType): + inner_type = get_proper_type( + self.expr_checker.analyze_type_type_callee(inner_type.item, ctx) + ) + + if isinstance(inner_type, FunctionLike): + outer_type = inner_type + elif isinstance(inner_type, Instance): + inner_call = get_proper_type( + analyze_member_access( + name="__call__", + typ=inner_type, + context=ctx, + is_lvalue=False, + is_super=False, + is_operator=True, + original_type=inner_type, + chk=self, + ) + ) + if isinstance(inner_call, FunctionLike): + outer_type = inner_call + elif isinstance(inner_type, UnionType): + union_type = make_simplified_union(inner_type.items) + if isinstance(union_type, UnionType): + items = [] + for item in union_type.items: + callable_item = self.extract_callable_type(item, ctx) + if callable_item is None: + break + items.append(callable_item) + else: + joined_type = get_proper_type(join.join_type_list(items)) + if isinstance(joined_type, FunctionLike): + outer_type = joined_type + else: + return self.extract_callable_type(union_type, ctx) + + if outer_type is None: + self.msg.not_callable(inner_type, ctx) + return None + if isinstance(outer_type, Overloaded): + return None + + assert isinstance(outer_type, CallableType) + return outer_type + + def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None: + # At this point we should have set the impl already, and all remaining + # items are decorators + + if self.can_skip_diagnostics: + return + + # Compute some info about the implementation (if it exists) for use below + impl_type: CallableType | None = None + if defn.impl: + if isinstance(defn.impl, FuncDef): + inner_type: Type | None = defn.impl.type + elif isinstance(defn.impl, Decorator): + inner_type = defn.impl.var.type + else: + assert False, "Impl isn't the right type" + + # This can happen if we've got an overload with a different + # decorator or if the implementation is untyped -- we gave up on the types. + impl_type = self.extract_callable_type(inner_type, defn.impl) + + is_descriptor_get = defn.info and defn.name == "__get__" + for i, item in enumerate(defn.items): + assert isinstance(item, Decorator) + sig1 = self.extract_callable_type(item.var.type, item) + if sig1 is None: + continue + + for j, item2 in enumerate(defn.items[i + 1 :]): + assert isinstance(item2, Decorator) + sig2 = self.extract_callable_type(item2.var.type, item2) + if sig2 is None: + continue + + if not are_argument_counts_overlapping(sig1, sig2): + continue + + if overload_can_never_match(sig1, sig2): + self.msg.overloaded_signature_will_never_match(i + 1, i + j + 2, item2.func) + elif not is_descriptor_get: + # Note: we force mypy to check overload signatures in strict-optional mode + # so we don't incorrectly report errors when a user tries typing an overload + # that happens to have a 'if the argument is None' fallback. + # + # For example, the following is fine in strict-optional mode but would throw + # the unsafe overlap error when strict-optional is disabled: + # + # @overload + # def foo(x: None) -> int: ... + # @overload + # def foo(x: str) -> str: ... + # + # See Python 2's map function for a concrete example of this kind of overload. + current_class = self.scope.active_class() + type_vars = current_class.defn.type_vars if current_class else [] + with state.strict_optional_set(True): + if is_unsafe_overlapping_overload_signatures(sig1, sig2, type_vars): + flip_note = ( + j == 0 + and not is_unsafe_overlapping_overload_signatures( + sig2, sig1, type_vars + ) + and not overload_can_never_match(sig2, sig1) + ) + self.msg.overloaded_signatures_overlap( + i + 1, i + j + 2, flip_note, item.func + ) + + if impl_type is not None: + assert defn.impl is not None + + # This is what we want from implementation, it should accept all arguments + # of an overload, but the return types should go the opposite way. + if is_callable_compatible( + impl_type, + sig1, + is_compat=is_subtype, + is_proper_subtype=False, + is_compat_return=lambda l, r: is_subtype(r, l), + ): + continue + # If the above check didn't work, we repeat some key steps in + # is_callable_compatible() to give a better error message. + + # We perform a unification step that's very similar to what + # 'is_callable_compatible' does -- the only difference is that + # we check and see if the impl_type's return value is a + # *supertype* of the overload alternative, not a *subtype*. + # + # This is to match the direction the implementation's return + # needs to be compatible in. + if impl_type.variables: + impl: CallableType | None = unify_generic_callable( + # Normalize both before unifying + impl_type.with_unpacked_kwargs(), + sig1.with_unpacked_kwargs(), + ignore_return=False, + return_constraint_direction=SUPERTYPE_OF, + ) + if impl is None: + self.msg.overloaded_signatures_typevar_specific(i + 1, defn.impl) + continue + else: + impl = impl_type + + # Prevent extra noise from inconsistent use of @classmethod by copying + # the first arg from the method being checked against. + if sig1.arg_types and defn.info: + impl = impl.copy_modified(arg_types=[sig1.arg_types[0]] + impl.arg_types[1:]) + + # Is the overload alternative's arguments subtypes of the implementation's? + if not is_callable_compatible( + impl, sig1, is_compat=is_subtype, is_proper_subtype=False, ignore_return=True + ): + self.msg.overloaded_signatures_param_specific(i + 1, defn.impl) + + # Is the overload alternative's return type a subtype of the implementation's? + if not ( + is_subtype(sig1.ret_type, impl.ret_type) + or is_subtype(impl.ret_type, sig1.ret_type) + ): + self.msg.overloaded_signatures_ret_specific(i + 1, defn.impl) + + # Here's the scoop about generators and coroutines. + # + # There are two kinds of generators: classic generators (functions + # with `yield` or `yield from` in the body) and coroutines + # (functions declared with `async def`). The latter are specified + # in PEP 492 and only available in Python >= 3.5. + # + # Classic generators can be parameterized with three types: + # - ty is the Yield type (the type of y in `yield y`) + # - tc is the type reCeived by yield (the type of c in `c = yield`). + # - tr is the Return type (the type of r in `return r`) + # + # A classic generator must define a return type that's either + # `Generator[ty, tc, tr]`, Iterator[ty], or Iterable[ty] (or + # object or Any). If tc/tr are not given, both are None. + # + # A coroutine must define a return type corresponding to tr; the + # other two are unconstrained. The "external" return type (seen + # by the caller) is Awaitable[tr]. + # + # In addition, there's the synthetic type AwaitableGenerator: it + # inherits from both Awaitable and Generator and can be used both + # in `yield from` and in `await`. This type is set automatically + # for functions decorated with `@types.coroutine` or + # `@asyncio.coroutine`. Its single parameter corresponds to tr. + # + # PEP 525 adds a new type, the asynchronous generator, which was + # first released in Python 3.6. Async generators are `async def` + # functions that can also `yield` values. They can be parameterized + # with two types, ty and tc, because they cannot return a value. + # + # There are several useful methods, each taking a type t and a + # flag c indicating whether it's for a generator or coroutine: + # + # - is_generator_return_type(t, c) returns whether t is a Generator, + # Iterator, Iterable (if not c), or Awaitable (if c), or + # AwaitableGenerator (regardless of c). + # - is_async_generator_return_type(t) returns whether t is an + # AsyncGenerator. + # - get_generator_yield_type(t, c) returns ty. + # - get_generator_receive_type(t, c) returns tc. + # - get_generator_return_type(t, c) returns tr. + + def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool: + """Is `typ` a valid type for a generator/coroutine? + + True if `typ` is a *supertype* of Generator or Awaitable. + Also true it it's *exactly* AwaitableGenerator (modulo type parameters). + """ + typ = get_proper_type(typ) + if is_coroutine: + # This means we're in Python 3.5 or later. + at = self.named_generic_type("typing.Awaitable", [AnyType(TypeOfAny.special_form)]) + if is_subtype(at, typ): + return True + else: + any_type = AnyType(TypeOfAny.special_form) + gt = self.named_generic_type("typing.Generator", [any_type, any_type, any_type]) + if is_subtype(gt, typ): + return True + return isinstance(typ, Instance) and typ.type.fullname == "typing.AwaitableGenerator" + + def is_async_generator_return_type(self, typ: Type) -> bool: + """Is `typ` a valid type for an async generator? + + True if `typ` is a supertype of AsyncGenerator. + """ + try: + any_type = AnyType(TypeOfAny.special_form) + agt = self.named_generic_type("typing.AsyncGenerator", [any_type, any_type]) + except KeyError: + # we're running on a version of typing that doesn't have AsyncGenerator yet + return False + return is_subtype(agt, typ) + + def get_generator_yield_type(self, return_type: Type, is_coroutine: bool) -> Type: + """Given the declared return type of a generator (t), return the type it yields (ty).""" + return_type = get_proper_type(return_type) + + if isinstance(return_type, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=return_type) + elif isinstance(return_type, UnionType): + return make_simplified_union( + [self.get_generator_yield_type(item, is_coroutine) for item in return_type.items] + ) + elif not self.is_generator_return_type( + return_type, is_coroutine + ) and not self.is_async_generator_return_type(return_type): + # If the function doesn't have a proper Generator (or + # Awaitable) return type, anything is permissible. + return AnyType(TypeOfAny.from_error) + elif not isinstance(return_type, Instance): + # Same as above, but written as a separate branch so the typechecker can understand. + return AnyType(TypeOfAny.from_error) + elif return_type.type.fullname == "typing.Awaitable": + # Awaitable: ty is Any. + return AnyType(TypeOfAny.special_form) + elif return_type.args: + # AwaitableGenerator, Generator, AsyncGenerator, Iterator, or Iterable; ty is args[0]. + ret_type = return_type.args[0] + # TODO not best fix, better have dedicated yield token + return ret_type + else: + # If the function's declared supertype of Generator has no type + # parameters (i.e. is `object`), then the yielded values can't + # be accessed so any type is acceptable. IOW, ty is Any. + # (However, see https://github.com/python/mypy/issues/1933) + return AnyType(TypeOfAny.special_form) + + def get_generator_receive_type(self, return_type: Type, is_coroutine: bool) -> Type: + """Given a declared generator return type (t), return the type its yield receives (tc).""" + return_type = get_proper_type(return_type) + + if isinstance(return_type, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=return_type) + elif isinstance(return_type, UnionType): + return make_simplified_union( + [self.get_generator_receive_type(item, is_coroutine) for item in return_type.items] + ) + elif not self.is_generator_return_type( + return_type, is_coroutine + ) and not self.is_async_generator_return_type(return_type): + # If the function doesn't have a proper Generator (or + # Awaitable) return type, anything is permissible. + return AnyType(TypeOfAny.from_error) + elif not isinstance(return_type, Instance): + # Same as above, but written as a separate branch so the typechecker can understand. + return AnyType(TypeOfAny.from_error) + elif return_type.type.fullname == "typing.Awaitable": + # Awaitable, AwaitableGenerator: tc is Any. + return AnyType(TypeOfAny.special_form) + elif ( + return_type.type.fullname in ("typing.Generator", "typing.AwaitableGenerator") + and len(return_type.args) >= 3 + ): + # Generator: tc is args[1]. + return return_type.args[1] + elif return_type.type.fullname == "typing.AsyncGenerator" and len(return_type.args) >= 2: + return return_type.args[1] + else: + # `return_type` is a supertype of Generator, so callers won't be able to send it + # values. IOW, tc is None. + return NoneType() + + def get_coroutine_return_type(self, return_type: Type) -> Type: + return_type = get_proper_type(return_type) + if isinstance(return_type, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=return_type) + assert isinstance(return_type, Instance), "Should only be called on coroutine functions." + # Note: return type is the 3rd type parameter of Coroutine. + return return_type.args[2] + + def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Type: + """Given the declared return type of a generator (t), return the type it returns (tr).""" + return_type = get_proper_type(return_type) + + if isinstance(return_type, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=return_type) + elif isinstance(return_type, UnionType): + return make_simplified_union( + [self.get_generator_return_type(item, is_coroutine) for item in return_type.items] + ) + elif not self.is_generator_return_type(return_type, is_coroutine): + # If the function doesn't have a proper Generator (or + # Awaitable) return type, anything is permissible. + return AnyType(TypeOfAny.from_error) + elif not isinstance(return_type, Instance): + # Same as above, but written as a separate branch so the typechecker can understand. + return AnyType(TypeOfAny.from_error) + elif return_type.type.fullname == "typing.Awaitable" and len(return_type.args) == 1: + # Awaitable: tr is args[0]. + return return_type.args[0] + elif ( + return_type.type.fullname in ("typing.Generator", "typing.AwaitableGenerator") + and len(return_type.args) >= 3 + ): + # AwaitableGenerator, Generator: tr is args[2]. + return return_type.args[2] + else: + # We have a supertype of Generator (Iterator, Iterable, object) + # Treat `Iterator[X]` as a shorthand for `Generator[X, Any, None]`. + return NoneType() + + def visit_func_def(self, defn: FuncDef) -> None: + if not self.recurse_into_functions and not defn.def_or_infer_vars: + return + with self.tscope.function_scope(defn), self.set_recurse_into_functions(): + self.check_func_item(defn, name=defn.name) + if not self.can_skip_diagnostics: + if defn.info: + if not defn.is_overload and not defn.is_decorated: + # If the definition is the implementation for an + # overload, the legality of the override has already + # been typechecked, and decorated methods will be + # checked when the decorator is. + found_method_base_classes = self.check_method_override(defn) + self.check_explicit_override_decorator(defn, found_method_base_classes) + self.check_inplace_operator_method(defn) + if defn.original_def: + # Override previous definition. + new_type = self.function_type(defn) + self.check_func_def_override(defn, new_type) + + def check_func_item( + self, + defn: FuncItem, + type_override: CallableType | None = None, + name: str | None = None, + allow_empty: bool = False, + ) -> None: + """Type check a function. + + If type_override is provided, use it as the function type. + """ + self.dynamic_funcs.append(defn.is_dynamic() and not type_override) + + enclosing_node_deferred = self.current_node_deferred + with self.enter_partial_types(is_function=True): + typ = self.function_type(defn) + if type_override: + typ = type_override.copy_modified(line=typ.line, column=typ.column) + if isinstance(typ, CallableType): + with self.enter_attribute_inference_context(): + self.check_func_def(defn, typ, name, allow_empty) + else: + raise RuntimeError("Not supported") + + self.dynamic_funcs.pop() + self.current_node_deferred = enclosing_node_deferred + + if name == "__exit__": + self.check__exit__return_type(defn) + # TODO: the following logic should move to the dataclasses plugin + # https://github.com/python/mypy/issues/15515 + if name == "__post_init__": + if dataclasses_plugin.is_processed_dataclass(defn.info): + dataclasses_plugin.check_post_init(self, defn, defn.info) + + def check_func_def_override(self, defn: FuncDef, new_type: FunctionLike) -> None: + assert defn.original_def is not None + if isinstance(defn.original_def, FuncDef): + # Function definition overrides function definition. + old_type = self.function_type(defn.original_def) + if not is_same_type(new_type, old_type): + self.msg.incompatible_conditional_function_def(defn, old_type, new_type) + else: + # Function definition overrides a variable initialized via assignment or a + # decorated function. + orig_type = defn.original_def.type + if orig_type is None: + # If other branch is unreachable, we don't type check it and so we might + # not have a type for the original definition + return + if isinstance(orig_type, PartialType): + if orig_type.type is None: + # Ah this is a partial type. Give it the type of the function. + orig_def = defn.original_def + if isinstance(orig_def, Decorator): + var = orig_def.var + else: + var = orig_def + partial_types = self.find_partial_types(var) + if partial_types is not None: + var.type = new_type + del partial_types[var] + else: + # Trying to redefine something like partial empty list as function. + self.fail(message_registry.INCOMPATIBLE_REDEFINITION, defn) + else: + name_expr = NameExpr(defn.name) + name_expr.node = defn.original_def + self.binder.assign_type(name_expr, new_type, orig_type) + self.check_subtype( + new_type, + orig_type, + defn, + message_registry.INCOMPATIBLE_REDEFINITION, + "redefinition with type", + "original type", + ) + + @contextmanager + def enter_attribute_inference_context(self) -> Iterator[None]: + old_types = self.inferred_attribute_types + self.inferred_attribute_types = {} + yield None + self.inferred_attribute_types = old_types + + def check_func_def( + self, defn: FuncItem, typ: CallableType, name: str | None, allow_empty: bool = False + ) -> None: + """Type check a function definition.""" + # Expand type variables with value restrictions to ordinary types. + self.check_typevar_defaults(typ.variables) + expanded = self.expand_typevars(defn, typ) + original_typ = typ + for item, typ in expanded: + old_binder = self.binder + self.binder = ConditionalTypeBinder(self.options) + with self.binder.top_frame_context(): + defn.expanded.append(item) + + # We may be checking a function definition or an anonymous + # function. In the first case, set up another reference with the + # precise type. + if not self.can_skip_diagnostics: + self.check_funcdef_item(item, typ, name, defn=defn, original_typ=original_typ) + + # Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`. + if defn.is_awaitable_coroutine: + # Update the return type to AwaitableGenerator. + # (This doesn't exist in typing.py, only in typing.pyi.) + t = typ.ret_type + c = defn.is_coroutine + ty = self.get_generator_yield_type(t, c) + tc = self.get_generator_receive_type(t, c) + if c: + tr = self.get_coroutine_return_type(t) + else: + tr = self.get_generator_return_type(t, c) + ret_type = self.named_generic_type( + "typing.AwaitableGenerator", [ty, tc, tr, t] + ) + typ = typ.copy_modified(ret_type=ret_type) + defn.type = typ + + # Push return type. + self.return_types.append(typ.ret_type) + + with self.scope.push_function(defn): + # We temporary push the definition to get the self type as + # visible from *inside* of this function/method. + ref_type: Type | None = self.scope.active_self_type() + + if typ.type_is: + arg_index = 0 + # For methods and classmethods, we want the second parameter + if ref_type is not None and defn.has_self_or_cls_argument: + arg_index = 1 + if arg_index < len(typ.arg_types) and not is_subtype( + typ.type_is, typ.arg_types[arg_index] + ): + self.fail( + message_registry.NARROWED_TYPE_NOT_SUBTYPE.format( + format_type(typ.type_is, self.options), + format_type(typ.arg_types[arg_index], self.options), + ), + item, + ) + + # Store argument types. + found_self = False + if isinstance(defn, FuncDef) and not defn.is_decorated: + found_self = self.require_correct_self_argument(typ, defn) + for i in range(len(typ.arg_types)): + arg_type = typ.arg_types[i] + if isinstance(arg_type, TypeVarType): + # Refuse covariant parameter type variables + # TODO: check recursively for inner type variables + if ( + arg_type.variance == COVARIANT + and defn.name not in ("__init__", "__new__", "__post_init__") + and not is_private(defn.name) # private methods are not inherited + and (i != 0 or not found_self) + ): + ctx: Context = arg_type + if ctx.line < 0: + ctx = typ + self.fail(message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx) + # Need to store arguments again for the expanded item. + store_argument_type(item, i, typ, self.named_generic_type) + + # Type check initialization expressions. + body_is_trivial = is_trivial_body(defn.body) + if not self.can_skip_diagnostics: + self.check_default_params(item, body_is_trivial) + + # Type check body in a new scope. + with self.binder.top_frame_context(): + # Copy some type narrowings from an outer function when it seems safe enough + # (i.e. we can't find an assignment that might change the type of the + # variable afterwards). + new_frame: Frame | None = None + for frame in old_binder.frames: + for key, narrowed_type in frame.types.items(): + key_var = extract_var_from_literal_hash(key) + if key_var is not None and not self.is_var_redefined_in_outer_context( + key_var, defn.line + ): + # It seems safe to propagate the type narrowing to a nested scope. + if new_frame is None: + new_frame = self.binder.push_frame() + new_frame.types[key] = narrowed_type + self.binder.declarations[key] = old_binder.declarations[key] + + if self.options.allow_redefinition_new and not self.is_stub: + # Add formal argument types to the binder. + for arg in defn.arguments: + # TODO: Add these directly using a fast path (possibly "put") + v = arg.variable + if v.type is not None: + n = NameExpr(v.name) + n.node = v + self.binder.assign_type(n, v.type, v.type) + + with self.scope.push_function(defn): + # We suppress reachability warnings for empty generator functions + # (return; yield) which have a "yield" that's unreachable by definition + # since it's only there to promote the function into a generator function. + # + # We also suppress reachability warnings when we use TypeVars with value + # restrictions: we only want to report a warning if a certain statement is + # marked as being suppressed in *all* of the expansions, but we currently + # have no good way of doing this. + # + # TODO: Find a way of working around this limitation + if _is_empty_generator_function(item) or len(expanded) >= 2: + self.binder.suppress_unreachable_warnings() + # When checking a third-party library, we can skip function body, + # if during semantic analysis we found that there are no attributes + # defined via self here. + if ( + not self.can_skip_diagnostics + or self.options.preserve_asts + or not isinstance(defn, FuncDef) + or defn.def_or_infer_vars + ): + self.accept(item.body) + unreachable = self.binder.is_unreachable() + if new_frame is not None: + self.binder.pop_frame(True, 0) + + if not unreachable: + if defn.is_generator or is_named_instance( + self.return_types[-1], "typing.AwaitableGenerator" + ): + return_type = self.get_generator_return_type( + self.return_types[-1], defn.is_coroutine + ) + elif defn.is_coroutine: + return_type = self.get_coroutine_return_type(self.return_types[-1]) + else: + return_type = self.return_types[-1] + return_type = get_proper_type(return_type) + + allow_empty = allow_empty or self.options.allow_empty_bodies + + show_error = ( + not body_is_trivial + or + # Allow empty bodies for abstract methods, overloads, in tests and stubs. + ( + not allow_empty + and not ( + isinstance(defn, FuncDef) and defn.abstract_status != NOT_ABSTRACT + ) + and not self.is_stub + ) + ) + + if ( + self.can_skip_diagnostics + # Ignore plugin generated methods, these usually don't need any bodies. + or ( + defn.info is not FUNC_NO_INFO + and ( + defn.name not in defn.info.names + or defn.info.names[defn.name].plugin_generated + ) + ) + # Ignore also definitions that appear in `if TYPE_CHECKING: ...` blocks. + # These can't be called at runtime anyway (similar to plugin-generated). + or (isinstance(defn, FuncDef) and defn.is_mypy_only) + # We want to minimize the fallout from checking empty bodies + # that was absent in many mypy versions. + or (body_is_trivial and is_subtype(NoneType(), return_type)) + ): + show_error = False + + if show_error and not self.current_node_deferred: + may_be_abstract = ( + body_is_trivial + and defn.info is not FUNC_NO_INFO + and defn.info.metaclass_type is not None + and defn.info.metaclass_type.type.has_base("abc.ABCMeta") + ) + if self.options.warn_no_return: + if not isinstance(return_type, (NoneType, AnyType)): + # Control flow fell off the end of a function that was + # declared to return a non-None type. + if isinstance(return_type, UninhabitedType): + # This is a NoReturn function + msg = message_registry.INVALID_IMPLICIT_RETURN + else: + msg = message_registry.MISSING_RETURN_STATEMENT + if body_is_trivial: + msg = msg._replace(code=codes.EMPTY_BODY) + self.fail(msg, defn) + if may_be_abstract: + self.note(message_registry.EMPTY_BODY_ABSTRACT, defn) + else: + msg = message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE + if body_is_trivial: + msg = msg._replace(code=codes.EMPTY_BODY) + # similar to code in check_return_stmt + if ( + not self.check_subtype( + subtype_label="implicitly returns", + subtype=NoneType(), + supertype_label="expected", + supertype=return_type, + context=defn, + msg=msg, + ) + and may_be_abstract + ): + self.note(message_registry.EMPTY_BODY_ABSTRACT, defn) + + self.return_types.pop() + + self.binder = old_binder + + def check_funcdef_item( + self, + item: FuncItem, + typ: CallableType, + name: str | None, + *, + defn: FuncItem, + original_typ: CallableType, + ) -> None: + if isinstance(item, FuncDef): + fdef = item + # Check if __init__ has an invalid return type. + if ( + fdef.info + and fdef.name in ("__init__", "__init_subclass__") + and not isinstance(get_proper_type(typ.ret_type), (NoneType, UninhabitedType)) + and not self.dynamic_funcs[-1] + ): + self.fail(message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name), item) + + # Check validity of __new__ signature + if fdef.info and fdef.name == "__new__": + self.check___new___signature(fdef, typ) + + self.check_for_missing_annotations(fdef) + if self.options.disallow_any_unimported: + if fdef.type and isinstance(fdef.type, CallableType): + ret_type = fdef.type.ret_type + if has_any_from_unimported_type(ret_type): + self.msg.unimported_type_becomes_any("Return type", ret_type, fdef) + for idx, arg_type in enumerate(fdef.type.arg_types): + if has_any_from_unimported_type(arg_type): + prefix = f'Argument {idx + 1} to "{fdef.name}"' + self.msg.unimported_type_becomes_any(prefix, arg_type, fdef) + check_for_explicit_any( + fdef.type, self.options, self.is_typeshed_stub, self.msg, context=fdef + ) + + if name: # Special method names + if ( + defn.info + and self.is_reverse_op_method(name) + and defn not in self.overload_impl_stack + ): + self.check_reverse_op_method(item, typ, name, defn) + elif name in ("__getattr__", "__getattribute__"): + self.check_getattr_method(typ, defn, name) + elif name == "__setattr__": + self.check_setattr_method(typ, defn) + + # Refuse contravariant return type variable + if isinstance(typ.ret_type, TypeVarType): + if typ.ret_type.variance == CONTRAVARIANT: + self.fail(message_registry.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT, typ.ret_type) + self.check_unbound_return_typevar(typ) + elif isinstance(original_typ.ret_type, TypeVarType) and original_typ.ret_type.values: + # Since type vars with values are expanded, the return type is changed + # to a raw value. This is a hack to get it back. + self.check_unbound_return_typevar(original_typ) + + # Check that Generator functions have the appropriate return type. + if defn.is_generator: + if defn.is_async_generator: + if not self.is_async_generator_return_type(typ.ret_type): + self.fail(message_registry.INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR, typ) + else: + if not self.is_generator_return_type(typ.ret_type, defn.is_coroutine): + self.fail(message_registry.INVALID_RETURN_TYPE_FOR_GENERATOR, typ) + + def require_correct_self_argument(self, func: Type, defn: FuncDef) -> bool: + func = get_proper_type(func) + if not isinstance(func, CallableType): + return False + + # Do not report errors for untyped methods in classes nested in untyped funcs. + if not ( + self.options.check_untyped_defs + or len(self.dynamic_funcs) < 2 + or not self.dynamic_funcs[-2] + or not defn.is_dynamic() + ): + return bool(func.arg_types) + + with self.scope.push_function(defn): + # We temporary push the definition to get the self type as + # visible from *inside* of this function/method. + ref_type: Type | None = self.scope.active_self_type() + if ref_type is None: + return False + + if not defn.has_self_or_cls_argument or ( + func.arg_kinds and func.arg_kinds[0] in [nodes.ARG_STAR, nodes.ARG_STAR2] + ): + return False + + if not func.arg_types: + self.fail( + 'Method must have at least one argument. Did you forget the "self" argument?', defn + ) + return False + + if self.can_skip_diagnostics: + return True + + arg_type = func.arg_types[0] + if defn.is_class or defn.name == "__new__": + ref_type = mypy.types.TypeType.make_normalized(ref_type) + if is_same_type(arg_type, ref_type): + return True + + # This level of erasure matches the one in checkmember.check_self_arg(), + # better keep these two checks consistent. + erased = get_proper_type(erase_typevars(erase_to_bound(arg_type))) + if not is_subtype(ref_type, erased, ignore_type_params=True): + if ( + isinstance(erased, Instance) + and erased.type.is_protocol + or isinstance(erased, TypeType) + and isinstance(erased.item, Instance) + and erased.item.type.is_protocol + ): + # We allow the explicit self-type to be not a supertype of + # the current class if it is a protocol. For such cases + # the consistency check will be performed at call sites. + msg = None + elif func.arg_names[0] in {"self", "cls"}: + msg = message_registry.ERASED_SELF_TYPE_NOT_SUPERTYPE.format( + erased.str_with_options(self.options), ref_type.str_with_options(self.options) + ) + else: + msg = message_registry.MISSING_OR_INVALID_SELF_TYPE + if msg: + self.fail(msg, defn) + return True + + def is_var_redefined_in_outer_context(self, v: Var, after_line: int) -> bool: + """Can the variable be assigned to at module top level or outer function? + + Note that this doesn't do a full CFG analysis but uses a line number based + heuristic that isn't correct in some (rare) cases. + """ + if v.is_final: + # Final vars are definitely never reassigned. + return False + + outers = self.tscope.outer_functions() + if not outers: + # Top-level function -- outer context is top level, and we can't reason about + # globals + return True + for outer in outers: + if isinstance(outer, FuncDef): + if find_last_var_assignment_line(outer.body, v) >= after_line: + return True + return False + + def check_unbound_return_typevar(self, typ: CallableType) -> None: + """Fails when the return typevar is not defined in arguments.""" + if isinstance(typ.ret_type, TypeVarType) and typ.ret_type in typ.variables: + arg_type_visitor = CollectArgTypeVarTypes() + for argtype in typ.arg_types: + argtype.accept(arg_type_visitor) + + if typ.ret_type not in arg_type_visitor.arg_types: + self.fail(message_registry.UNBOUND_TYPEVAR, typ.ret_type, code=TYPE_VAR) + upper_bound = get_proper_type(typ.ret_type.upper_bound) + if not ( + isinstance(upper_bound, Instance) + and upper_bound.type.fullname == "builtins.object" + ): + self.note( + "Consider using the upper bound " + f"{format_type(typ.ret_type.upper_bound, self.options)} instead", + context=typ.ret_type, + ) + + def check_default_params(self, item: FuncItem, body_is_trivial: bool) -> None: + for param in item.arguments: + if param.initializer is None: + continue + if body_is_trivial and isinstance(param.initializer, EllipsisExpr): + continue + name = param.variable.name + msg = "Incompatible default for " + if name.startswith("__tuple_param_"): + msg += f"tuple parameter {name[12:]}" + else: + msg += f'parameter "{name}"' + if ( + not self.options.implicit_optional + and isinstance(param.initializer, NameExpr) + and param.initializer.fullname == "builtins.None" + ): + notes = [ + "PEP 484 prohibits implicit Optional. " + "Accordingly, mypy has changed its default to no_implicit_optional=True", + "Use https://github.com/hauntsaninja/no_implicit_optional to automatically " + "upgrade your codebase", + ] + else: + notes = None + self.check_simple_assignment( + param.variable.type, + param.initializer, + context=param.initializer, + msg=ErrorMessage(msg, code=codes.ASSIGNMENT), + lvalue_name="parameter", + rvalue_name="default", + notes=notes, + ) + + def is_forward_op_method(self, method_name: str) -> bool: + return method_name in operators.reverse_op_methods + + def is_reverse_op_method(self, method_name: str) -> bool: + return method_name in operators.reverse_op_method_set + + def check_for_missing_annotations(self, fdef: FuncItem) -> None: + show_untyped = not self.is_typeshed_stub or self.options.warn_incomplete_stub + if not show_untyped: + return + + # Check for functions with unspecified/not fully specified types. + def is_unannotated_any(t: Type) -> bool: + if not isinstance(t, ProperType): + return False + return isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated + + has_explicit_annotation = isinstance(fdef.type, CallableType) and any( + not is_unannotated_any(t) for t in fdef.type.arg_types + [fdef.type.ret_type] + ) + + check_incomplete_defs = self.options.disallow_incomplete_defs and has_explicit_annotation + if self.options.disallow_untyped_defs or check_incomplete_defs: + if fdef.type is None and self.options.disallow_untyped_defs: + if not fdef.arguments or ( + len(fdef.arguments) == 1 + and (fdef.arg_names[0] == "self" or fdef.arg_names[0] == "cls") + ): + self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef) + if not has_return_statement(fdef) and not fdef.is_generator: + self.note( + 'Use "-> None" if function does not return a value', + fdef, + code=codes.NO_UNTYPED_DEF, + ) + else: + self.fail(message_registry.FUNCTION_TYPE_EXPECTED, fdef) + elif isinstance(fdef.type, CallableType): + ret_type = get_proper_type(fdef.type.ret_type) + if is_unannotated_any(ret_type): + self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef) + elif fdef.is_generator: + if is_unannotated_any( + self.get_generator_return_type(ret_type, fdef.is_coroutine) + ): + self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef) + elif fdef.is_coroutine and isinstance(ret_type, Instance): + if is_unannotated_any(self.get_coroutine_return_type(ret_type)): + self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef) + if any(is_unannotated_any(t) for t in fdef.type.arg_types): + self.fail(message_registry.PARAM_TYPE_EXPECTED, fdef) + + def check___new___signature(self, fdef: FuncDef, typ: CallableType) -> None: + self_type = fill_typevars_with_any(fdef.info) + bound_type = bind_self(typ, self_type, is_classmethod=True) + # Check that __new__ (after binding cls) returns an instance + # type (or any). + if fdef.info.is_metaclass(): + # This is a metaclass, so it must return a new unrelated type. + self.check_subtype( + bound_type.ret_type, + self.type_type(), + fdef, + message_registry.INVALID_NEW_TYPE, + "returns", + "but must return a subtype of", + ) + elif not isinstance( + get_proper_type(bound_type.ret_type), + (AnyType, Instance, TupleType, UninhabitedType, LiteralType), + ): + self.fail( + message_registry.NON_INSTANCE_NEW_TYPE.format( + format_type(bound_type.ret_type, self.options) + ), + fdef, + ) + else: + # And that it returns a subtype of the class + self.check_subtype( + bound_type.ret_type, + self_type, + fdef, + message_registry.INVALID_NEW_TYPE, + "returns", + "but must return a subtype of", + ) + + def check_reverse_op_method( + self, defn: FuncItem, reverse_type: CallableType, reverse_name: str, context: Context + ) -> None: + """Check a reverse operator method such as __radd__.""" + # Decides whether it's worth calling check_overlapping_op_methods(). + + # This used to check for some very obscure scenario. It now + # just decides whether it's worth calling + # check_overlapping_op_methods(). + + assert defn.info + + # First check for a valid signature + method_type = CallableType( + [AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)], + [nodes.ARG_POS, nodes.ARG_POS], + [None, None], + AnyType(TypeOfAny.special_form), + self.named_type("builtins.function"), + ) + if not is_subtype(reverse_type, method_type): + self.msg.invalid_signature(reverse_type, context) + return + + if reverse_name in ("__eq__", "__ne__"): + # These are defined for all objects => can't cause trouble. + return + + # With 'Any' or 'object' return type we are happy, since any possible + # return value is valid. + ret_type = get_proper_type(reverse_type.ret_type) + if isinstance(ret_type, AnyType): + return + if isinstance(ret_type, Instance): + if ret_type.type.fullname == "builtins.object": + return + if reverse_type.arg_kinds[0] == ARG_STAR: + reverse_type = reverse_type.copy_modified( + arg_types=[reverse_type.arg_types[0]] * 2, + arg_kinds=[ARG_POS] * 2, + arg_names=[reverse_type.arg_names[0], "_"], + ) + assert len(reverse_type.arg_types) >= 2 + + forward_name = operators.normal_from_reverse_op[reverse_name] + forward_inst = get_proper_type(reverse_type.arg_types[1]) + if isinstance(forward_inst, TypeVarType): + forward_inst = get_proper_type(forward_inst.upper_bound) + elif isinstance(forward_inst, TupleType): + forward_inst = tuple_fallback(forward_inst) + elif isinstance(forward_inst, (FunctionLike, TypedDictType, LiteralType)): + forward_inst = forward_inst.fallback + if isinstance(forward_inst, TypeType): + item = forward_inst.item + if isinstance(item, Instance): + opt_meta = item.type.metaclass_type + if opt_meta is not None: + forward_inst = opt_meta + + def has_readable_member(typ: UnionType | Instance, name: str) -> bool: + # TODO: Deal with attributes of TupleType etc. + if isinstance(typ, Instance): + return typ.type.has_readable_member(name) + return all( + (isinstance(x, UnionType) and has_readable_member(x, name)) + or (isinstance(x, Instance) and x.type.has_readable_member(name)) + for x in get_proper_types(typ.relevant_items()) + ) + + if not ( + isinstance(forward_inst, (Instance, UnionType)) + and has_readable_member(forward_inst, forward_name) + ): + return + forward_base = reverse_type.arg_types[1] + forward_type = self.expr_checker.analyze_external_member_access( + forward_name, forward_base, context=defn + ) + self.check_overlapping_op_methods( + reverse_type, + reverse_name, + defn.info, + forward_type, + forward_name, + forward_base, + context=defn, + ) + + def check_overlapping_op_methods( + self, + reverse_type: CallableType, + reverse_name: str, + reverse_class: TypeInfo, + forward_type: Type, + forward_name: str, + forward_base: Type, + context: Context, + ) -> None: + """Check for overlapping method and reverse method signatures. + + This function assumes that: + + - The reverse method has valid argument count and kinds. + - If the reverse operator method accepts some argument of type + X, the forward operator method also belong to class X. + + For example, if we have the reverse operator `A.__radd__(B)`, then the + corresponding forward operator must have the type `B.__add__(...)`. + """ + + # Note: Suppose we have two operator methods "A.__rOP__(B) -> R1" and + # "B.__OP__(C) -> R2". We check if these two methods are unsafely overlapping + # by using the following algorithm: + # + # 1. Rewrite "B.__OP__(C) -> R1" to "temp1(B, C) -> R1" + # + # 2. Rewrite "A.__rOP__(B) -> R2" to "temp2(B, A) -> R2" + # + # 3. Treat temp1 and temp2 as if they were both variants in the same + # overloaded function. (This mirrors how the Python runtime calls + # operator methods: we first try __OP__, then __rOP__.) + # + # If the first signature is unsafely overlapping with the second, + # report an error. + # + # 4. However, if temp1 shadows temp2 (e.g. the __rOP__ method can never + # be called), do NOT report an error. + # + # This behavior deviates from how we handle overloads -- many of the + # modules in typeshed seem to define __OP__ methods that shadow the + # corresponding __rOP__ method. + # + # Note: we do not attempt to handle unsafe overlaps related to multiple + # inheritance. (This is consistent with how we handle overloads: we also + # do not try checking unsafe overlaps due to multiple inheritance there.) + + for forward_item in flatten_nested_unions([forward_type]): + forward_item = get_proper_type(forward_item) + if isinstance(forward_item, CallableType): + if self.is_unsafe_overlapping_op(forward_item, forward_base, reverse_type): + self.msg.operator_method_signatures_overlap( + reverse_class, reverse_name, forward_base, forward_name, context + ) + elif isinstance(forward_item, Overloaded): + for item in forward_item.items: + if self.is_unsafe_overlapping_op(item, forward_base, reverse_type): + self.msg.operator_method_signatures_overlap( + reverse_class, reverse_name, forward_base, forward_name, context + ) + elif not isinstance(forward_item, AnyType): + self.msg.forward_operator_not_callable(forward_name, context) + + def is_unsafe_overlapping_op( + self, forward_item: CallableType, forward_base: Type, reverse_type: CallableType + ) -> bool: + # TODO: check argument kinds? + if len(forward_item.arg_types) < 1: + # Not a valid operator method -- can't succeed anyway. + return False + + # Erase the type if necessary to make sure we don't have a single + # TypeVar in forward_tweaked. (Having a function signature containing + # just a single TypeVar can lead to unpredictable behavior.) + forward_base_erased = forward_base + if isinstance(forward_base, TypeVarType): + forward_base_erased = erase_to_bound(forward_base) + + # Construct normalized function signatures corresponding to the + # operator methods. The first argument is the left operand and the + # second operand is the right argument -- we switch the order of + # the arguments of the reverse method. + + # TODO: this manipulation is dangerous if callables are generic. + # Shuffling arguments between callables can create meaningless types. + forward_tweaked = forward_item.copy_modified( + arg_types=[forward_base_erased, forward_item.arg_types[0]], + arg_kinds=[nodes.ARG_POS] * 2, + arg_names=[None] * 2, + ) + reverse_tweaked = reverse_type.copy_modified( + arg_types=[reverse_type.arg_types[1], reverse_type.arg_types[0]], + arg_kinds=[nodes.ARG_POS] * 2, + arg_names=[None] * 2, + ) + + reverse_base_erased = reverse_type.arg_types[0] + if isinstance(reverse_base_erased, TypeVarType): + reverse_base_erased = erase_to_bound(reverse_base_erased) + + if is_same_type(reverse_base_erased, forward_base_erased): + return False + elif is_subtype(reverse_base_erased, forward_base_erased): + first = reverse_tweaked + second = forward_tweaked + else: + first = forward_tweaked + second = reverse_tweaked + + current_class = self.scope.active_class() + type_vars = current_class.defn.type_vars if current_class else [] + return is_unsafe_overlapping_overload_signatures( + first, second, type_vars, partial_only=False + ) + + def check_inplace_operator_method(self, defn: FuncBase) -> None: + """Check an inplace operator method such as __iadd__. + + They cannot arbitrarily overlap with __add__. + """ + method = defn.name + if method not in operators.inplace_operator_methods: + return + typ = bind_self(self.function_type(defn)) + cls = defn.info + other_method = "__" + method[3:] + if cls.has_readable_member(other_method): + instance = fill_typevars(cls) + typ2 = get_proper_type( + self.expr_checker.analyze_external_member_access(other_method, instance, defn) + ) + fail = False + if isinstance(typ2, FunctionLike): + if not is_more_general_arg_prefix(typ, typ2): + fail = True + else: + # TODO overloads + fail = True + if fail: + self.msg.signatures_incompatible(method, other_method, defn) + + def check_getattr_method(self, typ: Type, context: Context, name: str) -> None: + if len(self.scope.stack) == 1: + # module scope + if name == "__getattribute__": + self.fail(message_registry.MODULE_LEVEL_GETATTRIBUTE, context) + return + # __getattr__ is fine at the module level as of Python 3.7 (PEP 562). We could + # show an error for Python < 3.7, but that would be annoying in code that supports + # both 3.7 and older versions. + method_type = CallableType( + [self.named_type("builtins.str")], + [nodes.ARG_POS], + [None], + AnyType(TypeOfAny.special_form), + self.named_type("builtins.function"), + ) + elif self.scope.active_class(): + method_type = CallableType( + [AnyType(TypeOfAny.special_form), self.named_type("builtins.str")], + [nodes.ARG_POS, nodes.ARG_POS], + [None, None], + AnyType(TypeOfAny.special_form), + self.named_type("builtins.function"), + ) + else: + return + if not is_subtype(typ, method_type): + self.msg.invalid_signature_for_special_method(typ, context, name) + + def check_setattr_method(self, typ: Type, context: Context) -> None: + if not self.scope.active_class(): + return + method_type = CallableType( + [ + AnyType(TypeOfAny.special_form), + self.named_type("builtins.str"), + AnyType(TypeOfAny.special_form), + ], + [nodes.ARG_POS, nodes.ARG_POS, nodes.ARG_POS], + [None, None, None], + NoneType(), + self.named_type("builtins.function"), + ) + if not is_subtype(typ, method_type): + self.msg.invalid_signature_for_special_method(typ, context, "__setattr__") + + def check_slots_definition(self, typ: Type, context: Context) -> None: + """Check the type of __slots__.""" + str_type = self.named_type("builtins.str") + expected_type = UnionType( + [str_type, self.named_generic_type("typing.Iterable", [str_type])] + ) + self.check_subtype( + typ, + expected_type, + context, + message_registry.INVALID_TYPE_FOR_SLOTS, + "actual type", + "expected type", + code=codes.ASSIGNMENT, + ) + + def check_match_args(self, var: Var, typ: Type, context: Context) -> None: + """Check that __match_args__ contains literal strings""" + if not self.scope.active_class(): + return + typ = get_proper_type(typ) + if not isinstance(typ, TupleType) or not all( + is_string_literal(item) for item in typ.items + ): + self.msg.note( + "__match_args__ must be a tuple containing string literals for checking " + "of match statements to work", + context, + code=codes.LITERAL_REQ, + ) + + def expand_typevars( + self, defn: FuncItem, typ: CallableType + ) -> list[tuple[FuncItem, CallableType]]: + # TODO use generator + subst: list[list[tuple[TypeVarId, Type]]] = [] + tvars = list(typ.variables) or [] + if defn.info: + # Class type variables + tvars += defn.info.defn.type_vars or [] + for tvar in tvars: + if isinstance(tvar, TypeVarType) and tvar.values: + subst.append([(tvar.id, value) for value in tvar.values]) + # Make a copy of the function to check for each combination of + # value restricted type variables. (Except when running mypyc, + # where we need one canonical version of the function.) + if subst and not (self.options.mypyc or self.options.inspections): + result: list[tuple[FuncItem, CallableType]] = [] + for substitutions in itertools.product(*subst): + mapping = dict(substitutions) + result.append((expand_func(defn, mapping), expand_type(typ, mapping))) + return result + else: + return [(defn, typ)] + + def check_explicit_override_decorator( + self, + defn: FuncDef | OverloadedFuncDef, + found_method_base_classes: list[TypeInfo] | None, + context: Context | None = None, + ) -> None: + plugin_generated = False + if defn.info and (node := defn.info.get(defn.name)) and node.plugin_generated: + # Do not report issues for plugin generated nodes, + # they can't realistically use `@override` for their methods. + plugin_generated = True + + if ( + not plugin_generated + and found_method_base_classes + and not defn.is_explicit_override + and defn.name not in ("__init__", "__new__") + and not is_private(defn.name) + ): + self.msg.explicit_override_decorator_missing( + defn.name, found_method_base_classes[0].fullname, context or defn + ) + + def check_method_override( + self, defn: FuncDef | OverloadedFuncDef | Decorator + ) -> list[TypeInfo] | None: + """Check if function definition is compatible with base classes. + + This may defer the method if a signature is not available in at least one base class. + Return ``None`` if that happens. + + Return a list of base classes which contain an attribute with the method name. + """ + if self.can_skip_diagnostics: + return None + # Check against definitions in base classes. + check_override_compatibility = ( + defn.name not in ("__init__", "__new__", "__init_subclass__", "__post_init__") + and (self.options.check_untyped_defs or not defn.is_dynamic()) + and ( + # don't check override for synthesized __replace__ methods from dataclasses + defn.name != "__replace__" + or defn.info.metadata.get("dataclass_tag") is None + ) + ) + found_method_base_classes: list[TypeInfo] = [] + for base in defn.info.mro[1:]: + result = self.check_method_or_accessor_override_for_base( + defn, base, check_override_compatibility + ) + if result is None: + # Node was deferred, we will have another attempt later. + return None + if result: + found_method_base_classes.append(base) + return found_method_base_classes + + def check_method_or_accessor_override_for_base( + self, + defn: FuncDef | OverloadedFuncDef | Decorator, + base: TypeInfo, + check_override_compatibility: bool, + ) -> bool | None: + """Check if method definition is compatible with a base class. + + Return ``None`` if the node was deferred because one of the corresponding + superclass nodes is not ready. + + Return ``True`` if an attribute with the method name was found in the base class. + """ + found_base_method = False + if base: + name = defn.name + base_attr = base.names.get(name) + if base_attr: + # First, check if we override a final (always an error, even with Any types). + if is_final_node(base_attr.node) and not is_private(name): + self.msg.cant_override_final(name, base.name, defn) + # Second, final can't override anything writeable independently of types. + if defn.is_final: + self.check_if_final_var_override_writable(name, base_attr.node, defn) + found_base_method = True + if check_override_compatibility: + # Check compatibility of the override signature + # (__init__, __new__, __init_subclass__ are special). + if self.check_method_override_for_base_with_name(defn, name, base): + return None + if name in operators.inplace_operator_methods: + # Figure out the name of the corresponding operator method. + method = "__" + name[3:] + # An inplace operator method such as __iadd__ might not be + # always introduced safely if a base class defined __add__. + # TODO can't come up with an example where this is + # necessary; now it's "just in case" + if self.check_method_override_for_base_with_name(defn, method, base): + return None + return found_base_method + + def check_setter_type_override(self, defn: OverloadedFuncDef, base: TypeInfo) -> None: + """Check override of a setter type of a mutable attribute. + + Currently, this should be only called when either base node or the current node + is a custom settable property (i.e. where setter type is different from getter type). + Note that this check is contravariant. + """ + typ, _ = self.node_type_from_base(defn.name, defn.info, defn, setter_type=True) + original_type, _ = self.node_type_from_base(defn.name, base, defn, setter_type=True) + # The caller should handle deferrals. + assert typ is not None and original_type is not None + + if not is_subtype(original_type, typ): + self.msg.incompatible_setter_override(defn.setter, typ, original_type, base) + + def check_method_override_for_base_with_name( + self, defn: FuncDef | OverloadedFuncDef | Decorator, name: str, base: TypeInfo + ) -> bool: + """Check if overriding an attribute `name` of `base` with `defn` is valid. + + Return True if the supertype node was not analysed yet, and `defn` was deferred. + """ + base_attr = base.names.get(name) + if not base_attr: + return False + # The name of the method is defined in the base class. + + # Point errors at the 'def' line (important for backward compatibility + # of type ignores). + if not isinstance(defn, Decorator): + context = defn + else: + context = defn.func + + # Construct the type of the overriding method. + if isinstance(defn, (FuncDef, OverloadedFuncDef)): + override_class_or_static = defn.is_class or defn.is_static + else: + override_class_or_static = defn.func.is_class or defn.func.is_static + typ, _ = self.node_type_from_base(defn.name, defn.info, defn) + if typ is None: + # This may only happen if we're checking `x-redefinition` member + # and `x` itself is for some reason gone. Normally the node should + # be reachable from the containing class by its name. + # The redefinition is never removed, use this as a sanity check to verify + # the reasoning above. + assert f"{defn.name}-redefinition" in defn.info.names + return False + + original_node = base_attr.node + # `original_type` can be partial if (e.g.) it is originally an + # instance variable from an `__init__` block that becomes deferred. + supertype_ready = True + original_type, _ = self.node_type_from_base(name, base, defn) + if original_type is None: + supertype_ready = False + if self.pass_num < self.last_pass: + # If there are passes left, defer this node until next pass, + # otherwise try reconstructing the method type from available information. + # For consistency, defer an enclosing top-level function (if any). + top_level = self.scope.top_level_function() + if isinstance(top_level, FuncDef): + self.defer_node(top_level, self.scope.enclosing_class(top_level)) + else: + # Specify enclosing class explicitly, as we check type override before + # entering e.g. decorators or overloads. + self.defer_node(defn, defn.info) + return True + elif isinstance(original_node, (FuncDef, OverloadedFuncDef)): + original_type = self.function_type(original_node) + elif isinstance(original_node, Decorator): + original_type = self.function_type(original_node.func) + elif isinstance(original_node, Var): + # Super type can define method as an attribute. + # See https://github.com/python/mypy/issues/10134 + + # We also check that sometimes `original_node.type` is None. + # This is the case when we use something like `__hash__ = None`. + if original_node.type is not None: + original_type = get_proper_type(original_node.type) + else: + original_type = NoneType() + else: + # Will always fail to typecheck below, since we know the node is a method + original_type = NoneType() + + always_allow_covariant = False + if is_settable_property(defn) and ( + is_settable_property(original_node) or isinstance(original_node, Var) + ): + if is_custom_settable_property(defn) or (is_custom_settable_property(original_node)): + # Unlike with getter, where we try to construct some fallback type in case of + # deferral during last_pass, we can't make meaningful setter checks if the + # supertype is not known precisely. + if supertype_ready: + always_allow_covariant = True + self.check_setter_type_override(defn, base) + + if isinstance(original_node, (FuncDef, OverloadedFuncDef)): + original_class_or_static = original_node.is_class or original_node.is_static + elif isinstance(original_node, Decorator): + fdef = original_node.func + original_class_or_static = fdef.is_class or fdef.is_static + else: + original_class_or_static = False # a variable can't be class or static + + typ = get_proper_type(typ) + original_type = get_proper_type(original_type) + + if ( + is_property(defn) + and isinstance(original_node, Var) + and not original_node.is_final + and (not original_node.is_property or original_node.is_settable_property) + and isinstance(defn, Decorator) + ): + # We only give an error where no other similar errors will be given. + if not isinstance(original_type, AnyType): + self.msg.fail( + "Cannot override writeable attribute with read-only property", + # Give an error on function line to match old behaviour. + defn.func, + code=codes.OVERRIDE, + ) + + if isinstance(original_type, AnyType) or isinstance(typ, AnyType): + pass + elif isinstance(original_type, FunctionLike) and isinstance(typ, FunctionLike): + # Check that the types are compatible. + ok = self.check_override( + typ, + original_type, + defn.name, + name, + base.name if base.module_name == self.tree.fullname else base.fullname, + original_class_or_static, + override_class_or_static, + context, + ) + # Check if this override is covariant. + if ( + ok + and original_node + and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes + and self.is_writable_attribute(original_node) + and not always_allow_covariant + and not is_subtype(original_type, typ, ignore_pos_arg_names=True) + ): + base_str, override_str = format_type_distinctly( + original_type, typ, options=self.options + ) + msg = message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE.with_additional_msg( + f' (base class "{base.name}" defined the type as {base_str},' + f" override has type {override_str})" + ) + self.fail(msg, context) + elif isinstance(original_type, UnionType) and any( + is_subtype(typ, orig_typ, ignore_pos_arg_names=True) + for orig_typ in original_type.items + ): + # This method is a subtype of at least one union variant. + if ( + original_node + and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes + and self.is_writable_attribute(original_node) + and not always_allow_covariant + ): + # Covariant override of mutable attribute. + base_str, override_str = format_type_distinctly( + original_type, typ, options=self.options + ) + msg = message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE.with_additional_msg( + f' (base class "{base.name}" defined the type as {base_str},' + f" override has type {override_str})" + ) + self.fail(msg, context) + elif is_equivalent(original_type, typ): + # Assume invariance for a non-callable attribute here. Note + # that this doesn't affect read-only properties which can have + # covariant overrides. + pass + elif ( + original_node + and (not self.is_writable_attribute(original_node) or always_allow_covariant) + and is_subtype(typ, original_type) + ): + # If the attribute is read-only, allow covariance + pass + else: + self.msg.signature_incompatible_with_supertype( + defn.name, name, base.name, context, original=original_type, override=typ + ) + return False + + def get_op_other_domain(self, tp: FunctionLike) -> Type | None: + if isinstance(tp, CallableType): + if tp.arg_kinds and tp.arg_kinds[0] == ARG_POS: + # For generic methods, domain comparison is tricky, as a first + # approximation erase all remaining type variables. + return erase_typevars(tp.arg_types[0], {v.id for v in tp.variables}) + return None + elif isinstance(tp, Overloaded): + raw_items = [self.get_op_other_domain(it) for it in tp.items] + items = [it for it in raw_items if it] + if items: + return make_simplified_union(items) + return None + else: + assert False, "Need to check all FunctionLike subtypes here" + + def check_override( + self, + override: FunctionLike, + original: FunctionLike, + name: str, + name_in_super: str, + supertype: str, + original_class_or_static: bool, + override_class_or_static: bool, + node: Context, + ) -> bool: + """Check a method override with given signatures. + + Arguments: + override: The signature of the overriding method. + original: The signature of the original supertype method. + name: The name of the overriding method. + Used primarily for generating error messages. + name_in_super: The name of the overridden in the superclass. + Used for generating error messages only. + supertype: The name of the supertype. + original_class_or_static: Indicates whether the original method (from the superclass) + is either a class method or a static method. + override_class_or_static: Indicates whether the overriding method (from the subclass) + is either a class method or a static method. + node: Context node. + """ + # Use boolean variable to clarify code. + fail = False + op_method_wider_note = False + if not is_subtype(override, original, ignore_pos_arg_names=True): + fail = True + elif isinstance(override, Overloaded) and self.is_forward_op_method(name): + # Operator method overrides cannot extend the domain, as + # this could be unsafe with reverse operator methods. + original_domain = self.get_op_other_domain(original) + override_domain = self.get_op_other_domain(override) + if ( + original_domain + and override_domain + and not is_subtype(override_domain, original_domain) + ): + fail = True + op_method_wider_note = True + if isinstance(override, FunctionLike): + if original_class_or_static and not override_class_or_static: + fail = True + elif isinstance(original, CallableType) and isinstance(override, CallableType): + if original.type_guard is not None and override.type_guard is None: + fail = True + if original.type_is is not None and override.type_is is None: + fail = True + + if is_private(name): + fail = False + + if fail: + emitted_msg = False + + offset_arguments = isinstance(override, CallableType) and override.unpack_kwargs + # Normalize signatures, so we get better diagnostics. + if isinstance(override, (CallableType, Overloaded)): + override = override.with_unpacked_kwargs() + if isinstance(original, (CallableType, Overloaded)): + original = original.with_unpacked_kwargs() + + if ( + isinstance(override, CallableType) + and isinstance(original, CallableType) + and len(override.arg_types) == len(original.arg_types) + and override.min_args == original.min_args + ): + # Give more detailed messages for the common case of both + # signatures having the same number of arguments and no + # overloads. + + # override might have its own generic function type + # variables. If an argument or return type of override + # does not have the correct subtyping relationship + # with the original type even after these variables + # are erased, then it is definitely an incompatibility. + + override_ids = override.type_var_ids() + type_name = None + definition = get_func_def(override) + if isinstance(definition, FuncDef): + type_name = definition.info.name + + def erase_override(t: Type) -> Type: + return erase_typevars(t, ids_to_erase=override_ids) + + for i, (sub_kind, super_kind) in enumerate( + zip(override.arg_kinds, original.arg_kinds) + ): + if sub_kind.is_positional() and super_kind.is_positional(): + override_arg_type = override.arg_types[i] + original_arg_type = original.arg_types[i] + elif sub_kind.is_named() and super_kind.is_named() and not offset_arguments: + arg_name = override.arg_names[i] + if arg_name in original.arg_names: + override_arg_type = override.arg_types[i] + original_i = original.arg_names.index(arg_name) + original_arg_type = original.arg_types[original_i] + else: + continue + else: + continue + if not is_subtype(original_arg_type, erase_override(override_arg_type)): + context: Context = node + if ( + isinstance(node, FuncDef) + and not node.is_property + and ( + not node.is_decorated # fast path + # allow trivial decorators like @classmethod and @override + or not (sym := node.info.get(node.name)) + or not isinstance(sym.node, Decorator) + or not sym.node.decorators + ) + ): + # If there's any decorator, we can no longer map arguments 1:1 reliably. + arg_node = node.arguments[i + override.bound()] + if arg_node.line != -1: + context = arg_node + self.msg.argument_incompatible_with_supertype( + i + 1, + name, + type_name, + name_in_super, + original_arg_type, + supertype, + context, + origin_context=node, + ) + emitted_msg = True + + if not is_subtype(erase_override(override.ret_type), original.ret_type): + self.msg.return_type_incompatible_with_supertype( + name, name_in_super, supertype, original.ret_type, override.ret_type, node + ) + emitted_msg = True + elif isinstance(override, Overloaded) and isinstance(original, Overloaded): + # Give a more detailed message in the case where the user is trying to + # override an overload, and the subclass's overload is plausible, except + # that the order of the variants are wrong. + # + # For example, if the parent defines the overload f(int) -> int and f(str) -> str + # (in that order), and if the child swaps the two and does f(str) -> str and + # f(int) -> int + order = [] + for child_variant in override.items: + for i, parent_variant in enumerate(original.items): + if is_subtype(child_variant, parent_variant): + order.append(i) + break + + if len(order) == len(original.items) and order != sorted(order): + self.msg.overload_signature_incompatible_with_supertype( + name, name_in_super, supertype, node + ) + emitted_msg = True + + if not emitted_msg: + # Fall back to generic incompatibility message. + self.msg.signature_incompatible_with_supertype( + name, name_in_super, supertype, node, original=original, override=override + ) + if op_method_wider_note: + self.note( + "Overloaded operator methods can't have wider argument types in overrides", + node, + code=codes.OVERRIDE, + ) + return not fail + + def check__exit__return_type(self, defn: FuncItem) -> None: + """Generate error if the return type of __exit__ is problematic. + + If __exit__ always returns False but the return type is declared + as bool, mypy thinks that a with statement may "swallow" + exceptions even though this is not the case, resulting in + invalid reachability inference. + """ + if not defn.type or not isinstance(defn.type, CallableType): + return + + ret_type = get_proper_type(defn.type.ret_type) + if not has_bool_item(ret_type): + return + + returns = all_return_statements(defn) + if not returns: + return + + if all( + isinstance(ret.expr, NameExpr) and ret.expr.fullname == "builtins.False" + for ret in returns + ): + self.msg.incorrect__exit__return(defn) + + def visit_class_def(self, defn: ClassDef) -> None: + """Type check a class definition.""" + typ = defn.info + for base in typ.mro[1:]: + if base.is_final: + self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name), defn) + if not can_have_shared_disjoint_base(typ.bases): + self.fail(message_registry.INCOMPATIBLE_DISJOINT_BASES.format(typ.name), defn) + with ( + self.tscope.class_scope(defn.info), + self.enter_partial_types(is_class=True), + self.enter_class(defn.info), + ): + old_binder = self.binder + self.binder = ConditionalTypeBinder(self.options) + with self.binder.top_frame_context(): + with self.scope.push_class(defn.info): + self.accept(defn.defs) + self.binder = old_binder + if not self.can_skip_diagnostics: + if not (defn.info.typeddict_type or defn.info.tuple_type or defn.info.is_enum): + # If it is not a normal class (not a special form) check class keywords. + self.check_init_subclass(defn) + if not defn.has_incompatible_baseclass: + # Otherwise we've already found errors; more errors are not useful + self.check_multiple_inheritance(typ) + self.check_metaclass_compatibility(typ) + self.check_final_deletable(typ) + + if defn.decorators: + sig: Type = type_object_type(defn.info, self.named_type) + # Decorators are applied in reverse order. + for decorator in reversed(defn.decorators): + if isinstance(decorator, CallExpr) and isinstance( + decorator.analyzed, PromoteExpr + ): + # _promote is a special type checking related construct. + continue + + dec = self.expr_checker.accept(decorator) + temp = self.temp_node(sig, context=decorator) + fullname = None + if isinstance(decorator, RefExpr): + fullname = decorator.fullname or None + + # TODO: Figure out how to have clearer error messages. + # (e.g. "class decorator must be a function that accepts a type." + old_allow_abstract_call = self.allow_abstract_call + self.allow_abstract_call = True + sig, _ = self.expr_checker.check_call( + dec, [temp], [nodes.ARG_POS], defn, callable_name=fullname + ) + self.allow_abstract_call = old_allow_abstract_call + # TODO: Apply the sig to the actual TypeInfo so we can handle decorators + # that completely swap out the type. (e.g. Callable[[Type[A]], Type[B]]) + if typ.defn.type_vars and typ.defn.type_args is None: + for base_inst in typ.bases: + for base_tvar, base_decl_tvar in zip( + base_inst.args, base_inst.type.defn.type_vars + ): + if ( + isinstance(base_tvar, TypeVarType) + and base_tvar.variance != INVARIANT + and isinstance(base_decl_tvar, TypeVarType) + and base_decl_tvar.variance != base_tvar.variance + ): + self.fail( + f'Variance of TypeVar "{base_tvar.name}" incompatible ' + "with variance in parent type", + context=defn, + code=codes.TYPE_VAR, + ) + if typ.defn.type_vars: + self.check_typevar_defaults(typ.defn.type_vars) + + if typ.is_protocol and typ.defn.type_vars: + self.check_protocol_variance(defn) + if not defn.has_incompatible_baseclass and defn.info.is_enum: + self.check_enum(defn) + infer_class_variances(defn.info) + + @contextmanager + def enter_class(self, type: TypeInfo) -> Iterator[None]: + original_type = self.type + self.type = type + try: + yield + finally: + self.type = original_type + + def check_final_deletable(self, typ: TypeInfo) -> None: + # These checks are only for mypyc. Only perform some checks that are easier + # to implement here than in mypyc. + for attr in typ.deletable_attributes: + node = typ.names.get(attr) + if node and isinstance(node.node, Var) and node.node.is_final: + self.fail(message_registry.CANNOT_MAKE_DELETABLE_FINAL, node.node) + + def check_init_subclass(self, defn: ClassDef) -> None: + """Check that keywords in a class definition are valid arguments for __init_subclass__(). + + In this example: + 1 class Base: + 2 def __init_subclass__(cls, thing: int): + 3 pass + 4 class Child(Base, thing=5): + 5 def __init_subclass__(cls): + 6 pass + 7 Child() + + Base.__init_subclass__(thing=5) is called at line 4. This is what we simulate here. + Child.__init_subclass__ is never called. + """ + if defn.info.metaclass_type and defn.info.metaclass_type.type.fullname not in ( + "builtins.type", + "abc.ABCMeta", + ): + # We can't safely check situations when both __init_subclass__ and a custom + # metaclass are present. + return + # At runtime, only Base.__init_subclass__ will be called, so + # we skip the current class itself. + for base in defn.info.mro[1:]: + if "__init_subclass__" not in base.names: + continue + name_expr = NameExpr(defn.name) + name_expr.node = base + callee = MemberExpr(name_expr, "__init_subclass__") + args = list(defn.keywords.values()) + arg_names: list[str | None] = list(defn.keywords.keys()) + # 'metaclass' keyword is consumed by the rest of the type machinery, + # and is never passed to __init_subclass__ implementations + if "metaclass" in arg_names: + idx = arg_names.index("metaclass") + arg_names.pop(idx) + args.pop(idx) + arg_kinds = [ARG_NAMED] * len(args) + call_expr = CallExpr(callee, args, arg_kinds, arg_names) + call_expr.line = defn.line + call_expr.column = defn.column + call_expr.end_line = defn.end_line + self.expr_checker.accept(call_expr, allow_none_return=True, always_allow_any=True) + # We are only interested in the first Base having __init_subclass__, + # all other bases have already been checked. + break + + def check_typevar_defaults(self, tvars: Sequence[TypeVarLikeType]) -> None: + for tv in tvars: + if not (isinstance(tv, TypeVarType) and tv.has_default()): + continue + if not is_subtype(tv.default, tv.upper_bound): + self.fail("TypeVar default must be a subtype of the bound type", tv) + if tv.values and not any(is_same_type(tv.default, value) for value in tv.values): + self.fail("TypeVar default must be one of the constraint types", tv) + + def check_enum(self, defn: ClassDef) -> None: + assert defn.info.is_enum + if defn.info.fullname not in ENUM_BASES and "__members__" in defn.info.names: + sym = defn.info.names["__members__"] + if isinstance(sym.node, Var) and sym.node.has_explicit_value: + # `__members__` will always be overwritten by `Enum` and is considered + # read-only so we disallow assigning a value to it + self.fail(message_registry.ENUM_MEMBERS_ATTR_WILL_BE_OVERRIDDEN, sym.node) + for base in defn.info.mro[1:-1]: # we don't need self and `object` + if base.is_enum and base.fullname not in ENUM_BASES: + self.check_final_enum(defn, base) + + if self.is_stub and self.tree.fullname not in {"enum", "_typeshed"}: + if not defn.info.enum_members: + self.fail( + f'Detected enum "{defn.info.fullname}" in a type stub with zero members. ' + "There is a chance this is due to a recent change in the semantics of " + "enum membership. If so, use `member = value` to mark an enum member, " + "instead of `member: type`", + defn, + ) + self.note( + "See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members", + defn, + ) + + self.check_enum_bases(defn) + self.check_enum_new(defn) + + def check_final_enum(self, defn: ClassDef, base: TypeInfo) -> None: + if base.enum_members: + self.fail(f'Cannot extend enum with existing members: "{base.name}"', defn) + + def is_final_enum_value(self, sym: SymbolTableNode) -> bool: + if isinstance(sym.node, (FuncBase, Decorator)): + return False # A method is fine + if not isinstance(sym.node, Var): + return True # Can be a class or anything else + + # Now, only `Var` is left, we need to check: + # 1. Private name like in `__prop = 1` + # 2. Dunder name like `__hash__ = some_hasher` + # 3. Sunder name like `_order_ = 'a, b, c'` + # 4. If it is a method / descriptor like in `method = classmethod(func)` + if ( + is_private(sym.node.name) + or is_dunder(sym.node.name) + or is_sunder(sym.node.name) + # TODO: make sure that `x = @class/staticmethod(func)` + # and `x = property(prop)` both work correctly. + # Now they are incorrectly counted as enum members. + or isinstance(get_proper_type(sym.node.type), FunctionLike) + ): + return False + + return self.is_stub or sym.node.has_explicit_value + + def check_enum_bases(self, defn: ClassDef) -> None: + """ + Non-enum mixins cannot appear after enum bases; this is disallowed at runtime: + + class Foo: ... + class Bar(enum.Enum, Foo): ... + + But any number of enum mixins can appear in a class definition + (even if multiple enum bases define __new__). So this is fine: + + class Foo(enum.Enum): + def __new__(cls, val): ... + class Bar(enum.Enum): + def __new__(cls, val): ... + class Baz(int, Foo, Bar, enum.Flag): ... + """ + enum_base: Instance | None = None + for base in defn.info.bases: + if enum_base is None and base.type.is_enum: + enum_base = base + continue + elif enum_base is not None and not base.type.is_enum: + self.fail( + f'No non-enum mixin classes are allowed after "{enum_base.str_with_options(self.options)}"', + defn, + ) + break + + def check_enum_new(self, defn: ClassDef) -> None: + def has_new_method(info: TypeInfo) -> bool: + new_method = info.get("__new__") + return bool( + new_method + and new_method.node + and new_method.node.fullname != "builtins.object.__new__" + ) + + has_new = False + for base in defn.info.bases: + candidate = False + + if base.type.is_enum: + # If we have an `Enum`, then we need to check all its bases. + candidate = any(not b.is_enum and has_new_method(b) for b in base.type.mro[1:-1]) + else: + candidate = has_new_method(base.type) + + if candidate and has_new: + self.fail( + "Only a single data type mixin is allowed for Enum subtypes, " + 'found extra "{}"'.format(base.str_with_options(self.options)), + defn, + ) + elif candidate: + has_new = True + + def check_protocol_variance(self, defn: ClassDef) -> None: + """Check that protocol definition is compatible with declared + variances of type variables. + + Note that we also prohibit declaring protocol classes as invariant + if they are actually covariant/contravariant, since this may break + transitivity of subtyping, see PEP 544. + """ + if self.can_skip_diagnostics: + return + if defn.type_args is not None: + # Using new-style syntax (PEP 695), so variance will be inferred + return + info = defn.info + object_type = Instance(info.mro[-1], []) + tvars = info.defn.type_vars + if self._variance_dummy_type is None: + _, dummy_info = self.make_fake_typeinfo("", "Dummy", "Dummy", []) + self._variance_dummy_type = Instance(dummy_info, []) + dummy = self._variance_dummy_type + for i, tvar in enumerate(tvars): + if not isinstance(tvar, TypeVarType): + # Variance of TypeVarTuple and ParamSpec is underspecified by PEPs. + continue + up_args: list[Type] = [ + object_type if i == j else dummy.copy_modified() for j, _ in enumerate(tvars) + ] + down_args: list[Type] = [ + UninhabitedType() if i == j else dummy.copy_modified() for j, _ in enumerate(tvars) + ] + up, down = Instance(info, up_args), Instance(info, down_args) + # TODO: add advanced variance checks for recursive protocols + if is_subtype(down, up, ignore_declared_variance=True): + expected = COVARIANT + elif is_subtype(up, down, ignore_declared_variance=True): + expected = CONTRAVARIANT + else: + expected = INVARIANT + if expected != tvar.variance: + self.msg.bad_proto_variance(tvar.variance, tvar.name, expected, defn) + + def check_multiple_inheritance(self, typ: TypeInfo) -> None: + """Check for multiple inheritance related errors.""" + if len(typ.bases) <= 1: + # No multiple inheritance. + return + # Verify that inherited attributes are compatible. + mro = typ.mro[1:] + all_names = {name for base in mro for name in base.names} + for name in sorted(all_names - typ.names.keys()): + # Sort for reproducible message order. + # Attributes defined in both the type and base are skipped. + # Normal checks for attribute compatibility should catch any problems elsewhere. + if is_private(name): + continue + # Compare the first base defining a name with the rest. + # Remaining bases may not be pairwise compatible as the first base provides + # the used definition. + i, base = next((i, base) for i, base in enumerate(mro) if name in base.names) + for base2 in mro[i + 1 :]: + if name in base2.names and base2 not in base.mro: + self.check_compatibility(name, base, base2, typ) + + def check_compatibility( + self, name: str, base1: TypeInfo, base2: TypeInfo, ctx: TypeInfo + ) -> None: + """Check if attribute name in base1 is compatible with base2 in multiple inheritance. + + Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have + a direct subclass relationship (i.e., the compatibility requirement only derives from + multiple inheritance). + + This check verifies that a definition taken from base1 (and mapped to the current + class ctx), is type compatible with the definition taken from base2 (also mapped), so + that unsafe subclassing like this can be detected: + class A(Generic[T]): + def foo(self, x: T) -> None: ... + + class B: + def foo(self, x: str) -> None: ... + + class C(B, A[int]): ... # this is unsafe because... + + x: A[int] = C() + x.foo # ...runtime type is (str) -> None, while static type is (int) -> None + """ + if name in ("__init__", "__new__", "__init_subclass__"): + # __init__ and friends can be incompatible -- it's a special case. + return + first = base1.names[name] + second = base2.names[name] + # Specify current_class explicitly as this function is called after leaving the class. + first_type, _ = self.node_type_from_base(name, base1, ctx, current_class=ctx) + second_type, _ = self.node_type_from_base(name, base2, ctx, current_class=ctx) + + # TODO: use more principled logic to decide is_subtype() vs is_equivalent(). + # We should rely on mutability of superclass node, not on types being Callable. + # (in particular handle settable properties with setter type different from getter). + + p_first_type = get_proper_type(first_type) + p_second_type = get_proper_type(second_type) + if isinstance(p_first_type, FunctionLike) and isinstance(p_second_type, FunctionLike): + if p_first_type.is_type_obj() and p_second_type.is_type_obj(): + # For class objects only check the subtype relationship of the classes, + # since we allow incompatible overrides of '__init__'/'__new__' + ok = is_subtype( + left=fill_typevars_with_any(p_first_type.type_object()), + right=fill_typevars_with_any(p_second_type.type_object()), + ) + else: + assert first_type and second_type + ok = is_subtype(first_type, second_type, ignore_pos_arg_names=True) + elif first_type and second_type: + if second.node is not None and not self.is_writable_attribute(second.node): + ok = is_subtype(first_type, second_type) + else: + ok = is_equivalent(first_type, second_type) + if ok: + if ( + first.node + and second.node + and self.is_writable_attribute(second.node) + and is_property(first.node) + and isinstance(first.node, Decorator) + and not isinstance(p_second_type, AnyType) + ): + self.msg.fail( + f'Cannot override writeable attribute "{name}" in base "{base2.name}"' + f' with read-only property in base "{base1.name}"', + ctx, + code=codes.OVERRIDE, + ) + else: + if first_type is None: + self.msg.cannot_determine_type_in_base(name, base1.name, ctx) + if second_type is None: + self.msg.cannot_determine_type_in_base(name, base2.name, ctx) + ok = True + # Final attributes can never be overridden, but can override + # non-final read-only attributes. + if is_final_node(second.node) and not is_private(name): + self.msg.cant_override_final(name, base2.name, ctx) + if is_final_node(first.node): + self.check_if_final_var_override_writable(name, second.node, ctx) + # Some attributes like __slots__ and __deletable__ are special, and the type can + # vary across class hierarchy. + if isinstance(second.node, Var) and second.node.allow_incompatible_override: + ok = True + if not ok: + self.msg.base_class_definitions_incompatible(name, base1, base2, ctx) + + def check_metaclass_compatibility(self, typ: TypeInfo) -> None: + """Ensures that metaclasses of all parent types are compatible.""" + if ( + typ.is_metaclass() + or typ.is_protocol + or typ.is_named_tuple + or typ.is_enum + or typ.typeddict_type is not None + ): + return # Reasonable exceptions from this check + + if typ.metaclass_type is None and any( + base.type.metaclass_type is not None for base in typ.bases + ): + self.fail( + "Metaclass conflict: the metaclass of a derived class must be " + "a (non-strict) subclass of the metaclasses of all its bases", + typ, + code=codes.METACLASS, + ) + explanation = typ.explain_metaclass_conflict() + if explanation: + self.note(explanation, typ, code=codes.METACLASS) + + def visit_import_from(self, node: ImportFrom) -> None: + for name, _ in node.names: + if (sym := self.globals.get(name)) is not None: + self.warn_deprecated(sym.node, node) + self.check_import(node) + + def visit_import_all(self, node: ImportAll) -> None: + self.check_import(node) + + def visit_import(self, node: Import) -> None: + self.check_import(node) + + def check_import(self, node: ImportBase) -> None: + for assign in node.assignments: + lvalue = assign.lvalues[0] + lvalue_type, _, __ = self.check_lvalue(lvalue) + if lvalue_type is None: + # TODO: This is broken. + lvalue_type = AnyType(TypeOfAny.special_form) + assert isinstance(assign.rvalue, NameExpr) + message = message_registry.INCOMPATIBLE_IMPORT_OF.format(assign.rvalue.name) + self.check_simple_assignment( + lvalue_type, + assign.rvalue, + node, + msg=message, + lvalue_name="local name", + rvalue_name="imported name", + ) + + # + # Statements + # + + def visit_block(self, b: Block) -> None: + if b.is_unreachable: + # This block was marked as being unreachable during semantic analysis. + # It turns out any blocks marked in this way are *intentionally* marked + # as unreachable -- so we don't display an error. + self.binder.unreachable() + return + for s in b.body: + if self.binder.is_unreachable(): + if not self.should_report_unreachable_issues(): + break + if not self.is_noop_for_reachability(s): + self.msg.unreachable_statement(s) + break + else: + self.accept(s) + # Clear expression cache after each statement to avoid unlimited growth. + self.expr_checker.expr_cache.clear() + + def should_report_unreachable_issues(self) -> bool: + return ( + self.in_checked_function() + and self.options.warn_unreachable + and not self.current_node_deferred + and not self.binder.is_unreachable_warning_suppressed() + ) + + def is_noop_for_reachability(self, s: Statement) -> bool: + """Returns 'true' if the given statement either throws an error of some kind + or is a no-op. + + We use this function while handling the '--warn-unreachable' flag. When + that flag is present, we normally report an error on any unreachable statement. + But if that statement is just something like a 'pass' or a just-in-case 'assert False', + reporting an error would be annoying. + """ + if isinstance(s, AssertStmt) and is_false_literal(s.expr): + return True + elif isinstance(s, ReturnStmt) and is_literal_not_implemented(s.expr): + return True + elif isinstance(s, RaiseStmt): + return True + elif isinstance(s, ExpressionStmt): + if isinstance(s.expr, CallExpr): + with self.expr_checker.msg.filter_errors(filter_revealed_type=True): + typ = get_proper_type( + self.expr_checker.accept( + s.expr, allow_none_return=True, always_allow_any=True + ) + ) + + if isinstance(typ, UninhabitedType): + return True + return False + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + """Type check an assignment statement. + + Handle all kinds of assignment statements (simple, indexed, multiple). + """ + + # Avoid type checking type aliases in stubs to avoid false + # positives about modern type syntax available in stubs such + # as X | Y. + if not (s.is_alias_def and self.is_stub): + with self.enter_final_context(s.is_final_def): + self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax) + + if s.is_alias_def: + self.check_type_alias_rvalue(s) + + if ( + s.type is not None + and self.options.disallow_any_unimported + and has_any_from_unimported_type(s.type) + ): + if isinstance(s.lvalues[-1], TupleExpr): + # This is a multiple assignment. Instead of figuring out which type is problematic, + # give a generic error message. + self.msg.unimported_type_becomes_any( + "A type on this line", AnyType(TypeOfAny.special_form), s + ) + else: + self.msg.unimported_type_becomes_any("Type of variable", s.type, s) + check_for_explicit_any(s.type, self.options, self.is_typeshed_stub, self.msg, context=s) + + if len(s.lvalues) > 1: + # Chained assignment (e.g. x = y = ...). + # Make sure that rvalue type will not be reinferred. + if not self.has_type(s.rvalue): + self.expr_checker.accept(s.rvalue) + rvalue = self.temp_node(self.lookup_type(s.rvalue), s) + for lv in s.lvalues[:-1]: + with self.enter_final_context(s.is_final_def): + self.check_assignment(lv, rvalue, s.type is None) + + self.check_final(s) + if ( + s.is_final_def + and s.type + and not has_no_typevars(s.type) + and self.scope.active_class() is not None + ): + self.fail(message_registry.DEPENDENT_FINAL_IN_CLASS_BODY, s) + + if s.unanalyzed_type and not self.in_checked_function(): + self.msg.annotation_in_unchecked_function(context=s) + + def check_type_alias_rvalue(self, s: AssignmentStmt) -> None: + with self.msg.filter_errors(): + alias_type = self.expr_checker.accept(s.rvalue) + self.store_type(s.lvalues[-1], alias_type) + + def check_assignment( + self, + lvalue: Lvalue, + rvalue: Expression, + infer_lvalue_type: bool = True, + new_syntax: bool = False, + ) -> None: + """Type check a single assignment: lvalue = rvalue.""" + if isinstance(lvalue, (TupleExpr, ListExpr)): + self.check_assignment_to_multiple_lvalues( + lvalue.items, rvalue, rvalue, infer_lvalue_type + ) + else: + self.try_infer_partial_generic_type_from_assignment(lvalue, rvalue, "=") + lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue, rvalue) + # If we're assigning to __getattr__ or similar methods, check that the signature is + # valid. + if isinstance(lvalue, NameExpr) and lvalue.node: + name = lvalue.node.name + if name in ("__setattr__", "__getattribute__", "__getattr__"): + # If an explicit type is given, use that. + if lvalue_type: + signature = lvalue_type + else: + signature = self.expr_checker.accept(rvalue) + if signature: + if name == "__setattr__": + self.check_setattr_method(signature, lvalue) + else: + self.check_getattr_method(signature, lvalue, name) + + if name == "__slots__" and self.scope.active_class() is not None: + typ = lvalue_type or self.expr_checker.accept(rvalue) + self.check_slots_definition(typ, lvalue) + if name == "__match_args__" and inferred is not None: + typ = self.expr_checker.accept(rvalue) + self.check_match_args(inferred, typ, lvalue) + if name == "__post_init__": + active_class = self.scope.active_class() + if active_class and dataclasses_plugin.is_processed_dataclass(active_class): + self.fail(message_registry.DATACLASS_POST_INIT_MUST_BE_A_FUNCTION, rvalue) + + if isinstance(lvalue, MemberExpr) and lvalue.name == "__match_args__": + self.fail(message_registry.CANNOT_MODIFY_MATCH_ARGS, lvalue) + + if lvalue_type: + if isinstance(lvalue_type, PartialType) and lvalue_type.type is None: + # Try to infer a proper type for a variable with a partial None type. + rvalue_type = self.expr_checker.accept(rvalue) + if isinstance(get_proper_type(rvalue_type), NoneType): + # This doesn't actually provide any additional information -- multiple + # None initializers preserve the partial None type. + return + + var = lvalue_type.var + if is_valid_inferred_type( + rvalue_type, self.options, is_lvalue_final=var.is_final + ): + partial_types = self.find_partial_types(var) + if partial_types is not None: + if not self.current_node_deferred: + # Partial type can't be final, so strip any literal values. + rvalue_type = remove_instance_last_known_values(rvalue_type) + inferred_type = make_simplified_union([rvalue_type, NoneType()]) + self.set_inferred_type(var, lvalue, inferred_type) + else: + var.type = None + del partial_types[var] + lvalue_type = var.type + else: + # Try to infer a partial type. + if not self.infer_partial_type(var, lvalue, rvalue_type): + # If that also failed, give up and let the caller know that we + # cannot read their mind. The definition site will be reported later. + # Calling .put() directly because the newly inferred type is + # not a subtype of None - we are not looking for narrowing + fallback = self.inference_error_fallback_type(rvalue_type) + self.binder.put(lvalue, fallback) + # Same as self.set_inference_error_fallback_type but inlined + # to avoid computing fallback twice. + # We are replacing partial now, so the variable type + # should remain optional. + self.set_inferred_type(var, lvalue, make_optional_type(fallback)) + elif ( + is_literal_none(rvalue) + and isinstance(lvalue, NameExpr) + and isinstance(lvalue.node, Var) + and lvalue.node.is_initialized_in_class + and not new_syntax + ): + # Allow None's to be assigned to class variables with non-Optional types. + rvalue_type = lvalue_type + elif ( + isinstance(lvalue, MemberExpr) and lvalue.kind is None + ): # Ignore member access to modules + instance_type = self.expr_checker.accept(lvalue.expr) + rvalue_type, lvalue_type, infer_lvalue_type = self.check_member_assignment( + lvalue, instance_type, lvalue_type, rvalue, context=rvalue + ) + else: + # Hacky special case for assigning a literal None + # to a variable defined in a previous if + # branch. When we detect this, we'll go back and + # make the type optional. This is somewhat + # unpleasant, and a generalization of this would + # be an improvement! + if ( + not self.options.allow_redefinition_new + and is_literal_none(rvalue) + and isinstance(lvalue, NameExpr) + and lvalue.kind == LDEF + and isinstance(lvalue.node, Var) + and lvalue.node.type + and lvalue.node in self.var_decl_frames + and not isinstance(get_proper_type(lvalue_type), AnyType) + ): + decl_frame_map = self.var_decl_frames[lvalue.node] + # Check if the nearest common ancestor frame for the definition site + # and the current site is the enclosing frame of an if/elif/else block. + has_if_ancestor = False + for frame in reversed(self.binder.frames): + if frame.id in decl_frame_map: + has_if_ancestor = frame.conditional_frame + break + if has_if_ancestor: + lvalue_type = make_optional_type(lvalue_type) + self.set_inferred_type(lvalue.node, lvalue, lvalue_type) + + rvalue_type, lvalue_type = self.check_simple_assignment( + lvalue_type, rvalue, context=rvalue, inferred=inferred, lvalue=lvalue + ) + # The above call may update inferred variable type. Prevent further + # inference. + inferred = None + + # Special case: only non-abstract non-protocol classes can be assigned to + # variables with explicit type `Type[A]`, where A is protocol or abstract. + p_rvalue_type = get_proper_type(rvalue_type) + p_lvalue_type = get_proper_type(lvalue_type) + if ( + isinstance(p_rvalue_type, FunctionLike) + and p_rvalue_type.is_type_obj() + and ( + p_rvalue_type.type_object().is_abstract + or p_rvalue_type.type_object().is_protocol + ) + and isinstance(p_lvalue_type, TypeType) + and isinstance(p_lvalue_type.item, Instance) + and ( + p_lvalue_type.item.type.is_abstract or p_lvalue_type.item.type.is_protocol + ) + ): + self.msg.concrete_only_assign(p_lvalue_type, rvalue) + return + if rvalue_type and infer_lvalue_type and not isinstance(lvalue_type, PartialType): + # Don't use type binder for definitions of special forms, like named tuples. + if not (isinstance(lvalue, NameExpr) and lvalue.is_special_form): + self.binder.assign_type(lvalue, rvalue_type, lvalue_type) + if ( + isinstance(lvalue, NameExpr) + and isinstance(lvalue.node, Var) + and lvalue.node.is_inferred + and lvalue.node.is_index_var + and lvalue_type is not None + ): + lvalue.node.type = remove_instance_last_known_values(lvalue_type) + elif ( + self.options.allow_redefinition_new + and lvalue_type is not None + and not isinstance(lvalue_type, PartialType) + # Note that `inferred is not None` is not a reliable check here, because + # simple assignments like x = "a" are inferred during semantic analysis. + and isinstance(lvalue, NameExpr) + and isinstance(lvalue.node, Var) + and lvalue.node.is_inferred + ): + # TODO: Can we use put() here? + self.binder.assign_type(lvalue, lvalue_type, lvalue_type) + + elif index_lvalue: + self.check_indexed_assignment(index_lvalue, rvalue, lvalue) + + if inferred: + type_context = self.get_variable_type_context(inferred, rvalue) + rvalue_type = self.expr_checker.accept(rvalue, type_context=type_context) + if not ( + inferred.is_final + or inferred.is_index_var + or (isinstance(lvalue, NameExpr) and lvalue.name == "__match_args__") + ): + rvalue_type = remove_instance_last_known_values(rvalue_type) + self.infer_variable_type(inferred, lvalue, rvalue_type, rvalue) + self.check_assignment_to_slots(lvalue) + if ( + isinstance(lvalue, RefExpr) + and not (isinstance(lvalue, NameExpr) and lvalue.name == "__match_args__") + and not self.can_skip_diagnostics + ): + # We check override here at the end after storing the inferred type, since + # override check will try to access the current attribute via symbol tables + # (like a regular attribute access). + self.check_compatibility_all_supers(lvalue, rvalue) + + # (type, operator) tuples for augmented assignments supported with partial types + partial_type_augmented_ops: Final = {("builtins.list", "+"), ("builtins.set", "|")} + + def get_variable_type_context(self, inferred: Var, rvalue: Expression) -> Type | None: + type_contexts = [] + if inferred.info: + for base in inferred.info.mro[1:]: + if inferred.name not in base.names: + continue + # For inference within class body, get supertype attribute as it would look on + # a class object for lambdas overriding methods, etc. + base_node = base.names[inferred.name].node + base_type, _ = self.node_type_from_base( + inferred.name, + base, + inferred, + is_class=is_method(base_node) + or isinstance(base_node, Var) + and not is_instance_var(base_node), + ) + if ( + base_type + and not (isinstance(base_node, Var) and base_node.invalid_partial_type) + and not isinstance(base_type, PartialType) + ): + type_contexts.append(base_type) + # Use most derived supertype as type context if available. + if not type_contexts: + if inferred.name == "__slots__" and self.scope.active_class() is not None: + str_type = self.named_type("builtins.str") + return self.named_generic_type("typing.Iterable", [str_type]) + if inferred.name == "__all__" and self.scope.is_top_level(): + str_type = self.named_type("builtins.str") + return self.named_generic_type("typing.Sequence", [str_type]) + return None + candidate = type_contexts[0] + for other in type_contexts: + if is_proper_subtype(other, candidate): + candidate = other + elif not is_subtype(candidate, other): + # Multiple incompatible candidates, cannot use any of them as context. + return None + return candidate + + def try_infer_partial_generic_type_from_assignment( + self, lvalue: Lvalue, rvalue: Expression, op: str + ) -> None: + """Try to infer a precise type for partial generic type from assignment. + + 'op' is '=' for normal assignment and a binary operator ('+', ...) for + augmented assignment. + + Example where this happens: + + x = [] + if foo(): + x = [1] # Infer List[int] as type of 'x' + """ + var = None + if ( + isinstance(lvalue, NameExpr) + and isinstance(lvalue.node, Var) + and isinstance(lvalue.node.type, PartialType) + ): + var = lvalue.node + elif isinstance(lvalue, MemberExpr): + var = self.expr_checker.get_partial_self_var(lvalue) + if var is not None: + typ = var.type + assert isinstance(typ, PartialType) + if typ.type is None: + return + # Return if this is an unsupported augmented assignment. + if op != "=" and (typ.type.fullname, op) not in self.partial_type_augmented_ops: + return + # TODO: some logic here duplicates the None partial type counterpart + # inlined in check_assignment(), see #8043. + partial_types = self.find_partial_types(var) + if partial_types is None: + return + rvalue_type = self.expr_checker.accept(rvalue) + rvalue_type = get_proper_type(rvalue_type) + if isinstance(rvalue_type, Instance): + if rvalue_type.type == typ.type and is_valid_inferred_type( + rvalue_type, self.options + ): + var.type = rvalue_type + del partial_types[var] + elif isinstance(rvalue_type, AnyType): + var.type = fill_typevars_with_any(typ.type) + del partial_types[var] + + def check_compatibility_all_supers(self, lvalue: RefExpr, rvalue: Expression) -> None: + lvalue_node = lvalue.node + # Check if we are a class variable with at least one base class + if ( + isinstance(lvalue_node, Var) + # If we have explicit annotation, there is no point in checking the override + # for each assignment, so we check only for the first one. + # TODO: for some reason annotated attributes on self are stored as inferred vars. + and ( + lvalue_node.line == lvalue.line + or lvalue_node.is_inferred + and not lvalue_node.explicit_self_type + ) + and lvalue.kind in (MDEF, None) # None for Vars defined via self + and len(lvalue_node.info.bases) > 0 + ): + for base in lvalue_node.info.mro[1:]: + tnode = base.names.get(lvalue_node.name) + if tnode is not None: + if not self.check_compatibility_classvar_super(lvalue_node, base, tnode.node): + # Show only one error per variable + break + + if not self.check_compatibility_final_super(lvalue_node, base, tnode.node): + # Show only one error per variable + break + + direct_bases = lvalue_node.info.direct_base_classes() + last_immediate_base = direct_bases[-1] if direct_bases else None + + # The historical behavior for inferred vars was to compare rvalue type against + # the type declared in a superclass. To preserve this behavior, we temporarily + # store the rvalue type on the variable. + actual_lvalue_type = None + if lvalue_node.is_inferred and not lvalue_node.explicit_self_type: + # Don't use partial types as context, similar to regular code path. + ctx = lvalue_node.type if not isinstance(lvalue_node.type, PartialType) else None + rvalue_type = self.expr_checker.accept(rvalue, ctx) + actual_lvalue_type = lvalue_node.type + lvalue_node.type = rvalue_type + lvalue_type, _ = self.node_type_from_base(lvalue_node.name, lvalue_node.info, lvalue) + if lvalue_node.is_inferred and not lvalue_node.explicit_self_type: + lvalue_node.type = actual_lvalue_type + + if not lvalue_type: + return + + for base in lvalue_node.info.mro[1:]: + # The type of "__slots__" and some other attributes usually doesn't need to + # be compatible with a base class. We'll still check the type of "__slots__" + # against "object" as an exception. + if lvalue_node.allow_incompatible_override and not ( + lvalue_node.name == "__slots__" and base.fullname == "builtins.object" + ): + continue + + if is_private(lvalue_node.name): + continue + + base_type, base_node = self.node_type_from_base(lvalue_node.name, base, lvalue) + # TODO: if the r.h.s. is a descriptor, we should check setter override as well. + custom_setter = is_custom_settable_property(base_node) + if isinstance(base_type, PartialType): + base_type = None + + if base_type: + assert base_node is not None + if not self.check_compatibility_super( + lvalue_type, + rvalue, + base, + base_type, + base_node, + always_allow_covariant=custom_setter, + ): + # Only show one error per variable; even if other + # base classes are also incompatible + return + if lvalue_type and custom_setter: + base_type, _ = self.node_type_from_base( + lvalue_node.name, base, lvalue, setter_type=True + ) + # Setter type for a custom property must be ready if + # the getter type is ready. + assert base_type is not None + if not is_subtype(base_type, lvalue_type): + self.msg.incompatible_setter_override( + lvalue, lvalue_type, base_type, base + ) + return + if base is last_immediate_base: + # At this point, the attribute was found to be compatible with all + # immediate parents. + break + + def check_compatibility_super( + self, + compare_type: Type, + rvalue: Expression, + base: TypeInfo, + base_type: Type, + base_node: Node, + always_allow_covariant: bool, + ) -> bool: + # TODO: check __set__() type override for custom descriptors. + # TODO: for descriptors check also class object access override. + ok = self.check_subtype( + compare_type, + base_type, + rvalue, + message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, + "expression has type", + f'base class "{base.name}" defined the type as', + ) + if ( + ok + and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes + and self.is_writable_attribute(base_node) + and not always_allow_covariant + ): + ok = self.check_subtype( + base_type, + compare_type, + rvalue, + message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE, + f'base class "{base.name}" defined the type as', + "expression has type", + ) + return ok + + def node_type_from_base( + self, + name: str, + base: TypeInfo, + context: Context, + *, + setter_type: bool = False, + is_class: bool = False, + current_class: TypeInfo | None = None, + ) -> tuple[Type | None, SymbolNode | None]: + """Find a type for a name in base class. + + Return the type found and the corresponding node defining the name or None + for both if the name is not defined in base or the node type is not known (yet). + The type returned is already properly mapped/bound to the subclass. + If setter_type is True, return setter types for settable properties (otherwise the + getter type is returned). + """ + base_node = base.names.get(name) + + # TODO: defer current node if the superclass node is not ready. + if ( + not base_node + or isinstance(base_node.node, (Var, Decorator)) + and not base_node.type + or isinstance(base_node.type, PartialType) + and base_node.type.type is not None + ): + return None, None + + if current_class is None: + self_type = self.scope.current_self_type() + else: + self_type = fill_typevars(current_class) + assert self_type is not None, "Internal error: base lookup outside class" + if isinstance(self_type, TupleType): + instance = tuple_fallback(self_type) + else: + instance = self_type + + mx = MemberContext( + is_lvalue=setter_type, + is_super=False, + is_operator=mypy.checkexpr.is_operator_method(name), + original_type=self_type, + context=context, + chk=self, + suppress_errors=True, + ) + # TODO: we should not filter "cannot determine type" errors here. + with self.msg.filter_errors(filter_deprecated=True): + if is_class: + fallback = instance.type.metaclass_type or mx.named_type("builtins.type") + base_type = analyze_class_attribute_access( + instance, name, mx, mcs_fallback=fallback, override_info=base + ) + else: + base_type = analyze_instance_member_access(name, instance, mx, base) + return base_type, base_node.node + + def check_compatibility_classvar_super( + self, node: Var, base: TypeInfo, base_node: Node | None + ) -> bool: + if not isinstance(base_node, Var): + return True + if node.is_classvar and not base_node.is_classvar: + self.fail(message_registry.CANNOT_OVERRIDE_INSTANCE_VAR.format(base.name), node) + return False + elif not node.is_classvar and base_node.is_classvar: + self.fail(message_registry.CANNOT_OVERRIDE_CLASS_VAR.format(base.name), node) + return False + return True + + def check_compatibility_final_super( + self, node: Var, base: TypeInfo, base_node: Node | None + ) -> bool: + """Check if an assignment overrides a final attribute in a base class. + + This only checks situations where either a node in base class is not a variable + but a final method, or where override is explicitly declared as final. + In these cases we give a more detailed error message. In addition, we check that + a final variable doesn't override writeable attribute, which is not safe. + + Other situations are checked in `check_final()`. + """ + if not isinstance(base_node, (Var, FuncBase, Decorator)): + return True + if is_private(node.name): + return True + if base_node.is_final and (node.is_final or not isinstance(base_node, Var)): + # Give this error only for explicit override attempt with `Final`, or + # if we are overriding a final method with variable. + # Other override attempts will be flagged as assignment to constant + # in `check_final()`. + self.msg.cant_override_final(node.name, base.name, node) + return False + if node.is_final: + if base.fullname in ENUM_BASES or node.name in ENUM_SPECIAL_PROPS: + return True + self.check_if_final_var_override_writable(node.name, base_node, node) + return True + + def check_if_final_var_override_writable( + self, name: str, base_node: Node | None, ctx: Context + ) -> None: + """Check that a final variable doesn't override writeable attribute. + + This is done to prevent situations like this: + class C: + attr = 1 + class D(C): + attr: Final = 2 + + x: C = D() + x.attr = 3 # Oops! + """ + writable = True + if base_node: + writable = self.is_writable_attribute(base_node) + if writable: + self.msg.final_cant_override_writable(name, ctx) + + def get_final_context(self) -> bool: + """Check whether we a currently checking a final declaration.""" + return self._is_final_def + + @contextmanager + def enter_final_context(self, is_final_def: bool) -> Iterator[None]: + """Store whether the current checked assignment is a final declaration.""" + old_ctx = self._is_final_def + self._is_final_def = is_final_def + try: + yield + finally: + self._is_final_def = old_ctx + + def check_final(self, s: AssignmentStmt | OperatorAssignmentStmt | AssignmentExpr) -> None: + """Check if this assignment does not assign to a final attribute. + + This function performs the check only for name assignments at module + and class scope. The assignments to `obj.attr` and `Cls.attr` are checked + in checkmember.py. + """ + if isinstance(s, AssignmentStmt): + lvs = self.flatten_lvalues(s.lvalues) + elif isinstance(s, AssignmentExpr): + lvs = [s.target] + else: + lvs = [s.lvalue] + is_final_decl = s.is_final_def if isinstance(s, AssignmentStmt) else False + if is_final_decl and (active_class := self.scope.active_class()): + lv = lvs[0] + assert isinstance(lv, RefExpr) + if lv.node is not None: + assert isinstance(lv.node, Var) + if ( + lv.node.final_unset_in_class + and not lv.node.final_set_in_init + and not self.is_stub # It is OK to skip initializer in stub files. + and + # Avoid extra error messages, if there is no type in Final[...], + # then we already reported the error about missing r.h.s. + isinstance(s, AssignmentStmt) + and s.type is not None + # Avoid extra error message for NamedTuples, + # they were reported during semanal + and not active_class.is_named_tuple + ): + self.msg.final_without_value(s) + for lv in lvs: + if isinstance(lv, RefExpr) and isinstance(lv.node, Var): + name = lv.node.name + cls = self.scope.active_class() + if cls is not None: + # These additional checks exist to give more error messages + # even if the final attribute was overridden with a new symbol + # (which is itself an error)... + for base in cls.mro[1:]: + sym = base.names.get(name) + # We only give this error if base node is variable, + # overriding final method will be caught in + # `check_compatibility_final_super()`. + if sym and isinstance(sym.node, Var): + if sym.node.is_final and not is_final_decl: + self.msg.cant_assign_to_final(name, sym.node.info is None, s) + # ...but only once + break + if lv.node.is_final and not is_final_decl: + self.msg.cant_assign_to_final(name, lv.node.info is None, s) + + def check_assignment_to_slots(self, lvalue: Lvalue) -> None: + if not isinstance(lvalue, MemberExpr): + return + + inst = get_proper_type(self.expr_checker.accept(lvalue.expr)) + if isinstance(inst, TypeVarType) and inst.id.is_self(): + # Unwrap self type + inst = get_proper_type(inst.upper_bound) + if not isinstance(inst, Instance): + return + if inst.type.slots is None: + return # Slots do not exist, we can allow any assignment + if lvalue.name in inst.type.slots: + return # We are assigning to an existing slot + for base_info in inst.type.mro[:-1]: + if base_info.names.get("__setattr__") is not None: + # When type has `__setattr__` defined, + # we can assign any dynamic value. + # We exclude object, because it always has `__setattr__`. + return + + definition = inst.type.get(lvalue.name) + if definition is None: + # We don't want to duplicate + # `"SomeType" has no attribute "some_attr"` + # error twice. + return + if self.is_assignable_slot(lvalue, definition.type): + return + + self.fail( + message_registry.NAME_NOT_IN_SLOTS.format(lvalue.name, inst.type.fullname), lvalue + ) + + def is_assignable_slot(self, lvalue: Lvalue, typ: Type | None) -> bool: + if getattr(lvalue, "node", None): + return False # This is a definition + + typ = get_proper_type(typ) + if typ is None or isinstance(typ, AnyType): + return True # Any can be literally anything, like `@property` + if isinstance(typ, Instance): + # When working with instances, we need to know if they contain + # `__set__` special method. Like `@property` does. + # This makes assigning to properties possible, + # even without extra slot spec. + return typ.type.get("__set__") is not None + if isinstance(typ, FunctionLike): + return True # Can be a property, or some other magic + if isinstance(typ, UnionType): + return all(self.is_assignable_slot(lvalue, u) for u in typ.items) + return False + + def flatten_rvalues(self, rvalues: list[Expression]) -> list[Expression]: + """Flatten expression list by expanding those * items that have tuple type. + + For each regular type item in the tuple type use a TempNode(), for an Unpack + item use a corresponding StarExpr(TempNode()). + """ + new_rvalues = [] + for rv in rvalues: + if not isinstance(rv, StarExpr): + new_rvalues.append(rv) + continue + typ = get_proper_type(self.expr_checker.accept(rv.expr)) + if not isinstance(typ, TupleType): + new_rvalues.append(rv) + continue + for t in typ.items: + if not isinstance(t, UnpackType): + new_rvalues.append(TempNode(t)) + else: + unpacked = get_proper_type(t.type) + if isinstance(unpacked, TypeVarTupleType): + fallback = unpacked.upper_bound + else: + assert ( + isinstance(unpacked, Instance) + and unpacked.type.fullname == "builtins.tuple" + ) + fallback = unpacked + new_rvalues.append(StarExpr(TempNode(fallback))) + return new_rvalues + + def check_assignment_to_multiple_lvalues( + self, + lvalues: list[Lvalue], + rvalue: Expression, + context: Context, + infer_lvalue_type: bool = True, + ) -> None: + if isinstance(rvalue, (TupleExpr, ListExpr)): + # Recursively go into Tuple or List expression rhs instead of + # using the type of rhs, because this allows more fine-grained + # control in cases like: a, b = [int, str] where rhs would get + # type List[object] + rvalues: list[Expression] = [] + iterable_type: Type | None = None + last_idx: int | None = None + for idx_rval, rval in enumerate(self.flatten_rvalues(rvalue.items)): + if isinstance(rval, StarExpr): + typs = get_proper_type(self.expr_checker.accept(rval.expr)) + if self.type_is_iterable(typs) and isinstance(typs, Instance): + if iterable_type is not None and iterable_type != self.iterable_item_type( + typs, rvalue + ): + self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context) + else: + if last_idx is None or last_idx + 1 == idx_rval: + rvalues.append(rval) + last_idx = idx_rval + iterable_type = self.iterable_item_type(typs, rvalue) + else: + self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context) + else: + self.fail(message_registry.ITERABLE_TYPE_EXPECTED.format(typs), context) + else: + rvalues.append(rval) + iterable_start: int | None = None + iterable_end: int | None = None + for i, rval in enumerate(rvalues): + if isinstance(rval, StarExpr): + typs = get_proper_type(self.expr_checker.accept(rval.expr)) + if self.type_is_iterable(typs) and isinstance(typs, Instance): + if iterable_start is None: + iterable_start = i + iterable_end = i + if ( + iterable_start is not None + and iterable_end is not None + and iterable_type is not None + ): + iterable_num = iterable_end - iterable_start + 1 + rvalue_needed = len(lvalues) - (len(rvalues) - iterable_num) + if rvalue_needed > 0: + rvalues = ( + rvalues[0:iterable_start] + + [TempNode(iterable_type, context=rval) for _ in range(rvalue_needed)] + + rvalues[iterable_end + 1 :] + ) + + if self.check_rvalue_count_in_assignment(lvalues, len(rvalues), context): + star_index = next( + (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues) + ) + + left_lvs = lvalues[:star_index] + star_lv = ( + cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None + ) + right_lvs = lvalues[star_index + 1 :] + + left_rvs, star_rvs, right_rvs = self.split_around_star( + rvalues, star_index, len(lvalues) + ) + + lr_pairs = list(zip(left_lvs, left_rvs)) + if star_lv: + rv_list = ListExpr(star_rvs) + rv_list.set_line(rvalue) + lr_pairs.append((star_lv.expr, rv_list)) + lr_pairs.extend(zip(right_lvs, right_rvs)) + + for lv, rv in lr_pairs: + self.check_assignment(lv, rv, infer_lvalue_type) + else: + self.check_multi_assignment(lvalues, rvalue, context, infer_lvalue_type) + + def check_rvalue_count_in_assignment( + self, + lvalues: list[Lvalue], + rvalue_count: int, + context: Context, + rvalue_unpack: int | None = None, + ) -> bool: + if rvalue_unpack is not None: + if not any(isinstance(e, StarExpr) for e in lvalues): + self.fail("Variadic tuple unpacking requires a star target", context) + return False + if len(lvalues) > rvalue_count: + self.fail(message_registry.TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK, context) + return False + left_star_index = next(i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)) + left_prefix = left_star_index + left_suffix = len(lvalues) - left_star_index - 1 + right_prefix = rvalue_unpack + right_suffix = rvalue_count - rvalue_unpack - 1 + if left_suffix > right_suffix or left_prefix > right_prefix: + # Case of asymmetric unpack like: + # rv: tuple[int, *Ts, int, int] + # x, y, *xs, z = rv + # it is technically valid, but is tricky to reason about. + # TODO: support this (at least if the r.h.s. unpack is a homogeneous tuple). + self.fail(message_registry.TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK, context) + return True + if any(isinstance(lvalue, StarExpr) for lvalue in lvalues): + if len(lvalues) - 1 > rvalue_count: + self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues) - 1, context) + return False + elif rvalue_count != len(lvalues): + self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues), context) + return False + return True + + def check_multi_assignment( + self, + lvalues: list[Lvalue], + rvalue: Expression, + context: Context, + infer_lvalue_type: bool = True, + rv_type: Type | None = None, + undefined_rvalue: bool = False, + ) -> None: + """Check the assignment of one rvalue to a number of lvalues.""" + + # Infer the type of an ordinary rvalue expression. + # TODO: maybe elsewhere; redundant. + rvalue_type = get_proper_type(rv_type or self.expr_checker.accept(rvalue)) + + if isinstance(rvalue_type, TypeVarLikeType): + rvalue_type = get_proper_type(rvalue_type.upper_bound) + + if isinstance(rvalue_type, UnionType): + # If this is an Optional type in non-strict Optional code, unwrap it. + relevant_items = rvalue_type.relevant_items() + if len(relevant_items) == 1: + rvalue_type = get_proper_type(relevant_items[0]) + + if ( + isinstance(rvalue_type, TupleType) + and find_unpack_in_list(rvalue_type.items) is not None + ): + # Normalize for consistent handling with "old-style" homogeneous tuples. + rvalue_type = expand_type(rvalue_type, {}) + + if isinstance(rvalue_type, AnyType): + for lv in lvalues: + if isinstance(lv, StarExpr): + lv = lv.expr + temp_node = self.temp_node( + AnyType(TypeOfAny.from_another_any, source_any=rvalue_type), context + ) + self.check_assignment(lv, temp_node, infer_lvalue_type) + elif isinstance(rvalue_type, TupleType): + self.check_multi_assignment_from_tuple( + lvalues, rvalue, rvalue_type, context, undefined_rvalue, infer_lvalue_type + ) + elif isinstance(rvalue_type, UnionType): + self.check_multi_assignment_from_union( + lvalues, rvalue, rvalue_type, context, infer_lvalue_type + ) + else: + rvalue_literal = rvalue_type + if isinstance(rvalue_type, Instance) and rvalue_type.type.fullname == "builtins.str": + if rvalue_type.last_known_value is None: + self.msg.unpacking_strings_disallowed(context) + else: + rvalue_literal = rvalue_type.last_known_value + if ( + isinstance(rvalue_literal, LiteralType) + and isinstance(rvalue_literal.value, str) + and len(lvalues) != len(rvalue_literal.value) + ): + self.msg.unpacking_strings_disallowed(context) + + self.check_multi_assignment_from_iterable( + lvalues, rvalue_type, context, infer_lvalue_type + ) + + def check_multi_assignment_from_union( + self, + lvalues: list[Expression], + rvalue: Expression, + rvalue_type: UnionType, + context: Context, + infer_lvalue_type: bool, + ) -> None: + """Check assignment to multiple lvalue targets when rvalue type is a Union[...]. + For example: + + t: Union[Tuple[int, int], Tuple[str, str]] + x, y = t + reveal_type(x) # Union[int, str] + + The idea in this case is to process the assignment for every item of the union. + Important note: the types are collected in two places, 'union_types' contains + inferred types for first assignments, 'assignments' contains the narrowed types + for binder. + """ + self.no_partial_types = True + transposed: tuple[list[Type], ...] = tuple([] for _ in self.flatten_lvalues(lvalues)) + # Notify binder that we want to defer bindings and instead collect types. + with self.binder.accumulate_type_assignments() as assignments: + for item in rvalue_type.items: + # Type check the assignment separately for each union item and collect + # the inferred lvalue types for each union item. + self.check_multi_assignment( + lvalues, + rvalue, + context, + infer_lvalue_type=infer_lvalue_type, + rv_type=item, + undefined_rvalue=True, + ) + for t, lv in zip(transposed, self.flatten_lvalues(lvalues)): + # We can access _type_maps directly since temporary type maps are + # only created within expressions. + t.append(self._type_maps[-1].pop(lv, AnyType(TypeOfAny.special_form))) + union_types = tuple(make_simplified_union(col) for col in transposed) + for expr, items in assignments.items(): + # Bind a union of types collected in 'assignments' to every expression. + if isinstance(expr, StarExpr): + expr = expr.expr + + # TODO: See comment in binder.py, ConditionalTypeBinder.assign_type + # It's unclear why the 'declared_type' param is sometimes 'None' + clean_items: list[tuple[Type, Type]] = [] + for type, declared_type in items: + assert declared_type is not None + clean_items.append((type, declared_type)) + + types, declared_types = zip(*clean_items) + self.binder.assign_type( + expr, + make_simplified_union(list(types)), + make_simplified_union(list(declared_types)), + ) + for union, lv in zip(union_types, self.flatten_lvalues(lvalues)): + # Properly store the inferred types. + _1, _2, inferred = self.check_lvalue(lv) + if inferred: + self.set_inferred_type(inferred, lv, union) + else: + self.store_type(lv, union) + self.no_partial_types = False + + def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]: + res: list[Expression] = [] + for lv in lvalues: + if isinstance(lv, (TupleExpr, ListExpr)): + res.extend(self.flatten_lvalues(lv.items)) + if isinstance(lv, StarExpr): + # Unwrap StarExpr, since it is unwrapped by other helpers. + lv = lv.expr + res.append(lv) + return res + + def check_multi_assignment_from_tuple( + self, + lvalues: list[Lvalue], + rvalue: Expression, + rvalue_type: TupleType, + context: Context, + undefined_rvalue: bool, + infer_lvalue_type: bool = True, + ) -> None: + rvalue_unpack = find_unpack_in_list(rvalue_type.items) + if self.check_rvalue_count_in_assignment( + lvalues, len(rvalue_type.items), context, rvalue_unpack=rvalue_unpack + ): + star_index = next( + (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues) + ) + + left_lvs = lvalues[:star_index] + star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None + right_lvs = lvalues[star_index + 1 :] + + if not undefined_rvalue: + # Infer rvalue again, now in the correct type context. + lvalue_type = self.lvalue_type_for_inference(lvalues, rvalue_type) + reinferred_rvalue_type = get_proper_type( + self.expr_checker.accept(rvalue, lvalue_type) + ) + + if isinstance(reinferred_rvalue_type, TypeVarLikeType): + reinferred_rvalue_type = get_proper_type(reinferred_rvalue_type.upper_bound) + if isinstance(reinferred_rvalue_type, UnionType): + # If this is an Optional type in non-strict Optional code, unwrap it. + relevant_items = reinferred_rvalue_type.relevant_items() + if len(relevant_items) == 1: + reinferred_rvalue_type = get_proper_type(relevant_items[0]) + if isinstance(reinferred_rvalue_type, UnionType): + self.check_multi_assignment_from_union( + lvalues, rvalue, reinferred_rvalue_type, context, infer_lvalue_type + ) + return + if isinstance(reinferred_rvalue_type, AnyType): + # We can get Any if the current node is + # deferred. Doing more inference in deferred nodes + # is hard, so give up for now. We can also get + # here if reinferring types above changes the + # inferred return type for an overloaded function + # to be ambiguous. + return + assert isinstance(reinferred_rvalue_type, TupleType) + rvalue_type = reinferred_rvalue_type + + left_rv_types, star_rv_types, right_rv_types = self.split_around_star( + rvalue_type.items, star_index, len(lvalues) + ) + + for lv, rv_type in zip(left_lvs, left_rv_types): + self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type) + if star_lv: + list_expr = ListExpr( + [ + ( + self.temp_node(rv_type, context) + if not isinstance(rv_type, UnpackType) + else StarExpr(self.temp_node(rv_type.type, context)) + ) + for rv_type in star_rv_types + ] + ) + list_expr.set_line(context) + self.check_assignment(star_lv.expr, list_expr, infer_lvalue_type) + for lv, rv_type in zip(right_lvs, right_rv_types): + self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type) + else: + # Store meaningful Any types for lvalues, errors are already given + # by check_rvalue_count_in_assignment() + if infer_lvalue_type: + for lv in lvalues: + if ( + isinstance(lv, NameExpr) + and isinstance(lv.node, Var) + and lv.node.type is None + ): + lv.node.type = AnyType(TypeOfAny.from_error) + elif isinstance(lv, StarExpr): + if ( + isinstance(lv.expr, NameExpr) + and isinstance(lv.expr.node, Var) + and lv.expr.node.type is None + ): + lv.expr.node.type = self.named_generic_type( + "builtins.list", [AnyType(TypeOfAny.from_error)] + ) + + def lvalue_type_for_inference(self, lvalues: list[Lvalue], rvalue_type: TupleType) -> Type: + star_index = next( + (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues) + ) + left_lvs = lvalues[:star_index] + star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None + right_lvs = lvalues[star_index + 1 :] + left_rv_types, star_rv_types, right_rv_types = self.split_around_star( + rvalue_type.items, star_index, len(lvalues) + ) + + type_parameters: list[Type] = [] + + def append_types_for_inference(lvs: list[Expression], rv_types: list[Type]) -> None: + for lv, rv_type in zip(lvs, rv_types): + sub_lvalue_type, index_expr, inferred = self.check_lvalue(lv) + if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType): + type_parameters.append(sub_lvalue_type) + else: # index lvalue + # TODO Figure out more precise type context, probably + # based on the type signature of the _set method. + type_parameters.append(rv_type) + + append_types_for_inference(left_lvs, left_rv_types) + + if star_lv: + sub_lvalue_type, index_expr, inferred = self.check_lvalue(star_lv.expr) + if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType): + type_parameters.extend([sub_lvalue_type] * len(star_rv_types)) + else: # index lvalue + # TODO Figure out more precise type context, probably + # based on the type signature of the _set method. + type_parameters.extend(star_rv_types) + + append_types_for_inference(right_lvs, right_rv_types) + + return TupleType(type_parameters, self.named_type("builtins.tuple")) + + def split_around_star( + self, items: list[T], star_index: int, length: int + ) -> tuple[list[T], list[T], list[T]]: + """Splits a list of items in three to match another list of length 'length' + that contains a starred expression at 'star_index' in the following way: + + star_index = 2, length = 5 (i.e., [a,b,*,c,d]), items = [1,2,3,4,5,6,7] + returns in: ([1,2], [3,4,5], [6,7]) + """ + nr_right_of_star = length - star_index - 1 + right_index = -nr_right_of_star if nr_right_of_star != 0 else len(items) + left = items[:star_index] + star = items[star_index:right_index] + right = items[right_index:] + return left, star, right + + def type_is_iterable(self, type: Type) -> bool: + type = get_proper_type(type) + if isinstance(type, FunctionLike) and type.is_type_obj(): + type = type.fallback + return is_subtype( + type, self.named_generic_type("typing.Iterable", [AnyType(TypeOfAny.special_form)]) + ) + + def check_multi_assignment_from_iterable( + self, + lvalues: list[Lvalue], + rvalue_type: Type, + context: Context, + infer_lvalue_type: bool = True, + ) -> None: + rvalue_type = get_proper_type(rvalue_type) + if self.type_is_iterable(rvalue_type): + item_type = self.iterable_item_type(rvalue_type, context) + for lv in lvalues: + if isinstance(lv, StarExpr): + items_type = self.named_generic_type("builtins.list", [item_type]) + self.check_assignment( + lv.expr, self.temp_node(items_type, context), infer_lvalue_type + ) + else: + self.check_assignment( + lv, self.temp_node(item_type, context), infer_lvalue_type + ) + else: + self.msg.type_not_iterable(rvalue_type, context) + + def check_lvalue( + self, lvalue: Lvalue, rvalue: Expression | None = None + ) -> tuple[Type | None, IndexExpr | None, Var | None]: + lvalue_type = None + index_lvalue = None + inferred = None + + # When revisiting the initial assignment (for example in a loop), + # treat is as regular if redefinitions are allowed. + skip_definition = ( + self.options.allow_redefinition_new + and isinstance(lvalue, NameExpr) + and isinstance(lvalue.node, Var) + and lvalue.node.is_inferred + and lvalue.node.type is not None + and not isinstance(lvalue.node.type, PartialType) + # Indexes in for loops require special handling, we need to reset them to + # a literal value on each loop, but binder doesn't work well with literals. + and not lvalue.node.is_index_var + ) + + if ( + self.is_definition(lvalue) + and (not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var)) + and not skip_definition + ): + if isinstance(lvalue, NameExpr): + assert isinstance(lvalue.node, Var) + inferred = lvalue.node + else: + assert isinstance(lvalue, MemberExpr) + self.expr_checker.accept(lvalue.expr) + inferred = lvalue.def_var + elif isinstance(lvalue, IndexExpr): + index_lvalue = lvalue + elif isinstance(lvalue, MemberExpr): + lvalue_type = self.expr_checker.analyze_ordinary_member_access(lvalue, True, rvalue) + self.store_type(lvalue, lvalue_type) + elif isinstance(lvalue, NameExpr): + lvalue_type = self.expr_checker.analyze_ref_expr(lvalue, lvalue=True) + if ( + self.options.allow_redefinition_new + and isinstance(lvalue.node, Var) + # We allow redefinition for function arguments inside function body. + # Although we normally do this for variables without annotation, users + # don't have a choice to leave a function argument without annotation. + and (lvalue.node.is_inferred or lvalue.node.is_argument) + ): + inferred = lvalue.node + self.store_type(lvalue, lvalue_type) + elif isinstance(lvalue, (TupleExpr, ListExpr)): + types = [ + self.check_lvalue(sub_expr)[0] or + # This type will be used as a context for further inference of rvalue, + # we put Uninhabited if there is no information available from lvalue. + UninhabitedType() + for sub_expr in lvalue.items + ] + lvalue_type = TupleType(types, self.named_type("builtins.tuple")) + elif isinstance(lvalue, StarExpr): + lvalue_type, _, _ = self.check_lvalue(lvalue.expr) + else: + lvalue_type = self.expr_checker.accept(lvalue) + + return lvalue_type, index_lvalue, inferred + + def is_definition(self, s: Lvalue) -> bool: + if isinstance(s, NameExpr): + if s.is_inferred_def: + return True + # If the node type is not defined, this must the first assignment + # that we process => this is a definition, even though the semantic + # analyzer did not recognize this as such. This can arise in code + # that uses isinstance checks, if type checking of the primary + # definition is skipped due to an always False type check. + node = s.node + if isinstance(node, Var): + return node.type is None + elif isinstance(s, MemberExpr): + return s.is_inferred_def + return False + + def infer_variable_type( + self, name: Var, lvalue: Lvalue, init_type: Type, context: Context + ) -> None: + """Infer the type of initialized variables from initializer type.""" + if isinstance(init_type, DeletedType): + self.msg.deleted_as_rvalue(init_type, context) + elif ( + not is_valid_inferred_type( + init_type, + self.options, + is_lvalue_final=name.is_final, + is_lvalue_member=isinstance(lvalue, MemberExpr), + ) + and not ( + # Trust None assignments to dunder methods + # This is a bit ad-hoc, but it improves protocol + # (non-)assignability, for instance `__hash__ = None` + self.scope.active_class() + and is_dunder(name.name) + and isinstance(get_proper_type(init_type), NoneType) + ) + and not self.no_partial_types + ): + # We cannot use the type of the initialization expression for full type + # inference (it's not specific enough), but we might be able to give + # partial type which will be made more specific later. A partial type + # gets generated in assignment like 'x = []' where item type is not known. + if name.name != "_" and not self.infer_partial_type(name, lvalue, init_type): + self.msg.need_annotation_for_var(name, context, self.options) + self.set_inference_error_fallback_type(name, lvalue, init_type) + elif ( + isinstance(lvalue, MemberExpr) + and self.inferred_attribute_types is not None + and lvalue.def_var + and lvalue.def_var in self.inferred_attribute_types + and not is_same_type(self.inferred_attribute_types[lvalue.def_var], init_type) + ): + # Multiple, inconsistent types inferred for an attribute. + self.msg.need_annotation_for_var(name, context, self.options) + name.type = AnyType(TypeOfAny.from_error) + else: + # Infer type of the target. + + # Make the type more general (strip away function names etc.). + init_type = strip_type(init_type) + + self.set_inferred_type(name, lvalue, init_type) + if self.options.allow_redefinition_new: + self.binder.assign_type(lvalue, init_type, init_type) + + def infer_partial_type(self, name: Var, lvalue: Lvalue, init_type: Type) -> bool: + init_type = get_proper_type(init_type) + if isinstance(init_type, NoneType) and ( + isinstance(lvalue, MemberExpr) or not self.options.allow_redefinition_new + ): + # When using --allow-redefinition-new, None types aren't special + # when inferring simple variable types. + partial_type = PartialType(None, name) + elif isinstance(init_type, Instance): + fullname = init_type.type.fullname + is_ref = isinstance(lvalue, RefExpr) + if ( + is_ref + and ( + fullname == "builtins.list" + or fullname == "builtins.set" + or fullname == "builtins.dict" + or fullname == "collections.OrderedDict" + ) + and all( + isinstance(t, (NoneType, UninhabitedType)) + for t in get_proper_types(init_type.args) + ) + ): + partial_type = PartialType(init_type.type, name) + elif is_ref and fullname == "collections.defaultdict": + arg0 = get_proper_type(init_type.args[0]) + arg1 = get_proper_type(init_type.args[1]) + if isinstance( + arg0, (NoneType, UninhabitedType) + ) and self.is_valid_defaultdict_partial_value_type(arg1): + arg1 = erase_type(arg1) + assert isinstance(arg1, Instance) + partial_type = PartialType(init_type.type, name, arg1) + else: + return False + else: + return False + else: + return False + self.set_inferred_type(name, lvalue, partial_type) + self.partial_types[-1].map[name] = lvalue + return True + + def is_valid_defaultdict_partial_value_type(self, t: ProperType) -> bool: + """Check if t can be used as the basis for a partial defaultdict value type. + + Examples: + + * t is 'int' --> True + * t is 'list[Never]' --> True + * t is 'dict[...]' --> False (only generic types with a single type + argument supported) + """ + if not isinstance(t, Instance): + return False + if len(t.args) == 0: + return True + if len(t.args) == 1: + arg = get_proper_type(t.args[0]) + if self.options.old_type_inference: + # Allow leaked TypeVars for legacy inference logic. + allowed = isinstance(arg, (UninhabitedType, NoneType, TypeVarType)) + else: + allowed = isinstance(arg, (UninhabitedType, NoneType)) + if allowed: + return True + return False + + def set_inferred_type(self, var: Var, lvalue: Lvalue, type: Type) -> None: + """Store inferred variable type. + + Store the type to both the variable node and the expression node that + refers to the variable (lvalue). If var is None, do nothing. + """ + if var and not self.current_node_deferred: + var.type = type + var.is_inferred = True + var.is_ready = True + if var not in self.var_decl_frames: + # Used for the hack to improve optional type inference in conditionals + self.var_decl_frames[var] = {frame.id for frame in self.binder.frames} + if isinstance(lvalue, MemberExpr) and self.inferred_attribute_types is not None: + # Store inferred attribute type so that we can check consistency afterwards. + if lvalue.def_var is not None: + self.inferred_attribute_types[lvalue.def_var] = type + self.store_type(lvalue, type) + p_type = get_proper_type(type) + definition = None + if isinstance(p_type, CallableType): + definition = p_type.definition + elif isinstance(p_type, Overloaded): + # Randomly select first item, if items are different, there will + # be an error during semantic analysis. + definition = p_type.items[0].definition + if definition: + if is_node_static(definition): + var.is_staticmethod = True + elif is_classmethod_node(definition): + var.is_classmethod = True + elif is_property(definition): + var.is_property = True + if isinstance(p_type, Overloaded): + # TODO: in theory we can have a property with a deleter only. + var.is_settable_property = True + assert isinstance(definition, Decorator), definition + var.setter_type = definition.var.setter_type + + def set_inference_error_fallback_type(self, var: Var, lvalue: Lvalue, type: Type) -> None: + """Store best known type for variable if type inference failed. + + If a program ignores error on type inference error, the variable should get some + inferred type so that it can be used later on in the program. Example: + + x = [] # type: ignore + x.append(1) # Should be ok! + + We implement this here by giving x a valid type (replacing inferred Never with Any). + """ + fallback = self.inference_error_fallback_type(type) + self.set_inferred_type(var, lvalue, fallback) + + def inference_error_fallback_type(self, type: Type) -> Type: + fallback = type.accept(SetNothingToAny()) + # Type variables may leak from inference, see https://github.com/python/mypy/issues/5738, + # we therefore need to erase them. + return erase_typevars(fallback) + + def simple_rvalue(self, rvalue: Expression) -> bool: + """Returns True for expressions for which inferred type should not depend on context. + + Note that this function can still return False for some expressions where inferred type + does not depend on context. It only exists for performance optimizations. + """ + if isinstance(rvalue, (IntExpr, StrExpr, BytesExpr, FloatExpr, RefExpr)): + return True + if isinstance(rvalue, CallExpr): + if isinstance(rvalue.callee, RefExpr) and isinstance( + rvalue.callee.node, SYMBOL_FUNCBASE_TYPES + ): + typ = rvalue.callee.node.type + if isinstance(typ, CallableType): + return not typ.variables + elif isinstance(typ, Overloaded): + return not any(item.variables for item in typ.items) + return False + + def infer_rvalue_with_fallback_context( + self, + lvalue_type: Type | None, + rvalue: Expression, + preferred_context: Type | None, + fallback_context: Type | None, + inferred: Var | None, + always_allow_any: bool, + ) -> Type: + """Infer rvalue type in two type context and select the best one. + + See comments below for supported fallback scenarios. + """ + assert fallback_context is not preferred_context + # TODO: make assignment checking correct in presence of walrus in r.h.s. + # We may accept r.h.s. twice. In presence of walrus this can lead to weird + # false negatives and "back action". A proper solution would be to use + # binder.accumulate_type_assignments() and assign the types inferred for type + # context that is ultimately used. This is however tricky with redefinitions. + # For now we simply disable second accept in cases known to cause problems, + # see e.g. testAssignToOptionalTupleWalrus. + binder_version = self.binder.version + + fallback_context_used = False + with ( + self.msg.filter_errors(save_filtered_errors=True) as local_errors, + self.local_type_map as type_map, + ): + rvalue_type = self.expr_checker.accept( + rvalue, type_context=preferred_context, always_allow_any=always_allow_any + ) + + # There are two cases where we want to try re-inferring r.h.s. in a fallback + # type context. First case is when redefinitions are allowed, and we got + # invalid type when using the preferred (empty) type context. + redefinition_fallback = ( + inferred is not None + and not inferred.is_argument + and not is_valid_inferred_type(rvalue_type, self.options) + ) + # For function arguments the preference order is opposite, and we use errors + # during type-checking as the fallback trigger. + argument_redefinition_fallback = ( + inferred is not None and inferred.is_argument and local_errors.has_new_errors() + ) + # Try re-inferring r.h.s. in empty context for union with explicit annotation, + # and use it results in a narrower type. This helps with various practical + # examples, see e.g. testOptionalTypeNarrowedByGenericCall. + union_fallback = ( + preferred_context is not None + and isinstance(get_proper_type(lvalue_type), UnionType) + and binder_version == self.binder.version + ) + + # Skip literal types, as they have special logic (for better errors). + try_fallback = redefinition_fallback or union_fallback or argument_redefinition_fallback + if try_fallback and not is_literal_type_like(rvalue_type): + with ( + self.msg.filter_errors(save_filtered_errors=True) as alt_local_errors, + self.local_type_map as alt_type_map, + ): + alt_rvalue_type = self.expr_checker.accept( + rvalue, fallback_context, always_allow_any=always_allow_any + ) + if ( + not alt_local_errors.has_new_errors() + and is_valid_inferred_type(alt_rvalue_type, self.options) + and ( + # For redefinition fallbacks we are fine getting not a subtype. + redefinition_fallback + or argument_redefinition_fallback + # Skip Any type, since it is special cased in binder. + or not isinstance(get_proper_type(alt_rvalue_type), AnyType) + and is_proper_subtype(alt_rvalue_type, rvalue_type) + ) + ): + fallback_context_used = True + rvalue_type = alt_rvalue_type + self.store_types(alt_type_map) + + if not fallback_context_used: + self.msg.add_errors(local_errors.filtered_errors()) + self.store_types(type_map) + return rvalue_type + + def check_simple_assignment( + self, + lvalue_type: Type | None, + rvalue: Expression, + context: Context, + msg: ErrorMessage = message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, + lvalue_name: str = "variable", + rvalue_name: str = "expression", + *, + notes: list[str] | None = None, + lvalue: Expression | None = None, + inferred: Var | None = None, + ) -> tuple[Type, Type | None]: + if self.is_stub and isinstance(rvalue, EllipsisExpr): + # '...' is always a valid initializer in a stub. + return AnyType(TypeOfAny.special_form), lvalue_type + else: + always_allow_any = lvalue_type is not None and not isinstance( + get_proper_type(lvalue_type), AnyType + ) + + # If redefinitions are allowed (i.e. we have --allow-redefinition-new + # and a variable without annotation) or if a variable has union type we + # try inferring r.h.s. twice with a fallback type context. The only exception + # is TypedDicts, they are often useless without context. + try_fallback = ( + inferred is not None or isinstance(get_proper_type(lvalue_type), UnionType) + ) and not self.simple_rvalue(rvalue) + + if not try_fallback or lvalue_type is None or is_typeddict_type_context(lvalue_type): + rvalue_type = self.expr_checker.accept( + rvalue, type_context=lvalue_type, always_allow_any=always_allow_any + ) + else: + # Prefer full type context for function arguments as this reduces + # false positives, see issue #19918 for discussion. + if inferred is not None and not inferred.is_argument: + preferred = None + fallback = lvalue_type + else: + preferred = lvalue_type + fallback = None + + rvalue_type = self.infer_rvalue_with_fallback_context( + lvalue_type, rvalue, preferred, fallback, inferred, always_allow_any + ) + + if ( + inferred is not None + and not is_valid_inferred_type(rvalue_type, self.options) + and ( + not inferred.type + or isinstance(inferred.type, PartialType) + # This additional check is to give an error instead of inferring + # a useless type like None | list[Never] in case of "double-partial" + # types that are not supported yet, see issue #20257. + or not is_subtype(rvalue_type, inferred.type) + ) + ): + self.msg.need_annotation_for_var(inferred, inferred, self.options) + rvalue_type = rvalue_type.accept(SetNothingToAny()) + + if ( + isinstance(lvalue, NameExpr) + and inferred is not None + and inferred.type is not None + and not inferred.is_final + ): + new_inferred = remove_instance_last_known_values(rvalue_type) + # Should we widen the inferred type or the lvalue? Variables defined + # at module level or class bodies can't be widened in functions, or + # in another module. + if ( + not self.refers_to_different_scope(lvalue) + and not isinstance(inferred.type, PartialType) + and not is_proper_subtype(new_inferred, inferred.type) + ): + lvalue_type = make_simplified_union([inferred.type, new_inferred]) + # Widen the type to the union of original and new type. + if not inferred.is_index_var: + # Skip index variables as they are reset on each loop. + self.widened_vars.append(inferred.name) + self.set_inferred_type(inferred, lvalue, lvalue_type) + self.binder.put(lvalue, rvalue_type) + # TODO: A bit hacky, maybe add a binder method that does put and + # updates declaration? + lit = literal_hash(lvalue) + if lit is not None: + self.binder.declarations[lit] = lvalue_type + + if isinstance(rvalue_type, DeletedType): + self.msg.deleted_as_rvalue(rvalue_type, context) + if isinstance(lvalue_type, DeletedType): + self.msg.deleted_as_lvalue(lvalue_type, context) + elif lvalue_type: + self.check_subtype( + # Preserve original aliases for error messages when possible. + rvalue_type, + lvalue_type, + context, + msg, + f"{rvalue_name} has type", + f"{lvalue_name} has type", + notes=notes, + ) + return rvalue_type, lvalue_type + + def refers_to_different_scope(self, name: NameExpr) -> bool: + if name.kind == LDEF: + # TODO: Consider reference to outer function as a different scope? + return False + elif self.scope.top_level_function() is not None: + # A non-local reference from within a function must refer to a different scope + return True + elif name.kind == GDEF and name.fullname.rpartition(".")[0] != self.tree.fullname: + # Reference to global definition from another module + return True + return False + + def check_member_assignment( + self, + lvalue: MemberExpr, + instance_type: Type, + set_lvalue_type: Type, + rvalue: Expression, + context: Context, + ) -> tuple[Type, Type, bool]: + """Type member assignment. + + This defers to check_simple_assignment, unless the member expression + is a descriptor, in which case this checks descriptor semantics as well. + + Return the inferred rvalue_type, inferred lvalue_type, and whether to use the binder + for this assignment. + """ + instance_type = get_proper_type(instance_type) + # Descriptors don't participate in class-attribute access + if (isinstance(instance_type, FunctionLike) and instance_type.is_type_obj()) or isinstance( + instance_type, TypeType + ): + rvalue_type, _ = self.check_simple_assignment(set_lvalue_type, rvalue, context) + return rvalue_type, set_lvalue_type, True + + with self.msg.filter_errors(filter_deprecated=True): + get_lvalue_type = self.expr_checker.analyze_ordinary_member_access( + lvalue, is_lvalue=False + ) + + # Special case: if the rvalue_type is a subtype of '__get__' type, and + # '__get__' type is narrower than '__set__', then we invoke the binder to narrow type + # by this assignment. Technically, this is not safe, but in practice this is + # what a user expects. + rvalue_type, _ = self.check_simple_assignment(set_lvalue_type, rvalue, context) + rvalue_type = rvalue_type if is_subtype(rvalue_type, get_lvalue_type) else get_lvalue_type + return rvalue_type, set_lvalue_type, is_subtype(get_lvalue_type, set_lvalue_type) + + def check_indexed_assignment( + self, lvalue: IndexExpr, rvalue: Expression, context: Context + ) -> None: + """Type check indexed assignment base[index] = rvalue. + + The lvalue argument is the base[index] expression. + """ + self.try_infer_partial_type_from_indexed_assignment(lvalue, rvalue) + basetype = get_proper_type(self.expr_checker.accept(lvalue.base)) + method_type = self.expr_checker.analyze_external_member_access( + "__setitem__", basetype, lvalue + ) + + lvalue.method_type = method_type + res_type, _ = self.expr_checker.check_method_call( + "__setitem__", + basetype, + method_type, + [lvalue.index, rvalue], + [nodes.ARG_POS, nodes.ARG_POS], + context, + ) + res_type = get_proper_type(res_type) + if isinstance(res_type, UninhabitedType) and not res_type.ambiguous: + self.binder.unreachable() + + def replace_partial_type( + self, var: Var, new_type: Type, partial_types: dict[Var, Context] + ) -> None: + """Replace the partial type of var with a non-partial type.""" + var.type = new_type + # Updating a partial type should invalidate expression caches. + self.binder.version += 1 + del partial_types[var] + if self.options.allow_redefinition_new: + # When using --allow-redefinition-new, binder tracks all types of + # simple variables. + n = NameExpr(var.name) + n.node = var + self.binder.assign_type(n, new_type, new_type) + + def try_infer_partial_type_from_indexed_assignment( + self, lvalue: IndexExpr, rvalue: Expression + ) -> None: + # TODO: Should we share some of this with try_infer_partial_type? + var = None + if isinstance(lvalue.base, RefExpr) and isinstance(lvalue.base.node, Var): + var = lvalue.base.node + elif isinstance(lvalue.base, MemberExpr): + var = self.expr_checker.get_partial_self_var(lvalue.base) + if isinstance(var, Var): + if isinstance(var.type, PartialType): + type_type = var.type.type + if type_type is None: + return # The partial type is None. + partial_types = self.find_partial_types(var) + if partial_types is None: + return + typename = type_type.fullname + if ( + typename == "builtins.dict" + or typename == "collections.OrderedDict" + or typename == "collections.defaultdict" + ): + # TODO: Don't infer things twice. + key_type = self.expr_checker.accept(lvalue.index) + value_type = self.expr_checker.accept(rvalue) + if ( + is_valid_inferred_type(key_type, self.options) + and is_valid_inferred_type(value_type, self.options) + and not self.current_node_deferred + and not ( + typename == "collections.defaultdict" + and var.type.value_type is not None + and not is_equivalent(value_type, var.type.value_type) + ) + ): + new_type = self.named_generic_type(typename, [key_type, value_type]) + self.replace_partial_type(var, new_type, partial_types) + + def type_requires_usage(self, typ: Type) -> tuple[str, ErrorCode] | None: + """Some types require usage in all cases. The classic example is + an unused coroutine. + + In the case that it does require usage, returns a note to attach + to the error message. + """ + proper_type = get_proper_type(typ) + if isinstance(proper_type, Instance): + # We use different error codes for generic awaitable vs coroutine. + # Coroutines are on by default, whereas generic awaitables are not. + if proper_type.type.fullname == "typing.Coroutine": + return ("Are you missing an await?", UNUSED_COROUTINE) + if proper_type.type.get("__await__") is not None: + return ("Are you missing an await?", UNUSED_AWAITABLE) + return None + + def visit_expression_stmt(self, s: ExpressionStmt) -> None: + expr_type = self.expr_checker.accept(s.expr, allow_none_return=True, always_allow_any=True) + error_note_and_code = self.type_requires_usage(expr_type) + if error_note_and_code: + error_note, code = error_note_and_code + self.fail( + message_registry.TYPE_MUST_BE_USED.format(format_type(expr_type, self.options)), + s, + code=code, + ) + self.note(error_note, s, code=code) + + def visit_return_stmt(self, s: ReturnStmt) -> None: + """Type check a return statement.""" + self.check_return_stmt(s) + self.binder.unreachable() + + def infer_context_dependent( + self, expr: Expression, type_ctx: Type, allow_none_func_call: bool + ) -> ProperType: + """Infer type of expression with fallback to empty type context.""" + with self.msg.filter_errors(filter_deprecated=True, save_filtered_errors=True) as msg: + with ( + self.local_type_map as type_map, + # Prevent any narrowing (e.g. from walrus) to have effect during second accept. + self.binder.frame_context(can_skip=False, discard=True), + ): + typ = get_proper_type( + self.expr_checker.accept( + expr, type_ctx, allow_none_return=allow_none_func_call + ) + ) + if not msg.has_new_errors(): + self.store_types(type_map) + return typ + + # If there are errors with the original type context, try re-inferring in empty context. + original_messages = msg.filtered_errors() + original_type_map = type_map + with self.msg.filter_errors(filter_deprecated=True, save_filtered_errors=True) as msg: + with self.local_type_map as type_map: + alt_typ = get_proper_type( + self.expr_checker.accept(expr, None, allow_none_return=allow_none_func_call) + ) + if not msg.has_new_errors() and is_subtype(alt_typ, type_ctx): + self.store_types(type_map) + return alt_typ + + # If empty fallback didn't work, use results from the original type context. + self.msg.add_errors(original_messages) + self.store_types(original_type_map) + return typ + + def check_return_stmt(self, s: ReturnStmt) -> None: + defn = self.scope.current_function() + if defn is not None: + if defn.is_generator: + return_type = self.get_generator_return_type( + self.return_types[-1], defn.is_coroutine + ) + elif defn.is_coroutine: + return_type = self.get_coroutine_return_type(self.return_types[-1]) + else: + return_type = self.return_types[-1] + return_type = get_proper_type(return_type) + + is_lambda = isinstance(defn, LambdaExpr) + if isinstance(return_type, UninhabitedType): + # Avoid extra error messages for failed inference in lambdas + if not is_lambda and not return_type.ambiguous: + self.fail(message_registry.NO_RETURN_EXPECTED, s) + return + + if s.expr: + declared_none_return = isinstance(return_type, NoneType) + declared_any_return = isinstance(return_type, AnyType) + + # This controls whether or not we allow a function call that + # returns None as the expression of this return statement. + # E.g. `return f()` for some `f` that returns None. We allow + # this only if we're in a lambda or in a function that returns + # `None` or `Any`. + allow_none_func_call = is_lambda or declared_none_return or declared_any_return + + # Return with a value. + if ( + isinstance(s.expr, (CallExpr, ListExpr, TupleExpr, DictExpr, SetExpr, OpExpr)) + or isinstance(s.expr, AwaitExpr) + and isinstance(s.expr.expr, CallExpr) + ): + # For expressions that (strongly) depend on type context (i.e. those that + # are handled like a function call), we allow fallback to empty type context + # in case of errors, this improves user experience in some cases, + # see e.g. testReturnFallbackInference. + typ = self.infer_context_dependent(s.expr, return_type, allow_none_func_call) + else: + typ = get_proper_type( + self.expr_checker.accept( + s.expr, return_type, allow_none_return=allow_none_func_call + ) + ) + # Treat NotImplemented as having type Any, consistent with its + # definition in typeshed prior to python/typeshed#4222. + if isinstance(typ, Instance) and typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES: + typ = AnyType(TypeOfAny.special_form) + + if defn.is_async_generator: + self.fail(message_registry.RETURN_IN_ASYNC_GENERATOR, s) + return + # Returning a value of type Any is always fine. + if isinstance(typ, AnyType): + # (Unless you asked to be warned in that case, and the + # function is not declared to return Any) + if ( + self.options.warn_return_any + and not self.current_node_deferred + and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type) + and not ( + defn.name in BINARY_MAGIC_METHODS + and is_literal_not_implemented(s.expr) + ) + and not ( + isinstance(return_type, Instance) + and return_type.type.fullname == "builtins.object" + ) + and not is_lambda + ): + self.msg.incorrectly_returning_any(return_type, s) + return + + # Disallow return expressions in functions declared to return + # None, subject to two exceptions below. + if declared_none_return: + # Lambdas are allowed to have None returns. + # Functions returning a value of type None are allowed to have a None return. + if is_lambda or isinstance(typ, NoneType): + return + self.fail(message_registry.NO_RETURN_VALUE_EXPECTED, s) + else: + self.check_subtype( + subtype_label="got", + subtype=typ, + supertype_label="expected", + supertype=return_type, + context=s.expr, + outer_context=s, + msg=message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE, + ) + else: + # Empty returns are valid in Generators with Any typed returns, but not in + # coroutines. + if ( + defn.is_generator + and not defn.is_coroutine + and isinstance(return_type, AnyType) + ): + return + + if isinstance(return_type, (NoneType, AnyType)): + return + + if self.in_checked_function(): + self.fail(message_registry.RETURN_VALUE_EXPECTED, s) + + def visit_if_stmt(self, s: IfStmt) -> None: + """Type check an if statement.""" + # This frame records the knowledge from previous if/elif clauses not being taken. + # Fall-through to the original frame is handled explicitly in each block. + with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=0): + for e, b in zip(s.expr, s.body): + t = get_proper_type(self.expr_checker.accept(e)) + + if isinstance(t, DeletedType): + self.msg.deleted_as_rvalue(t, s) + + if_map, else_map = self.find_isinstance_check(e) + + s.unreachable_else = is_unreachable_map(else_map) + + # XXX Issue a warning if condition is always False? + with self.binder.frame_context(can_skip=True, fall_through=2): + self.push_type_map(if_map, from_assignment=False) + self.accept(b) + + # XXX Issue a warning if condition is always True? + self.push_type_map(else_map, from_assignment=False) + + with self.binder.frame_context(can_skip=False, fall_through=2): + if s.else_body: + self.accept(s.else_body) + + def visit_while_stmt(self, s: WhileStmt) -> None: + """Type check a while statement.""" + if_stmt = IfStmt([s.expr], [s.body], None) + if_stmt.set_line(s) + self.accept_loop(if_stmt, s.else_body, exit_condition=s.expr) + + def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None: + """Type check an operator assignment statement, e.g. x += 1.""" + self.try_infer_partial_generic_type_from_assignment(s.lvalue, s.rvalue, s.op) + if isinstance(s.lvalue, MemberExpr): + # Special case, some additional errors may be given for + # assignments to read-only or final attributes. + lvalue_type = self.expr_checker.visit_member_expr(s.lvalue, True) + else: + lvalue_type = self.expr_checker.accept(s.lvalue) + inplace, method = infer_operator_assignment_method(lvalue_type, s.op) + if inplace: + # There is __ifoo__, treat as x = x.__ifoo__(y) + rvalue_type, _ = self.expr_checker.check_op(method, lvalue_type, s.rvalue, s) + if not is_subtype(rvalue_type, lvalue_type): + self.msg.incompatible_operator_assignment(s.op, s) + else: + # There is no __ifoo__, treat as x = x y + expr = OpExpr(s.op, s.lvalue, s.rvalue) + expr.set_line(s) + self.check_assignment( + lvalue=s.lvalue, rvalue=expr, infer_lvalue_type=True, new_syntax=False + ) + self.check_final(s) + + def visit_assert_stmt(self, s: AssertStmt) -> None: + self.expr_checker.accept(s.expr) + + if isinstance(s.expr, TupleExpr) and len(s.expr.items) > 0: + self.fail(message_registry.MALFORMED_ASSERT, s) + + # If this is asserting some isinstance check, bind that type in the following code + true_map, else_map = self.find_isinstance_check(s.expr) + if s.msg is not None: + self.expr_checker.analyze_cond_branch( + else_map, s.msg, None, suppress_unreachable_errors=False + ) + self.push_type_map(true_map) + + def visit_raise_stmt(self, s: RaiseStmt) -> None: + """Type check a raise statement.""" + if s.expr: + self.type_check_raise(s.expr, s) + if s.from_expr: + self.type_check_raise(s.from_expr, s, optional=True) + self.binder.unreachable() + + def type_check_raise(self, e: Expression, s: RaiseStmt, optional: bool = False) -> None: + typ = get_proper_type(self.expr_checker.accept(e)) + if isinstance(typ, DeletedType): + self.msg.deleted_as_rvalue(typ, e) + return + + exc_type = self.named_type("builtins.BaseException") + expected_type_items = [exc_type, TypeType(exc_type)] + if optional: + # This is used for `x` part in a case like `raise e from x`, + # where we allow `raise e from None`. + expected_type_items.append(NoneType()) + + self.check_subtype( + typ, UnionType.make_union(expected_type_items), s, message_registry.INVALID_EXCEPTION + ) + + if isinstance(typ, FunctionLike): + # https://github.com/python/mypy/issues/11089 + self.expr_checker.check_call(typ, [], [], e) + + if (isinstance(typ, Instance) and typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES) or ( + isinstance(e, CallExpr) + and isinstance(e.callee, RefExpr) + and e.callee.fullname == "builtins.NotImplemented" + ): + self.fail( + message_registry.INVALID_EXCEPTION.with_additional_msg( + '; did you mean "NotImplementedError"?' + ), + s, + ) + + def visit_try_stmt(self, s: TryStmt) -> None: + """Type check a try statement.""" + + iter_errors = None + + # Our enclosing frame will get the result if the try/except falls through. + # This one gets all possible states after the try block exited abnormally + # (by exception, return, break, etc.) + with self.binder.frame_context(can_skip=False, fall_through=0): + # Not only might the body of the try statement exit + # abnormally, but so might an exception handler or else + # clause. The finally clause runs in *all* cases, so we + # need an outer try frame to catch all intermediate states + # in case an exception is raised during an except or else + # clause. As an optimization, only create the outer try + # frame when there actually is a finally clause. + self.visit_try_without_finally(s, try_frame=bool(s.finally_body)) + if s.finally_body: + # First we check finally_body is type safe on all abnormal exit paths + iter_errors = IterationDependentErrors() + with IterationErrorWatcher(self.msg.errors, iter_errors): + self.accept(s.finally_body) + + if s.finally_body: + # Then we try again for the more restricted set of options + # that can fall through. (Why do we need to check the + # finally clause twice? Depending on whether the finally + # clause was reached by the try clause falling off the end + # or exiting abnormally, after completing the finally clause + # either flow will continue to after the entire try statement + # or the exception/return/etc. will be processed and control + # flow will escape. We need to check that the finally clause + # type checks in both contexts, but only the resulting types + # from the latter context affect the type state in the code + # that follows the try statement.) + assert iter_errors is not None + if not self.binder.is_unreachable(): + with IterationErrorWatcher(self.msg.errors, iter_errors): + self.accept(s.finally_body) + self.msg.iteration_dependent_errors(iter_errors) + + def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None: + """Type check a try statement, ignoring the finally block. + + On entry, the top frame should receive all flow that exits the + try block abnormally (i.e., such that the else block does not + execute), and its parent should receive all flow that exits + the try block normally. + """ + # This frame will run the else block if the try fell through. + # In that case, control flow continues to the parent of what + # was the top frame on entry. + with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=try_frame): + # This frame receives exit via exception, and runs exception handlers + with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=2): + # Finally, the body of the try statement + with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=True): + self.accept(s.body) + for i in range(len(s.handlers)): + with self.binder.frame_context(can_skip=True, fall_through=4): + typ = s.types[i] + if typ: + t = self.check_except_handler_test(typ, s.is_star) + var = s.vars[i] + if var: + # To support local variables, we make this a definition line, + # causing assignment to set the variable's type. + var.is_inferred_def = True + self.check_assignment(var, self.temp_node(t, var)) + self.accept(s.handlers[i]) + var = s.vars[i] + if var: + # Exception variables are deleted. + # Unfortunately, this doesn't let us detect usage before the + # try/except block. + source = var.name + if isinstance(var.node, Var): + new_type = DeletedType(source=source) + var.node.type = new_type + if self.options.allow_redefinition_new: + # TODO: Should we use put() here? + self.binder.assign_type(var, new_type, new_type) + if not self.options.allow_redefinition_new: + self.binder.cleanse(var) + if s.else_body: + self.accept(s.else_body) + + def check_except_handler_test(self, n: Expression, is_star: bool) -> Type: + """Type check an exception handler test clause.""" + typ = self.expr_checker.accept(n) + + all_types: list[Type] = [] + test_types = self.get_types_from_except_handler(typ, n) + + for ttype in get_proper_types(test_types): + if isinstance(ttype, AnyType): + all_types.append(ttype) + continue + if isinstance(ttype, UninhabitedType): + continue + + if isinstance(ttype, FunctionLike): + item = ttype.items[0] + if not item.is_type_obj(): + self.fail(message_registry.INVALID_EXCEPTION_TYPE, n) + return self.default_exception_type(is_star) + exc_type = erase_typevars(item.ret_type) + elif isinstance(ttype, TypeType): + exc_type = ttype.item + else: + self.fail(message_registry.INVALID_EXCEPTION_TYPE, n) + return self.default_exception_type(is_star) + + if not is_subtype(exc_type, self.named_type("builtins.BaseException")): + self.fail(message_registry.INVALID_EXCEPTION_TYPE, n) + return self.default_exception_type(is_star) + + all_types.append(exc_type) + + if is_star: + new_all_types: list[Type] = [] + for typ in all_types: + if is_proper_subtype(typ, self.named_type("builtins.BaseExceptionGroup")): + self.fail(message_registry.INVALID_EXCEPTION_GROUP, n) + new_all_types.append(AnyType(TypeOfAny.from_error)) + else: + new_all_types.append(typ) + return self.wrap_exception_group(new_all_types) + return make_simplified_union(all_types) + + def default_exception_type(self, is_star: bool) -> Type: + """Exception type to return in case of a previous type error.""" + any_type = AnyType(TypeOfAny.from_error) + if is_star: + return self.named_generic_type("builtins.ExceptionGroup", [any_type]) + return any_type + + def wrap_exception_group(self, types: Sequence[Type]) -> Type: + """Transform except* variable type into an appropriate exception group.""" + arg = make_simplified_union(types) + if is_subtype(arg, self.named_type("builtins.Exception")): + base = "builtins.ExceptionGroup" + else: + base = "builtins.BaseExceptionGroup" + return self.named_generic_type(base, [arg]) + + def get_types_from_except_handler(self, typ: Type, n: Expression) -> list[Type]: + """Helper for check_except_handler_test to retrieve handler types.""" + typ = get_proper_type(typ) + if isinstance(typ, TupleType): + merged_type = make_simplified_union(typ.items) + if isinstance(merged_type, UnionType): + return merged_type.relevant_items() + return [merged_type] + elif is_named_instance(typ, "builtins.tuple"): + # variadic tuple + merged_type = make_simplified_union((typ.args[0],)) + if isinstance(merged_type, UnionType): + return merged_type.relevant_items() + return [merged_type] + elif isinstance(typ, UnionType): + return [ + union_typ + for item in typ.relevant_items() + for union_typ in self.get_types_from_except_handler(item, n) + ] + else: + return [typ] + + def visit_for_stmt(self, s: ForStmt) -> None: + """Type check a for statement.""" + if s.is_async: + iterator_type, item_type = self.analyze_async_iterable_item_type(s.expr) + else: + iterator_type, item_type = self.analyze_iterable_item_type(s.expr) + s.inferred_item_type = item_type + s.inferred_iterator_type = iterator_type + + self.accept_loop( + s.body, + s.else_body, + on_enter_body=lambda: self.analyze_index_variables( + s.index, item_type, s.index_type is None, s + ), + ) + + def analyze_async_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]: + """Analyse async iterable expression and return iterator and iterator item types.""" + echk = self.expr_checker + iterable = echk.accept(expr) + iterator = echk.check_method_call_by_name("__aiter__", iterable, [], [], expr)[0] + awaitable = echk.check_method_call_by_name("__anext__", iterator, [], [], expr)[0] + item_type = echk.check_awaitable_expr( + awaitable, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_FOR + ) + return iterator, item_type + + def analyze_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]: + """Analyse iterable expression and return iterator and iterator item types.""" + iterator, iterable = self.analyze_iterable_item_type_without_expression( + self.expr_checker.accept(expr), context=expr + ) + int_type = self.analyze_range_native_int_type(expr) + if int_type: + return iterator, int_type + return iterator, iterable + + def analyze_iterable_item_type_without_expression( + self, type: Type, context: Context + ) -> tuple[Type, Type]: + """Analyse iterable type and return iterator and iterator item types.""" + echk = self.expr_checker + iterable: Type + iterable = get_proper_type(type) + iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], context)[0] + + if ( + isinstance(iterable, TupleType) + and iterable.partial_fallback.type.fullname == "builtins.tuple" + ): + return iterator, tuple_fallback(iterable).args[0] + else: + # Non-tuple iterable. + iterable = echk.check_method_call_by_name("__next__", iterator, [], [], context)[0] + return iterator, iterable + + def analyze_range_native_int_type(self, expr: Expression) -> Type | None: + """Try to infer native int item type from arguments to range(...). + + For example, return i64 if the expression is "range(0, i64(n))". + + Return None if unsuccessful. + """ + if ( + isinstance(expr, CallExpr) + and isinstance(expr.callee, RefExpr) + and expr.callee.fullname == "builtins.range" + and 1 <= len(expr.args) <= 3 + and all(kind == ARG_POS for kind in expr.arg_kinds) + ): + native_int: Type | None = None + ok = True + for arg in expr.args: + argt = get_proper_type(self.lookup_type(arg)) + if isinstance(argt, Instance) and argt.type.fullname in MYPYC_NATIVE_INT_NAMES: + if native_int is None: + native_int = argt + elif argt != native_int: + ok = False + if ok and native_int: + return native_int + return None + + def analyze_container_item_type(self, typ: Type) -> Type | None: + """Check if a type is a nominal container of a union of such. + + Return the corresponding container item type. + """ + typ = get_proper_type(typ) + if isinstance(typ, UnionType): + types: list[Type] = [] + for item in typ.items: + c_type = self.analyze_container_item_type(item) + if c_type: + types.append(c_type) + return UnionType.make_union(types) + if isinstance(typ, Instance) and typ.type.has_base("typing.Container"): + supertype = self.named_type("typing.Container").type + super_instance = map_instance_to_supertype(typ, supertype) + assert len(super_instance.args) == 1 + return super_instance.args[0] + if isinstance(typ, TupleType): + return self.analyze_container_item_type(tuple_fallback(typ)) + return None + + def analyze_index_variables( + self, index: Expression, item_type: Type, infer_lvalue_type: bool, context: Context + ) -> None: + """Type check or infer for loop or list comprehension index vars.""" + self.check_assignment(index, self.temp_node(item_type, context), infer_lvalue_type) + + def visit_del_stmt(self, s: DelStmt) -> None: + if isinstance(s.expr, IndexExpr): + e = s.expr + m = MemberExpr(e.base, "__delitem__") + m.line = s.line + m.column = s.column + c = CallExpr(m, [e.index], [nodes.ARG_POS], [None]) + c.line = s.line + c.column = s.column + self.expr_checker.accept(c, allow_none_return=True) + else: + s.expr.accept(self.expr_checker) + for elt in flatten(s.expr): + if isinstance(elt, NameExpr): + self.binder.assign_type( + elt, DeletedType(source=elt.name), get_declaration(elt) + ) + + def visit_decorator(self, e: Decorator) -> None: + for d in e.decorators: + if isinstance(d, RefExpr): + if d.fullname == "typing.no_type_check": + e.var.type = AnyType(TypeOfAny.special_form) + e.var.is_ready = True + return + self.visit_decorator_inner(e) + + def visit_decorator_inner( + self, e: Decorator, allow_empty: bool = False, skip_first_item: bool = False + ) -> None: + if self.recurse_into_functions or e.func.def_or_infer_vars: + with self.tscope.function_scope(e.func), self.set_recurse_into_functions(): + self.check_func_item(e.func, name=e.func.name, allow_empty=allow_empty) + + # Process decorators from the inside out to determine decorated signature, which + # may be different from the declared signature. + sig: Type = self.function_type(e.func) + non_trivial_decorator = False + # For settable properties skip the first decorator (that is @foo.setter). + for d in reversed(e.decorators[1:] if skip_first_item else e.decorators): + if refers_to_fullname(d, "abc.abstractmethod"): + # This is a hack to avoid spurious errors because of incomplete type + # of @abstractmethod in the test fixtures. + continue + if refers_to_fullname(d, OVERLOAD_NAMES): + if not allow_empty: + self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, e) + continue + non_trivial_decorator = True + dec = self.expr_checker.accept(d) + temp = self.temp_node(sig, context=d) + fullname = None + if isinstance(d, RefExpr): + fullname = d.fullname or None + # if this is an expression like @b.a where b is an object, get the type of b, + # so we can pass it the method hook in the plugins + object_type: Type | None = None + if fullname is None and isinstance(d, MemberExpr) and self.has_type(d.expr): + object_type = self.lookup_type(d.expr) + fullname = self.expr_checker.method_fullname(object_type, d.name) + self.check_for_untyped_decorator(e.func, dec, d) + sig, t2 = self.expr_checker.check_call( + dec, [temp], [nodes.ARG_POS], e, callable_name=fullname, object_type=object_type + ) + if non_trivial_decorator: + self.check_untyped_after_decorator(sig, e.func) + self.require_correct_self_argument(sig, e.func) + sig = set_callable_name(sig, e.func) + if isinstance(sig, CallableType): + sig.definition = e + e.var.type = sig + e.var.is_ready = True + if e.func.is_property: + if isinstance(sig, CallableType): + if len([k for k in sig.arg_kinds if k.is_required()]) > 1: + self.msg.fail("Too many arguments for property", e) + self.check_incompatible_property_override(e) + # For overloaded functions/properties we already checked override for overload as a whole. + if allow_empty or skip_first_item: + return + if e.func.info and not e.is_overload: + found_method_base_classes = self.check_method_override(e) + if ( + e.func.is_explicit_override + and not found_method_base_classes + and found_method_base_classes is not None + # If the class has Any fallback, we can't be certain that a method + # is really missing - it might come from unfollowed import. + and not e.func.info.fallback_to_any + ): + self.msg.no_overridable_method(e.func.name, e.func) + self.check_explicit_override_decorator(e.func, found_method_base_classes) + + if e.func.info and e.func.name in ("__init__", "__new__"): + if e.type and not isinstance(get_proper_type(e.type), (FunctionLike, AnyType)): + self.fail(message_registry.BAD_CONSTRUCTOR_TYPE, e) + + if e.func.original_def and isinstance(sig, FunctionLike): + # Function definition overrides function definition. + self.check_func_def_override(e.func, sig) + + def check_for_untyped_decorator( + self, func: FuncDef, dec_type: Type, dec_expr: Expression + ) -> None: + if ( + self.options.disallow_untyped_decorators + and is_typed_callable(func.type) + and is_untyped_decorator(dec_type) + and not self.current_node_deferred + ): + self.msg.typed_function_untyped_decorator(func.name, dec_expr) + + def check_incompatible_property_override(self, e: Decorator) -> None: + if not e.var.is_settable_property and e.func.info: + name = e.func.name + for base in e.func.info.mro[1:]: + base_attr = base.names.get(name) + if not base_attr: + continue + if ( + isinstance(base_attr.node, OverloadedFuncDef) + and base_attr.node.is_property + and cast(Decorator, base_attr.node.items[0]).var.is_settable_property + ): + self.fail(message_registry.READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE, e) + + def visit_with_stmt(self, s: WithStmt) -> None: + exceptions_maybe_suppressed = False + for expr, target in zip(s.expr, s.target): + if s.is_async: + exit_ret_type = self.check_async_with_item(expr, target, s.unanalyzed_type is None) + else: + exit_ret_type = self.check_with_item(expr, target, s.unanalyzed_type is None) + + # Based on the return type, determine if this context manager 'swallows' + # exceptions or not. We determine this using a heuristic based on the + # return type of the __exit__ method -- see the discussion in + # https://github.com/python/mypy/issues/7214 and the section about context managers + # in https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#conventions + # for more details. + + exit_ret_type = get_proper_type(exit_ret_type) + if is_literal_type(exit_ret_type, "builtins.bool", False): + continue + + if is_literal_type(exit_ret_type, "builtins.bool", True) or ( + isinstance(exit_ret_type, Instance) + and exit_ret_type.type.fullname == "builtins.bool" + and state.strict_optional + ): + # Note: if strict-optional is disabled, this bool instance + # could actually be an Optional[bool]. + exceptions_maybe_suppressed = True + + if exceptions_maybe_suppressed: + # Treat this 'with' block in the same way we'd treat a 'try: BODY; except: pass' + # block. This means control flow can continue after the 'with' even if the 'with' + # block immediately returns. + with self.binder.frame_context(can_skip=True, try_frame=True): + self.accept(s.body) + else: + self.accept(s.body) + + def check_untyped_after_decorator(self, typ: Type, func: FuncDef) -> None: + if not self.options.disallow_any_decorated or self.is_stub or self.current_node_deferred: + return + + if mypy.checkexpr.has_any_type(typ): + self.msg.untyped_decorated_function(typ, func) + + def check_async_with_item( + self, expr: Expression, target: Expression | None, infer_lvalue_type: bool + ) -> Type: + echk = self.expr_checker + ctx = echk.accept(expr) + obj = echk.check_method_call_by_name("__aenter__", ctx, [], [], expr)[0] + obj = echk.check_awaitable_expr( + obj, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER + ) + if target: + self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type) + arg = self.temp_node(AnyType(TypeOfAny.special_form), expr) + res, _ = echk.check_method_call_by_name( + "__aexit__", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr + ) + return echk.check_awaitable_expr( + res, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT + ) + + def check_with_item( + self, expr: Expression, target: Expression | None, infer_lvalue_type: bool + ) -> Type: + echk = self.expr_checker + ctx = echk.accept(expr) + obj = echk.check_method_call_by_name("__enter__", ctx, [], [], expr)[0] + if target: + self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type) + arg = self.temp_node(AnyType(TypeOfAny.special_form), expr) + res, _ = echk.check_method_call_by_name( + "__exit__", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr + ) + return res + + def visit_break_stmt(self, s: BreakStmt) -> None: + self.binder.handle_break() + + def visit_continue_stmt(self, s: ContinueStmt) -> None: + self.binder.handle_continue() + return + + def visit_match_stmt(self, s: MatchStmt) -> None: + # In sync with similar actions elsewhere, narrow the target if + # we are matching an AssignmentExpr + unwrapped_subject = collapse_walrus(s.subject) + named_subject = self._make_named_statement_for_match(s, unwrapped_subject) + with self.binder.frame_context(can_skip=False, fall_through=0): + subject_type = get_proper_type(self.expr_checker.accept(s.subject)) + + if isinstance(subject_type, DeletedType): + self.msg.deleted_as_rvalue(subject_type, s) + + # We infer types of patterns twice. The first pass is used + # to infer the types of capture variables. The type of a + # capture variable may depend on multiple patterns (it + # will be a union of all capture types). This pass ignores + # guard expressions. + pattern_types = [self.pattern_checker.accept(p, subject_type) for p in s.patterns] + type_maps: list[TypeMap] = [t.captures for t in pattern_types] + inferred_types = self.infer_variable_types_from_type_maps(type_maps) + + # The second pass narrows down the types and type checks bodies. + unmatched_types: TypeMap = {s.subject: UninhabitedType()} + for p, g, b in zip(s.patterns, s.guards, s.bodies): + current_subject_type = self.expr_checker.narrow_type_from_binder( + named_subject, subject_type + ) + pattern_type = self.pattern_checker.accept(p, current_subject_type) + with self.binder.frame_context(can_skip=True, fall_through=2): + pattern_map, else_map = conditional_types_to_typemaps( + named_subject, pattern_type.type, pattern_type.rest_type + ) + # Maybe the subject type can be inferred from constraints on + # its attribute/item? + if named_subject in pattern_map: + pattern_map[unwrapped_subject] = pattern_map[named_subject] + if named_subject in else_map: + else_map[unwrapped_subject] = else_map[named_subject] + pattern_map = self.propagate_up_typemap_info(pattern_map) + else_map = self.propagate_up_typemap_info(else_map) + self.remove_capture_conflicts(pattern_type.captures, inferred_types) + self.push_type_map(pattern_map, from_assignment=False) + if pattern_map: + for expr, typ in pattern_map.items(): + self.push_type_map( + self._get_recursive_sub_patterns_map(expr, typ), + from_assignment=False, + ) + self.push_type_map(pattern_type.captures, from_assignment=False) + if g is not None: + with self.binder.frame_context(can_skip=False, fall_through=3): + gt = get_proper_type(self.expr_checker.accept(g)) + + if isinstance(gt, DeletedType): + self.msg.deleted_as_rvalue(gt, s) + + guard_map, guard_else_map = self.find_isinstance_check(g) + else_map = or_conditional_maps(else_map, guard_else_map) + + # If the guard narrowed the subject, copy the narrowed types over + if isinstance(p, AsPattern): + case_target = p.pattern or p.name + if isinstance(case_target, NameExpr): + for type_map in (guard_map, else_map): + for expr in list(type_map): + if not ( + isinstance(expr, NameExpr) + and expr.fullname == case_target.fullname + ): + continue + type_map[named_subject] = type_map[expr] + + self.push_type_map(guard_map, from_assignment=False) + self.accept(b) + else: + self.accept(b) + self.push_type_map(else_map, from_assignment=False) + unmatched_types = else_map + + if not is_unreachable_map(unmatched_types) and not self.current_node_deferred: + for typ in unmatched_types.values(): + self.msg.match_statement_inexhaustive_match(typ, s) + + # This is needed due to a quirk in frame_context. Without it types will stay narrowed + # after the match. + with self.binder.frame_context(can_skip=False, fall_through=2): + pass + + def _make_named_statement_for_match(self, s: MatchStmt, subject: Expression) -> Expression: + """Construct a fake NameExpr for inference if a match clause is complex.""" + if self.binder.can_put_directly(subject): + # Already named - we should infer type of it as given + return subject + elif s.subject_dummy is not None: + return s.subject_dummy + else: + # Create a dummy subject expression to handle cases where a match statement's subject + # is not a literal value. This lets us correctly narrow types and check exhaustivity + # This is hack! + name = self.new_unique_dummy_name("match") + v = Var(name) + named_subject = NameExpr(name) + named_subject.node = v + s.subject_dummy = named_subject + return named_subject + + def _get_recursive_sub_patterns_map( + self, expr: Expression, typ: Type + ) -> dict[Expression, Type]: + sub_patterns_map: dict[Expression, Type] = {} + typ_ = get_proper_type(typ) + if isinstance(expr, TupleExpr) and isinstance(typ_, TupleType): + # When matching a tuple expression with a sequence pattern, narrow individual tuple items + assert len(expr.items) == len(typ_.items) + for item_expr, item_typ in zip(expr.items, typ_.items): + sub_patterns_map[item_expr] = item_typ + sub_patterns_map.update(self._get_recursive_sub_patterns_map(item_expr, item_typ)) + + return sub_patterns_map + + def infer_variable_types_from_type_maps( + self, type_maps: list[TypeMap] + ) -> dict[SymbolNode, Type]: + # Type maps may contain variables inherited from previous code which are not + # necessary `Var`s (e.g. a function defined earlier with the same name). + all_captures: dict[SymbolNode, list[tuple[NameExpr, Type]]] = defaultdict(list) + for tm in type_maps: + if not is_unreachable_map(tm): + for expr, typ in tm.items(): + if isinstance(expr, NameExpr): + node = expr.node + assert node is not None + all_captures[node].append((expr, typ)) + + inferred_types: dict[SymbolNode, Type] = {} + for var, captures in all_captures.items(): + already_exists = False + types: list[Type] = [] + for expr, typ in captures: + types.append(typ) + + previous_type, _, _ = self.check_lvalue(expr) + if previous_type is not None: + already_exists = True + if isinstance(expr.node, Var) and expr.node.is_final: + self.msg.cant_assign_to_final(expr.name, False, expr) + if self.check_subtype( + typ, + previous_type, + expr, + msg=message_registry.INCOMPATIBLE_TYPES_IN_CAPTURE, + subtype_label="pattern captures type", + supertype_label="variable has type", + ): + inferred_types[var] = previous_type + + if not already_exists: + new_type = UnionType.make_union(types) + # Infer the union type at the first occurrence + first_occurrence, _ = captures[0] + # If it didn't exist before ``match``, it's a Var. + assert isinstance(var, Var) + inferred_types[var] = new_type + self.infer_variable_type(var, first_occurrence, new_type, first_occurrence) + return inferred_types + + def remove_capture_conflicts( + self, type_map: TypeMap, inferred_types: dict[SymbolNode, Type] + ) -> None: + if not is_unreachable_map(type_map): + for expr, typ in list(type_map.items()): + if isinstance(expr, NameExpr): + node = expr.node + if node not in inferred_types or not is_subtype(typ, inferred_types[node]): + del type_map[expr] + + def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: + if o.alias_node: + self.check_typevar_defaults(o.alias_node.alias_tvars) + + with self.msg.filter_errors(): + self.expr_checker.accept(o.value) + + def make_fake_typeinfo( + self, + curr_module_fullname: str, + class_gen_name: str, + class_short_name: str, + bases: list[Instance], + ) -> tuple[ClassDef, TypeInfo]: + # Build the fake ClassDef and TypeInfo together. + # The ClassDef is full of lies and doesn't actually contain a body. + # Use format_bare to generate a nice name for error messages. + # We skip fully filling out a handful of TypeInfo fields because they + # should be irrelevant for a generated type like this: + # is_protocol, protocol_members, is_abstract + cdef = ClassDef(class_short_name, Block([])) + cdef.fullname = curr_module_fullname + "." + class_gen_name + info = TypeInfo(SymbolTable(), cdef, curr_module_fullname) + cdef.info = info + info.bases = bases + calculate_mro(info) + info.metaclass_type = info.calculate_metaclass_type() + return cdef, info + + def intersect_instances( + self, instances: tuple[Instance, Instance], errors: list[tuple[str, str]] + ) -> Instance | None: + """Try creating an ad-hoc intersection of the given instances. + + Note that this function does *not* try and create a full-fledged + intersection type. Instead, it returns an instance of a new ad-hoc + subclass of the given instances. + + This is mainly useful when you need a way of representing some + theoretical subclass of the instances the user may be trying to use + the generated intersection can serve as a placeholder. + + This function will create a fresh subclass the first time you call it. + So this means calling `self.intersect_intersection([inst_1, inst_2], ctx)` + twice will return the same subclass of inst_1 and inst_2. + + Returns None if creating the subclass is impossible (e.g. due to + MRO errors or incompatible signatures). If we do successfully create + a subclass, its TypeInfo will automatically be added to the global scope. + """ + curr_module = self.scope.stack[0] + assert isinstance(curr_module, MypyFile) + + # First, retry narrowing while allowing promotions (they are disabled by default + # for isinstance() checks, etc). This way we will still type-check branches like + # x: complex = 1 + # if isinstance(x, int): + # ... + left, right = instances + if is_proper_subtype(left, right, ignore_promotions=False): + return left + if is_proper_subtype(right, left, ignore_promotions=False): + return right + + def _get_base_classes(instances_: tuple[Instance, Instance]) -> list[Instance]: + base_classes_ = [] + for inst in instances_: + if inst.type.is_intersection: + expanded = inst.type.bases + else: + expanded = [inst] + + for expanded_inst in expanded: + base_classes_.append(expanded_inst) + return base_classes_ + + def _make_fake_typeinfo_and_full_name( + base_classes_: list[Instance], curr_module_: MypyFile, options: Options + ) -> tuple[TypeInfo, str]: + names = [format_type_bare(x, options=options, verbosity=2) for x in base_classes_] + name = f"" + if (symbol := curr_module_.names.get(name)) is not None: + assert isinstance(symbol.node, TypeInfo) + return symbol.node, name + cdef, info_ = self.make_fake_typeinfo(curr_module_.fullname, name, name, base_classes_) + return info_, name + + base_classes = _get_base_classes(instances) + # We use the pretty_names_list for error messages but for the real name that goes + # into the symbol table because it is not specific enough. + pretty_names_list = pretty_seq( + format_type_distinctly(*base_classes, options=self.options, bare=True), "and" + ) + + if not can_have_shared_disjoint_base(base_classes): + errors.append((pretty_names_list, "have distinct disjoint bases")) + return None + + new_errors = [] + for base in base_classes: + if base.type.is_final: + new_errors.append((pretty_names_list, f'"{base.type.name}" is final')) + if new_errors: + errors.extend(new_errors) + return None + + try: + info, full_name = _make_fake_typeinfo_and_full_name( + base_classes, curr_module, self.options + ) + with self.msg.filter_errors() as local_errors: + self.check_multiple_inheritance(info) + if local_errors.has_new_errors(): + # "class A(B, C)" unsafe, now check "class A(C, B)": + base_classes = _get_base_classes(instances[::-1]) + info, full_name = _make_fake_typeinfo_and_full_name( + base_classes, curr_module, self.options + ) + with self.msg.filter_errors() as local_errors: + self.check_multiple_inheritance(info) + info.is_intersection = True + except MroError: + errors.append((pretty_names_list, "would have inconsistent method resolution order")) + return None + if local_errors.has_new_errors(): + errors.append((pretty_names_list, "would have incompatible method signatures")) + return None + + curr_module.names[full_name] = SymbolTableNode(GDEF, info, False, module_hidden=True) + return Instance(info, [], extra_attrs=instances[0].extra_attrs or instances[1].extra_attrs) + + def intersect_instance_callable(self, typ: Instance, callable_type: CallableType) -> Instance: + """Creates a fake type that represents the intersection of an Instance and a CallableType. + + It operates by creating a bare-minimum dummy TypeInfo that + subclasses type and adds a __call__ method matching callable_type. + """ + + # In order for this to work in incremental mode, the type we generate needs to + # have a valid fullname and a corresponding entry in a symbol table. We generate + # a unique name inside the symbol table of the current module. + cur_module = self.scope.stack[0] + assert isinstance(cur_module, MypyFile) + gen_name = gen_unique_name(f"", cur_module.names) + + # Synthesize a fake TypeInfo + short_name = format_type_bare(typ, self.options) + cdef, info = self.make_fake_typeinfo(cur_module.fullname, gen_name, short_name, [typ]) + + # Build up a fake FuncDef so we can populate the symbol table. + func_def = FuncDef("__call__", [], Block([]), callable_type) + func_def._fullname = cdef.fullname + ".__call__" + func_def.info = info + info.names["__call__"] = SymbolTableNode(MDEF, func_def) + + cur_module.names[gen_name] = SymbolTableNode(GDEF, info) + + return Instance(info, [], extra_attrs=typ.extra_attrs) + + def make_fake_callable(self, typ: Instance) -> Instance: + """Produce a new type that makes type Callable with a generic callable type.""" + + fallback = self.named_type("builtins.function") + callable_type = CallableType( + [AnyType(TypeOfAny.explicit), AnyType(TypeOfAny.explicit)], + [nodes.ARG_STAR, nodes.ARG_STAR2], + [None, None], + ret_type=AnyType(TypeOfAny.explicit), + fallback=fallback, + is_ellipsis_args=True, + ) + + return self.intersect_instance_callable(typ, callable_type) + + def partition_by_callable( + self, typ: Type, unsound_partition: bool + ) -> tuple[list[Type], list[Type]]: + """Partitions a type into callable subtypes and uncallable subtypes. + + Thus, given: + `callables, uncallables = partition_by_callable(type)` + + If we assert `callable(type)` then `type` has type Union[*callables], and + If we assert `not callable(type)` then `type` has type Union[*uncallables] + + If unsound_partition is set, assume that anything that is not + clearly callable is in fact not callable. Otherwise we generate a + new subtype that *is* callable. + + Guaranteed to not return [], []. + """ + typ = get_proper_type(typ) + + if isinstance(typ, (FunctionLike, TypeType)): + return [typ], [] + + if isinstance(typ, AnyType): + return [typ], [typ] + + if isinstance(typ, NoneType): + return [], [typ] + + if isinstance(typ, UnionType): + callables = [] + uncallables: list[Type] = [] + for subtype in typ.items: + # Use unsound_partition when handling unions in order to + # allow the expected type discrimination. + subcallables, subuncallables = self.partition_by_callable( + subtype, unsound_partition=True + ) + callables.extend(subcallables) + uncallables.extend(subuncallables) + return callables, uncallables + + if isinstance(typ, TypeVarType): + # We could do better probably? + # Refine the type variable's bound as our type in the case that + # callable() is true. This unfortunately loses the information that + # the type is a type variable in that branch. + # This matches what is done for isinstance, but it may be possible to + # do better. + # If it is possible for the false branch to execute, return the original + # type to avoid losing type information. + callables, uncallables = self.partition_by_callable( + erase_to_union_or_bound(typ), unsound_partition + ) + uncallables = [typ] if uncallables else [] + return callables, uncallables + + # A TupleType is callable if its fallback is, but needs special handling + # when we dummy up a new type. + ityp = typ + if isinstance(typ, TupleType): + ityp = tuple_fallback(typ) + + if isinstance(ityp, Instance): + method = ityp.type.get_method("__call__") + if method and method.type: + callables, uncallables = self.partition_by_callable( + method.type, unsound_partition=False + ) + if callables and not uncallables: + # Only consider the type callable if its __call__ method is + # definitely callable. + return [typ], [] + + if not unsound_partition: + fake = self.make_fake_callable(ityp) + if isinstance(typ, TupleType): + fake.type.tuple_type = TupleType(typ.items, fake) + return [fake.type.tuple_type], [typ] + return [fake], [typ] + + if unsound_partition: + return [], [typ] + else: + # We don't know how properly make the type callable. + return [typ], [typ] + + def conditional_callable_type_map( + self, expr: Expression, current_type: Type | None + ) -> tuple[TypeMap, TypeMap]: + """Takes in an expression and the current type of the expression. + + Returns a 2-tuple: The first element is a map from the expression to + the restricted type if it were callable. The second element is a + map from the expression to the type it would hold if it weren't + callable. + """ + if not current_type: + return {}, {} + + if isinstance(get_proper_type(current_type), AnyType): + return {}, {} + + callables, uncallables = self.partition_by_callable(current_type, unsound_partition=False) + + if callables and uncallables: + callable_map = {expr: UnionType.make_union(callables)} + uncallable_map = {expr: UnionType.make_union(uncallables)} + return callable_map, uncallable_map + + elif callables: + return {}, {expr: UninhabitedType()} + + return {expr: UninhabitedType()}, {} + + def conditional_types_for_iterable( + self, item_type: Type, iterable_type: Type + ) -> tuple[Type, Type]: + """ + Narrows the type of `iterable_type` based on the type of `item_type`. + For now, we only support narrowing unions of TypedDicts based on left operand being literal string(s). + """ + if_types: list[Type] = [] + else_types: list[Type] = [] + + iterable_type = get_proper_type(iterable_type) + if isinstance(iterable_type, UnionType): + possible_iterable_types = get_proper_types(iterable_type.relevant_items()) + else: + possible_iterable_types = [iterable_type] + + item_str_literals = try_getting_str_literals_from_type(item_type) + + for possible_iterable_type in possible_iterable_types: + if item_str_literals and isinstance(possible_iterable_type, TypedDictType): + for key in item_str_literals: + if key in possible_iterable_type.required_keys: + if_types.append(possible_iterable_type) + elif ( + key in possible_iterable_type.items or not possible_iterable_type.is_final + ): + if_types.append(possible_iterable_type) + else_types.append(possible_iterable_type) + else: + else_types.append(possible_iterable_type) + else: + if_types.append(possible_iterable_type) + else_types.append(possible_iterable_type) + + return UnionType.make_union(if_types), UnionType.make_union(else_types) + + def _is_truthy_type(self, t: ProperType) -> bool: + return ( + ( + isinstance(t, Instance) + and bool(t.type) + and not t.type.has_readable_member("__bool__") + and not t.type.has_readable_member("__len__") + and t.type.fullname != "builtins.object" + ) + or isinstance(t, FunctionLike) + or ( + isinstance(t, UnionType) + and all(self._is_truthy_type(t) for t in get_proper_types(t.items)) + ) + ) + + def check_for_truthy_type(self, t: Type, expr: Expression) -> None: + """ + Check if a type can have a truthy value. + + Used in checks like:: + + if x: # <--- + + not x # <--- + """ + if not state.strict_optional: + return # if everything can be None, all bets are off + + t = get_proper_type(t) + if not self._is_truthy_type(t): + return + + def format_expr_type() -> str: + typ = format_type(t, self.options) + if isinstance(expr, MemberExpr): + return f'Member "{expr.name}" has type {typ}' + elif isinstance(expr, RefExpr) and expr.fullname: + return f'"{expr.fullname}" has type {typ}' + elif isinstance(expr, CallExpr): + if isinstance(expr.callee, MemberExpr): + return f'"{expr.callee.name}" returns {typ}' + elif isinstance(expr.callee, RefExpr) and expr.callee.fullname: + return f'"{expr.callee.fullname}" returns {typ}' + return f"Call returns {typ}" + else: + return f"Expression has type {typ}" + + def get_expr_name() -> str: + if isinstance(expr, (NameExpr, MemberExpr)): + return f'"{expr.name}"' + else: + # return type if expr has no name + return format_type(t, self.options) + + if isinstance(t, FunctionLike): + self.fail(message_registry.FUNCTION_ALWAYS_TRUE.format(get_expr_name()), expr) + elif isinstance(t, UnionType): + self.fail(message_registry.TYPE_ALWAYS_TRUE_UNIONTYPE.format(format_expr_type()), expr) + elif isinstance(t, Instance) and t.type.fullname == "typing.Iterable": + _, info = self.make_fake_typeinfo("typing", "Collection", "Collection", []) + self.fail( + message_registry.ITERABLE_ALWAYS_TRUE.format( + format_expr_type(), format_type(Instance(info, t.args), self.options) + ), + expr, + ) + else: + self.fail(message_registry.TYPE_ALWAYS_TRUE.format(format_expr_type()), expr) + + def find_isinstance_check( + self, node: Expression, *, in_boolean_context: bool = True + ) -> tuple[TypeMap, TypeMap]: + """Find any isinstance checks (within a chain of ands). Includes + implicit and explicit checks for None and calls to callable. + Also includes TypeGuard and TypeIs functions. + + Return value is a map of variables to their types if the condition + is true and a map of variables to their types if the condition is false. + + If either of the values in the tuple is None, then that particular + branch can never occur. + + If `in_boolean_context=True` is passed, it means that we handle + a walrus expression. We treat rhs values + in expressions like `(a := A())` specially: + for example, some errors are suppressed. + + May return {}, {}. + Can return None, None in situations involving NoReturn. + """ + if_map, else_map = self.find_isinstance_check_helper( + node, in_boolean_context=in_boolean_context + ) + new_if_map = self.propagate_up_typemap_info(if_map) + new_else_map = self.propagate_up_typemap_info(else_map) + return new_if_map, new_else_map + + def find_isinstance_check_helper( + self, node: Expression, *, in_boolean_context: bool = True + ) -> tuple[TypeMap, TypeMap]: + if is_true_literal(node): + return {}, {node: UninhabitedType()} + if is_false_literal(node): + return {node: UninhabitedType()}, {} + + if isinstance(node, CallExpr) and len(node.args) != 0: + expr = collapse_walrus(node.args[0]) + if refers_to_fullname(node.callee, "builtins.isinstance"): + if len(node.args) != 2: # the error will be reported elsewhere + return {}, {} + if literal(expr) == LITERAL_TYPE: + return conditional_types_to_typemaps( + expr, + *self.conditional_types_with_intersection( + self.lookup_type(expr), self.get_isinstance_type(node.args[1]), expr + ), + ) + elif refers_to_fullname(node.callee, "builtins.issubclass"): + if len(node.args) != 2: # the error will be reported elsewhere + return {}, {} + if literal(expr) == LITERAL_TYPE: + return self.infer_issubclass_maps(node, expr) + elif refers_to_fullname(node.callee, "builtins.callable"): + if len(node.args) != 1: # the error will be reported elsewhere + return {}, {} + if literal(expr) == LITERAL_TYPE: + vartype = self.lookup_type(expr) + return self.conditional_callable_type_map(expr, vartype) + elif refers_to_fullname(node.callee, "builtins.hasattr"): + if len(node.args) != 2: # the error will be reported elsewhere + return {}, {} + attr = try_getting_str_literals(node.args[1], self.lookup_type(node.args[1])) + if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1: + return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0]) + else: + type_is, type_guard = None, None + called_type = self.lookup_type_or_none(node.callee) + if called_type is not None: + called_type = get_proper_type(called_type) + # TODO: there are some more cases in check_call() to handle. + # If the callee is an instance, try to extract TypeGuard/TypeIs from its __call__ method. + if isinstance(called_type, Instance): + call = find_member("__call__", called_type, called_type, is_operator=True) + if call is not None: + called_type = get_proper_type(call) + if isinstance(called_type, CallableType): + type_is, type_guard = called_type.type_is, called_type.type_guard + + # If the callee is a RefExpr, extract TypeGuard/TypeIs directly. + if isinstance(node.callee, RefExpr): + type_is, type_guard = node.callee.type_is, node.callee.type_guard + if type_guard is not None or type_is is not None: + # TODO: Follow *args, **kwargs + if node.arg_kinds[0] != nodes.ARG_POS: + # *assuming* the overloaded function is correct, there's a couple cases: + # 1) The first argument has different names, but is pos-only. We don't + # care about this case, the argument must be passed positionally. + # 2) The first argument allows keyword reference, therefore must be the + # same between overloads. + if isinstance(called_type, (CallableType, Overloaded)): + name = called_type.items[0].arg_names[0] + if name in node.arg_names: + idx = node.arg_names.index(name) + # we want the idx-th variable to be narrowed + expr = collapse_walrus(node.args[idx]) + else: + kind = "guard" if type_guard is not None else "narrower" + self.fail( + message_registry.TYPE_GUARD_POS_ARG_REQUIRED.format(kind), node + ) + return {}, {} + if literal(expr) == LITERAL_TYPE: + # Note: we wrap the target type, so that we can special case later. + # Namely, for isinstance() we use a normal meet, while TypeGuard is + # considered "always right" (i.e. even if the types are not overlapping). + # Also note that a care must be taken to unwrap this back at read places + # where we use this to narrow down declared type. + if type_guard is not None: + return {expr: TypeGuardedType(type_guard)}, {} + else: + assert type_is is not None + return conditional_types_to_typemaps( + expr, + *self.conditional_types_with_intersection( + self.lookup_type(expr), + [TypeRange(type_is, is_upper_bound=False)], + expr, + consider_runtime_isinstance=False, + ), + ) + elif isinstance(node, ComparisonExpr): + return self.comparison_type_narrowing_helper(node) + elif isinstance(node, AssignmentExpr): + if_map: TypeMap + else_map: TypeMap + if_map = {} + else_map = {} + + if_assignment_map, else_assignment_map = self.find_isinstance_check(node.target) + if_map.update(if_assignment_map) + else_map.update(else_assignment_map) + + if_condition_map, else_condition_map = self.find_isinstance_check( + node.value, in_boolean_context=False + ) + + if_map.update(if_condition_map) + else_map.update(else_condition_map) + + return if_map, else_map + elif isinstance(node, OpExpr) and node.op == "and": + left_if_vars, left_else_vars = self.find_isinstance_check(node.left) + right_if_vars, right_else_vars = self.find_isinstance_check(node.right) + + # (e1 and e2) is true if both e1 and e2 are true, + # and false if at least one of e1 and e2 is false. + return ( + and_conditional_maps(left_if_vars, right_if_vars), + # Note that if left else type is Any, we can't add any additional + # types to it, since the right maps were computed assuming + # the left is True, which may be not the case in the else branch. + or_conditional_maps(left_else_vars, right_else_vars, coalesce_any=True), + ) + elif isinstance(node, OpExpr) and node.op == "or": + left_if_vars, left_else_vars = self.find_isinstance_check(node.left) + right_if_vars, right_else_vars = self.find_isinstance_check(node.right) + + # (e1 or e2) is true if at least one of e1 or e2 is true, + # and false if both e1 and e2 are false. + return ( + or_conditional_maps(left_if_vars, right_if_vars), + and_conditional_maps(left_else_vars, right_else_vars), + ) + elif isinstance(node, UnaryExpr) and node.op == "not": + left, right = self.find_isinstance_check(node.expr) + return right, left + elif ( + literal(node) == LITERAL_TYPE + and self.has_type(node) + and self.can_be_narrowed_with_len(self.lookup_type(node)) + # Only translate `if x` to `if len(x) > 0` when possible. + and not custom_special_method(self.lookup_type(node), "__bool__") + and self.options.strict_optional + ): + # Combine a `len(x) > 0` check with the default logic below. + yes_type, no_type = self.narrow_with_len(self.lookup_type(node), ">", 0) + if_map = {node: true_only(yes_type)} + else_map = {node: false_only(no_type)} + return if_map, else_map + + # Restrict the type of the variable to True-ish/False-ish in the if and else branches + # respectively + original_vartype = self.lookup_type(node) + if in_boolean_context: + # We don't check `:=` values in expressions like `(a := A())`, + # because they produce two error messages. + self.check_for_truthy_type(original_vartype, node) + vartype = try_expanding_sum_type_to_union(original_vartype, "builtins.bool") + + if_map = {node: true_only(vartype)} + else_map = {node: false_only(vartype)} + return if_map, else_map + + def comparison_type_narrowing_helper(self, node: ComparisonExpr) -> tuple[TypeMap, TypeMap]: + """Infer type narrowing from a comparison expression.""" + # Step 1: Obtain the types of each operand and whether or not we can + # narrow their types. (For example, we shouldn't try narrowing the + # types of literal string or enum expressions). + + operands = [collapse_walrus(x) for x in node.operands] + operand_types = [] + narrowable_operand_index_to_hash = {} + for i, expr in enumerate(operands): + if not self.has_type(expr): + return {}, {} + expr_type = self.lookup_type(expr) + operand_types.append(expr_type) + + if ( + literal(expr) == LITERAL_TYPE + and not is_literal_none(expr) + and not is_literal_not_implemented(expr) + and not is_false_literal(expr) + and not is_true_literal(expr) + and not self.is_literal_enum(expr) + # CallableType type objects are usually already maximally specific + and not ( + isinstance(p_expr := get_proper_type(expr_type), FunctionLike) + and p_expr.is_type_obj() + ) + # This is a little ad hoc, in the absence of intersection types + and not (isinstance(p_expr, TypeType) and isinstance(p_expr.item, TypeVarType)) + ): + h = literal_hash(expr) + if h is not None: + narrowable_operand_index_to_hash[i] = h + + # Step 2: Group operands chained by either the 'is' or '==' operands + # together. For all other operands, we keep them in groups of size 2. + # So the expression: + # + # x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8 + # + # ...is converted into the simplified operator list: + # + # [("==", [0, 1, 2]), ("<", [2, 3]), ("<", [3, 4]), + # ("is", [4, 5, 6]), ("is not", [6, 7]), ("is not", [7, 8])] + # + # We group identity/equality expressions so we can propagate information + # we discover about one operand across the entire chain. We don't bother + # handling 'is not' and '!=' chains in a special way: those are very rare + # in practice. + + simplified_operator_list = group_comparison_operands( + node.pairwise(), narrowable_operand_index_to_hash, {"==", "is"} + ) + + # Step 3: Analyze each group and infer more precise type maps for each + # assignable operand, if possible. We combine these type maps together + # in the final step. + + partial_type_maps = [] + for operator, expr_indices in simplified_operator_list: + if_map: TypeMap + else_map: TypeMap + + if operator in {"is", "is not", "==", "!="}: + if_map, else_map = self.narrow_type_by_identity_equality( + operator, + operands, + operand_types, + expr_indices, + narrowable_indices=narrowable_operand_index_to_hash.keys(), + ) + elif operator in {"in", "not in"}: + assert len(expr_indices) == 2 + left_index, right_index = expr_indices + item_type = operand_types[left_index] + iterable_type = operand_types[right_index] + + if_map = {} + else_map = {} + + if left_index in narrowable_operand_index_to_hash: + collection_item_type = get_proper_type(builtin_item_type(iterable_type)) + if collection_item_type is not None: + if_map, else_map = self.narrow_type_by_identity_equality( + "==", + operands=[operands[left_index], operands[right_index]], + operand_types=[item_type, collection_item_type], + expr_indices=[0, 1], + narrowable_indices={0}, + ) + + # TODO: This remove_optional code should no longer be needed. The only + # thing it does is paper over a pre-existing deficiency in equality + # narrowing w.r.t to enums. + # We only try and narrow away 'None' for now + if ( + not is_unreachable_map(if_map) + and is_overlapping_none(item_type) + and not is_overlapping_none(collection_item_type) + and not ( + isinstance(collection_item_type, Instance) + and collection_item_type.type.fullname == "builtins.object" + ) + and is_overlapping_erased_types(item_type, collection_item_type) + ): + if_map[operands[left_index]] = remove_optional(item_type) + + if right_index in narrowable_operand_index_to_hash: + if_type, else_type = self.conditional_types_for_iterable( + item_type, iterable_type + ) + expr = operands[right_index] + if_map[expr] = if_type + else_map[expr] = else_type + + else: + if_map = {} + else_map = {} + + if operator in {"is not", "!=", "not in"}: + if_map, else_map = else_map, if_map + + partial_type_maps.append((if_map, else_map)) + + # If we have found non-trivial restrictions from the regular comparisons, + # then return soon. Otherwise try to infer restrictions involving `len(x)`. + # TODO: support regular and len() narrowing in the same chain. + if any(len(m[0]) or len(m[1]) for m in partial_type_maps): + return reduce_conditional_maps(partial_type_maps, use_meet=True) + else: + # Use meet for `and` maps to get correct results for chained checks + # like `if 1 < len(x) < 4: ...` + return reduce_conditional_maps(self.find_tuple_len_narrowing(node), use_meet=True) + + def narrow_type_by_identity_equality( + self, + operator: str, + operands: list[Expression], + operand_types: list[Type], + expr_indices: list[int], + narrowable_indices: AbstractSet[int], + ) -> tuple[TypeMap, TypeMap]: + """ + Calculate type maps for '==', '!=', 'is' or 'is not' expression, ignoring `type(x)` checks. + + The 'operands' and 'operand_types' lists should be the full list of operands used + in the overall comparison expression. The 'chain_indices' list is the list of indices + actually used within this identity comparison chain. + + So if we have the expression: + + a <= b is c is d <= e + + ...then 'operands' and 'operand_types' would be lists of length 5 and 'chain_indices' + would be the list [1, 2, 3]. + + The 'narrowable_indices' parameter is the set of all indices we are allowed + to refine the types of: that is, all operands that will potentially be a part of + the output TypeMaps. + + """ + # is_target_for_value_narrowing: + # If the operator returns True when compared to this target, do we narrow in else branch? + # E.g. if operator is "==", then: + # - is_target_for_value_narrowing(str) == False + # - is_target_for_value_narrowing(Literal["asdf"]) == True + is_target_for_value_narrowing: Callable[[ProperType], bool] + + # should_coerce_literals: + # Ideally, we should always attempt to have this set to True. Unfortunately, for now, + # performing this coercion can sometimes result in overly aggressive narrowing when taking + # in the context of other type checker behaviour. + should_coerce_literals: bool + + # custom_eq_indices: + # Operands at these indices define a custom `__eq__`. These can do arbitrary things, so we + # have to be more careful about what narrowing we can conclude from a successful comparison + custom_eq_indices: set[int] + + # enum_comparison_is_ambiguous: + # `if x is Fruits.APPLE` we know `x` is `Fruits.APPLE`, but `if x == Fruits.APPLE: ...` + # it could e.g. be an int or str if Fruits is an IntEnum or StrEnum. + # See ambiguous_enum_equality_keys for more details + enum_comparison_is_ambiguous: bool + + if operator in {"is", "is not"}: + is_target_for_value_narrowing = is_singleton_identity_type + should_coerce_literals = True + custom_eq_indices = set() + enum_comparison_is_ambiguous = False + + elif operator in {"==", "!="}: + is_target_for_value_narrowing = is_singleton_equality_type + + should_coerce_literals = False + for i in expr_indices: + typ = get_proper_type(operand_types[i]) + if is_literal_type_like(typ) or (isinstance(typ, Instance) and typ.type.is_enum): + should_coerce_literals = True + break + + custom_eq_indices = {i for i in expr_indices if has_custom_eq_checks(operand_types[i])} + enum_comparison_is_ambiguous = True + else: + raise AssertionError + + all_if_maps: list[TypeMap] = [] + all_else_maps: list[TypeMap] = [] + + # For each narrowable index, we see what we can narrow based on each relevant target + for i in expr_indices: + if i not in narrowable_indices: + continue + if i in custom_eq_indices: + # Handled later + continue + + expr_type = operand_types[i] + expr_enum_keys = ambiguous_enum_equality_keys(expr_type) + expr_type = try_expanding_sum_type_to_union(coerce_to_literal(expr_type), None) + for j in expr_indices: + if i == j: + continue + if j in custom_eq_indices: + # We can't use types with custom __eq__ as targets for narrowing + # E.g. if (x: int | None) == (y: CustomEq | None), we cannot narrow x to None + continue + target_type = operand_types[j] + if should_coerce_literals: + target_type = coerce_to_literal(target_type) + + if ( + # See comments in ambiguous_enum_equality_keys + enum_comparison_is_ambiguous + and len(expr_enum_keys | ambiguous_enum_equality_keys(target_type)) > 1 + ): + continue + + target = TypeRange(target_type, is_upper_bound=False) + + if_map, else_map = conditional_types_to_typemaps( + operands[i], *conditional_types(expr_type, [target], from_equality=True) + ) + if is_target_for_value_narrowing(get_proper_type(target_type)): + all_if_maps.append(if_map) + all_else_maps.append(else_map) + else: + # For value targets, it is safe to narrow in the negative case. + # e.g. if (x: Literal[5] | None) != (y: Literal[5]), we can narrow x to None + # However, for non-value targets, we cannot do this narrowing, + # and so we ignore else_map + # e.g. if (x: str | None) != (y: str), we cannot narrow x to None + + # It is correct to always narrow here. It improves behaviour on tests and + # detects many inaccurate type annotations on primer. + # However, because mypy does not currently check unreachable code, it feels + # risky to narrow to unreachable without --warn-unreachable or not + # at module level + # See also this specific primer comment, where I force primer to run with + # --warn-unreachable to see what code we would stop checking: + # https://github.com/python/mypy/pull/20660#issuecomment-3865794148 + if ( + self.options.warn_unreachable and len(self.scope.stack) != 1 + ) or not is_unreachable_map(if_map): + all_if_maps.append(if_map) + + # Handle narrowing for operands with custom __eq__ methods specially + # In most cases, we won't be able to do any narrowing + for i in custom_eq_indices: + if i not in narrowable_indices: + continue + union_expr_type = get_proper_type(operand_types[i]) + if not isinstance(union_expr_type, UnionType): + # Here we won't be able to do any positive narrowing, because we can't conclude + # anything from a custom __eq__ returning True. + # But we might be able to do some negative narrowing, since we can assume + # a custom __eq__ is reflexive. This should only apply to custom __eq__ enums, + # see testNarrowingEqualityCustomEqualityEnum + expr_type = operand_types[i] + for j in expr_indices: + if j in custom_eq_indices: + continue + target_type = operand_types[j] + if should_coerce_literals: + target_type = coerce_to_literal(target_type) + target = TypeRange(target_type, is_upper_bound=False) + if is_target_for_value_narrowing(get_proper_type(target_type)): + if_map, else_map = conditional_types_to_typemaps( + operands[i], + *conditional_types(expr_type, [target], from_equality=True), + ) + all_else_maps.append(else_map) + continue + + # If our operand with custom __eq__ is a union, where only some members of the union + # implement custom __eq__, then we can narrow down the other members as usual. + # This is basically the same logic as the main narrowing loop above. + or_if_maps: list[TypeMap] = [] + or_else_maps: list[TypeMap] = [] + for expr_type in union_expr_type.items: + if has_custom_eq_checks(expr_type): + # Always include the union items with custom __eq__ in the type + # we narrow to in the if_map + or_if_maps.append({operands[i]: expr_type}) + + expr_type = coerce_to_literal(try_expanding_sum_type_to_union(expr_type, None)) + for j in expr_indices: + if j in custom_eq_indices: + if i == j: + continue + # If we compare to a target with custom __eq__, we cannot narrow at all + if is_overlapping_none(expr_type) and not is_overlapping_none( + operand_types[j] + ): + # Narrow away from None. This is unsound, we're hoping that no one + # has a custom __eq__ that returns True for None. + or_if_maps.append({operands[i]: remove_optional(expr_type)}) + else: + or_if_maps.append({operands[i]: expr_type}) + continue + target_type = operand_types[j] + if should_coerce_literals: + target_type = coerce_to_literal(target_type) + target = TypeRange(target_type, is_upper_bound=False) + + if_map, else_map = conditional_types_to_typemaps( + operands[i], + *conditional_types( + expr_type, [target], default=expr_type, from_equality=True + ), + ) + or_if_maps.append(if_map) + if is_target_for_value_narrowing(get_proper_type(target_type)): + or_else_maps.append(else_map) + + all_if_maps.append(reduce_or_conditional_type_maps(or_if_maps)) + all_else_maps.append(reduce_or_conditional_type_maps(or_else_maps)) + + # Handle narrowing for comparisons that produce additional narrowing, like + # `type(x) == T` or `x.__class__ is T` + for i in expr_indices: + type_expr = operands[i] + if ( + isinstance(type_expr, CallExpr) + and refers_to_fullname(type_expr.callee, "builtins.type") + and len(type_expr.args) == 1 + ): + expr_in_type_expr = type_expr.args[0] + elif isinstance(type_expr, MemberExpr) and type_expr.name == "__class__": + expr_in_type_expr = type_expr.expr + else: + continue + + p_expr_type = get_proper_type(operand_types[i]) + if isinstance(p_expr_type, TypeType) and isinstance(p_expr_type.item, TypeVarType): + # This mirrors logic in comparison_type_narrowing_helper + # In theory, this is like `i not in narrowable_indices`, except that + # narrowable_indices filters all type(x) narrowing as it's a call + continue + + for j in expr_indices: + if i == j: + continue + expr = operands[j] + + current_type_range = self.get_type_range_of_type(operand_types[j]) + if current_type_range is None: + continue + if isinstance(get_proper_type(current_type_range.item), AnyType): + # Avoid widening to Any for checks like `type(x) is type(y: Any)`. + # We patch this here because it is desirable to widen to any for cases like + # isinstance(x, (y: Any)) + continue + + arg_type = self.lookup_type(expr_in_type_expr) + if_type, else_type = self.conditional_types_with_intersection( + arg_type, [current_type_range], expr_in_type_expr + ) + if if_type is not None and ( + not current_type_range.is_upper_bound + and not is_equivalent(if_type, current_type_range.item) + ): + # type(x) and x.__class__ checks must exact match + if_type = UninhabitedType() + + if_map, else_map = conditional_types_to_typemaps( + expr_in_type_expr, if_type, else_type + ) + + is_final = ( + expr.node.is_final + if isinstance(expr, RefExpr) and isinstance(expr.node, TypeInfo) + else False + ) + all_if_maps.append(if_map) + if is_final: + # We can only narrow `type(x) == T` in the negative case if T is final + all_else_maps.append(else_map) + + # We will not have duplicate entries in our type maps if we only have two operands, + # so we can skip running meets on the intersections + if_map = reduce_and_conditional_type_maps(all_if_maps, use_meet=len(operands) > 2) + else_map = reduce_or_conditional_type_maps(all_else_maps) + return if_map, else_map + + def propagate_up_typemap_info(self, new_types: TypeMap) -> TypeMap: + """Attempts refining parent expressions of any MemberExpr or IndexExprs in new_types. + + This function iterates through new_types and attempts to use the information to try + refining any parent types that happen to be unions. + + For example, suppose there are two types "A = Tuple[int, int]" and "B = Tuple[str, str]". + Next, suppose that 'new_types' specifies the expression 'foo[0]' has a refined type + of 'int' and that 'foo' was previously deduced to be of type Union[A, B]. + + Then, this function will observe that since A[0] is an int and B[0] is not, the type of + 'foo' can be further refined from Union[A, B] into just B. + + We perform this kind of "parent narrowing" for member lookup expressions and indexing + expressions into tuples, namedtuples, and typeddicts. We repeat this narrowing + recursively if the parent is also a "lookup expression". So for example, if we have + the expression "foo['bar'].baz[0]", we'd potentially end up refining types for the + expressions "foo", "foo['bar']", and "foo['bar'].baz". + + We return the newly refined map. This map is guaranteed to be a superset of 'new_types'. + """ + all_mappings = [new_types] + for expr, expr_type in new_types.items(): + all_mappings.append(self.refine_parent_types(expr, expr_type)) + return reduce_and_conditional_type_maps(all_mappings, use_meet=True) + + def refine_parent_types(self, expr: Expression, expr_type: Type) -> TypeMap: + """Checks if the given expr is a 'lookup operation' into a union and iteratively refines + the parent types based on the 'expr_type'. + + For example, if 'expr' is an expression like 'a.b.c.d', we'll potentially return refined + types for expressions 'a', 'a.b', and 'a.b.c'. + + For more details about what a 'lookup operation' is and how we use the expr_type to refine + the parent types of lookup_expr, see the docstring in 'propagate_up_typemap_info'. + """ + output: dict[Expression, Type] = {} + + # Note: parent_expr and parent_type are progressively refined as we crawl up the + # parent lookup chain. + while True: + # First, check if this expression is one that's attempting to + # "lookup" some key in the parent type. If so, save the parent type + # and create function that will try replaying the same lookup + # operation against arbitrary types. + if isinstance(expr, MemberExpr): + parent_expr = self._propagate_walrus_assignments(expr.expr, output) + parent_type = self.lookup_type_or_none(parent_expr) + member_name = expr.name + + def replay_lookup(new_parent_type: ProperType) -> Type | None: + with self.msg.filter_errors() as w: + member_type = analyze_member_access( + name=member_name, + typ=new_parent_type, + context=parent_expr, + is_lvalue=False, + is_super=False, + is_operator=False, + original_type=new_parent_type, + chk=self, + in_literal_context=False, + ) + if w.has_new_errors(): + return None + else: + return member_type + + elif isinstance(expr, IndexExpr): + parent_expr = self._propagate_walrus_assignments(expr.base, output) + parent_type = self.lookup_type_or_none(parent_expr) + + self._propagate_walrus_assignments(expr.index, output) + index_type = self.lookup_type_or_none(expr.index) + if index_type is None: + return output + + str_literals = try_getting_str_literals_from_type(index_type) + if str_literals is not None: + # Refactoring these two indexing replay functions is surprisingly + # tricky -- see https://github.com/python/mypy/pull/7917, which + # was blocked by https://github.com/mypyc/mypyc/issues/586 + def replay_lookup(new_parent_type: ProperType) -> Type | None: + if not isinstance(new_parent_type, TypedDictType): + return None + try: + assert str_literals is not None + member_types = [new_parent_type.items[key] for key in str_literals] + except KeyError: + return None + return make_simplified_union(member_types) + + else: + int_literals = try_getting_int_literals_from_type(index_type) + if int_literals is not None: + + def replay_lookup(new_parent_type: ProperType) -> Type | None: + if not isinstance(new_parent_type, TupleType): + return None + try: + assert int_literals is not None + member_types = [new_parent_type.items[key] for key in int_literals] + except IndexError: + return None + return make_simplified_union(member_types) + + else: + return output + else: + return output + + # If we somehow didn't previously derive the parent type, abort completely + # with what we have so far: something went wrong at an earlier stage. + if parent_type is None: + return output + + # We currently only try refining the parent type if it's a Union. + # If not, there's no point in trying to refine any further parents + # since we have no further information we can use to refine the lookup + # chain, so we end early as an optimization. + parent_type = get_proper_type(parent_type) + if not isinstance(parent_type, UnionType): + return output + + # Take each element in the parent union and replay the original lookup procedure + # to figure out which parents are compatible. + new_parent_types = [] + for item in flatten_nested_unions(parent_type.items): + member_type = replay_lookup(get_proper_type(item)) + if member_type is None: + # We were unable to obtain the member type. So, we give up on refining this + # parent type entirely and abort. + return output + + if is_overlapping_types(member_type, expr_type): + new_parent_types.append(item) + + # If none of the parent types overlap (if we derived an empty union), something + # went wrong. We should never hit this case, but deriving the uninhabited type or + # reporting an error both seem unhelpful. So we abort. + if not new_parent_types: + return output + + expr = parent_expr + expr_type = output[parent_expr] = make_simplified_union(new_parent_types) + + def _propagate_walrus_assignments( + self, expr: Expression, type_map: dict[Expression, Type] + ) -> Expression: + """Add assignments from walrus expressions to inferred types. + + Only considers nested assignment exprs, does not recurse into other types. + This may be added later if necessary by implementing a dedicated visitor. + """ + if isinstance(expr, AssignmentExpr): + if isinstance(expr.value, AssignmentExpr): + self._propagate_walrus_assignments(expr.value, type_map) + assigned_type = self.lookup_type_or_none(expr.value) + parent_expr = collapse_walrus(expr) + if assigned_type is not None: + type_map[parent_expr] = assigned_type + return parent_expr + return expr + + def is_len_of_tuple(self, expr: Expression) -> bool: + """Is this expression a `len(x)` call where x is a tuple or union of tuples?""" + if not isinstance(expr, CallExpr): + return False + if not refers_to_fullname(expr.callee, "builtins.len"): + return False + if len(expr.args) != 1: + return False + expr = expr.args[0] + if literal(expr) != LITERAL_TYPE: + return False + if not self.has_type(expr): + return False + return self.can_be_narrowed_with_len(self.lookup_type(expr)) + + def can_be_narrowed_with_len(self, typ: Type) -> bool: + """Is this a type that can benefit from length check type restrictions? + + Currently supported types are TupleTypes, Instances of builtins.tuple, and + unions involving such types. + """ + if custom_special_method(typ, "__len__"): + # If user overrides builtin behavior, we can't do anything. + return False + p_typ = get_proper_type(typ) + # Note: we are conservative about tuple subclasses, because some code may rely on + # the fact that tuple_type of fallback TypeInfo matches the original TupleType. + if isinstance(p_typ, TupleType): + if any(isinstance(t, UnpackType) for t in p_typ.items): + return p_typ.partial_fallback.type.fullname == "builtins.tuple" + return True + if isinstance(p_typ, Instance): + return p_typ.type.has_base("builtins.tuple") + if isinstance(p_typ, UnionType): + return any(self.can_be_narrowed_with_len(t) for t in p_typ.items) + return False + + def literal_int_expr(self, expr: Expression) -> int | None: + """Is this expression an int literal, or a reference to an int constant? + + If yes, return the corresponding int value, otherwise return None. + """ + if not self.has_type(expr): + return None + expr_type = self.lookup_type(expr) + expr_type = coerce_to_literal(expr_type) + proper_type = get_proper_type(expr_type) + if not isinstance(proper_type, LiteralType): + return None + if not isinstance(proper_type.value, int): + return None + return proper_type.value + + def find_tuple_len_narrowing(self, node: ComparisonExpr) -> list[tuple[TypeMap, TypeMap]]: + """Top-level logic to find type restrictions from a length check on tuples. + + We try to detect `if` checks like the following: + x: tuple[int, int] | tuple[int, int, int] + y: tuple[int, int] | tuple[int, int, int] + if len(x) == len(y) == 2: + a, b = x # OK + c, d = y # OK + + z: tuple[int, ...] + if 1 < len(z) < 4: + x = z # OK + and report corresponding type restrictions to the binder. + """ + # First step: group consecutive `is` and `==` comparisons together. + # This is essentially a simplified version of group_comparison_operands(), + # tuned to the len()-like checks. Note that we don't propagate indirect + # restrictions like e.g. `len(x) > foo() > 1` yet, since it is tricky. + # TODO: propagate indirect len() comparison restrictions. + chained = [] + last_group = set() + for op, left, right in node.pairwise(): + if isinstance(left, AssignmentExpr): + left = left.value + if isinstance(right, AssignmentExpr): + right = right.value + if op in ("is", "=="): + last_group.add(left) + last_group.add(right) + else: + if last_group: + chained.append(("==", list(last_group))) + last_group = set() + if op in {"is not", "!=", "<", "<=", ">", ">="}: + chained.append((op, [left, right])) + if last_group: + chained.append(("==", list(last_group))) + + yes_map: TypeMap + no_map: TypeMap + + # Second step: infer type restrictions from each group found above. + type_maps = [] + for op, items in chained: + # TODO: support unions of literal types as len() comparison targets. + if not any(self.literal_int_expr(it) is not None for it in items): + continue + if not any(self.is_len_of_tuple(it) for it in items): + continue + + # At this step we know there is at least one len(x) and one literal in the group. + if op in ("is", "=="): + literal_values = set() + tuples = [] + for it in items: + lit = self.literal_int_expr(it) + if lit is not None: + literal_values.add(lit) + continue + if self.is_len_of_tuple(it): + assert isinstance(it, CallExpr) + tuples.append(it.args[0]) + if len(literal_values) > 1: + # More than one different literal value found, like 1 == len(x) == 2, + # so the corresponding branch is unreachable. + yes_map = {tpl: UninhabitedType() for tpl in tuples} + return [(yes_map, {})] + size = literal_values.pop() + if size > MAX_PRECISE_TUPLE_SIZE: + # Avoid creating huge tuples from checks like if len(x) == 300. + continue + for tpl in tuples: + yes_type, no_type = self.narrow_with_len(self.lookup_type(tpl), op, size) + yes_map = {tpl: yes_type} + no_map = {tpl: no_type} + type_maps.append((yes_map, no_map)) + else: + left, right = items + if self.is_len_of_tuple(right): + # Normalize `1 < len(x)` and similar as `len(x) > 1`. + left, right = right, left + op = flip_ops.get(op, op) + r_size = self.literal_int_expr(right) + assert r_size is not None + if r_size > MAX_PRECISE_TUPLE_SIZE: + # Avoid creating huge unions from checks like if len(x) > 300. + continue + assert isinstance(left, CallExpr) + yes_type, no_type = self.narrow_with_len( + self.lookup_type(left.args[0]), op, r_size + ) + yes_map = {left.args[0]: yes_type} + no_map = {left.args[0]: no_type} + type_maps.append((yes_map, no_map)) + return type_maps + + def narrow_with_len(self, typ: Type, op: str, size: int) -> tuple[Type, Type]: + """Dispatch tuple type narrowing logic depending on the kind of type we got.""" + typ = get_proper_type(typ) + if isinstance(typ, TupleType): + return self.refine_tuple_type_with_len(typ, op, size) + elif isinstance(typ, Instance): + return self.refine_instance_type_with_len(typ, op, size) + elif isinstance(typ, UnionType): + yes_types = [] + no_types = [] + other_types = [] + for t in typ.items: + if not self.can_be_narrowed_with_len(t): + other_types.append(t) + continue + yt, nt = self.narrow_with_len(t, op, size) + yes_types.append(yt) + no_types.append(nt) + yes_types += other_types + no_types += other_types + yes_type = make_simplified_union(yes_types) + no_type = make_simplified_union(no_types) + return yes_type, no_type + else: + assert False, "Unsupported type for len narrowing" + + def refine_tuple_type_with_len(self, typ: TupleType, op: str, size: int) -> tuple[Type, Type]: + """Narrow a TupleType using length restrictions.""" + unpack_index = find_unpack_in_list(typ.items) + if unpack_index is None: + # For fixed length tuple situation is trivial, it is either reachable or not, + # depending on the current length, expected length, and the comparison op. + method = int_op_to_method[op] + if method(typ.length(), size): + return typ, UninhabitedType() + return UninhabitedType(), typ + unpack = typ.items[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + if isinstance(unpacked, TypeVarTupleType): + # For tuples involving TypeVarTuple unpack we can't do much except + # inferring reachability, and recording the restrictions on TypeVarTuple + # for further "manual" use elsewhere. + min_len = typ.length() - 1 + unpacked.min_len + if op in ("==", "is"): + if min_len <= size: + return typ, typ + return UninhabitedType(), typ + elif op in ("<", "<="): + if op == "<=": + size += 1 + if min_len < size: + prefix = typ.items[:unpack_index] + suffix = typ.items[unpack_index + 1 :] + # TODO: also record max_len to avoid false negatives? + unpack = UnpackType(unpacked.copy_modified(min_len=size - typ.length() + 1)) + return typ, typ.copy_modified(items=prefix + [unpack] + suffix) + return UninhabitedType(), typ + else: + yes_type, no_type = self.refine_tuple_type_with_len(typ, neg_ops[op], size) + return no_type, yes_type + # Homogeneous variadic item is the case where we are most flexible. Essentially, + # we adjust the variadic item by "eating away" from it to satisfy the restriction. + assert isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple" + min_len = typ.length() - 1 + arg = unpacked.args[0] + prefix = typ.items[:unpack_index] + suffix = typ.items[unpack_index + 1 :] + if op in ("==", "is"): + if min_len <= size: + # TODO: return fixed union + prefixed variadic tuple for no_type? + return typ.copy_modified(items=prefix + [arg] * (size - min_len) + suffix), typ + return UninhabitedType(), typ + elif op in ("<", "<="): + if op == "<=": + size += 1 + if min_len < size: + # Note: there is some ambiguity w.r.t. to where to put the additional + # items: before or after the unpack. However, such types are equivalent, + # so we always put them before for consistency. + no_type = typ.copy_modified( + items=prefix + [arg] * (size - min_len) + [unpack] + suffix + ) + yes_items = [] + for n in range(size - min_len): + yes_items.append(typ.copy_modified(items=prefix + [arg] * n + suffix)) + return UnionType.make_union(yes_items, typ.line, typ.column), no_type + return UninhabitedType(), typ + else: + yes_type, no_type = self.refine_tuple_type_with_len(typ, neg_ops[op], size) + return no_type, yes_type + + def refine_instance_type_with_len( + self, typ: Instance, op: str, size: int + ) -> tuple[Type, Type]: + """Narrow a homogeneous tuple using length restrictions.""" + base = map_instance_to_supertype(typ, self.lookup_typeinfo("builtins.tuple")) + arg = base.args[0] + # Again, we are conservative about subclasses until we gain more confidence. + allow_precise = ( + PRECISE_TUPLE_TYPES in self.options.enable_incomplete_feature + ) and typ.type.fullname == "builtins.tuple" + if op in ("==", "is"): + # TODO: return fixed union + prefixed variadic tuple for no_type? + return TupleType(items=[arg] * size, fallback=typ), typ + elif op in ("<", "<="): + if op == "<=": + size += 1 + if allow_precise: + unpack = UnpackType(self.named_generic_type("builtins.tuple", [arg])) + no_type: Type = TupleType(items=[arg] * size + [unpack], fallback=typ) + else: + no_type = typ + if allow_precise: + items = [] + for n in range(size): + items.append(TupleType([arg] * n, fallback=typ)) + yes_type: Type = UnionType.make_union(items, typ.line, typ.column) + else: + yes_type = typ + return yes_type, no_type + else: + yes_type, no_type = self.refine_instance_type_with_len(typ, neg_ops[op], size) + return no_type, yes_type + + # + # Helpers + # + @overload + def check_subtype( + self, + subtype: Type, + supertype: Type, + context: Context, + msg: str, + subtype_label: str | None = None, + supertype_label: str | None = None, + *, + notes: list[str] | None = None, + code: ErrorCode | None = None, + outer_context: Context | None = None, + ) -> bool: ... + + @overload + def check_subtype( + self, + subtype: Type, + supertype: Type, + context: Context, + msg: ErrorMessage, + subtype_label: str | None = None, + supertype_label: str | None = None, + *, + notes: list[str] | None = None, + outer_context: Context | None = None, + ) -> bool: ... + + def check_subtype( + self, + subtype: Type, + supertype: Type, + context: Context, + msg: str | ErrorMessage, + subtype_label: str | None = None, + supertype_label: str | None = None, + *, + notes: list[str] | None = None, + code: ErrorCode | None = None, + outer_context: Context | None = None, + ) -> bool: + """Generate an error if the subtype is not compatible with supertype.""" + if is_subtype(subtype, supertype, options=self.options): + return True + + if isinstance(msg, str): + msg = ErrorMessage(msg, code=code) + + if self.msg.prefer_simple_messages(): + self.fail(msg, context) # Fast path -- skip all fancy logic + return False + + orig_subtype = subtype + subtype = get_proper_type(subtype) + orig_supertype = supertype + supertype = get_proper_type(supertype) + if self.msg.try_report_long_tuple_assignment_error( + subtype, supertype, context, msg, subtype_label, supertype_label + ): + return False + extra_info: list[str] = [] + note_msg = "" + notes = notes or [] + if subtype_label is not None or supertype_label is not None: + subtype_str, supertype_str = format_type_distinctly( + orig_subtype, orig_supertype, options=self.options + ) + if subtype_label is not None: + extra_info.append(subtype_label + " " + subtype_str) + if supertype_label is not None: + extra_info.append(supertype_label + " " + supertype_str) + note_msg = make_inferred_type_note( + outer_context or context, subtype, supertype, supertype_str + ) + if isinstance(subtype, Instance) and isinstance(supertype, Instance): + notes = append_invariance_notes(notes, subtype, supertype) + if isinstance(subtype, UnionType) and isinstance(supertype, UnionType): + notes = append_union_note(notes, subtype, supertype, self.options) + if extra_info: + msg = msg.with_additional_msg(" (" + ", ".join(extra_info) + ")") + + error = self.fail(msg, context) + for note in notes: + self.msg.note(note, context, code=msg.code) + if note_msg: + self.note(note_msg, context, code=msg.code) + self.msg.maybe_note_concatenate_pos_args(subtype, supertype, context, code=msg.code) + if ( + isinstance(supertype, Instance) + and supertype.type.is_protocol + and isinstance(subtype, (CallableType, Instance, TupleType, TypedDictType, TypeType)) + ): + self.msg.report_protocol_problems(subtype, supertype, context, parent_error=error) + if isinstance(supertype, CallableType) and isinstance(subtype, Instance): + call = find_member("__call__", subtype, subtype, is_operator=True) + if call: + self.msg.note_call(subtype, call, context, code=msg.code) + if isinstance(subtype, (CallableType, Overloaded)) and isinstance(supertype, Instance): + if supertype.type.is_protocol and "__call__" in supertype.type.protocol_members: + call = find_member("__call__", supertype, subtype, is_operator=True) + assert call is not None + if not is_subtype(subtype, call, options=self.options): + self.msg.note_call(supertype, call, context, code=msg.code) + self.check_possible_missing_await(subtype, supertype, context, code=msg.code) + return False + + def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None: + """If type implements Awaitable[X] with non-Any X, return X. + + In all other cases return None. This method must be called in context + of local_errors. + """ + if isinstance(get_proper_type(typ), PartialType): + # Partial types are special, ignore them here. + return None + try: + aw_type = self.expr_checker.check_awaitable_expr( + typ, Context(), "", ignore_binder=True + ) + except KeyError: + # This is a hack to speed up tests by not including Awaitable in all typing stubs. + return None + if local_errors.has_new_errors(): + return None + if isinstance(get_proper_type(aw_type), (AnyType, UnboundType)): + return None + return aw_type + + @contextmanager + def checking_await_set(self) -> Iterator[None]: + self.checking_missing_await = True + try: + yield + finally: + self.checking_missing_await = False + + def check_possible_missing_await( + self, subtype: Type, supertype: Type, context: Context, code: ErrorCode | None + ) -> None: + """Check if the given type becomes a subtype when awaited.""" + if self.checking_missing_await: + # Avoid infinite recursion. + return + with self.checking_await_set(), self.msg.filter_errors() as local_errors: + aw_type = self.get_precise_awaitable_type(subtype, local_errors) + if aw_type is None: + return + if not self.check_subtype( + aw_type, supertype, context, msg=message_registry.INCOMPATIBLE_TYPES + ): + return + self.msg.possible_missing_await(context, code) + + def named_type(self, name: str) -> Instance: + """Return an instance type with given name and implicit Any type args. + + For example, named_type('builtins.object') produces the 'object' type. + """ + if name == "builtins.str": + if instance_cache.str_type is None: + instance_cache.str_type = self._named_type(name) + return instance_cache.str_type + if name == "builtins.function": + if instance_cache.function_type is None: + instance_cache.function_type = self._named_type(name) + return instance_cache.function_type + if name == "builtins.int": + if instance_cache.int_type is None: + instance_cache.int_type = self._named_type(name) + return instance_cache.int_type + if name == "builtins.bool": + if instance_cache.bool_type is None: + instance_cache.bool_type = self._named_type(name) + return instance_cache.bool_type + if name == "builtins.object": + if instance_cache.object_type is None: + instance_cache.object_type = self._named_type(name) + return instance_cache.object_type + return self._named_type(name) + + def _named_type(self, name: str) -> Instance: + # Assume that the name refers to a type. + sym = self.lookup_qualified(name) + node = sym.node + if isinstance(node, TypeAlias): + assert isinstance(node.target, Instance) # type: ignore[misc] + node = node.target.type + assert isinstance(node, TypeInfo), node + any_type = AnyType(TypeOfAny.from_omitted_generics) + return Instance(node, [any_type] * len(node.defn.type_vars)) + + def named_generic_type(self, name: str, args: list[Type]) -> Instance: + """Return an instance with the given name and type arguments. + + Assume that the number of arguments is correct. Assume that + the name refers to a compatible generic type. + """ + info = self.lookup_typeinfo(name) + args = [remove_instance_last_known_values(arg) for arg in args] + # TODO: assert len(args) == len(info.defn.type_vars) + return Instance(info, args) + + def lookup_typeinfo(self, fullname: str) -> TypeInfo: + # Assume that the name refers to a class. + sym = self.lookup_qualified(fullname) + node = sym.node + assert isinstance(node, TypeInfo), node + return node + + def type_type(self) -> Instance: + """Return instance type 'type'.""" + return self.named_type("builtins.type") + + def str_type(self) -> Instance: + """Return instance type 'str'.""" + return self.named_type("builtins.str") + + def store_type(self, node: Expression, typ: Type) -> None: + """Store the type of a node in the type map.""" + self._type_maps[-1][node] = typ + + def has_type(self, node: Expression) -> bool: + return any(node in m for m in reversed(self._type_maps)) + + def lookup_type_or_none(self, node: Expression) -> Type | None: + for m in reversed(self._type_maps): + if node in m: + return m[node] + return None + + def lookup_type(self, node: Expression) -> Type: + for m in reversed(self._type_maps): + t = m.get(node) + if t is not None: + return t + raise KeyError(node) + + def store_types(self, d: dict[Expression, Type]) -> None: + self._type_maps[-1].update(d) + + def in_checked_function(self) -> bool: + """Should we type-check the current function? + + - Yes if --check-untyped-defs is set. + - Yes outside functions. + - Yes in annotated functions. + - No otherwise. + """ + return ( + self.options.check_untyped_defs or not self.dynamic_funcs or not self.dynamic_funcs[-1] + ) + + def lookup(self, name: str) -> SymbolTableNode: + """Look up a definition from the symbol table with the given name.""" + if name in self.globals: + return self.globals[name] + else: + b = self.globals.get("__builtins__", None) + if b: + assert isinstance(b.node, MypyFile) + table = b.node.names + if name in table: + return table[name] + raise KeyError(f"Failed lookup: {name}") + + def lookup_qualified(self, name: str) -> SymbolTableNode: + if "." not in name: + return self.lookup(name) + else: + parts = name.split(".") + n = self.modules[parts[0]] + for i in range(1, len(parts) - 1): + sym = n.names.get(parts[i]) + assert sym is not None, "Internal error: attempted lookup of unknown name" + assert isinstance(sym.node, MypyFile) + n = sym.node + last = parts[-1] + if last in n.names: + return n.names[last] + elif len(parts) == 2 and parts[0] in ("builtins", "typing"): + fullname = ".".join(parts) + if fullname in SUGGESTED_TEST_FIXTURES: + suggestion = ", e.g. add '[{} fixtures/{}]' to your test".format( + parts[0], SUGGESTED_TEST_FIXTURES[fullname] + ) + else: + suggestion = "" + raise KeyError( + "Could not find builtin symbol '{}' (If you are running a " + "test case, use a fixture that " + "defines this symbol{})".format(last, suggestion) + ) + else: + msg = "Failed qualified lookup: '{}' (fullname = '{}')." + raise KeyError(msg.format(last, name)) + + @contextmanager + def enter_partial_types( + self, *, is_function: bool = False, is_class: bool = False + ) -> Iterator[None]: + """Enter a new scope for collecting partial types. + + Also report errors for (some) variables which still have partial + types, i.e. we couldn't infer a complete type. + """ + is_local = (self.partial_types and self.partial_types[-1].is_local) or is_function + self.partial_types.append(PartialTypeScope({}, is_function, is_local)) + yield + + # Don't complain about not being able to infer partials if it is + # at the toplevel (with allow_untyped_globals) or if it is in an + # untyped function being checked with check_untyped_defs. + permissive = (self.options.allow_untyped_globals and not is_local) or ( + self.options.check_untyped_defs and self.dynamic_funcs and self.dynamic_funcs[-1] + ) + + partial_types, _, _ = self.partial_types.pop() + if not self.current_node_deferred: + for var, context in partial_types.items(): + if isinstance(var.type, PartialType) and var.type.type is None and not permissive: + var.type = NoneType() + else: + if var not in self.partial_reported and not permissive: + self.msg.need_annotation_for_var(var, context, self.options) + self.partial_reported.add(var) + if var.type: + fixed = fixup_partial_type(var.type) + var.invalid_partial_type = fixed != var.type + var.type = fixed + + def handle_partial_var_type( + self, typ: PartialType, is_lvalue: bool, node: Var, context: Context + ) -> Type: + """Handle a reference to a partial type through a var. + + (Used by checkexpr and checkmember.) + """ + in_scope, is_local, partial_types = self.find_partial_types_in_all_scopes(node) + if typ.type is None and in_scope: + # 'None' partial type. It has a well-defined type. In an lvalue context + # we want to preserve the knowledge of it being a partial type. + if not is_lvalue: + return NoneType() + else: + return typ + else: + if partial_types is not None and not self.current_node_deferred: + if in_scope: + context = partial_types[node] + if is_local or not self.options.allow_untyped_globals: + self.msg.need_annotation_for_var(node, context, self.options) + self.partial_reported.add(node) + else: + # Defer the node -- we might get a better type in the outer scope + self.handle_cannot_determine_type(node.name, context) + return fixup_partial_type(typ) + + def is_defined_in_base_class(self, var: Var) -> bool: + if not var.info: + return False + return var.info.fallback_to_any or any( + base.get(var.name) is not None for base in var.info.mro[1:] + ) + + def find_partial_types(self, var: Var) -> dict[Var, Context] | None: + """Look for an active partial type scope containing variable. + + A scope is active if assignments in the current context can refine a partial + type originally defined in the scope. This is affected by the local_partial_types + configuration option. + """ + in_scope, _, partial_types = self.find_partial_types_in_all_scopes(var) + if in_scope: + return partial_types + return None + + def find_partial_types_in_all_scopes( + self, var: Var + ) -> tuple[bool, bool, dict[Var, Context] | None]: + """Look for partial type scope containing variable. + + Return tuple (is the scope active, is the scope a local scope, scope). + """ + for scope in reversed(self.partial_types): + if var in scope.map: + # All scopes within the outermost function are active. Scopes out of + # the outermost function are inactive to allow local reasoning (important + # for fine-grained incremental mode). + disallow_other_scopes = self.options.local_partial_types + + # There are two exceptions: + if isinstance(var.type, PartialType) and var.type.type is not None and var.info: + # We always prohibit non-None partial types at class scope + # for historical reasons. + disallow_other_scopes = True + if isinstance(var.type, PartialType) and var.type.type is None: + # We always allow None partial types, since this is a common use case. + # It is special-cased in fine-grained incremental mode. + disallow_other_scopes = False + + scope_active = ( + not disallow_other_scopes or scope.is_local == self.partial_types[-1].is_local + ) + return scope_active, scope.is_local, scope.map + return False, False, None + + def temp_node(self, t: Type, context: Context | None = None) -> TempNode: + """Create a temporary node with the given, fixed type.""" + return TempNode(t, context=context) + + def fail( + self, msg: str | ErrorMessage, context: Context, *, code: ErrorCode | None = None + ) -> ErrorInfo: + """Produce an error message.""" + if isinstance(msg, ErrorMessage): + return self.msg.fail(msg.value, context, code=msg.code) + return self.msg.fail(msg, context, code=code) + + def note( + self, + msg: str | ErrorMessage, + context: Context, + offset: int = 0, + *, + code: ErrorCode | None = None, + ) -> None: + """Produce a note.""" + if isinstance(msg, ErrorMessage): + self.msg.note(msg.value, context, code=msg.code) + return + self.msg.note(msg, context, offset=offset, code=code) + + def iterable_item_type(self, it: ProperType, context: Context) -> Type: + if isinstance(it, Instance): + iterable = map_instance_to_supertype(it, self.lookup_typeinfo("typing.Iterable")) + item_type = iterable.args[0] + if not isinstance(get_proper_type(item_type), AnyType): + # This relies on 'map_instance_to_supertype' returning 'Iterable[Any]' + # in case there is no explicit base class. + return item_type + # Try also structural typing. + return self.analyze_iterable_item_type_without_expression(it, context)[1] + + def function_type(self, func: FuncBase) -> FunctionLike: + return function_type(func, self.named_type("builtins.function")) + + def push_type_map(self, type_map: TypeMap, *, from_assignment: bool = True) -> None: + if is_unreachable_map(type_map): + self.binder.unreachable() + else: + for expr, type in type_map.items(): + self.binder.put(expr, type, from_assignment=from_assignment) + + def infer_issubclass_maps(self, node: CallExpr, expr: Expression) -> tuple[TypeMap, TypeMap]: + """Infer type restrictions for an expression in issubclass call.""" + vartype = self.lookup_type(expr) + type = self.get_isinstance_type(node.args[1]) + if isinstance(vartype, TypeVarType): + vartype = vartype.upper_bound + vartype = get_proper_type(vartype) + if isinstance(vartype, UnionType): + union_list = [] + for t in get_proper_types(vartype.items): + if isinstance(t, TypeType): + union_list.append(t.item) + else: + # This is an error that should be reported earlier + # if we reach here, we refuse to do any type inference. + return {}, {} + vartype = UnionType(union_list) + elif isinstance(vartype, TypeType): + vartype = vartype.item + elif isinstance(vartype, Instance) and vartype.type.is_metaclass(): + vartype = self.named_type("builtins.object") + else: + # Any other object whose type we don't know precisely + # for example, Any or a custom metaclass. + return {}, {} # unknown type + yes_type, no_type = self.conditional_types_with_intersection(vartype, type, expr) + yes_map, no_map = conditional_types_to_typemaps(expr, yes_type, no_type) + yes_map, no_map = map(convert_to_typetype, (yes_map, no_map)) + return yes_map, no_map + + @overload + def conditional_types_with_intersection( + self, + expr_type: Type, + type_ranges: list[TypeRange] | None, + ctx: Context, + default: None = None, + *, + consider_runtime_isinstance: bool = True, + ) -> tuple[Type | None, Type | None]: ... + + @overload + def conditional_types_with_intersection( + self, + expr_type: Type, + type_ranges: list[TypeRange] | None, + ctx: Context, + default: Type, + *, + consider_runtime_isinstance: bool = True, + ) -> tuple[Type, Type]: ... + + def conditional_types_with_intersection( + self, + expr_type: Type, + type_ranges: list[TypeRange] | None, + ctx: Context, + default: Type | None = None, + *, + consider_runtime_isinstance: bool = True, + ) -> tuple[Type | None, Type | None]: + initial_types = conditional_types( + expr_type, + type_ranges, + default, + consider_runtime_isinstance=consider_runtime_isinstance, + ) + # For some reason, doing "yes_map, no_map = conditional_types_to_typemaps(...)" + # doesn't work: mypyc will decide that 'yes_map' is of type None if we try. + yes_type: Type | None = initial_types[0] + no_type: Type | None = initial_types[1] + + if not isinstance(get_proper_type(yes_type), UninhabitedType) or type_ranges is None: + return yes_type, no_type + + # If conditional_types was unable to successfully narrow the expr_type + # using the type_ranges and concluded if-branch is unreachable, we try + # computing it again using a different algorithm that tries to generate + # an ad-hoc intersection between the expr_type and the type_ranges. + proper_type = get_proper_type(expr_type) + if isinstance(proper_type, UnionType): + possible_expr_types = get_proper_types(proper_type.relevant_items()) + else: + possible_expr_types = [proper_type] + + possible_target_types = [] + for tr in type_ranges: + item = get_proper_type(tr.item) + if isinstance(item, (Instance, NoneType)): + possible_target_types.append(item) + if not possible_target_types: + return yes_type, no_type + + out = [] + errors: list[tuple[str, str]] = [] + for v in possible_expr_types: + if not isinstance(v, Instance): + return yes_type, no_type + for t in possible_target_types: + if isinstance(t, NoneType): + errors.append((f'"{v.type.name}" and "NoneType"', '"NoneType" is final')) + continue + intersection = self.intersect_instances((v, t), errors) + if intersection is None: + continue + out.append(intersection) + if not out: + # Only report errors if no element in the union worked. + if self.should_report_unreachable_issues(): + for types, reason in errors: + self.msg.impossible_intersection(types, reason, ctx) + return UninhabitedType(), expr_type + new_yes_type = make_simplified_union(out) + return new_yes_type, expr_type + + def is_writable_attribute(self, node: Node) -> bool: + """Check if an attribute is writable""" + if isinstance(node, Var): + if node.is_property and not node.is_settable_property: + return False + return True + elif isinstance(node, OverloadedFuncDef) and node.is_property: + first_item = node.items[0] + assert isinstance(first_item, Decorator) + return first_item.var.is_settable_property + return False + + def get_isinstance_type( + self, expr: Expression, flatten_tuples: bool = True + ) -> list[TypeRange] | None: + """Get the type(s) resulting from an isinstance check. + + Returns an empty list for isinstance(x, ()). + """ + if isinstance(expr, OpExpr) and expr.op == "|": + left: list[TypeRange] | None + right: list[TypeRange] | None + if is_literal_none(expr.left): + left = [TypeRange(NoneType(), is_upper_bound=False)] + else: + left = self.get_isinstance_type(expr.left, flatten_tuples=False) + if is_literal_none(expr.right): + right = [TypeRange(NoneType(), is_upper_bound=False)] + else: + right = self.get_isinstance_type(expr.right, flatten_tuples=False) + if left is None or right is None: + return None + return left + right + + if flatten_tuples: + type_ranges = [] + for typ in flatten_types_if_tuple(self.lookup_type(expr)): + type_range = self.get_type_range_of_type(typ) + if type_range is None: + return None + type_ranges.append(type_range) + return type_ranges + + else: + type_range = self.get_type_range_of_type(self.lookup_type(expr)) + if type_range is None: + return None + return [type_range] + + def get_type_range_of_type(self, typ: Type) -> TypeRange | None: + typ = get_proper_type(typ) + if isinstance(typ, TypeVarType): + typ = get_proper_type(typ.upper_bound) + + if isinstance(typ, UnionType): + type_ranges = [self.get_type_range_of_type(item) for item in typ.items] + item = make_simplified_union([t.item for t in type_ranges if t is not None]) + return TypeRange(item, is_upper_bound=True) + if isinstance(typ, FunctionLike) and typ.is_type_obj(): + # If a type is generic, `isinstance` can only narrow its variables to Any. + any_parameterized = fill_typevars_with_any(typ.type_object()) + # Tuples may have unattended type variables among their items + if isinstance(any_parameterized, TupleType): + erased_type = erase_typevars(any_parameterized) + else: + erased_type = any_parameterized + return TypeRange(erased_type, is_upper_bound=False) + if isinstance(typ, TypeType): + # Type[A] means "any type that is a subtype of A" rather than "precisely type A" + # we indicate this by setting is_upper_bound flag + is_upper_bound = True + if isinstance(typ.item, NoneType): + # except for Type[None], because "'NoneType' is not an acceptable base type" + is_upper_bound = False + if isinstance(typ.item, Instance) and typ.item.type.is_final: + is_upper_bound = False + return TypeRange(typ.item, is_upper_bound=is_upper_bound) + if isinstance(typ, AnyType): + return TypeRange(typ, is_upper_bound=False) + if isinstance(typ, Instance) and typ.type.fullname == "builtins.type": + object_type = Instance(typ.type.mro[-1], []) + return TypeRange(object_type, is_upper_bound=True) + if isinstance(typ, Instance) and typ.type.fullname == "types.UnionType" and typ.args: + return TypeRange(UnionType(typ.args), is_upper_bound=False) + if isinstance(typ, Instance) and typ.type.fullname == "typing._SpecialForm": + # This is probably an alias to a Union object. We don't have the args here so we can't + # conclude anything + return None + if not is_subtype(self.named_type("builtins.type"), typ): + # We saw something, but it couldn't possibly be valid + return TypeRange(UninhabitedType(), is_upper_bound=False) + + # This is e.g. a variable of type object, so we can't conclude anything + return None + + def is_literal_enum(self, n: Expression) -> bool: + """Returns true if this expression (with the given type context) is an Enum literal. + + For example, if we had an enum: + + class Foo(Enum): + A = 1 + B = 2 + + ...and if the expression 'Foo' referred to that enum within the current type context, + then the expression 'Foo.A' would be a literal enum. However, if we did 'a = Foo.A', + then the variable 'a' would *not* be a literal enum. + + We occasionally special-case expressions like 'Foo.A' and treat them as a single primitive + unit for the same reasons we sometimes treat 'True', 'False', or 'None' as a single + primitive unit. + """ + if not isinstance(n, MemberExpr) or not isinstance(n.expr, NameExpr): + return False + + parent_type = self.lookup_type_or_none(n.expr) + member_type = self.lookup_type_or_none(n) + if member_type is None or parent_type is None: + return False + + parent_type = get_proper_type(parent_type) + member_type = get_proper_type(coerce_to_literal(member_type)) + if not isinstance(parent_type, FunctionLike) or not isinstance(member_type, LiteralType): + return False + + if not parent_type.is_type_obj(): + return False + + return ( + member_type.is_enum_literal() + and member_type.fallback.type == parent_type.type_object() + ) + + def add_any_attribute_to_type(self, typ: Type, name: str) -> Type: + """Inject an extra attribute with Any type using fallbacks.""" + orig_typ = typ + typ = get_proper_type(typ) + any_type = AnyType(TypeOfAny.unannotated) + if isinstance(typ, Instance): + result = typ.copy_with_extra_attr(name, any_type) + # For instances, we erase the possible module name, so that restrictions + # become anonymous types.ModuleType instances, allowing hasattr() to + # have effect on modules. + assert result.extra_attrs is not None + result.extra_attrs.mod_name = None + return result + if isinstance(typ, TupleType): + fallback = typ.partial_fallback.copy_with_extra_attr(name, any_type) + return typ.copy_modified(fallback=fallback) + if isinstance(typ, CallableType): + fallback = typ.fallback.copy_with_extra_attr(name, any_type) + return typ.copy_modified(fallback=fallback) + if isinstance(typ, TypeType) and isinstance(typ.item, Instance): + return TypeType.make_normalized( + self.add_any_attribute_to_type(typ.item, name), is_type_form=typ.is_type_form + ) + if isinstance(typ, TypeVarType): + return typ.copy_modified( + upper_bound=self.add_any_attribute_to_type(typ.upper_bound, name), + values=[self.add_any_attribute_to_type(v, name) for v in typ.values], + ) + if isinstance(typ, UnionType): + with_attr, without_attr = self.partition_union_by_attr(typ, name) + return make_simplified_union( + with_attr + [self.add_any_attribute_to_type(typ, name) for typ in without_attr] + ) + return orig_typ + + def hasattr_type_maps( + self, expr: Expression, source_type: Type, name: str + ) -> tuple[TypeMap, TypeMap]: + """Simple support for hasattr() checks. + + Essentially the logic is following: + * In the if branch, keep types that already has a valid attribute as is, + for other inject an attribute with `Any` type. + * In the else branch, remove types that already have a valid attribute, + while keeping the rest. + """ + if self.has_valid_attribute(source_type, name): + return {expr: source_type}, {} + + source_type = get_proper_type(source_type) + if isinstance(source_type, UnionType): + _, without_attr = self.partition_union_by_attr(source_type, name) + yes_map = {expr: self.add_any_attribute_to_type(source_type, name)} + return yes_map, {expr: make_simplified_union(without_attr)} + + type_with_attr = self.add_any_attribute_to_type(source_type, name) + if type_with_attr != source_type: + return {expr: type_with_attr}, {} + return {}, {} + + def partition_union_by_attr( + self, source_type: UnionType, name: str + ) -> tuple[list[Type], list[Type]]: + with_attr = [] + without_attr = [] + for item in source_type.items: + if self.has_valid_attribute(item, name): + with_attr.append(item) + else: + without_attr.append(item) + return with_attr, without_attr + + def has_valid_attribute(self, typ: Type, name: str) -> bool: + p_typ = get_proper_type(typ) + if isinstance(p_typ, AnyType): + return False + if isinstance(p_typ, Instance) and p_typ.extra_attrs and p_typ.extra_attrs.mod_name: + # Presence of module_symbol_table means this check will skip ModuleType.__getattr__ + module_symbol_table = p_typ.type.names + else: + module_symbol_table = None + with self.msg.filter_errors() as watcher: + analyze_member_access( + name, + typ, + TempNode(AnyType(TypeOfAny.special_form)), + is_lvalue=False, + is_super=False, + is_operator=False, + original_type=typ, + chk=self, + # This is not a real attribute lookup so don't mess with deferring nodes. + no_deferral=True, + module_symbol_table=module_symbol_table, + ) + return not watcher.has_new_errors() + + def get_expression_type(self, node: Expression, type_context: Type | None = None) -> Type: + return self.expr_checker.accept(node, type_context=type_context) + + def is_defined_in_stub(self, typ: Instance, /) -> bool: + return self.modules[typ.type.module_name].is_stub + + def check_deprecated(self, node: Node | None, context: Context) -> None: + """Warn if deprecated and not directly imported with a `from` statement.""" + if isinstance(node, Decorator): + node = node.func + if isinstance(node, (FuncDef, OverloadedFuncDef, TypeInfo)) and ( + node.deprecated is not None + ): + for imp in self.tree.imports: + if isinstance(imp, ImportFrom) and any(node.name == n[0] for n in imp.names): + break + else: + self.warn_deprecated(node, context) + + def warn_deprecated(self, node: Node | None, context: Context) -> None: + """Warn if deprecated.""" + if isinstance(node, Decorator): + node = node.func + if ( + isinstance(node, (FuncDef, OverloadedFuncDef, TypeInfo)) + and (deprecated := node.deprecated) is not None + and not self.is_typeshed_stub + and not any( + node.fullname == p or node.fullname.startswith(f"{p}.") + for p in self.options.deprecated_calls_exclude + ) + ): + warn = self.msg.note if self.options.report_deprecated_as_note else self.msg.fail + warn(deprecated, context, code=codes.DEPRECATED) + + def new_unique_dummy_name(self, namespace: str) -> str: + """Generate a name that is guaranteed to be unique for this TypeChecker instance.""" + name = f"dummy-{namespace}-{self._unique_id}" + self._unique_id += 1 + return name + + # leafs + + def visit_pass_stmt(self, o: PassStmt, /) -> None: + return None + + def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None: + return None + + def visit_global_decl(self, o: GlobalDecl, /) -> None: + return None + + +class TypeCheckerAsSemanticAnalyzer(SemanticAnalyzerCoreInterface): + """ + Adapts TypeChecker to the SemanticAnalyzerCoreInterface, + allowing most type expressions to be parsed during the TypeChecker pass. + + See ExpressionChecker.try_parse_as_type_expression() to understand how this + class is used. + """ + + _chk: TypeChecker + _names: dict[str, SymbolTableNode] + did_fail: bool + + def __init__(self, chk: TypeChecker, names: dict[str, SymbolTableNode]) -> None: + self._chk = chk + self._names = names + self.did_fail = False + + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + sym = self._names.get(name) + # All names being looked up should have been previously gathered, + # even if the related SymbolTableNode does not refer to a valid SymbolNode + assert sym is not None, name + return sym + + def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode: + ret = self.lookup_fully_qualified_or_none(fullname) + assert ret is not None, fullname + return ret + + def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None: + try: + return self._chk.lookup_qualified(fullname) + except KeyError: + return None + + def fail( + self, + msg: str, + ctx: Context, + serious: bool = False, + *, + blocker: bool = False, + code: ErrorCode | None = None, + ) -> None: + self.did_fail = True + + def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + pass + + def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: + if feature not in self._chk.options.enable_incomplete_feature: + self.fail("__ignored__", ctx) + return False + return True + + def record_incomplete_ref(self) -> None: + pass + + def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None: + pass + + def is_incomplete_namespace(self, fullname: str) -> bool: + return False + + @property + def final_iteration(self) -> bool: + return True + + def is_future_flag_set(self, flag: str) -> bool: + return self._chk.tree.is_future_flag_set(flag) + + @property + def is_stub_file(self) -> bool: + return self._chk.tree.is_stub + + def is_func_scope(self) -> bool: + # Return arbitrary value. + # + # This method is currently only used to decide whether to pair + # a fail() message with a note() message or not. Both of those + # message types are ignored. + return False + + @property + def type(self) -> TypeInfo | None: + return self._chk.type + + +class CollectArgTypeVarTypes(TypeTraverserVisitor): + """Collects the non-nested argument types in a set.""" + + def __init__(self) -> None: + self.arg_types: set[TypeVarType] = set() + + def visit_type_var(self, t: TypeVarType) -> None: + self.arg_types.add(t) + + +@overload +def conditional_types( + current_type: Type, + proposed_type_ranges: list[TypeRange] | None, + default: None = None, + *, + consider_runtime_isinstance: bool = True, + from_equality: bool = False, +) -> tuple[Type | None, Type | None]: ... + + +@overload +def conditional_types( + current_type: Type, + proposed_type_ranges: list[TypeRange] | None, + default: Type, + *, + consider_runtime_isinstance: bool = True, + from_equality: bool = False, +) -> tuple[Type, Type]: ... + + +def conditional_types( + current_type: Type, + proposed_type_ranges: list[TypeRange] | None, + default: Type | None = None, + *, + consider_runtime_isinstance: bool = True, + from_equality: bool = False, +) -> tuple[Type | None, Type | None]: + """Takes in the current type and a proposed type of an expression. + + Returns a 2-tuple: + The first element is the proposed type, if the expression can be the proposed type. + (or default, if default is set and the expression is a subtype of the proposed type). + The second element is the type it would hold if it was not the proposed type, if any. + (or default, if default is set and the expression is not a subtype of the proposed type). + + UninhabitedType means unreachable. + None means no new information can be inferred. + """ + if proposed_type_ranges is None: + # An isinstance check, but we don't understand the type + return current_type, default + + if not proposed_type_ranges: + # This is the case for `if isinstance(x, ())` which always returns False. + return UninhabitedType(), default + + if len(proposed_type_ranges) == 1: + # expand e.g. bool -> Literal[True] | Literal[False] + target = proposed_type_ranges[0].item + target = get_proper_type(target) + if isinstance(target, LiteralType) and ( + target.is_enum_literal() or isinstance(target.value, bool) + ): + enum_name = target.fallback.type.fullname + current_type = try_expanding_sum_type_to_union(current_type, enum_name) + + proposed_type: Type + remaining_type: Type + + p_current_type = get_proper_type(current_type) + # factorize over union types: isinstance(A|B, C) -> yes = A_yes | B_yes + if isinstance(p_current_type, UnionType): + yes_items: list[Type] = [] + no_items: list[Type] = [] + for union_item in p_current_type.items: + yes_type, no_type = conditional_types( + union_item, + proposed_type_ranges, + default=union_item, + consider_runtime_isinstance=consider_runtime_isinstance, + from_equality=from_equality, + ) + yes_items.append(yes_type) + no_items.append(no_type) + + proposed_type = make_simplified_union(yes_items) + remaining_type = make_simplified_union(no_items) + return proposed_type, remaining_type + + proposed_type = make_simplified_union([type_range.item for type_range in proposed_type_ranges]) + items = proposed_type.items if isinstance(proposed_type, UnionType) else [proposed_type] + for i in range(len(items)): + item = get_proper_type(items[i]) + # Avoid ever narrowing to a NewType. The principle is values of NewType should only be + # produce by explicit wrapping + while isinstance(item, Instance) and item.type.is_newtype: + item = item.type.bases[0] + items[i] = item + proposed_type = get_proper_type(UnionType.make_union(items)) + + if isinstance(p_current_type, AnyType): + return proposed_type, current_type + if isinstance(proposed_type, AnyType): + # We don't really know much about the proposed type, so we shouldn't + # attempt to narrow anything. Instead, we broaden the expr to Any to + # avoid false positives + return proposed_type, default + if not any(type_range.is_upper_bound for type_range in proposed_type_ranges): + # concrete subtype + if is_proper_subtype(current_type, proposed_type, ignore_promotions=True): + return default, UninhabitedType() + + # structural subtypes + if ( + isinstance(proposed_type, CallableType) + or (isinstance(proposed_type, Instance) and proposed_type.type.is_protocol) + ) and is_subtype(current_type, proposed_type, ignore_promotions=True): + # Note: It's possible that current_type=`Any | Proto` while proposed_type=`Proto` + # so we cannot return `Never` for the else branch + remainder = restrict_subtype_away( + current_type, + default if default is not None else proposed_type, + consider_runtime_isinstance=consider_runtime_isinstance, + ) + return default, remainder + + if from_equality: + # We erase generic args because values with different generic types can compare equal + # For instance, cast(list[str], []) and cast(list[int], []) + proposed_type = shallow_erase_type_for_equality(proposed_type) + if not is_overlapping_types(current_type, proposed_type, ignore_promotions=False): + # Equality narrowing is one of the places at runtime where subtyping with promotion + # does happen to match runtime semantics + # Expression is never of any type in proposed_type_ranges + return UninhabitedType(), default + if not is_overlapping_types(current_type, proposed_type, ignore_promotions=True): + return default, default + else: + if not is_overlapping_types(current_type, proposed_type, ignore_promotions=True): + # Expression is never of any type in proposed_type_ranges + return UninhabitedType(), default + + # we can only restrict when the type is precise, not bounded + proposed_precise_type = UnionType.make_union( + [type_range.item for type_range in proposed_type_ranges if not type_range.is_upper_bound] + ) + remaining_type = restrict_subtype_away( + current_type, + proposed_precise_type, + consider_runtime_isinstance=consider_runtime_isinstance, + ) + + # Avoid widening the type + if is_proper_subtype(p_current_type, proposed_type, ignore_promotions=True): + proposed_type = default if default is not None else current_type + + return proposed_type, remaining_type + + +def conditional_types_to_typemaps( + expr: Expression, yes_type: Type | None, no_type: Type | None +) -> tuple[TypeMap, TypeMap]: + expr = collapse_walrus(expr) + + yes_map = {} if yes_type is None else {expr: yes_type} + no_map = {} if no_type is None else {expr: no_type} + return yes_map, no_map + + +def gen_unique_name(base: str, table: SymbolTable) -> str: + """Generate a name that does not appear in table by appending numbers to base.""" + if base not in table: + return base + i = 1 + while base + str(i) in table: + i += 1 + return base + str(i) + + +def is_true_literal(n: Expression) -> bool: + """Returns true if this expression is the 'True' literal/keyword.""" + return refers_to_fullname(n, "builtins.True") or isinstance(n, IntExpr) and n.value != 0 + + +def is_false_literal(n: Expression) -> bool: + """Returns true if this expression is the 'False' literal/keyword.""" + return refers_to_fullname(n, "builtins.False") or isinstance(n, IntExpr) and n.value == 0 + + +def is_literal_none(n: Expression) -> bool: + """Returns true if this expression is the 'None' literal/keyword.""" + return isinstance(n, NameExpr) and n.fullname == "builtins.None" + + +def is_literal_not_implemented(n: Expression | None) -> bool: + return isinstance(n, NameExpr) and n.fullname == "builtins.NotImplemented" + + +def _is_empty_generator_function(func: FuncItem) -> bool: + """ + Checks whether a function's body is 'return; yield' (the yield being added only + to promote the function into a generator function). + """ + body = func.body.body + return ( + len(body) == 2 + and isinstance(ret_stmt := body[0], ReturnStmt) + and (ret_stmt.expr is None or is_literal_none(ret_stmt.expr)) + and isinstance(expr_stmt := body[1], ExpressionStmt) + and isinstance(yield_expr := expr_stmt.expr, YieldExpr) + and (yield_expr.expr is None or is_literal_none(yield_expr.expr)) + ) + + +def builtin_item_type(tp: Type) -> Type | None: + """Get the item type of a builtin container. + + If 'tp' is not one of the built containers (these includes NamedTuple and TypedDict) + or if the container is not parameterized (like List or List[Any]) + return None. This function is used to narrow optional types in situations like this: + + x: Optional[int] + if x in (1, 2, 3): + x + 42 # OK + + Note: this is only OK for built-in containers, where we know the behavior + of __contains__. + """ + tp = get_proper_type(tp) + + if isinstance(tp, Instance): + if tp.type.fullname in [ + "builtins.list", + "builtins.tuple", + "builtins.dict", + "builtins.set", + "builtins.frozenset", + "_collections_abc.dict_keys", + "typing.KeysView", + ]: + if not tp.args: + # TODO: fix tuple in lib-stub/builtins.pyi (it should be generic). + return None + if not isinstance(get_proper_type(tp.args[0]), AnyType): + return tp.args[0] + elif isinstance(tp, TupleType): + normalized_items = [] + for it in tp.items: + # This use case is probably rare, but not handling unpacks here can cause crashes. + if isinstance(it, UnpackType): + unpacked = get_proper_type(it.type) + if isinstance(unpacked, TypeVarTupleType): + unpacked = get_proper_type(unpacked.upper_bound) + assert ( + isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple" + ) + normalized_items.append(unpacked.args[0]) + else: + normalized_items.append(it) + if all(not isinstance(it, AnyType) for it in get_proper_types(normalized_items)): + return make_simplified_union(normalized_items) # this type is not externally visible + elif isinstance(tp, TypedDictType): + # TypedDict always has non-optional string keys. Find the key type from the Mapping + # base class. + for base in tp.fallback.type.mro: + if base.fullname == "typing.Mapping": + return map_instance_to_supertype(tp.fallback, base).args[0] + assert False, "No Mapping base class found for TypedDict fallback" + return None + + +def is_unreachable_map(map: TypeMap) -> bool: + return any(isinstance(get_proper_type(v), UninhabitedType) for v in map.values()) + + +def and_conditional_maps(m1: TypeMap, m2: TypeMap, *, use_meet: bool = False) -> TypeMap: + """Calculate what information we can learn from the truth of (e1 and e2) + in terms of the information that we can learn from the truth of e1 and + the truth of e2. + """ + # Both conditions can be true; combine the information. Anything + # we learn from either conditions' truth is valid. If the same + # expression's type is refined by both conditions, we somewhat + # arbitrarily give precedence to m2 unless m1 value is Any. + # In the future, we could use an intersection type or meet_types(). + result = m2.copy() + m2_keys = {literal_hash(n2) for n2 in m2} + for n1 in m1: + if literal_hash(n1) not in m2_keys or isinstance( + get_proper_type(m1[n1]), (AnyType, UninhabitedType) + ): + result[n1] = m1[n1] + if use_meet: + # For now, meet common keys only if specifically requested. + # This is currently used for tuple types narrowing, where having + # a precise result is important. + for n1 in m1: + for n2 in m2: + if literal_hash(n1) == literal_hash(n2): + result[n1] = meet_types(m1[n1], m2[n2]) + return result + + +def or_conditional_maps(m1: TypeMap, m2: TypeMap, *, coalesce_any: bool = False) -> TypeMap: + """Calculate what information we can learn from the truth of (e1 or e2) + in terms of the information that we can learn from the truth of e1 and + the truth of e2. If coalesce_any is True, consider Any a supertype when + joining restrictions. + """ + + if is_unreachable_map(m1): + return m2 + if is_unreachable_map(m2): + return m1 + # Both conditions can be true. Combine information about + # expressions whose type is refined by both conditions. (We do not + # learn anything about expressions whose type is refined by only + # one condition.) + result: dict[Expression, Type] = {} + for n1 in m1: + for n2 in m2: + if literal_hash(n1) == literal_hash(n2): + if coalesce_any and isinstance(get_proper_type(m1[n1]), AnyType): + result[n1] = m1[n1] + else: + result[n1] = make_simplified_union([m1[n1], m2[n2]]) + return result + + +def reduce_conditional_maps( + type_maps: list[tuple[TypeMap, TypeMap]], use_meet: bool = False +) -> tuple[TypeMap, TypeMap]: + """Reduces a list containing pairs of if/else TypeMaps into a single pair. + + We "and" together all of the if TypeMaps and "or" together the else TypeMaps. So + for example, if we had the input: + + [ + ({x: TypeIfX, shared: TypeIfShared1}, {x: TypeElseX, shared: TypeElseShared1}), + ({y: TypeIfY, shared: TypeIfShared2}, {y: TypeElseY, shared: TypeElseShared2}), + ] + + ...we'd return the output: + + ( + {x: TypeIfX, y: TypeIfY, shared: PseudoIntersection[TypeIfShared1, TypeIfShared2]}, + {shared: Union[TypeElseShared1, TypeElseShared2]}, + ) + + ...where "PseudoIntersection[X, Y] == Y" because mypy actually doesn't understand intersections + yet, so we settle for just arbitrarily picking the right expr's type. + + We only retain the shared expression in the 'else' case because we don't actually know + whether x was refined or y was refined -- only just that one of the two was refined. + """ + if len(type_maps) == 0: + return {}, {} + elif len(type_maps) == 1: + return type_maps[0] + else: + final_if_map, final_else_map = type_maps[0] + for if_map, else_map in type_maps[1:]: + final_if_map = and_conditional_maps(final_if_map, if_map, use_meet=use_meet) + final_else_map = or_conditional_maps(final_else_map, else_map) + + return final_if_map, final_else_map + + +def reduce_or_conditional_type_maps(ms: list[TypeMap]) -> TypeMap: + """Reduces a list of TypeMaps into a single TypeMap by "or"-ing them together.""" + if len(ms) == 0: + return {} + if len(ms) == 1: + return ms[0] + result = ms[0] + for m in ms[1:]: + result = or_conditional_maps(result, m) + return result + + +def reduce_and_conditional_type_maps(ms: list[TypeMap], *, use_meet: bool) -> TypeMap: + """Reduces a list of TypeMaps into a single TypeMap by "and"-ing them together.""" + if len(ms) == 0: + return {} + if len(ms) == 1: + return ms[0] + result = ms[0] + for m in ms[1:]: + if not m: + continue # this is a micro-optimisation + result = and_conditional_maps(result, m, use_meet=use_meet) + return result + + +BUILTINS_CUSTOM_EQ_CHECKS: Final = { + "builtins.bytearray", + "builtins.memoryview", + "builtins.frozenset", + "_collections_abc.dict_keys", + "_collections_abc.dict_items", +} + + +def has_custom_eq_checks(t: Type) -> bool: + return ( + custom_special_method(t, "__eq__", check_all=False) + or custom_special_method(t, "__ne__", check_all=False) + # custom_special_method has special casing for builtins.* and typing.* that make the + # above always return False. So here we return True if the a value of a builtin type + # will ever compare equal to value of another type, e.g. a bytes value can compare equal + # to a bytearray value. + or ( + isinstance(pt := get_proper_type(t), Instance) + and pt.type.fullname in BUILTINS_CUSTOM_EQ_CHECKS + ) + ) + + +def convert_to_typetype(type_map: TypeMap) -> TypeMap: + converted_type_map: dict[Expression, Type] = {} + for expr, typ in type_map.items(): + t = typ + if isinstance(t, TypeVarType): + t = t.upper_bound + t = get_proper_type(t) + + # TODO: should we only allow unions of instances as per PEP 484? + if isinstance(t, UninhabitedType): + converted_type_map[expr] = typ + elif isinstance(t, (UnionType, Instance, NoneType)): + converted_type_map[expr] = TypeType.make_normalized(typ) + else: + # unknown type; error was likely reported earlier + return {} + return converted_type_map + + +def flatten(t: Expression) -> list[Expression]: + """Flatten a nested sequence of tuples/lists into one list of nodes.""" + if isinstance(t, (TupleExpr, ListExpr)): + return [b for a in t.items for b in flatten(a)] + elif isinstance(t, StarExpr): + return flatten(t.expr) + else: + return [t] + + +def flatten_types_if_tuple(t: Type) -> list[Type]: + """Flatten a nested sequence of tuples into one list of nodes.""" + t = get_proper_type(t) + if isinstance(t, UnionType): + return [UnionType.make_union([b for a in t.items for b in flatten_types_if_tuple(a)])] + if isinstance(t, TupleType): + return [b for a in t.items for b in flatten_types_if_tuple(a)] + elif is_named_instance(t, "builtins.tuple"): + return [t.args[0]] + return [t] + + +def expand_func(defn: FuncItem, map: dict[TypeVarId, Type]) -> FuncItem: + visitor = TypeTransformVisitor(map) + ret = visitor.node(defn) + assert isinstance(ret, FuncItem) + return ret + + +class TypeTransformVisitor(TransformVisitor): + def __init__(self, map: dict[TypeVarId, Type]) -> None: + super().__init__() + self.map = map + + def type(self, type: Type) -> Type: + return expand_type(type, self.map) + + +def are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool: + """Can a single call match both t and s, based just on positional argument counts?""" + min_args = max(t.min_args, s.min_args) + max_args = min(t.max_possible_positional_args(), s.max_possible_positional_args()) + return min_args <= max_args + + +def expand_callable_variants(c: CallableType) -> list[CallableType]: + """Expand a generic callable using all combinations of type variables' values/bounds.""" + for tv in c.variables: + # We need to expand self-type before other variables, because this is the only + # type variable that can have other type variables in the upper bound. + if tv.id.is_self(): + c = expand_type(c, {tv.id: tv.upper_bound}).copy_modified( + variables=[v for v in c.variables if not v.id.is_self()] + ) + break + + if not c.is_generic(): + # Fast path. + return [c] + + tvar_values = [] + for tvar in c.variables: + if isinstance(tvar, TypeVarType) and tvar.values: + tvar_values.append(tvar.values) + else: + tvar_values.append([tvar.upper_bound]) + + variants = [] + for combination in itertools.product(*tvar_values): + tvar_map = {tv.id: subst for (tv, subst) in zip(c.variables, combination)} + variants.append(expand_type(c, tvar_map).copy_modified(variables=[])) + return variants + + +def is_unsafe_overlapping_overload_signatures( + signature: CallableType, + other: CallableType, + class_type_vars: list[TypeVarLikeType], + partial_only: bool = True, +) -> bool: + """Check if two overloaded signatures are unsafely overlapping or partially overlapping. + + We consider two functions 's' and 't' to be unsafely overlapping if three + conditions hold: + + 1. s's parameters are partially overlapping with t's. i.e. there are calls that are + valid for both signatures. + 2. for these common calls, some of t's parameters types are wider that s's. + 3. s's return type is NOT a subset of t's. + + Note that we use subset rather than subtype relationship in these checks because: + * Overload selection happens at runtime, not statically. + * This results in more lenient behavior. + This can cause false negatives (e.g. if overloaded function returns an externally + visible attribute with invariant type), but such situations are rare. In general, + overloads in Python are generally unsafe, so we intentionally try to avoid giving + non-actionable errors (see more details in comments below). + + Assumes that 'signature' appears earlier in the list of overload + alternatives then 'other' and that their argument counts are overlapping. + """ + # Try detaching callables from the containing class so that all TypeVars + # are treated as being free, i.e. the signature is as seen from inside the class, + # where "self" is not yet bound to anything. + signature = detach_callable(signature, class_type_vars) + other = detach_callable(other, class_type_vars) + + # Note: We repeat this check twice in both directions compensate for slight + # asymmetries in 'is_callable_compatible'. + + other_expanded = expand_callable_variants(other) + for sig_variant in expand_callable_variants(signature): + for other_variant in other_expanded: + # Using only expanded callables may cause false negatives, we can add + # more variants (e.g. using inference between callables) in the future. + if is_subset_no_promote(sig_variant.ret_type, other_variant.ret_type): + continue + if not ( + is_callable_compatible( + sig_variant, + other_variant, + is_compat=is_overlapping_types_for_overload, + check_args_covariantly=False, + is_proper_subtype=False, + is_compat_return=lambda l, r: not is_subset_no_promote(l, r), + allow_partial_overlap=True, + ) + or is_callable_compatible( + other_variant, + sig_variant, + is_compat=is_overlapping_types_for_overload, + check_args_covariantly=True, + is_proper_subtype=False, + is_compat_return=lambda l, r: not is_subset_no_promote(r, l), + allow_partial_overlap=True, + ) + ): + continue + # Using the same `allow_partial_overlap` flag as before, can cause false + # negatives in case where star argument is used in a catch-all fallback overload. + # But again, practicality beats purity here. + if not partial_only or not is_callable_compatible( + other_variant, + sig_variant, + is_compat=is_subset_no_promote, + check_args_covariantly=True, + is_proper_subtype=False, + ignore_return=True, + allow_partial_overlap=True, + ): + return True + return False + + +def detach_callable(typ: CallableType, class_type_vars: list[TypeVarLikeType]) -> CallableType: + """Ensures that the callable's type variables are 'detached' and independent of the context. + + A callable normally keeps track of the type variables it uses within its 'variables' field. + However, if the callable is from a method and that method is using a class type variable, + the callable will not keep track of that type variable since it belongs to the class. + """ + if not class_type_vars: + # Fast path, nothing to update. + return typ + return typ.copy_modified(variables=list(typ.variables) + class_type_vars) + + +def overload_can_never_match(signature: CallableType, other: CallableType) -> bool: + """Check if the 'other' method can never be matched due to 'signature'. + + This can happen if signature's parameters are all strictly broader then + other's parameters. + + Assumes that both signatures have overlapping argument counts. + """ + # The extra erasure is needed to prevent spurious errors + # in situations where an `Any` overload is used as a fallback + # for an overload with type variables. The spurious error appears + # because the type variables turn into `Any` during unification in + # the below subtype check and (surprisingly?) `is_proper_subtype(Any, Any)` + # returns `True`. + # TODO: find a cleaner solution instead of this ad-hoc erasure. + exp_signature = expand_type( + signature, {tvar.id: erase_def_to_union_or_bound(tvar) for tvar in signature.variables} + ) + return is_callable_compatible( + exp_signature, other, is_compat=is_more_precise, is_proper_subtype=True, ignore_return=True + ) + + +def is_more_general_arg_prefix(t: FunctionLike, s: FunctionLike) -> bool: + """Does t have wider arguments than s?""" + # TODO should an overload with additional items be allowed to be more + # general than one with fewer items (or just one item)? + if isinstance(t, CallableType): + if isinstance(s, CallableType): + return is_callable_compatible( + t, s, is_compat=is_proper_subtype, is_proper_subtype=True, ignore_return=True + ) + elif isinstance(t, FunctionLike): + if isinstance(s, FunctionLike): + if len(t.items) == len(s.items): + return all( + is_same_arg_prefix(items, itemt) for items, itemt in zip(t.items, s.items) + ) + return False + + +def is_same_arg_prefix(t: CallableType, s: CallableType) -> bool: + return is_callable_compatible( + t, + s, + is_compat=is_same_type, + is_proper_subtype=True, + ignore_return=True, + check_args_covariantly=True, + ignore_pos_arg_names=True, + ) + + +def infer_operator_assignment_method(typ: Type, operator: str) -> tuple[bool, str]: + """Determine if operator assignment on given value type is in-place, and the method name. + + For example, if operator is '+', return (True, '__iadd__') or (False, '__add__') + depending on which method is supported by the type. + """ + typ = get_proper_type(typ) + method = operators.op_methods[operator] + existing_method = None + if isinstance(typ, Instance): + existing_method = _find_inplace_method(typ, method, operator) + elif isinstance(typ, TypedDictType): + existing_method = _find_inplace_method(typ.fallback, method, operator) + + if existing_method is not None: + return True, existing_method + return False, method + + +def _find_inplace_method(inst: Instance, method: str, operator: str) -> str | None: + if operator in operators.ops_with_inplace_method: + inplace_method = "__i" + method[2:] + if inst.type.has_readable_member(inplace_method): + return inplace_method + return None + + +def is_valid_inferred_type( + typ: Type, options: Options, is_lvalue_final: bool = False, is_lvalue_member: bool = False +) -> bool: + """Is an inferred type valid and needs no further refinement? + + Examples of invalid types include the None type (when we are not assigning + None to a final lvalue) or List[]. + + When not doing strict Optional checking, all types containing None are + invalid. When doing strict Optional checking, only None and types that are + incompletely defined (i.e. contain UninhabitedType) are invalid. + """ + proper_type = get_proper_type(typ) + if isinstance(proper_type, NoneType): + # If the lvalue is final, we may immediately infer NoneType when the + # initializer is None. + # + # If not, we want to defer making this decision. The final inferred + # type could either be NoneType or an Optional type, depending on + # the context. This resolution happens in leave_partial_types when + # we pop a partial types scope. + return is_lvalue_final or (not is_lvalue_member and options.allow_redefinition_new) + elif isinstance(proper_type, UninhabitedType): + return False + return not typ.accept(InvalidInferredTypes()) + + +class InvalidInferredTypes(BoolTypeQuery): + """Find type components that are not valid for an inferred type. + + These include type, and any uninhabited types resulting from failed + (ambiguous) type inference. + """ + + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_uninhabited_type(self, t: UninhabitedType) -> bool: + return t.ambiguous + + def visit_erased_type(self, t: ErasedType) -> bool: + # This can happen inside a lambda. + return True + + def visit_type_var(self, t: TypeVarType) -> bool: + # This is needed to prevent leaking into partial types during + # multi-step type inference. + return t.id.is_meta_var() + + def visit_tuple_type(self, t: TupleType, /) -> bool: + # Exclude fallback to avoid bogus "need type annotation" errors + return self.query_types(t.items) + + +class SetNothingToAny(TypeTranslator): + """Replace all ambiguous Uninhabited types with Any (to avoid spurious extra errors).""" + + def visit_uninhabited_type(self, t: UninhabitedType) -> Type: + if t.ambiguous: + return AnyType(TypeOfAny.from_error) + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # Target of the alias cannot be an ambiguous UninhabitedType, so we just + # replace the arguments. + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def is_classmethod_node(node: SymbolNode | None) -> bool | None: + """Find out if a node describes a classmethod.""" + if isinstance(node, Decorator): + node = node.func + if isinstance(node, FuncDef): + return node.is_class + if isinstance(node, Var): + return node.is_classmethod + return None + + +def is_node_static(node: SymbolNode | None) -> bool | None: + """Find out if a node describes a static function method.""" + if isinstance(node, Decorator): + node = node.func + if isinstance(node, FuncDef): + return node.is_static + if isinstance(node, Var): + return node.is_staticmethod + return None + + +TKey = TypeVar("TKey") +TValue = TypeVar("TValue") + + +class DisjointDict(Generic[TKey, TValue]): + """An variation of the union-find algorithm/data structure where instead of keeping + track of just disjoint sets, we keep track of disjoint dicts -- keep track of multiple + Set[Key] -> Set[Value] mappings, where each mapping's keys are guaranteed to be disjoint. + + This data structure is currently used exclusively by 'group_comparison_operands' below + to merge chains of '==' and 'is' comparisons when two or more chains use the same expression + in best-case O(n), where n is the number of operands. + + Specifically, the `add_mapping()` function and `items()` functions will take on average + O(k + v) and O(n) respectively, where k and v are the number of keys and values we're adding + for a given chain. Note that k <= n and v <= n. + + We hit these average/best-case scenarios for most user code: e.g. when the user has just + a single chain like 'a == b == c == d == ...' or multiple disjoint chains like + 'a==b < c==d < e==f < ...'. (Note that a naive iterative merging would be O(n^2) for + the latter case). + + In comparison, this data structure will make 'group_comparison_operands' have a worst-case + runtime of O(n*log(n)): 'add_mapping()' and 'items()' are worst-case O(k*log(n) + v) and + O(k*log(n)) respectively. This happens only in the rare case where the user keeps repeatedly + making disjoint mappings before merging them in a way that persistently dodges the path + compression optimization in '_lookup_root_id', which would end up constructing a single + tree of height log_2(n). This makes root lookups no longer amoritized constant time when we + finally call 'items()'. + """ + + def __init__(self) -> None: + # Each key maps to a unique ID + self._key_to_id: dict[TKey, int] = {} + + # Each id points to the parent id, forming a forest of upwards-pointing trees. If the + # current id already is the root, it points to itself. We gradually flatten these trees + # as we perform root lookups: eventually all nodes point directly to its root. + self._id_to_parent_id: dict[int, int] = {} + + # Each root id in turn maps to the set of values. + self._root_id_to_values: dict[int, set[TValue]] = {} + + def add_mapping(self, keys: set[TKey], values: set[TValue]) -> None: + """Adds a 'Set[TKey] -> Set[TValue]' mapping. If there already exists a mapping + containing one or more of the given keys, we merge the input mapping with the old one. + + Note that the given set of keys must be non-empty -- otherwise, nothing happens. + """ + if not keys: + return + + subtree_roots = [self._lookup_or_make_root_id(key) for key in keys] + new_root = subtree_roots[0] + + root_values = self._root_id_to_values[new_root] + root_values.update(values) + for subtree_root in subtree_roots[1:]: + if subtree_root == new_root or subtree_root not in self._root_id_to_values: + continue + self._id_to_parent_id[subtree_root] = new_root + root_values.update(self._root_id_to_values.pop(subtree_root)) + + def items(self) -> list[tuple[set[TKey], set[TValue]]]: + """Returns all disjoint mappings in key-value pairs.""" + root_id_to_keys: dict[int, set[TKey]] = {} + for key in self._key_to_id: + root_id = self._lookup_root_id(key) + if root_id not in root_id_to_keys: + root_id_to_keys[root_id] = set() + root_id_to_keys[root_id].add(key) + + output = [] + for root_id, keys in root_id_to_keys.items(): + output.append((keys, self._root_id_to_values[root_id])) + + return output + + def _lookup_or_make_root_id(self, key: TKey) -> int: + if key in self._key_to_id: + return self._lookup_root_id(key) + else: + new_id = len(self._key_to_id) + self._key_to_id[key] = new_id + self._id_to_parent_id[new_id] = new_id + self._root_id_to_values[new_id] = set() + return new_id + + def _lookup_root_id(self, key: TKey) -> int: + i = self._key_to_id[key] + while i != self._id_to_parent_id[i]: + # Optimization: make keys directly point to their grandparents to speed up + # future traversals. This prevents degenerate trees of height n from forming. + new_parent = self._id_to_parent_id[self._id_to_parent_id[i]] + self._id_to_parent_id[i] = new_parent + i = new_parent + return i + + +def group_comparison_operands( + pairwise_comparisons: Iterable[tuple[str, Expression, Expression]], + operand_to_literal_hash: Mapping[int, Key], + operators_to_group: set[str], +) -> list[tuple[str, list[int]]]: + """Group a series of comparison operands together chained by any operand + in the 'operators_to_group' set. All other pairwise operands are kept in + groups of size 2. + + For example, suppose we have the input comparison expression: + + x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8 + + If we get these expressions in a pairwise way (e.g. by calling ComparisonExpr's + 'pairwise()' method), we get the following as input: + + [('==', x0, x1), ('==', x1, x2), ('<', x2, x3), ('<', x3, x4), + ('is', x4, x5), ('is', x5, x6), ('is not', x6, x7), ('is not', x7, x8)] + + If `operators_to_group` is the set {'==', 'is'}, this function will produce + the following "simplified operator list": + + [("==", [0, 1, 2]), ("<", [2, 3]), ("<", [3, 4]), + ("is", [4, 5, 6]), ("is not", [6, 7]), ("is not", [7, 8])] + + Note that (a) we yield *indices* to the operands rather then the operand + expressions themselves and that (b) operands used in a consecutive chain + of '==' or 'is' are grouped together. + + If two of these chains happen to contain operands with the same underlying + literal hash (e.g. are assignable and correspond to the same expression), + we combine those chains together. For example, if we had: + + same == x < y == same + + ...and if 'operand_to_literal_hash' contained the same values for the indices + 0 and 3, we'd produce the following output: + + [("==", [0, 1, 2, 3]), ("<", [1, 2])] + + But if the 'operand_to_literal_hash' did *not* contain an entry, we'd instead + default to returning: + + [("==", [0, 1]), ("<", [1, 2]), ("==", [2, 3])] + + This function is currently only used to assist with type-narrowing refinements + and is extracted out to a helper function so we can unit test it. + """ + groups: dict[str, DisjointDict[Key, int]] = {op: DisjointDict() for op in operators_to_group} + + simplified_operator_list: list[tuple[str, list[int]]] = [] + last_operator: str | None = None + current_indices: set[int] = set() + current_hashes: set[Key] = set() + for i, (operator, left_expr, right_expr) in enumerate(pairwise_comparisons): + if last_operator is None: + last_operator = operator + + if current_indices and (operator != last_operator or operator not in operators_to_group): + # If some of the operands in the chain are assignable, defer adding it: we might + # end up needing to merge it with other chains that appear later. + if not current_hashes: + simplified_operator_list.append((last_operator, sorted(current_indices))) + else: + groups[last_operator].add_mapping(current_hashes, current_indices) + last_operator = operator + current_indices = set() + current_hashes = set() + + # Note: 'i' corresponds to the left operand index, so 'i + 1' is the + # right operand. + current_indices.add(i) + current_indices.add(i + 1) + + # We only ever want to combine operands/combine chains for these operators + if operator in operators_to_group: + left_hash = operand_to_literal_hash.get(i) + if left_hash is not None: + current_hashes.add(left_hash) + right_hash = operand_to_literal_hash.get(i + 1) + if right_hash is not None: + current_hashes.add(right_hash) + + if last_operator is not None: + if not current_hashes: + simplified_operator_list.append((last_operator, sorted(current_indices))) + else: + groups[last_operator].add_mapping(current_hashes, current_indices) + + # Now that we know which chains happen to contain the same underlying expressions + # and can be merged together, add in this info back to the output. + for operator, disjoint_dict in groups.items(): + for keys, indices in disjoint_dict.items(): + simplified_operator_list.append((operator, sorted(indices))) + + # For stability, reorder list by the first operand index to appear + simplified_operator_list.sort(key=lambda item: item[1][0]) + return simplified_operator_list + + +def is_typed_callable(c: Type | None) -> bool: + c = get_proper_type(c) + if not c or not isinstance(c, CallableType): + return False + return not all( + isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated + for t in get_proper_types(c.arg_types + [c.ret_type]) + ) + + +def is_untyped_decorator(typ: Type | None) -> bool: + typ = get_proper_type(typ) + if not typ: + return True + elif isinstance(typ, CallableType): + return not is_typed_callable(typ) + elif isinstance(typ, Instance): + method = typ.type.get_method("__call__") + if method: + if isinstance(method, Decorator): + return is_untyped_decorator(method.func.type) or is_untyped_decorator( + method.var.type + ) + + if isinstance(method.type, Overloaded): + return any(is_untyped_decorator(item) for item in method.type.items) + else: + return not is_typed_callable(method.type) + else: + return False + elif isinstance(typ, Overloaded): + return any(is_untyped_decorator(item) for item in typ.items) + return True + + +def is_static(func: FuncBase | Decorator) -> bool: + if isinstance(func, Decorator): + return is_static(func.func) + elif isinstance(func, FuncBase): + return func.is_static + assert False, f"Unexpected func type: {type(func)}" + + +def is_property(defn: SymbolNode) -> bool: + if isinstance(defn, FuncDef): + return defn.is_property + if isinstance(defn, Decorator): + return defn.func.is_property + if isinstance(defn, OverloadedFuncDef): + if defn.items and isinstance(defn.items[0], Decorator): + return defn.items[0].func.is_property + return False + + +def is_settable_property(defn: SymbolNode | None) -> TypeGuard[OverloadedFuncDef]: + if isinstance(defn, OverloadedFuncDef): + if defn.items and isinstance(defn.items[0], Decorator): + return defn.items[0].func.is_property + return False + + +def is_custom_settable_property(defn: SymbolNode | None) -> bool: + """Check if a node is a settable property with a non-trivial setter type. + + By non-trivial here we mean that it is known (i.e. definition was already type + checked), it is not Any, and it is different from the property getter type. + """ + if defn is None: + return False + if not is_settable_property(defn): + return False + first_item = defn.items[0] + assert isinstance(first_item, Decorator) + if not first_item.var.is_settable_property: + return False + var = first_item.var + if var.type is None or var.setter_type is None or isinstance(var.type, PartialType): + # The caller should defer in case of partial types or not ready variables. + return False + setter_type = var.setter_type.arg_types[1] + if isinstance(get_proper_type(setter_type), AnyType): + return False + return not is_same_type(get_property_type(get_proper_type(var.type)), setter_type) + + +def get_property_type(t: ProperType) -> ProperType: + if isinstance(t, CallableType): + return get_proper_type(t.ret_type) + if isinstance(t, Overloaded): + return get_proper_type(t.items[0].ret_type) + return t + + +def is_subset_no_promote(left: Type, right: Type) -> bool: + return is_subtype(left, right, ignore_promotions=True, always_covariant=True) + + +def is_overlapping_types_for_overload(left: Type, right: Type) -> bool: + # Note that among other effects 'overlap_for_overloads' flag will effectively + # ignore possible overlap between type variables and None. This is technically + # unsafe, but unsafety is tiny and this prevents some common use cases like: + # @overload + # def foo(x: None) -> None: .. + # @overload + # def foo(x: T) -> Foo[T]: ... + return is_overlapping_types(left, right, ignore_promotions=True, overlap_for_overloads=True) + + +def is_private(node_name: str) -> bool: + """Check if node is private to class definition.""" + return node_name.startswith("__") and not node_name.endswith("__") + + +def is_string_literal(typ: Type) -> bool: + strs = try_getting_str_literals_from_type(typ) + return strs is not None and len(strs) == 1 + + +def has_bool_item(typ: ProperType) -> bool: + """Return True if type is 'bool' or a union with a 'bool' item.""" + if is_named_instance(typ, "builtins.bool"): + return True + if isinstance(typ, UnionType): + return any(is_named_instance(item, "builtins.bool") for item in typ.items) + return False + + +def collapse_walrus(e: Expression) -> Expression: + """If an expression is an AssignmentExpr, pull out the assignment target. + + We don't make any attempt to pull out all the targets in code like `x := (y := z)`. + We could support narrowing those if that sort of code turns out to be common. + """ + if isinstance(e, AssignmentExpr): + return e.target + return e + + +def find_last_var_assignment_line(n: Node, v: Var) -> int: + """Find the highest line number of a potential assignment to variable within node. + + This supports local and global variables. + + Return -1 if no assignment was found. + """ + visitor = VarAssignVisitor(v) + n.accept(visitor) + return visitor.last_line + + +class VarAssignVisitor(TraverserVisitor): + def __init__(self, v: Var) -> None: + self.last_line = -1 + self.lvalue = False + self.var_node = v + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + self.lvalue = True + for lv in s.lvalues: + lv.accept(self) + self.lvalue = False + + def visit_name_expr(self, e: NameExpr) -> None: + if self.lvalue and e.node is self.var_node: + self.last_line = max(self.last_line, e.line) + + def visit_member_expr(self, e: MemberExpr) -> None: + old_lvalue = self.lvalue + self.lvalue = False + super().visit_member_expr(e) + self.lvalue = old_lvalue + + def visit_index_expr(self, e: IndexExpr) -> None: + old_lvalue = self.lvalue + self.lvalue = False + super().visit_index_expr(e) + self.lvalue = old_lvalue + + def visit_with_stmt(self, s: WithStmt) -> None: + self.lvalue = True + for lv in s.target: + if lv is not None: + lv.accept(self) + self.lvalue = False + s.body.accept(self) + + def visit_for_stmt(self, s: ForStmt) -> None: + self.lvalue = True + s.index.accept(self) + self.lvalue = False + s.body.accept(self) + if s.else_body: + s.else_body.accept(self) + + def visit_assignment_expr(self, e: AssignmentExpr) -> None: + self.lvalue = True + e.target.accept(self) + self.lvalue = False + e.value.accept(self) + + def visit_as_pattern(self, p: AsPattern) -> None: + if p.pattern is not None: + p.pattern.accept(self) + if p.name is not None: + self.lvalue = True + p.name.accept(self) + self.lvalue = False + + def visit_starred_pattern(self, p: StarredPattern) -> None: + if p.capture is not None: + self.lvalue = True + p.capture.accept(self) + self.lvalue = False + + +def ambiguous_enum_equality_keys(t: Type) -> set[str]: + """ + Used when narrowing types based on equality. + + Certain kinds of enums can compare equal to values of other types, so doing type math + the way `conditional_types` does will be misleading if you expect it to correspond to + conditions based on equality comparisons. + + For example, StrEnum classes can compare equal to str values. So if we see + `val: StrEnum; if val == "foo": ...` we currently avoid narrowing. + Note that we do wish to continue narrowing for `if val == StrEnum.MEMBER: ...` + """ + # We need these things for this to be ambiguous: + # (1) an IntEnum or StrEnum type or enum subclass of int or str + # (2) either a different IntEnum/StrEnum type or a non-enum type ("") + result = set() + t = get_proper_type(t) + if isinstance(t, UnionType): + for item in t.items: + result.update(ambiguous_enum_equality_keys(item)) + elif isinstance(t, Instance): + if t.last_known_value: + result.update(ambiguous_enum_equality_keys(t.last_known_value)) + elif t.type.is_enum and any( + base.fullname in ("enum.IntEnum", "enum.StrEnum", "builtins.str", "builtins.int") + for base in t.type.mro + ): + result.add(t.type.fullname) + elif not t.type.is_enum: + # These might compare equal to IntEnum/StrEnum types (e.g. Decimal), so + # let's be conservative + result.add("") + elif isinstance(t, LiteralType): + result.update(ambiguous_enum_equality_keys(t.fallback)) + elif isinstance(t, NoneType): + pass + else: + result.add("") + return result + + +def is_typeddict_type_context(lvalue_type: Type) -> bool: + lvalue_type = get_proper_type(lvalue_type) + if isinstance(lvalue_type, TypedDictType): + return True + if isinstance(lvalue_type, UnionType): + for item in lvalue_type.items: + if is_typeddict_type_context(item): + return True + return False + + +def is_method(node: SymbolNode | None) -> bool: + if isinstance(node, OverloadedFuncDef): + return not node.is_property + if isinstance(node, Decorator): + return not node.var.is_property + return isinstance(node, FuncDef) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_shared.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_shared.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..968ea9ddf54d975c639423294ea298bc140f759b Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_shared.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_shared.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..55d9e15764178f8599b9f366b8879d37069afbc2 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_shared.py @@ -0,0 +1,365 @@ +"""Shared definitions used by different parts of type checker.""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Iterator, Sequence, Set as AbstractSet +from contextlib import contextmanager +from typing import NamedTuple, overload + +from mypy_extensions import trait + +from mypy.errorcodes import ErrorCode +from mypy.errors import ErrorWatcher +from mypy.message_registry import ErrorMessage +from mypy.nodes import ( + ArgKind, + Context, + Expression, + FuncItem, + LambdaExpr, + MypyFile, + Node, + RefExpr, + SymbolNode, + TypeInfo, + Var, +) +from mypy.plugin import CheckerPluginInterface, Plugin +from mypy.types import ( + CallableType, + Instance, + LiteralValue, + Overloaded, + PartialType, + TupleType, + Type, + TypedDictType, + TypeType, +) +from mypy.typevars import fill_typevars + + +# An object that represents either a precise type or a type with an upper bound; +# it is important for correct type inference with isinstance. +class TypeRange(NamedTuple): + item: Type + is_upper_bound: bool # False => precise type + + +@trait +class ExpressionCheckerSharedApi: + @abstractmethod + def accept( + self, + node: Expression, + type_context: Type | None = None, + allow_none_return: bool = False, + always_allow_any: bool = False, + is_callee: bool = False, + ) -> Type: + raise NotImplementedError + + @abstractmethod + def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type: + raise NotImplementedError + + @abstractmethod + def check_call( + self, + callee: Type, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + arg_names: Sequence[str | None] | None = None, + callable_node: Expression | None = None, + callable_name: str | None = None, + object_type: Type | None = None, + original_type: Type | None = None, + ) -> tuple[Type, Type]: + raise NotImplementedError + + @abstractmethod + def transform_callee_type( + self, + callable_name: str | None, + callee: Type, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + arg_names: Sequence[str | None] | None = None, + object_type: Type | None = None, + ) -> Type: + raise NotImplementedError + + @abstractmethod + def method_fullname(self, object_type: Type, method_name: str) -> str | None: + raise NotImplementedError + + @abstractmethod + def check_method_call_by_name( + self, + method: str, + base_type: Type, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + original_type: Type | None = None, + ) -> tuple[Type, Type]: + raise NotImplementedError + + @abstractmethod + def visit_typeddict_index_expr( + self, td_type: TypedDictType, index: Expression, setitem: bool = False + ) -> tuple[Type, set[str]]: + raise NotImplementedError + + @abstractmethod + def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type: + raise NotImplementedError + + @abstractmethod + def analyze_static_reference( + self, + node: SymbolNode, + ctx: Context, + is_lvalue: bool, + *, + include_modules: bool = True, + suppress_errors: bool = False, + ) -> Type: + raise NotImplementedError + + +@trait +class TypeCheckerSharedApi(CheckerPluginInterface): + plugin: Plugin + module_refs: set[str] + scope: CheckerScope + checking_missing_await: bool + allow_constructor_cache: bool + + @property + @abstractmethod + def expr_checker(self) -> ExpressionCheckerSharedApi: + raise NotImplementedError + + @abstractmethod + def named_type(self, name: str) -> Instance: + raise NotImplementedError + + @abstractmethod + def lookup_typeinfo(self, fullname: str) -> TypeInfo: + raise NotImplementedError + + @abstractmethod + def lookup_type(self, node: Expression) -> Type: + raise NotImplementedError + + @abstractmethod + def handle_cannot_determine_type(self, name: str, context: Context) -> None: + raise NotImplementedError + + @abstractmethod + def handle_partial_var_type( + self, typ: PartialType, is_lvalue: bool, node: Var, context: Context + ) -> Type: + raise NotImplementedError + + @overload + @abstractmethod + def check_subtype( + self, + subtype: Type, + supertype: Type, + context: Context, + msg: str, + subtype_label: str | None = None, + supertype_label: str | None = None, + *, + notes: list[str] | None = None, + code: ErrorCode | None = None, + outer_context: Context | None = None, + ) -> bool: ... + + @overload + @abstractmethod + def check_subtype( + self, + subtype: Type, + supertype: Type, + context: Context, + msg: ErrorMessage, + subtype_label: str | None = None, + supertype_label: str | None = None, + *, + notes: list[str] | None = None, + outer_context: Context | None = None, + ) -> bool: ... + + # Unfortunately, mypyc doesn't support abstract overloads yet. + @abstractmethod + def check_subtype( + self, + subtype: Type, + supertype: Type, + context: Context, + msg: str | ErrorMessage, + subtype_label: str | None = None, + supertype_label: str | None = None, + *, + notes: list[str] | None = None, + code: ErrorCode | None = None, + outer_context: Context | None = None, + ) -> bool: + raise NotImplementedError + + @abstractmethod + def get_final_context(self) -> bool: + raise NotImplementedError + + @overload + @abstractmethod + def conditional_types_with_intersection( + self, + expr_type: Type, + type_ranges: list[TypeRange] | None, + ctx: Context, + default: None = None, + ) -> tuple[Type | None, Type | None]: ... + + @overload + @abstractmethod + def conditional_types_with_intersection( + self, expr_type: Type, type_ranges: list[TypeRange] | None, ctx: Context, default: Type + ) -> tuple[Type, Type]: ... + + # Unfortunately, mypyc doesn't support abstract overloads yet. + @abstractmethod + def conditional_types_with_intersection( + self, + expr_type: Type, + type_ranges: list[TypeRange] | None, + ctx: Context, + default: Type | None = None, + ) -> tuple[Type | None, Type | None]: + raise NotImplementedError + + @abstractmethod + def narrow_type_by_identity_equality( + self, + operator: str, + operands: list[Expression], + operand_types: list[Type], + expr_indices: list[int], + narrowable_indices: AbstractSet[int], + ) -> tuple[dict[Expression, Type] | None, dict[Expression, Type] | None]: + raise NotImplementedError + + @abstractmethod + def check_deprecated(self, node: Node | None, context: Context) -> None: + raise NotImplementedError + + @abstractmethod + def warn_deprecated(self, node: Node | None, context: Context) -> None: + raise NotImplementedError + + @abstractmethod + def type_is_iterable(self, type: Type) -> bool: + raise NotImplementedError + + @abstractmethod + def iterable_item_type( + self, it: Instance | CallableType | TypeType | Overloaded, context: Context + ) -> Type: + raise NotImplementedError + + @abstractmethod + @contextmanager + def checking_await_set(self) -> Iterator[None]: + raise NotImplementedError + + @abstractmethod + def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None: + raise NotImplementedError + + @abstractmethod + def add_any_attribute_to_type(self, typ: Type, name: str) -> Type: + raise NotImplementedError + + @abstractmethod + def is_defined_in_stub(self, typ: Instance, /) -> bool: + raise NotImplementedError + + +class CheckerScope: + # We keep two stacks combined, to maintain the relative order + stack: list[TypeInfo | FuncItem | MypyFile] + + def __init__(self, module: MypyFile) -> None: + self.stack = [module] + + def current_function(self) -> FuncItem | None: + for e in reversed(self.stack): + if isinstance(e, FuncItem): + return e + return None + + def top_level_function(self) -> FuncItem | None: + """Return top-level non-lambda function.""" + for e in self.stack: + if isinstance(e, FuncItem) and not isinstance(e, LambdaExpr): + return e + return None + + def active_class(self) -> TypeInfo | None: + if isinstance(self.stack[-1], TypeInfo): + return self.stack[-1] + return None + + def enclosing_class(self, func: FuncItem | None = None) -> TypeInfo | None: + """Is there a class *directly* enclosing this function?""" + func = func or self.current_function() + assert func, "This method must be called from inside a function" + index = self.stack.index(func) + assert index, "CheckerScope stack must always start with a module" + enclosing = self.stack[index - 1] + if isinstance(enclosing, TypeInfo): + return enclosing + return None + + def active_self_type(self) -> Instance | TupleType | None: + """An instance or tuple type representing the current class. + + This returns None unless we are in class body or in a method. + In particular, inside a function nested in method this returns None. + """ + info = self.active_class() + if not info and self.current_function(): + info = self.enclosing_class() + if info: + return fill_typevars(info) + return None + + def current_self_type(self) -> Instance | TupleType | None: + """Same as active_self_type() but handle functions nested in methods.""" + for item in reversed(self.stack): + if isinstance(item, TypeInfo): + return fill_typevars(item) + return None + + def is_top_level(self) -> bool: + """Is current scope top-level (no classes or functions)?""" + return len(self.stack) == 1 + + @contextmanager + def push_function(self, item: FuncItem) -> Iterator[None]: + self.stack.append(item) + yield + self.stack.pop() + + @contextmanager + def push_class(self, info: TypeInfo) -> Iterator[None]: + self.stack.append(info) + yield + self.stack.pop() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a74e59aac135afaa713e5e3d4f6020d3b055473a Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.py new file mode 100644 index 0000000000000000000000000000000000000000..9b988ad18ba4f7cc46e1946f8a6f2343da322084 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Final + +from mypy.checker_shared import TypeCheckerSharedApi + +# This is global mutable state. Don't add anything here unless there's a very +# good reason. + + +class TypeCheckerState: + # Wrap this in a class since it's faster that using a module-level attribute. + + def __init__(self, type_checker: TypeCheckerSharedApi | None) -> None: + # Value varies by file being processed + self.type_checker = type_checker + + @contextmanager + def set(self, value: TypeCheckerSharedApi) -> Iterator[None]: + saved = self.type_checker + self.type_checker = value + try: + yield + finally: + self.type_checker = saved + + +checker_state: Final = TypeCheckerState(type_checker=None) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkexpr.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkexpr.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f3430217062f83736c0a43cd760eb22ce8419ca7 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkexpr.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkexpr.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkexpr.py new file mode 100644 index 0000000000000000000000000000000000000000..84d8fa67fd177453f3dbb85c344e7a80fb981cd8 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkexpr.py @@ -0,0 +1,6904 @@ +"""Expression type checker. This file is conceptually part of TypeChecker.""" + +from __future__ import annotations + +import enum +import itertools +import time +from collections import defaultdict +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager, nullcontext +from typing import ClassVar, Final, TypeAlias as _TypeAlias, cast, overload +from typing_extensions import assert_never + +import mypy.checker +import mypy.errorcodes as codes +from mypy import applytype, erasetype, join, message_registry, nodes, operators, types +from mypy.argmap import ArgTypeExpander, map_actuals_to_formals, map_formals_to_actuals +from mypy.checker_shared import ExpressionCheckerSharedApi +from mypy.checkmember import analyze_member_access, has_operator +from mypy.checkstrformat import StringFormatterChecker +from mypy.constant_fold import constant_fold_expr +from mypy.erasetype import erase_type, remove_instance_last_known_values, replace_meta_vars +from mypy.errors import ErrorInfo, ErrorWatcher, report_internal_error +from mypy.expandtype import ( + expand_type, + expand_type_by_instance, + freshen_all_functions_type_vars, + freshen_function_type_vars, +) +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.infer import ArgumentInferContext, infer_function_type_arguments, infer_type_arguments +from mypy.literals import literal +from mypy.lookup import lookup_fully_qualified +from mypy.maptype import map_instance_to_supertype +from mypy.meet import is_overlapping_types, narrow_declared_type +from mypy.message_registry import ErrorMessage +from mypy.messages import MessageBuilder, format_type +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + ARG_STAR, + ARG_STAR2, + IMPLICITLY_ABSTRACT, + LAMBDA_NAME, + LITERAL_TYPE, + REVEAL_LOCALS, + REVEAL_TYPE, + UNBOUND_IMPORTED, + ArgKind, + AssertTypeExpr, + AssignmentExpr, + AwaitExpr, + BytesExpr, + CallExpr, + CastExpr, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + Context, + Decorator, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + FloatExpr, + FuncDef, + GeneratorExpr, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MaybeTypeExpression, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + NotParsed, + OpExpr, + OverloadedFuncDef, + ParamSpecExpr, + PlaceholderNode, + PromoteExpr, + RefExpr, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + StrExpr, + SuperExpr, + SymbolNode, + SymbolTableNode, + TemplateStrExpr, + TempNode, + TupleExpr, + TypeAlias, + TypeAliasExpr, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeInfo, + TypeVarExpr, + TypeVarLikeExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + YieldExpr, + YieldFromExpr, + get_member_expr_fullname, +) +from mypy.options import PRECISE_TUPLE_TYPES +from mypy.plugin import ( + FunctionContext, + FunctionSigContext, + MethodContext, + MethodSigContext, + Plugin, +) +from mypy.semanal_enum import ENUM_BASES +from mypy.state import state +from mypy.subtypes import ( + covers_at_runtime, + find_member, + is_equivalent, + is_same_type, + is_subtype, + non_method_protocol_members, +) +from mypy.traverser import ( + all_name_and_member_expressions, + has_await_expression, + has_str_expression, +) +from mypy.tvar_scope import TypeVarLikeScope +from mypy.typeanal import ( + TypeAnalyser, + check_for_explicit_any, + fix_instance, + has_any_from_unimported_type, + instantiate_type_alias, + make_optional_type, + set_any_tvars, + validate_instance, +) +from mypy.typeops import ( + callable_type, + custom_special_method, + erase_to_union_or_bound, + false_only, + fixup_partial_type, + freeze_all_type_vars, + function_type, + get_all_type_vars, + get_type_vars, + is_literal_type_like, + make_simplified_union, + true_only, + try_expanding_sum_type_to_union, + try_getting_str_literals, + tuple_fallback, + type_object_type, +) +from mypy.types import ( + LITERAL_TYPE_NAMES, + TUPLE_LIKE_INSTANCE_NAMES, + AnyType, + CallableType, + DeletedType, + ErasedType, + ExtraAttrs, + FunctionLike, + Instance, + LiteralType, + LiteralValue, + NoneType, + Overloaded, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + flatten_nested_tuples, + flatten_nested_unions, + get_proper_type, + get_proper_types, + has_recursive_types, + has_type_vars, + is_named_instance, + split_with_prefix_and_suffix, +) +from mypy.types_utils import ( + is_generic_instance, + is_overlapping_none, + is_self_type_like, + remove_optional, +) +from mypy.typestate import type_state +from mypy.typevars import fill_typevars +from mypy.visitor import ExpressionVisitor + +# Type of callback user for checking individual function arguments. See +# check_args() below for details. +ArgChecker: _TypeAlias = Callable[ + [Type, Type, ArgKind, Type, int, int, CallableType, Type | None, Context, Context], None +] + +# Maximum nesting level for math union in overloads, setting this to large values +# may cause performance issues. The reason is that although union math algorithm we use +# nicely captures most corner cases, its worst case complexity is exponential, +# see https://github.com/python/mypy/pull/5255#discussion_r196896335 for discussion. +MAX_UNIONS: Final = 5 + + +# Types considered safe for comparisons with --strict-equality due to known behaviour of __eq__. +# NOTE: All these types are subtypes of AbstractSet. +OVERLAPPING_TYPES_ALLOWLIST: Final = [ + "builtins.set", + "builtins.frozenset", + "typing.KeysView", + "typing.ItemsView", + "_collections_abc.dict_keys", + "_collections_abc.dict_items", +] +OVERLAPPING_BYTES_ALLOWLIST: Final = { + "builtins.bytes", + "builtins.bytearray", + "builtins.memoryview", +} + + +class TooManyUnions(Exception): + """Indicates that we need to stop splitting unions in an attempt + to match an overload in order to save performance. + """ + + +def allow_fast_container_literal(t: Type) -> bool: + if isinstance(t, TypeAliasType) and t.is_recursive: + return False + t = get_proper_type(t) + return isinstance(t, Instance) or ( + isinstance(t, TupleType) and all(allow_fast_container_literal(it) for it in t.items) + ) + + +class Finished(Exception): + """Raised if we can terminate overload argument check early (no match).""" + + +@enum.unique +class UseReverse(enum.Enum): + """Used in `visit_op_expr` to enable or disable reverse method checks.""" + + DEFAULT = 0 + ALWAYS = 1 + NEVER = 2 + + +USE_REVERSE_DEFAULT: Final = UseReverse.DEFAULT +USE_REVERSE_ALWAYS: Final = UseReverse.ALWAYS +USE_REVERSE_NEVER: Final = UseReverse.NEVER + + +class ExpressionChecker(ExpressionVisitor[Type], ExpressionCheckerSharedApi): + """Expression type checker. + + This class works closely together with checker.TypeChecker. + """ + + # Some services are provided by a TypeChecker instance. + chk: mypy.checker.TypeChecker + # This is shared with TypeChecker, but stored also here for convenience. + msg: MessageBuilder + # Type context for type inference + type_context: list[Type | None] + + strfrm_checker: StringFormatterChecker + plugin: Plugin + + _arg_infer_context_cache: ArgumentInferContext | None + + def __init__( + self, + chk: mypy.checker.TypeChecker, + msg: MessageBuilder, + plugin: Plugin, + per_line_checking_time_ns: dict[int, int], + ) -> None: + """Construct an expression type checker.""" + self.chk = chk + self.msg = msg + self.plugin = plugin + self.per_line_checking_time_ns = per_line_checking_time_ns + self.collect_line_checking_stats = chk.options.line_checking_stats is not None + # Are we already visiting some expression? This is used to avoid double counting + # time for nested expressions. + self.in_expression = False + self.type_context = [None] + + # Temporary overrides for expression types. This is currently + # used by the union math in overloads. + # TODO: refactor this to use a pattern similar to one in + # multiassign_from_union, or maybe even combine the two? + self.type_overrides: dict[Expression, Type] = {} + self.strfrm_checker = StringFormatterChecker(self.chk, self.msg) + + # Callee in a call expression is in some sense both runtime context and + # type context, because we support things like C[int](...). Store information + # on whether current expression is a callee, to give better error messages + # related to type context. + self.is_callee = False + type_state.infer_polymorphic = not self.chk.options.old_type_inference + + self._arg_infer_context_cache = None + self.expr_cache: dict[ + tuple[Expression, Type | None], + tuple[int, Type, list[ErrorInfo], dict[Expression, Type]], + ] = {} + self.in_lambda_expr = False + + self._literal_true: Instance | None = None + self._literal_false: Instance | None = None + + def reset(self) -> None: + self.expr_cache.clear() + + def visit_name_expr(self, e: NameExpr) -> Type: + """Type check a name expression. + + It can be of any kind: local, member or global. + """ + result = self.analyze_ref_expr(e) + narrowed = self.narrow_type_from_binder(e, result) + self.chk.check_deprecated(e.node, e) + return narrowed + + def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type: + result: Type | None = None + node = e.node + + if isinstance(e, NameExpr) and e.is_special_form: + # A special form definition, nothing to check here. + return AnyType(TypeOfAny.special_form) + + if isinstance(node, Var): + # Variable reference. + result = self.analyze_var_ref(node, e) + if isinstance(result, PartialType): + result = self.chk.handle_partial_var_type(result, lvalue, node, e) + elif isinstance(node, Decorator): + result = self.analyze_var_ref(node.var, e) + elif isinstance(node, OverloadedFuncDef): + if node.type is None: + if self.chk.in_checked_function() and node.items: + self.chk.handle_cannot_determine_type(node.name, e) + result = AnyType(TypeOfAny.from_error) + else: + result = node.type + elif isinstance(node, (FuncDef, TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)): + result = self.analyze_static_reference(node, e, e.is_alias_rvalue or lvalue) + else: + if isinstance(node, PlaceholderNode): + assert False, f"PlaceholderNode {node.fullname!r} leaked to checker" + # Unknown reference; use any type implicitly to avoid + # generating extra type errors. + result = AnyType(TypeOfAny.from_error) + if isinstance(node, TypeInfo): + if isinstance(result, CallableType) and isinstance( # type: ignore[misc] + result.ret_type, Instance + ): + # We need to set correct line and column + # TODO: always do this in type_object_type by passing the original context + result.ret_type.line = e.line + result.ret_type.column = e.column + if is_type_type_context(self.type_context[-1]): + # This is the type in a type[] expression, so substitute type + # variables with Any. + result = erasetype.erase_typevars(result) + assert result is not None + return result + + def analyze_static_reference( + self, + node: SymbolNode, + ctx: Context, + is_lvalue: bool, + *, + include_modules: bool = True, + suppress_errors: bool = False, + ) -> Type: + """ + This is the version of analyze_ref_expr() that doesn't do any deferrals. + + This function can be used by member access to "static" attributes. For example, + when accessing module attributes in protocol checks, or accessing attributes of + special kinds (like TypeAlias, TypeInfo, etc.) on an instance or class object. + # TODO: merge with analyze_ref_expr() when we are confident about performance. + """ + if isinstance(node, (Var, Decorator, OverloadedFuncDef)): + return node.type or AnyType(TypeOfAny.special_form) + elif isinstance(node, FuncDef): + return function_type(node, self.named_type("builtins.function")) + elif isinstance(node, TypeInfo): + # Reference to a type object. + if node.typeddict_type: + # We special-case TypedDict, because they don't define any constructor. + return self.typeddict_callable(node) + elif node.fullname == "types.NoneType": + # We special case NoneType, because its stub definition is not related to None. + return TypeType(NoneType()) + else: + return type_object_type(node, self.named_type) + elif isinstance(node, TypeAlias): + # Something that refers to a type alias appears in runtime context. + # Note that we suppress bogus errors for alias redefinitions, + # they are already reported in semanal.py. + with self.msg.filter_errors() if suppress_errors else nullcontext(): + return self.alias_type_in_runtime_context( + node, ctx=ctx, alias_definition=is_lvalue + ) + elif isinstance(node, TypeVarExpr): + return self.named_type("typing.TypeVar") + elif isinstance(node, (ParamSpecExpr, TypeVarTupleExpr)): + return self.object_type() + elif isinstance(node, MypyFile): + # Reference to a module object. + return self.module_type(node) if include_modules else AnyType(TypeOfAny.special_form) + return AnyType(TypeOfAny.from_error) + + def analyze_var_ref(self, var: Var, context: Context) -> Type: + if var.type: + var_type = get_proper_type(var.type) + if isinstance(var_type, Instance): + if var.fullname == "typing.Any": + # The typeshed type is 'object'; give a more useful type in runtime context + return self.named_type("typing._SpecialForm") + if self.is_literal_context() and var_type.last_known_value is not None: + return var_type.last_known_value + if var.name in {"True", "False"}: + return self.infer_literal_expr_type(var.name == "True", "builtins.bool") + return var.type + else: + if not var.is_ready and self.chk.in_checked_function(): + self.chk.handle_cannot_determine_type(var.name, context) + # Implicit 'Any' type. + return AnyType(TypeOfAny.special_form) + + def module_type(self, node: MypyFile) -> Instance: + try: + result = self.named_type("types.ModuleType") + except KeyError: + # In test cases might 'types' may not be available. + # Fall back to a dummy 'object' type instead to + # avoid a crash. + # Make a copy so that we don't set extra_attrs (below) on a shared instance. + result = self.named_type("builtins.object").copy_modified() + module_attrs: dict[str, Type] = {} + immutable = set() + for name, n in node.names.items(): + if not n.module_public: + continue + if isinstance(n.node, Var) and n.node.is_final: + immutable.add(name) + if n.node is None: + module_attrs[name] = AnyType(TypeOfAny.from_error) + else: + # TODO: what to do about nested module references? + # They are non-trivial because there may be import cycles. + module_attrs[name] = self.analyze_static_reference( + n.node, n.node, False, include_modules=False, suppress_errors=True + ) + result.extra_attrs = ExtraAttrs(module_attrs, immutable, node.fullname) + return result + + def visit_call_expr(self, e: CallExpr, allow_none_return: bool = False) -> Type: + """Type check a call expression.""" + if e.analyzed: + if isinstance(e.analyzed, NamedTupleExpr) and not e.analyzed.is_typed: + # Type check the arguments, but ignore the results. This relies + # on the typeshed stubs to type check the arguments. + self.visit_call_expr_inner(e) + # It's really a special form that only looks like a call. + return self.accept(e.analyzed, self.type_context[-1]) + return self.visit_call_expr_inner(e, allow_none_return=allow_none_return) + + def refers_to_typeddict(self, base: Expression) -> bool: + if not isinstance(base, RefExpr): + return False + if isinstance(base.node, TypeInfo) and base.node.typeddict_type is not None: + # Direct reference. + return True + return isinstance(base.node, TypeAlias) and isinstance( + get_proper_type(base.node.target), TypedDictType + ) + + def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) -> Type: + if ( + self.refers_to_typeddict(e.callee) + or isinstance(e.callee, IndexExpr) + and self.refers_to_typeddict(e.callee.base) + ): + typeddict_callable = get_proper_type(self.accept(e.callee, is_callee=True)) + if isinstance(typeddict_callable, CallableType): + typeddict_type = get_proper_type(typeddict_callable.ret_type) + assert isinstance(typeddict_type, TypedDictType) + return self.check_typeddict_call( + typeddict_type, e.arg_kinds, e.arg_names, e.args, e, typeddict_callable + ) + if ( + isinstance(e.callee, NameExpr) + and e.callee.name in ("isinstance", "issubclass") + and len(e.args) == 2 + ): + for typ in mypy.checker.flatten(e.args[1]): + node = None + if isinstance(typ, NameExpr): + try: + node = self.chk.lookup_qualified(typ.name) + except KeyError: + # Undefined names should already be reported in semantic analysis. + pass + if is_expr_literal_type(typ): + self.msg.cannot_use_function_with_type(e.callee.name, "Literal", e) + continue + if node and isinstance(node.node, TypeAlias): + target = get_proper_type(node.node.target) + if isinstance(target, AnyType): + self.msg.cannot_use_function_with_type(e.callee.name, "Any", e) + continue + if isinstance(target, NoneType): + continue + if ( + isinstance(typ, IndexExpr) + and isinstance(typ.analyzed, (TypeApplication, TypeAliasExpr)) + ) or ( + isinstance(typ, NameExpr) + and node + and isinstance(node.node, TypeAlias) + and not node.node.no_args + and not ( + isinstance(union_target := get_proper_type(node.node.target), UnionType) + and ( + union_target.uses_pep604_syntax + or self.chk.options.python_version >= (3, 10) + ) + ) + ): + self.msg.type_arguments_not_allowed(e) + if isinstance(typ, RefExpr) and isinstance(typ.node, TypeInfo): + if typ.node.typeddict_type: + self.msg.cannot_use_function_with_type(e.callee.name, "TypedDict", e) + elif typ.node.is_newtype: + self.msg.cannot_use_function_with_type(e.callee.name, "NewType", e) + self.try_infer_partial_type(e) + type_context = None + if isinstance(e.callee, LambdaExpr): + formal_to_actual = map_actuals_to_formals( + e.arg_kinds, + e.arg_names, + e.callee.arg_kinds, + e.callee.arg_names, + lambda i: self.accept(e.args[i]), + ) + + arg_types = [ + join.join_type_list([self.accept(e.args[j]) for j in formal_to_actual[i]]) + for i in range(len(e.callee.arg_kinds)) + ] + type_context = CallableType( + arg_types, + e.callee.arg_kinds, + e.callee.arg_names, + ret_type=self.object_type(), + fallback=self.named_type("builtins.function"), + ) + callee_type = get_proper_type( + self.accept(e.callee, type_context, always_allow_any=True, is_callee=True) + ) + + # Figure out the full name of the callee for plugin lookup. + object_type = None + member = None + fullname = None + if isinstance(e.callee, RefExpr): + # There are two special cases where plugins might act: + # * A "static" reference/alias to a class or function; + # get_function_hook() will be invoked for these. + fullname = e.callee.fullname or None + if isinstance(e.callee.node, TypeAlias): + target = get_proper_type(e.callee.node.target) + if isinstance(target, Instance): + fullname = target.type.fullname + # * Call to a method on object that has a full name (see + # method_fullname() for details on supported objects); + # get_method_hook() and get_method_signature_hook() will + # be invoked for these. + if ( + not fullname + and isinstance(e.callee, MemberExpr) + and self.chk.has_type(e.callee.expr) + ): + member = e.callee.name + object_type = self.chk.lookup_type(e.callee.expr) + + if ( + self.chk.options.disallow_untyped_calls + and self.chk.in_checked_function() + and isinstance(callee_type, CallableType) + and callee_type.implicit + and callee_type.name != LAMBDA_NAME + ): + if fullname is None and member is not None: + assert object_type is not None + fullname = self.method_fullname(object_type, member) + if not fullname or not any( + fullname == p or fullname.startswith(f"{p}.") + for p in self.chk.options.untyped_calls_exclude + ): + self.msg.untyped_function_call(callee_type, e) + + ret_type = self.check_call_expr_with_callee_type( + callee_type, e, fullname, object_type, member + ) + if isinstance(e.callee, RefExpr) and len(e.args) == 2: + if e.callee.fullname in ("builtins.isinstance", "builtins.issubclass"): + self.check_runtime_protocol_test(e) + if e.callee.fullname == "builtins.issubclass": + self.check_protocol_issubclass(e) + if isinstance(e.callee, MemberExpr) and e.callee.name == "format": + self.check_str_format_call(e) + ret_type = get_proper_type(ret_type) + if isinstance(ret_type, UnionType): + ret_type = make_simplified_union(ret_type.items) + if isinstance(ret_type, UninhabitedType) and not ret_type.ambiguous: + self.chk.binder.unreachable() + # Warn on calls to functions that always return None. The check + # of ret_type is both a common-case optimization and prevents reporting + # the error in dynamic functions (where it will be Any). + if ( + not allow_none_return + and isinstance(ret_type, NoneType) + and self.always_returns_none(e.callee) + ): + self.chk.msg.does_not_return_value(callee_type, e) + return ret_type + + def check_str_format_call(self, e: CallExpr) -> None: + """More precise type checking for str.format() calls on literals and folded constants.""" + assert isinstance(e.callee, MemberExpr) + format_value = None + folded_callee_expr = constant_fold_expr(e.callee.expr, "") + if isinstance(folded_callee_expr, str): + format_value = folded_callee_expr + elif self.chk.has_type(e.callee.expr): + typ = get_proper_type(self.chk.lookup_type(e.callee.expr)) + if ( + isinstance(typ, Instance) + and typ.type.is_enum + and isinstance(typ.last_known_value, LiteralType) + and isinstance(typ.last_known_value.value, str) + ): + value_type = typ.type.names[typ.last_known_value.value].type + if isinstance(value_type, Type): + typ = get_proper_type(value_type) + base_typ = try_getting_literal(typ) + if isinstance(base_typ, LiteralType) and isinstance(base_typ.value, str): + format_value = base_typ.value + if format_value is not None: + self.strfrm_checker.check_str_format_call(e, format_value) + + def method_fullname(self, object_type: Type, method_name: str) -> str | None: + """Convert a method name to a fully qualified name, based on the type of the object that + it is invoked on. Return `None` if the name of `object_type` cannot be determined. + """ + object_type = get_proper_type(object_type) + + if isinstance(object_type, CallableType) and object_type.is_type_obj(): + # For class method calls, object_type is a callable representing the class object. + # We "unwrap" it to a regular type, as the class/instance method difference doesn't + # affect the fully qualified name. + object_type = get_proper_type(object_type.ret_type) + elif isinstance(object_type, TypeType): + object_type = object_type.item + + type_name = None + if isinstance(object_type, Instance): + type_name = object_type.type.fullname + elif isinstance(object_type, (TypedDictType, LiteralType)): + info = object_type.fallback.type.get_containing_type_info(method_name) + type_name = info.fullname if info is not None else None + elif isinstance(object_type, TupleType): + type_name = tuple_fallback(object_type).type.fullname + + if type_name: + return f"{type_name}.{method_name}" + else: + return None + + def always_returns_none(self, node: Expression) -> bool: + """Check if `node` refers to something explicitly annotated as only returning None.""" + if isinstance(node, RefExpr): + if self.defn_returns_none(node.node): + return True + if isinstance(node, MemberExpr) and node.node is None: # instance or class attribute + typ = get_proper_type(self.chk.lookup_type(node.expr)) + if isinstance(typ, Instance): + info = typ.type + elif isinstance(typ, CallableType) and typ.is_type_obj(): + ret_type = get_proper_type(typ.ret_type) + if isinstance(ret_type, Instance): + info = ret_type.type + else: + return False + else: + return False + sym = info.get(node.name) + if sym and self.defn_returns_none(sym.node): + return True + return False + + def defn_returns_none(self, defn: SymbolNode | None) -> bool: + """Check if `defn` can _only_ return None.""" + if isinstance(defn, FuncDef): + return isinstance(defn.type, CallableType) and isinstance( + get_proper_type(defn.type.ret_type), NoneType + ) + if isinstance(defn, OverloadedFuncDef): + return all(self.defn_returns_none(item) for item in defn.items) + if isinstance(defn, Var): + typ = get_proper_type(defn.type) + if ( + not defn.is_inferred + and isinstance(typ, CallableType) + and isinstance(get_proper_type(typ.ret_type), NoneType) + ): + return True + if isinstance(typ, Instance): + sym = typ.type.get("__call__") + if sym and self.defn_returns_none(sym.node): + return True + return False + + def check_runtime_protocol_test(self, e: CallExpr) -> None: + for expr in mypy.checker.flatten(e.args[1]): + tp = get_proper_type(self.chk.lookup_type(expr)) + if ( + isinstance(tp, FunctionLike) + and tp.is_type_obj() + and tp.type_object().is_protocol + and not tp.type_object().runtime_protocol + ): + self.chk.fail(message_registry.RUNTIME_PROTOCOL_EXPECTED, e) + + def check_protocol_issubclass(self, e: CallExpr) -> None: + for expr in mypy.checker.flatten(e.args[1]): + tp = get_proper_type(self.chk.lookup_type(expr)) + if isinstance(tp, FunctionLike) and tp.is_type_obj() and tp.type_object().is_protocol: + attr_members = non_method_protocol_members(tp.type_object()) + if attr_members: + self.chk.msg.report_non_method_protocol(tp.type_object(), attr_members, e) + + def check_typeddict_call( + self, + callee: TypedDictType, + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None], + args: list[Expression], + context: Context, + orig_callee: Type | None, + ) -> Type: + if args and all(ak in (ARG_NAMED, ARG_STAR2) for ak in arg_kinds): + # ex: Point(x=42, y=1337, **extras) + # This is a bit ugly, but this is a price for supporting all possible syntax + # variants for TypedDict constructors. + kwargs = zip([StrExpr(n) if n is not None else None for n in arg_names], args) + result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee) + if result is not None: + validated_kwargs, always_present_keys = result + return self.check_typeddict_call_with_kwargs( + callee, validated_kwargs, context, orig_callee, always_present_keys + ) + return AnyType(TypeOfAny.from_error) + + if len(args) == 1 and arg_kinds[0] == ARG_POS: + unique_arg = args[0] + if isinstance(unique_arg, DictExpr): + # ex: Point({'x': 42, 'y': 1337, **extras}) + return self.check_typeddict_call_with_dict( + callee, unique_arg.items, context, orig_callee + ) + if isinstance(unique_arg, CallExpr) and isinstance(unique_arg.analyzed, DictExpr): + # ex: Point(dict(x=42, y=1337, **extras)) + return self.check_typeddict_call_with_dict( + callee, unique_arg.analyzed.items, context, orig_callee + ) + + if not args: + # ex: EmptyDict() + return self.check_typeddict_call_with_kwargs(callee, {}, context, orig_callee, set()) + + self.chk.fail(message_registry.INVALID_TYPEDDICT_ARGS, context) + return AnyType(TypeOfAny.from_error) + + def validate_typeddict_kwargs( + self, kwargs: Iterable[tuple[Expression | None, Expression]], callee: TypedDictType + ) -> tuple[dict[str, list[Expression]], set[str]] | None: + # All (actual or mapped from ** unpacks) expressions that can match given key. + result = defaultdict(list) + # Keys that are guaranteed to be present no matter what (e.g. for all items of a union) + always_present_keys = set() + # Indicates latest encountered ** unpack among items. + last_star_found = None + + for item_name_expr, item_arg in kwargs: + if item_name_expr: + key_type = self.accept(item_name_expr) + values = try_getting_str_literals(item_name_expr, key_type) + literal_value = None + if values and len(values) == 1: + literal_value = values[0] + if literal_value is None: + key_context = item_name_expr or item_arg + self.chk.fail( + message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL, + key_context, + code=codes.LITERAL_REQ, + ) + return None + else: + # A directly present key unconditionally shadows all previously found + # values from ** items. + # TODO: for duplicate keys, type-check all values. + result[literal_value] = [item_arg] + always_present_keys.add(literal_value) + else: + last_star_found = item_arg + if not self.validate_star_typeddict_item( + item_arg, callee, result, always_present_keys + ): + return None + if self.chk.options.extra_checks and last_star_found is not None: + absent_keys = [] + for key in callee.items: + if key not in callee.required_keys and key not in result: + absent_keys.append(key) + if absent_keys: + # Having an optional key not explicitly declared by a ** unpacked + # TypedDict is unsafe, it may be an (incompatible) subtype at runtime. + # TODO: catch the cases where a declared key is overridden by a subsequent + # ** item without it (and not again overridden with complete ** item). + self.msg.non_required_keys_absent_with_star(absent_keys, last_star_found) + return result, always_present_keys + + def validate_star_typeddict_item( + self, + item_arg: Expression, + callee: TypedDictType, + result: dict[str, list[Expression]], + always_present_keys: set[str], + ) -> bool: + """Update keys/expressions from a ** expression in TypedDict constructor. + + Note `result` and `always_present_keys` are updated in place. Return true if the + expression `item_arg` may valid in `callee` TypedDict context. + """ + inferred = get_proper_type(self.accept(item_arg, type_context=callee)) + possible_tds = [] + if isinstance(inferred, TypedDictType): + possible_tds = [inferred] + elif isinstance(inferred, UnionType): + for item in get_proper_types(inferred.relevant_items()): + if isinstance(item, TypedDictType): + possible_tds.append(item) + elif not self.valid_unpack_fallback_item(item): + self.msg.unsupported_target_for_star_typeddict(item, item_arg) + return False + elif not self.valid_unpack_fallback_item(inferred): + self.msg.unsupported_target_for_star_typeddict(inferred, item_arg) + return False + all_keys: set[str] = set() + for td in possible_tds: + all_keys |= td.items.keys() + for key in all_keys: + arg = TempNode( + UnionType.make_union([td.items[key] for td in possible_tds if key in td.items]) + ) + arg.set_line(item_arg) + if all(key in td.required_keys for td in possible_tds): + always_present_keys.add(key) + # Always present keys override previously found values. This is done + # to support use cases like `Config({**defaults, **overrides})`, where + # some `overrides` types are narrower that types in `defaults`, and + # former are too wide for `Config`. + if result[key]: + first = result[key][0] + if not isinstance(first, TempNode): + # We must always preserve any non-synthetic values, so that + # we will accept them even if they are shadowed. + result[key] = [first, arg] + else: + result[key] = [arg] + else: + result[key] = [arg] + else: + # If this key is not required at least in some item of a union + # it may not shadow previous item, so we need to type check both. + result[key].append(arg) + return True + + def valid_unpack_fallback_item(self, typ: ProperType) -> bool: + if isinstance(typ, AnyType): + return True + if not isinstance(typ, Instance) or not typ.type.has_base("typing.Mapping"): + return False + mapped = map_instance_to_supertype(typ, self.chk.lookup_typeinfo("typing.Mapping")) + return all(isinstance(a, AnyType) for a in get_proper_types(mapped.args)) + + def match_typeddict_call_with_dict( + self, + callee: TypedDictType, + kwargs: list[tuple[Expression | None, Expression]], + context: Context, + ) -> bool: + result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee) + if result is not None: + validated_kwargs, _ = result + return callee.required_keys <= set(validated_kwargs.keys()) <= set(callee.items.keys()) + else: + return False + + def check_typeddict_call_with_dict( + self, + callee: TypedDictType, + kwargs: list[tuple[Expression | None, Expression]], + context: Context, + orig_callee: Type | None, + ) -> Type: + result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee) + if result is not None: + validated_kwargs, always_present_keys = result + return self.check_typeddict_call_with_kwargs( + callee, + kwargs=validated_kwargs, + context=context, + orig_callee=orig_callee, + always_present_keys=always_present_keys, + ) + else: + return AnyType(TypeOfAny.from_error) + + def typeddict_callable(self, info: TypeInfo) -> CallableType: + """Construct a reasonable type for a TypedDict type in runtime context. + + If it appears as a callee, it will be special-cased anyway, e.g. it is + also allowed to accept a single positional argument if it is a dict literal. + + Note it is not safe to move this to type_object_type() since it will crash + on plugin-generated TypedDicts, that may not have the special_alias. + """ + assert info.special_alias is not None + target = info.special_alias.target + assert isinstance(target, ProperType) and isinstance(target, TypedDictType) + return self.typeddict_callable_from_context(target, info.defn.type_vars) + + def typeddict_callable_from_context( + self, callee: TypedDictType, variables: Sequence[TypeVarLikeType] | None = None + ) -> CallableType: + return CallableType( + list(callee.items.values()), + [ + ArgKind.ARG_NAMED if name in callee.required_keys else ArgKind.ARG_NAMED_OPT + for name in callee.items + ], + list(callee.items.keys()), + callee, + self.named_type("builtins.type"), + variables=variables, + is_bound=True, + ) + + def check_typeddict_call_with_kwargs( + self, + callee: TypedDictType, + kwargs: dict[str, list[Expression]], + context: Context, + orig_callee: Type | None, + always_present_keys: set[str], + ) -> Type: + actual_keys = kwargs.keys() + if callee.to_be_mutated: + assigned_readonly_keys = actual_keys & callee.readonly_keys + if assigned_readonly_keys: + self.msg.readonly_keys_mutated(assigned_readonly_keys, context=context) + if not ( + callee.required_keys <= always_present_keys and actual_keys <= callee.items.keys() + ): + if not (actual_keys <= callee.items.keys()): + self.msg.unexpected_typeddict_keys( + callee, + expected_keys=[ + key + for key in callee.items.keys() + if key in callee.required_keys or key in actual_keys + ], + actual_keys=list(actual_keys), + context=context, + ) + if not (callee.required_keys <= always_present_keys): + self.msg.unexpected_typeddict_keys( + callee, + expected_keys=[ + key for key in callee.items.keys() if key in callee.required_keys + ], + actual_keys=[ + key for key in always_present_keys if key in callee.required_keys + ], + context=context, + ) + if callee.required_keys > actual_keys: + # found_set is a sub-set of the required_keys + # This means we're missing some keys and as such, we can't + # properly type the object + return AnyType(TypeOfAny.from_error) + + orig_callee = get_proper_type(orig_callee) + if isinstance(orig_callee, CallableType): + infer_callee = orig_callee + else: + # Try reconstructing from type context. + if callee.fallback.type.special_alias is not None: + infer_callee = self.typeddict_callable(callee.fallback.type) + else: + # Likely a TypedDict type generated by a plugin. + infer_callee = self.typeddict_callable_from_context(callee) + + # We don't show any errors, just infer types in a generic TypedDict type, + # a custom error message will be given below, if there are errors. + with self.msg.filter_errors(), self.chk.local_type_map: + orig_ret_type, _ = self.check_callable_call( + infer_callee, + # We use first expression for each key to infer type variables of a generic + # TypedDict. This is a bit arbitrary, but in most cases will work better than + # trying to infer a union or a join. + [args[0] for args in kwargs.values()], + [ArgKind.ARG_NAMED] * len(kwargs), + context, + list(kwargs.keys()), + None, + None, + None, + ) + + ret_type = get_proper_type(orig_ret_type) + if not isinstance(ret_type, TypedDictType): + # If something went really wrong, type-check call with original type, + # this may give a better error message. + ret_type = callee + + for item_name, item_expected_type in ret_type.items.items(): + if item_name in kwargs: + item_values = kwargs[item_name] + for item_value in item_values: + self.chk.check_simple_assignment( + lvalue_type=item_expected_type, + rvalue=item_value, + context=item_value, + msg=ErrorMessage( + message_registry.INCOMPATIBLE_TYPES.value, code=codes.TYPEDDICT_ITEM + ), + lvalue_name=f'TypedDict item "{item_name}"', + rvalue_name="expression", + ) + + return orig_ret_type + + def get_partial_self_var(self, expr: MemberExpr) -> Var | None: + """Get variable node for a partial self attribute. + + If the expression is not a self attribute, or attribute is not variable, + or variable is not partial, return None. + """ + if not ( + isinstance(expr.expr, NameExpr) + and isinstance(expr.expr.node, Var) + and expr.expr.node.is_self + ): + # Not a self.attr expression. + return None + info = self.chk.scope.enclosing_class() + if not info or expr.name not in info.names: + # Don't mess with partial types in superclasses. + return None + sym = info.names[expr.name] + if isinstance(sym.node, Var) and isinstance(sym.node.type, PartialType): + return sym.node + return None + + # Types and methods that can be used to infer partial types. + item_args: ClassVar[dict[str, list[str]]] = { + "builtins.list": ["append"], + "builtins.set": ["add", "discard"], + } + container_args: ClassVar[dict[str, dict[str, list[str]]]] = { + "builtins.list": {"extend": ["builtins.list"]}, + "builtins.dict": {"update": ["builtins.dict"]}, + "collections.OrderedDict": {"update": ["builtins.dict"]}, + "builtins.set": {"update": ["builtins.set", "builtins.list"]}, + } + + def try_infer_partial_type(self, e: CallExpr) -> None: + """Try to make partial type precise from a call.""" + if not isinstance(e.callee, MemberExpr): + return + callee = e.callee + if isinstance(callee.expr, RefExpr): + # Call a method with a RefExpr callee, such as 'x.method(...)'. + ret = self.get_partial_var(callee.expr) + if ret is None: + return + var, partial_types = ret + typ = self.try_infer_partial_value_type_from_call(e, callee.name, var) + # Var may be deleted from partial_types in try_infer_partial_value_type_from_call + if typ is not None and var in partial_types: + self.chk.replace_partial_type(var, typ, partial_types) + elif isinstance(callee.expr, IndexExpr) and isinstance(callee.expr.base, RefExpr): + # Call 'x[y].method(...)'; may infer type of 'x' if it's a partial defaultdict. + if callee.expr.analyzed is not None: + return # A special form + base = callee.expr.base + index = callee.expr.index + ret = self.get_partial_var(base) + if ret is None: + return + var, partial_types = ret + partial_type = get_partial_instance_type(var.type) + if partial_type is None or partial_type.value_type is None: + return + value_type = self.try_infer_partial_value_type_from_call(e, callee.name, var) + if value_type is not None: + # Infer key type. + key_type = self.accept(index) + if mypy.checker.is_valid_inferred_type(key_type, self.chk.options): + # Store inferred partial type. + assert partial_type.type is not None + typename = partial_type.type.fullname + new_type = self.chk.named_generic_type(typename, [key_type, value_type]) + self.chk.replace_partial_type(var, new_type, partial_types) + + def get_partial_var(self, ref: RefExpr) -> tuple[Var, dict[Var, Context]] | None: + var = ref.node + if var is None and isinstance(ref, MemberExpr): + var = self.get_partial_self_var(ref) + if not isinstance(var, Var): + return None + partial_types = self.chk.find_partial_types(var) + if partial_types is None: + return None + return var, partial_types + + def try_infer_partial_value_type_from_call( + self, e: CallExpr, methodname: str, var: Var + ) -> Instance | None: + """Try to make partial type precise from a call such as 'x.append(y)'.""" + if self.chk.current_node_deferred: + return None + partial_type = get_partial_instance_type(var.type) + if partial_type is None: + return None + if partial_type.value_type: + typename = partial_type.value_type.type.fullname + else: + assert partial_type.type is not None + typename = partial_type.type.fullname + # Sometimes we can infer a full type for a partial List, Dict or Set type. + # TODO: Don't infer argument expression twice. + if ( + typename in self.item_args + and methodname in self.item_args[typename] + and e.arg_kinds == [ARG_POS] + ): + item_type = self.accept(e.args[0]) + if mypy.checker.is_valid_inferred_type(item_type, self.chk.options): + return self.chk.named_generic_type(typename, [item_type]) + elif ( + typename in self.container_args + and methodname in self.container_args[typename] + and e.arg_kinds == [ARG_POS] + ): + arg_type = get_proper_type(self.accept(e.args[0])) + if isinstance(arg_type, Instance): + arg_typename = arg_type.type.fullname + if arg_typename in self.container_args[typename][methodname]: + if all( + mypy.checker.is_valid_inferred_type(item_type, self.chk.options) + for item_type in arg_type.args + ): + return self.chk.named_generic_type(typename, list(arg_type.args)) + elif isinstance(arg_type, AnyType): + return self.chk.named_type(typename) + + return None + + def apply_function_plugin( + self, + callee: CallableType, + arg_kinds: list[ArgKind], + arg_types: list[Type], + arg_names: Sequence[str | None] | None, + formal_to_actual: list[list[int]], + args: list[Expression], + fullname: str, + object_type: Type | None, + context: Context, + ) -> Type: + """Use special case logic to infer the return type of a specific named function/method. + + Caller must ensure that a plugin hook exists. There are two different cases: + + - If object_type is None, the caller must ensure that a function hook exists + for fullname. + - If object_type is not None, the caller must ensure that a method hook exists + for fullname. + + Return the inferred return type. + """ + num_formals = len(callee.arg_types) + formal_arg_types: list[list[Type]] = [[] for _ in range(num_formals)] + formal_arg_exprs: list[list[Expression]] = [[] for _ in range(num_formals)] + formal_arg_names: list[list[str | None]] = [[] for _ in range(num_formals)] + formal_arg_kinds: list[list[ArgKind]] = [[] for _ in range(num_formals)] + for formal, actuals in enumerate(formal_to_actual): + for actual in actuals: + formal_arg_types[formal].append(arg_types[actual]) + formal_arg_exprs[formal].append(args[actual]) + if arg_names: + formal_arg_names[formal].append(arg_names[actual]) + else: + formal_arg_names[formal].append(None) + formal_arg_kinds[formal].append(arg_kinds[actual]) + + if object_type is None: + # Apply function plugin + callback = self.plugin.get_function_hook(fullname) + assert callback is not None # Assume that caller ensures this + return callback( + FunctionContext( + arg_types=formal_arg_types, + arg_kinds=formal_arg_kinds, + callee_arg_names=callee.arg_names, + arg_names=formal_arg_names, + default_return_type=callee.ret_type, + args=formal_arg_exprs, + context=context, + api=self.chk, + ) + ) + else: + # Apply method plugin + method_callback = self.plugin.get_method_hook(fullname) + assert method_callback is not None # Assume that caller ensures this + object_type = get_proper_type(object_type) + return method_callback( + MethodContext( + type=object_type, + arg_types=formal_arg_types, + arg_kinds=formal_arg_kinds, + callee_arg_names=callee.arg_names, + arg_names=formal_arg_names, + default_return_type=callee.ret_type, + args=formal_arg_exprs, + context=context, + api=self.chk, + ) + ) + + def apply_signature_hook( + self, + callee: FunctionLike, + args: list[Expression], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + hook: Callable[[list[list[Expression]], CallableType], FunctionLike], + ) -> FunctionLike: + """Helper to apply a signature hook for either a function or method""" + if isinstance(callee, CallableType): + num_formals = len(callee.arg_kinds) + formal_to_actual = map_actuals_to_formals( + arg_kinds, + arg_names, + callee.arg_kinds, + callee.arg_names, + lambda i: self.accept(args[i]), + ) + formal_arg_exprs: list[list[Expression]] = [[] for _ in range(num_formals)] + for formal, actuals in enumerate(formal_to_actual): + for actual in actuals: + formal_arg_exprs[formal].append(args[actual]) + return hook(formal_arg_exprs, callee) + else: + assert isinstance(callee, Overloaded) + items = [] + for item in callee.items: + adjusted = self.apply_signature_hook(item, args, arg_kinds, arg_names, hook) + assert isinstance(adjusted, CallableType) + items.append(adjusted) + return Overloaded(items) + + def apply_function_signature_hook( + self, + callee: FunctionLike, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + arg_names: Sequence[str | None] | None, + signature_hook: Callable[[FunctionSigContext], FunctionLike], + ) -> FunctionLike: + """Apply a plugin hook that may infer a more precise signature for a function.""" + return self.apply_signature_hook( + callee, + args, + arg_kinds, + arg_names, + (lambda args, sig: signature_hook(FunctionSigContext(args, sig, context, self.chk))), + ) + + def apply_method_signature_hook( + self, + callee: FunctionLike, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + arg_names: Sequence[str | None] | None, + object_type: Type, + signature_hook: Callable[[MethodSigContext], FunctionLike], + ) -> FunctionLike: + """Apply a plugin hook that may infer a more precise signature for a method.""" + pobject_type = get_proper_type(object_type) + return self.apply_signature_hook( + callee, + args, + arg_kinds, + arg_names, + ( + lambda args, sig: signature_hook( + MethodSigContext(pobject_type, args, sig, context, self.chk) + ) + ), + ) + + def transform_callee_type( + self, + callable_name: str | None, + callee: Type, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + arg_names: Sequence[str | None] | None = None, + object_type: Type | None = None, + ) -> Type: + """Attempt to determine a more accurate signature for a method call. + + This is done by looking up and applying a method signature hook (if one exists for the + given method name). + + If no matching method signature hook is found, callee is returned unmodified. The same + happens if the arguments refer to a non-method callable (this is allowed so that the code + calling transform_callee_type needs to perform fewer boilerplate checks). + + Note: this method is *not* called automatically as part of check_call, because in some + cases check_call is called multiple times while checking a single call (for example when + dealing with overloads). Instead, this method needs to be called explicitly + (if appropriate) before the signature is passed to check_call. + """ + callee = get_proper_type(callee) + if callable_name is not None and isinstance(callee, FunctionLike): + if object_type is not None: + method_sig_hook = self.plugin.get_method_signature_hook(callable_name) + if method_sig_hook: + return self.apply_method_signature_hook( + callee, args, arg_kinds, context, arg_names, object_type, method_sig_hook + ) + else: + function_sig_hook = self.plugin.get_function_signature_hook(callable_name) + if function_sig_hook: + return self.apply_function_signature_hook( + callee, args, arg_kinds, context, arg_names, function_sig_hook + ) + + return callee + + def is_generic_decorator_overload_call( + self, callee_type: CallableType, args: list[Expression] + ) -> Overloaded | None: + """Check if this looks like an application of a generic function to overload argument.""" + assert callee_type.variables + if len(callee_type.arg_types) != 1 or len(args) != 1: + # TODO: can we handle more general cases? + return None + if not isinstance(get_proper_type(callee_type.arg_types[0]), CallableType): + return None + if not isinstance(get_proper_type(callee_type.ret_type), CallableType): + return None + with self.chk.local_type_map: + with self.msg.filter_errors(): + arg_type = get_proper_type(self.accept(args[0], type_context=None)) + if isinstance(arg_type, Overloaded): + return arg_type + return None + + def handle_decorator_overload_call( + self, callee_type: CallableType, overloaded: Overloaded, ctx: Context + ) -> tuple[Type, Type] | None: + """Type-check application of a generic callable to an overload. + + We check call on each individual overload item, and then combine results into a new + overload. This function should be only used if callee_type takes and returns a Callable. + """ + result = [] + inferred_args = [] + for item in overloaded.items: + arg = TempNode(typ=item) + with self.msg.filter_errors() as err: + item_result, inferred_arg = self.check_call(callee_type, [arg], [ARG_POS], ctx) + if err.has_new_errors(): + # This overload doesn't match. + continue + p_item_result = get_proper_type(item_result) + if not isinstance(p_item_result, CallableType): + continue + p_inferred_arg = get_proper_type(inferred_arg) + if not isinstance(p_inferred_arg, CallableType): + continue + inferred_args.append(p_inferred_arg) + result.append(p_item_result) + if not result or not inferred_args: + # None of the overload matched (or overload was initially malformed). + return None + return Overloaded(result), Overloaded(inferred_args) + + def check_call_expr_with_callee_type( + self, + callee_type: Type, + e: CallExpr, + callable_name: str | None, + object_type: Type | None, + member: str | None = None, + ) -> Type: + """Type check call expression. + + The callee_type should be used as the type of callee expression. In particular, + in case of a union type this can be a particular item of the union, so that we can + apply plugin hooks to each item. + + The 'member', 'callable_name' and 'object_type' are only used to call plugin hooks. + If 'callable_name' is None but 'member' is not None (member call), try constructing + 'callable_name' using 'object_type' (the base type on which the method is called), + for example 'typing.Mapping.get'. + """ + if callable_name is None and member is not None: + assert object_type is not None + callable_name = self.method_fullname(object_type, member) + object_type = get_proper_type(object_type) + if callable_name: + # Try to refine the call signature using plugin hooks before checking the call. + callee_type = self.transform_callee_type( + callable_name, callee_type, e.args, e.arg_kinds, e, e.arg_names, object_type + ) + # Unions are special-cased to allow plugins to act on each item in the union. + elif member is not None and isinstance(object_type, UnionType): + return self.check_union_call_expr(e, object_type, member) + ret_type, callee_type = self.check_call( + callee_type, + e.args, + e.arg_kinds, + e, + e.arg_names, + callable_node=e.callee, + callable_name=callable_name, + object_type=object_type, + ) + proper_callee = get_proper_type(callee_type) + if isinstance(e.callee, RefExpr) and isinstance(proper_callee, CallableType): + # Cache it for find_isinstance_check() + if proper_callee.type_guard is not None: + e.callee.type_guard = proper_callee.type_guard + if proper_callee.type_is is not None: + e.callee.type_is = proper_callee.type_is + return ret_type + + def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str) -> Type: + """Type check calling a member expression where the base type is a union.""" + res: list[Type] = [] + for typ in flatten_nested_unions(object_type.relevant_items()): + # Member access errors are already reported when visiting the member expression. + with self.msg.filter_errors(): + item = analyze_member_access( + member, + typ, + e, + is_lvalue=False, + is_super=False, + is_operator=False, + original_type=object_type, + chk=self.chk, + in_literal_context=self.is_literal_context(), + self_type=typ, + ) + narrowed = self.narrow_type_from_binder(e.callee, item, skip_non_overlapping=True) + if narrowed is None: + continue + callable_name = self.method_fullname(typ, member) + item_object_type = typ if callable_name else None + res.append( + self.check_call_expr_with_callee_type(narrowed, e, callable_name, item_object_type) + ) + return make_simplified_union(res) + + def check_call( + self, + callee: Type, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + arg_names: Sequence[str | None] | None = None, + callable_node: Expression | None = None, + callable_name: str | None = None, + object_type: Type | None = None, + original_type: Type | None = None, + ) -> tuple[Type, Type]: + """Type check a call. + + Also infer type arguments if the callee is a generic function. + + Return (result type, inferred callee type). + + Arguments: + callee: type of the called value + args: actual argument expressions + arg_kinds: contains nodes.ARG_* constant for each argument in args + describing whether the argument is positional, *arg, etc. + context: current expression context, used for inference. + arg_names: names of arguments (optional) + callable_node: associate the inferred callable type to this node, + if specified + callable_name: Fully-qualified name of the function/method to call, + or None if unavailable (examples: 'builtins.open', 'typing.Mapping.get') + object_type: If callable_name refers to a method, the type of the object + on which the method is being called + """ + callee = get_proper_type(callee) + + if isinstance(callee, CallableType): + if callee.variables: + overloaded = self.is_generic_decorator_overload_call(callee, args) + if overloaded is not None: + # Special casing for inline application of generic callables to overloads. + # Supporting general case would be tricky, but this should cover 95% of cases. + overloaded_result = self.handle_decorator_overload_call( + callee, overloaded, context + ) + if overloaded_result is not None: + return overloaded_result + + return self.check_callable_call( + callee, + args, + arg_kinds, + context, + arg_names, + callable_node, + callable_name, + object_type, + ) + elif isinstance(callee, Overloaded): + return self.check_overload_call( + callee, args, arg_kinds, arg_names, callable_name, object_type, context + ) + elif isinstance(callee, AnyType) or not self.chk.in_checked_function(): + return self.check_any_type_call(args, arg_kinds, callee, context) + elif isinstance(callee, UnionType): + return self.check_union_call(callee, args, arg_kinds, arg_names, context) + elif isinstance(callee, Instance): + call_function = analyze_member_access( + "__call__", + callee, + context, + is_lvalue=False, + is_super=False, + is_operator=True, + original_type=original_type or callee, + chk=self.chk, + in_literal_context=self.is_literal_context(), + ) + callable_name = callee.type.fullname + ".__call__" + # Apply method signature hook, if one exists + call_function = self.transform_callee_type( + callable_name, call_function, args, arg_kinds, context, arg_names, callee + ) + result = self.check_call( + call_function, + args, + arg_kinds, + context, + arg_names, + callable_node, + callable_name, + callee, + ) + if callable_node: + # check_call() stored "call_function" as the type, which is incorrect. + # Override the type. + self.chk.store_type(callable_node, callee) + return result + elif isinstance(callee, TypeVarType): + return self.check_call( + callee.upper_bound, args, arg_kinds, context, arg_names, callable_node + ) + elif isinstance(callee, TypeType): + item = self.analyze_type_type_callee(callee.item, context) + return self.check_call(item, args, arg_kinds, context, arg_names, callable_node) + elif isinstance(callee, TupleType): + return self.check_call( + tuple_fallback(callee), + args, + arg_kinds, + context, + arg_names, + callable_node, + callable_name, + object_type, + original_type=callee, + ) + elif isinstance(callee, UninhabitedType): + ret = UninhabitedType() + ret.ambiguous = callee.ambiguous + return callee, ret + else: + return self.msg.not_callable(callee, context), AnyType(TypeOfAny.from_error) + + def check_callable_call( + self, + callee: CallableType, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + arg_names: Sequence[str | None] | None, + callable_node: Expression | None, + callable_name: str | None, + object_type: Type | None, + ) -> tuple[Type, Type]: + """Type check a call that targets a callable value. + + See the docstring of check_call for more information. + """ + # Always unpack **kwargs before checking a call. + callee = callee.with_unpacked_kwargs().with_normalized_var_args() + if callable_name is None and callee.name: + callable_name = callee.name + ret_type = get_proper_type(callee.ret_type) + if callee.is_type_obj() and isinstance(ret_type, Instance): + callable_name = ret_type.type.fullname + if isinstance(callable_node, RefExpr) and callable_node.fullname in ENUM_BASES: + # An Enum() call that failed SemanticAnalyzerPass2.check_enum_call(). + return callee.ret_type, callee + + if ( + callee.is_type_obj() + and callee.type_object().is_protocol + # Exception for Type[...] + and not callee.from_type_type + ): + self.chk.fail( + message_registry.CANNOT_INSTANTIATE_PROTOCOL.format(callee.type_object().name), + context, + ) + elif ( + callee.is_type_obj() + and callee.type_object().is_abstract + # Exception for Type[...] + and not callee.from_type_type + and not callee.type_object().fallback_to_any + ): + type = callee.type_object() + # Determine whether the implicitly abstract attributes are functions with + # None-compatible return types. + abstract_attributes: dict[str, bool] = {} + for attr_name, abstract_status in type.abstract_attributes: + if abstract_status == IMPLICITLY_ABSTRACT: + abstract_attributes[attr_name] = self.can_return_none(type, attr_name) + else: + abstract_attributes[attr_name] = False + self.msg.cannot_instantiate_abstract_class( + callee.type_object().name, abstract_attributes, context + ) + + var_arg = callee.var_arg() + if var_arg and isinstance(var_arg.typ, UnpackType): + # It is hard to support multiple variadic unpacks (except for old-style *args: int), + # fail gracefully to avoid crashes later. + seen_unpack = False + for arg, arg_kind in zip(args, arg_kinds): + if arg_kind != ARG_STAR: + continue + arg_type = get_proper_type(self.accept(arg)) + if not isinstance(arg_type, TupleType) or any( + isinstance(t, UnpackType) for t in arg_type.items + ): + if seen_unpack: + self.msg.fail( + "Passing multiple variadic unpacks in a call is not supported", + context, + code=codes.CALL_ARG, + ) + return AnyType(TypeOfAny.from_error), callee + seen_unpack = True + + # This is tricky: return type may contain its own type variables, like in + # def [S] (S) -> def [T] (T) -> tuple[S, T], so we need to update their ids + # to avoid possible id clashes if this call itself appears in a generic + # function body. + ret_type = get_proper_type(callee.ret_type) + if isinstance(ret_type, CallableType) and ret_type.variables: + fresh_ret_type = freshen_all_functions_type_vars(callee.ret_type) + freeze_all_type_vars(fresh_ret_type) + callee = callee.copy_modified(ret_type=fresh_ret_type) + + if callee.is_generic(): + callee = freshen_function_type_vars(callee) + callee = self.infer_function_type_arguments_using_context(callee, context) + + formal_to_actual = map_actuals_to_formals( + arg_kinds, + arg_names, + callee.arg_kinds, + callee.arg_names, + lambda i: self.accept(args[i]), + ) + + if callee.is_generic(): + need_refresh = any( + isinstance(v, (ParamSpecType, TypeVarTupleType)) for v in callee.variables + ) + callee = self.infer_function_type_arguments( + callee, args, arg_kinds, arg_names, formal_to_actual, need_refresh, context + ) + if need_refresh: + # Argument kinds etc. may have changed due to + # ParamSpec or TypeVarTuple variables being replaced with an arbitrary + # number of arguments; recalculate actual-to-formal map + formal_to_actual = map_actuals_to_formals( + arg_kinds, + arg_names, + callee.arg_kinds, + callee.arg_names, + lambda i: self.accept(args[i]), + ) + + param_spec = callee.param_spec() + if ( + param_spec is not None + and arg_kinds == [ARG_STAR, ARG_STAR2] + and len(formal_to_actual) == 2 + ): + arg1 = self.accept(args[0]) + arg2 = self.accept(args[1]) + if ( + isinstance(arg1, ParamSpecType) + and isinstance(arg2, ParamSpecType) + and arg1.flavor == ParamSpecFlavor.ARGS + and arg2.flavor == ParamSpecFlavor.KWARGS + and arg1.id == arg2.id == param_spec.id + ): + return callee.ret_type, callee + + arg_types = self.infer_arg_types_in_context(callee, args, arg_kinds, formal_to_actual) + + self.check_argument_count( + callee, + arg_types, + arg_kinds, + arg_names, + formal_to_actual, + context, + object_type, + callable_name, + ) + + self.check_argument_types( + arg_types, arg_kinds, args, callee, formal_to_actual, context, object_type=object_type + ) + + if ( + callee.is_type_obj() + and (len(arg_types) == 1) + and is_equivalent(callee.ret_type, self.named_type("builtins.type")) + ): + callee = callee.copy_modified(ret_type=TypeType.make_normalized(arg_types[0])) + + if callable_node: + # Store the inferred callable type. + self.chk.store_type(callable_node, callee) + + if callable_name and ( + (object_type is None and self.plugin.get_function_hook(callable_name)) + or (object_type is not None and self.plugin.get_method_hook(callable_name)) + ): + new_ret_type = self.apply_function_plugin( + callee, + arg_kinds, + arg_types, + arg_names, + formal_to_actual, + args, + callable_name, + object_type, + context, + ) + callee = callee.copy_modified(ret_type=new_ret_type) + return callee.ret_type, callee + + def can_return_none(self, type: TypeInfo, attr_name: str) -> bool: + """Is the given attribute a method with a None-compatible return type? + + Overloads are only checked if there is an implementation. + """ + if not state.strict_optional: + # If strict-optional is not set, is_subtype(NoneType(), T) is always True. + # So, we cannot do anything useful here in that case. + return False + for base in type.mro: + symnode = base.names.get(attr_name) + if symnode is None: + continue + node = symnode.node + if isinstance(node, OverloadedFuncDef): + node = node.impl + if isinstance(node, Decorator): + node = node.func + if isinstance(node, FuncDef): + if node.type is not None: + assert isinstance(node.type, CallableType) + return is_subtype(NoneType(), node.type.ret_type) + return False + + def analyze_type_type_callee(self, item: ProperType, context: Context) -> Type: + """Analyze the callee X in X(...) where X is Type[item]. + + Return a Y that we can pass to check_call(Y, ...). + """ + if isinstance(item, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=item) + if isinstance(item, Instance): + res = type_object_type(item.type, self.named_type) + if isinstance(res, CallableType): + res = res.copy_modified(from_type_type=True) + expanded = expand_type_by_instance(res, item) + if isinstance(expanded, CallableType): + # Callee of the form Type[...] should never be generic, only + # proper class objects can be. + expanded = expanded.copy_modified(variables=[]) + return expanded + if isinstance(item, UnionType): + return UnionType( + [ + self.analyze_type_type_callee(get_proper_type(tp), context) + for tp in item.relevant_items() + ], + item.line, + ) + if isinstance(item, TypeVarType): + # Pretend we're calling the typevar's upper bound, + # i.e. its constructor (a poor approximation for reality, + # but better than AnyType...), but replace the return type + # with typevar. + callee = self.analyze_type_type_callee(get_proper_type(item.upper_bound), context) + callee = get_proper_type(callee) + if isinstance(callee, CallableType): + callee = callee.copy_modified(ret_type=item) + elif isinstance(callee, Overloaded): + callee = Overloaded([c.copy_modified(ret_type=item) for c in callee.items]) + return callee + # We support Type of namedtuples but not of tuples in general + if isinstance(item, TupleType) and tuple_fallback(item).type.fullname != "builtins.tuple": + return self.analyze_type_type_callee(tuple_fallback(item), context) + if isinstance(item, TypedDictType): + return self.typeddict_callable_from_context(item) + + self.msg.unsupported_type_type(item, context) + return AnyType(TypeOfAny.from_error) + + def infer_arg_types_in_empty_context(self, args: list[Expression]) -> list[Type]: + """Infer argument expression types in an empty context. + + In short, we basically recurse on each argument without considering + in what context the argument was called. + """ + res: list[Type] = [] + + for arg in args: + arg_type = self.accept(arg) + if has_erased_component(arg_type): + res.append(NoneType()) + else: + res.append(arg_type) + return res + + def infer_more_unions_for_recursive_type(self, type_context: Type) -> bool: + """Adjust type inference of unions if type context has a recursive type. + + Return the old state. The caller must assign it to type_state.infer_unions + afterwards. + + This is a hack to better support inference for recursive types. + + Note: This is performance-sensitive and must not be a context manager + until mypyc supports them better. + """ + old = type_state.infer_unions + if has_recursive_types(type_context): + type_state.infer_unions = True + return old + + def infer_arg_types_in_context( + self, + callee: CallableType, + args: list[Expression], + arg_kinds: list[ArgKind], + formal_to_actual: list[list[int]], + ) -> list[Type]: + """Infer argument expression types using a callable type as context. + + For example, if callee argument 2 has type List[int], infer the + argument expression with List[int] type context. + + Returns the inferred types of *actual arguments*. + """ + # Precompute arg_context so that we type check argument expressions in evaluation order + arg_context: list[Type | None] = [None] * len(args) + for fi, actuals in enumerate(formal_to_actual): + for ai in actuals: + if arg_kinds[ai].is_star(): + continue + arg_context[ai] = callee.arg_types[fi] + + res = [] + for arg, ctx in zip(args, arg_context): + if ctx is not None: + # When the outer context for a function call is known to be recursive, + # we solve type constraints inferred from arguments using unions instead + # of joins. This is a bit arbitrary, but in practice it works for most + # cases. A cleaner alternative would be to switch to single bin type + # inference, but this is a lot of work. + old = self.infer_more_unions_for_recursive_type(ctx) + res.append(self.accept(arg, ctx)) + # We need to manually restore union inference state, ugh. + type_state.infer_unions = old + else: + res.append(self.accept(arg)) + return res + + def infer_function_type_arguments_using_context( + self, callable: CallableType, error_context: Context + ) -> CallableType: + """Unify callable return type to type context to infer type vars. + + For example, if the return type is set[t] where 't' is a type variable + of callable, and if the context is set[int], return callable modified + by substituting 't' with 'int'. + """ + ctx = self.type_context[-1] + if not ctx: + return callable + # The return type may have references to type metavariables that + # we are inferring right now. We must consider them as indeterminate + # and they are not potential results; thus we replace them with the + # special ErasedType type. On the other hand, class type variables are + # valid results. + erased_ctx = replace_meta_vars(ctx, ErasedType()) + ret_type = callable.ret_type + if is_overlapping_none(ret_type) and is_overlapping_none(ctx): + # If both the context and the return type are optional, unwrap the optional, + # since in 99% cases this is what a user expects. In other words, we replace + # Optional[T] <: Optional[int] + # with + # T <: int + # while the former would infer T <: Optional[int]. + ret_type = remove_optional(ret_type) + erased_ctx = remove_optional(erased_ctx) + # + # TODO: Instead of this hack and the one below, we need to use outer and + # inner contexts at the same time. This is however not easy because of two + # reasons: + # * We need to support constraints like [1 <: 2, 2 <: X], i.e. with variables + # on both sides. (This is not too hard.) + # * We need to update all the inference "infrastructure", so that all + # variables in an expression are inferred at the same time. + # (And this is hard, also we need to be careful with lambdas that require + # two passes.) + proper_ret = get_proper_type(ret_type) + if ( + isinstance(proper_ret, TypeVarType) + or isinstance(proper_ret, UnionType) + and all(isinstance(get_proper_type(u), TypeVarType) for u in proper_ret.items) + ): + # Another special case: the return type is a type variable. If it's unrestricted, + # we could infer a too general type for the type variable if we use context, + # and this could result in confusing and spurious type errors elsewhere. + # + # So we give up and just use function arguments for type inference, with just two + # exceptions: + # + # 1. If the context is a generic instance type, actually use it as context, as + # this *seems* to usually be the reasonable thing to do. + # + # See also github issues #462 and #360. + # + # 2. If the context is some literal type, we want to "propagate" that information + # down so that we infer a more precise type for literal expressions. For example, + # the expression `3` normally has an inferred type of `builtins.int`: but if it's + # in a literal context like below, we want it to infer `Literal[3]` instead. + # + # def expects_literal(x: Literal[3]) -> None: pass + # def identity(x: T) -> T: return x + # + # expects_literal(identity(3)) # Should type-check + # TODO: we may want to add similar exception if all arguments are lambdas, since + # in this case external context is almost everything we have. + if not is_generic_instance(ctx) and not is_literal_type_like(ctx): + return callable.copy_modified() + args = infer_type_arguments( + callable.variables, ret_type, erased_ctx, skip_unsatisfied=True + ) + # Only substitute non-Uninhabited and non-erased types. + new_args: list[Type | None] = [] + for arg in args: + if has_uninhabited_component(arg) or has_erased_component(arg): + new_args.append(None) + else: + new_args.append(arg) + # Don't show errors after we have only used the outer context for inference. + # We will use argument context to infer more variables. + return self.apply_generic_arguments( + callable, new_args, error_context, skip_unsatisfied=True + ) + + def infer_function_type_arguments( + self, + callee_type: CallableType, + args: list[Expression], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + formal_to_actual: list[list[int]], + need_refresh: bool, + context: Context, + ) -> CallableType: + """Infer the type arguments for a generic callee type. + + Infer based on the types of arguments. + + Return a derived callable type that has the arguments applied. + """ + if self.chk.in_checked_function(): + # Disable type errors during type inference. There may be errors + # due to partial available context information at this time, but + # these errors can be safely ignored as the arguments will be + # inferred again later. + with self.msg.filter_errors(): + arg_types = self.infer_arg_types_in_context( + callee_type, args, arg_kinds, formal_to_actual + ) + + arg_pass_nums = self.get_arg_infer_passes( + callee_type, args, arg_types, formal_to_actual, len(args) + ) + + pass1_args: list[Type | None] = [] + for i, arg in enumerate(arg_types): + if arg_pass_nums[i] > 1: + pass1_args.append(None) + else: + pass1_args.append(arg) + + inferred_args, _ = infer_function_type_arguments( + callee_type, + pass1_args, + arg_kinds, + arg_names, + formal_to_actual, + context=self.argument_infer_context(), + strict=self.chk.in_checked_function(), + ) + + if 2 in arg_pass_nums: + # Second pass of type inference. + callee_type, inferred_args = self.infer_function_type_arguments_pass2( + callee_type, + args, + arg_kinds, + arg_names, + formal_to_actual, + inferred_args, + need_refresh, + context, + ) + + if ( + callee_type.special_sig == "dict" + and len(inferred_args) == 2 + and (ARG_NAMED in arg_kinds or ARG_STAR2 in arg_kinds) + ): + # HACK: Infer str key type for dict(...) with keyword args. The type system + # can't represent this so we special case it, as this is a pretty common + # thing. This doesn't quite work with all possible subclasses of dict + # if they shuffle type variables around, as we assume that there is a 1-1 + # correspondence with dict type variables. This is a marginal issue and + # a little tricky to fix so it's left unfixed for now. + first_arg = get_proper_type(inferred_args[0]) + if isinstance(first_arg, (NoneType, UninhabitedType)): + inferred_args[0] = self.named_type("builtins.str") + elif not first_arg or not is_subtype(self.named_type("builtins.str"), first_arg): + self.chk.fail(message_registry.KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE, context) + + if not self.chk.options.old_type_inference and any( + a is None + or isinstance(get_proper_type(a), UninhabitedType) + or set(get_type_vars(a)) & set(callee_type.variables) + for a in inferred_args + ): + if need_refresh: + # Technically we need to refresh formal_to_actual after *each* inference pass, + # since each pass can expand ParamSpec or TypeVarTuple. Although such situations + # are very rare, not doing this can cause crashes. + formal_to_actual = map_actuals_to_formals( + arg_kinds, + arg_names, + callee_type.arg_kinds, + callee_type.arg_names, + lambda a: self.accept(args[a]), + ) + # If the regular two-phase inference didn't work, try inferring type + # variables while allowing for polymorphic solutions, i.e. for solutions + # potentially involving free variables. + # TODO: support the similar inference for return type context. + poly_inferred_args, free_vars = infer_function_type_arguments( + callee_type, + arg_types, + arg_kinds, + arg_names, + formal_to_actual, + context=self.argument_infer_context(), + strict=self.chk.in_checked_function(), + allow_polymorphic=True, + ) + poly_callee_type = self.apply_generic_arguments( + callee_type, poly_inferred_args, context + ) + # Try applying inferred polymorphic type if possible, e.g. Callable[[T], T] can + # be interpreted as def [T] (T) -> T, but dict[T, T] cannot be expressed. + applied = applytype.apply_poly(poly_callee_type, free_vars) + if applied is not None and all( + a is not None and not isinstance(get_proper_type(a), UninhabitedType) + for a in poly_inferred_args + ): + freeze_all_type_vars(applied) + return applied + # If it didn't work, erase free variables as uninhabited, to avoid confusing errors. + unknown = UninhabitedType() + unknown.ambiguous = True + inferred_args = [ + ( + expand_type( + a, {v.id: unknown for v in list(callee_type.variables) + free_vars} + ) + if a is not None + else None + ) + for a in poly_inferred_args + ] + else: + # In dynamically typed functions use implicit 'Any' types for + # type variables. + inferred_args = [AnyType(TypeOfAny.unannotated)] * len(callee_type.variables) + return self.apply_inferred_arguments(callee_type, inferred_args, context) + + def infer_function_type_arguments_pass2( + self, + callee_type: CallableType, + args: list[Expression], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + formal_to_actual: list[list[int]], + old_inferred_args: Sequence[Type | None], + need_refresh: bool, + context: Context, + ) -> tuple[CallableType, list[Type | None]]: + """Perform second pass of generic function type argument inference. + + The second pass is needed for arguments with types such as Callable[[T], S], + where both T and S are type variables, when the actual argument is a + lambda with inferred types. The idea is to infer the type variable T + in the first pass (based on the types of other arguments). This lets + us infer the argument and return type of the lambda expression and + thus also the type variable S in this second pass. + + Return (the callee with type vars applied, inferred actual arg types). + """ + # None or erased types in inferred types mean that there was not enough + # information to infer the argument. Replace them with None values so + # that they are not applied yet below. + inferred_args = list(old_inferred_args) + for i, arg in enumerate(get_proper_types(inferred_args)): + if isinstance(arg, (NoneType, UninhabitedType)) or has_erased_component(arg): + inferred_args[i] = None + callee_type = self.apply_generic_arguments(callee_type, inferred_args, context) + + if not callee_type.is_generic(): + # Fast path, second pass can't give new information. + return callee_type, [] + + if need_refresh: + formal_to_actual = map_actuals_to_formals( + arg_kinds, + arg_names, + callee_type.arg_kinds, + callee_type.arg_names, + lambda a: self.accept(args[a]), + ) + + # Same as during first pass, disable type errors (we still have partial context). + with self.msg.filter_errors(): + arg_types = self.infer_arg_types_in_context( + callee_type, args, arg_kinds, formal_to_actual + ) + + inferred_args, _ = infer_function_type_arguments( + callee_type, + arg_types, + arg_kinds, + arg_names, + formal_to_actual, + context=self.argument_infer_context(), + ) + + return callee_type, inferred_args + + def argument_infer_context(self) -> ArgumentInferContext: + if self._arg_infer_context_cache is None: + self._arg_infer_context_cache = ArgumentInferContext( + self.chk.named_type("typing.Mapping"), self.chk.named_type("typing.Iterable") + ) + return self._arg_infer_context_cache + + def get_arg_infer_passes( + self, + callee: CallableType, + args: list[Expression], + arg_types: list[Type], + formal_to_actual: list[list[int]], + num_actuals: int, + ) -> list[int]: + """Return pass numbers for args for two-pass argument type inference. + + For each actual, the pass number is either 1 (first pass) or 2 (second + pass). + + Two-pass argument type inference primarily lets us infer types of + lambdas more effectively. + """ + res = [1] * num_actuals + for i, arg in enumerate(callee.arg_types): + skip_param_spec = False + p_formal = get_proper_type(callee.arg_types[i]) + if isinstance(p_formal, CallableType) and p_formal.param_spec(): + for j in formal_to_actual[i]: + p_actual = get_proper_type(arg_types[j]) + # This is an exception from the usual logic where we put generic Callable + # arguments in the second pass. If we have a non-generic actual, it is + # likely to infer good constraints, for example if we have: + # def run(Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ... + # def test(x: int, y: int) -> int: ... + # run(test, 1, 2) + # we will use `test` for inference, since it will allow to infer also + # argument *names* for P <: [x: int, y: int]. + if isinstance(p_actual, Instance): + call_method = find_member("__call__", p_actual, p_actual, is_operator=True) + if call_method is not None: + p_actual = get_proper_type(call_method) + if ( + isinstance(p_actual, CallableType) + and not p_actual.variables + and not isinstance(args[j], LambdaExpr) + ): + skip_param_spec = True + break + if not skip_param_spec and arg.accept(ArgInferSecondPassQuery()): + for j in formal_to_actual[i]: + res[j] = 2 + return res + + def apply_inferred_arguments( + self, callee_type: CallableType, inferred_args: Sequence[Type | None], context: Context + ) -> CallableType: + """Apply inferred values of type arguments to a generic function. + + Inferred_args contains the values of function type arguments. + """ + # Report error if some of the variables could not be solved. In that + # case assume that all variables have type Any to avoid extra + # bogus error messages. + for inferred_type, tv in zip(inferred_args, callee_type.variables): + if not inferred_type or has_erased_component(inferred_type): + # Could not infer a non-trivial type for a type variable. + self.msg.could_not_infer_type_arguments(callee_type, tv, context) + inferred_args = [AnyType(TypeOfAny.from_error)] * len(inferred_args) + # Apply the inferred types to the function type. In this case the + # return type must be CallableType, since we give the right number of type + # arguments. + return self.apply_generic_arguments(callee_type, inferred_args, context) + + def check_argument_count( + self, + callee: CallableType, + actual_types: list[Type], + actual_kinds: list[ArgKind], + actual_names: Sequence[str | None] | None, + formal_to_actual: list[list[int]], + context: Context | None, + object_type: Type | None = None, + callable_name: str | None = None, + ) -> bool: + """Check that there is a value for all required arguments to a function. + + Also check that there are no duplicate values for arguments. Report found errors + using 'messages' if it's not None. If 'messages' is given, 'context' must also be given. + + Return False if there were any errors. Otherwise return True + """ + if context is None: + # Avoid "is None" checks + context = TempNode(AnyType(TypeOfAny.special_form)) + + # TODO(jukka): We could return as soon as we find an error if messages is None. + + # Collect dict of all actual arguments matched to formal arguments, with occurrence count + all_actuals: dict[int, int] = {} + for actuals in formal_to_actual: + for a in actuals: + all_actuals[a] = all_actuals.get(a, 0) + 1 + + ok, is_unexpected_arg_error = self.check_for_extra_actual_arguments( + callee, actual_types, actual_kinds, actual_names, all_actuals, context + ) + + # Check for too many or few values for formals. + for i, kind in enumerate(callee.arg_kinds): + mapped_args = formal_to_actual[i] + if kind.is_required() and not mapped_args and not is_unexpected_arg_error: + # No actual for a mandatory formal + if kind.is_positional(): + self.msg.too_few_arguments(callee, context, actual_names) + if object_type and callable_name and "." in callable_name: + self.missing_classvar_callable_note(object_type, callable_name, context) + else: + argname = callee.arg_names[i] or "?" + self.msg.missing_named_argument(callee, context, argname) + ok = False + elif not kind.is_star() and is_duplicate_mapping( + mapped_args, actual_types, actual_kinds + ): + if self.chk.in_checked_function() or isinstance( + get_proper_type(actual_types[mapped_args[0]]), TupleType + ): + self.msg.duplicate_argument_value(callee, i, context) + ok = False + elif ( + kind.is_named() + and mapped_args + and actual_kinds[mapped_args[0]] not in [nodes.ARG_NAMED, nodes.ARG_STAR2] + ): + # Positional argument when expecting a keyword argument. + self.msg.too_many_positional_arguments(callee, context) + ok = False + elif callee.param_spec() is not None: + if not mapped_args and callee.special_sig != "partial": + self.msg.too_few_arguments(callee, context, actual_names) + ok = False + elif len(mapped_args) > 1: + paramspec_entries = sum( + isinstance(get_proper_type(actual_types[k]), ParamSpecType) + for k in mapped_args + ) + if actual_kinds[mapped_args[0]] == nodes.ARG_STAR and paramspec_entries > 1: + self.msg.fail("ParamSpec.args should only be passed once", context) + ok = False + if actual_kinds[mapped_args[0]] == nodes.ARG_STAR2 and paramspec_entries > 1: + self.msg.fail("ParamSpec.kwargs should only be passed once", context) + ok = False + return ok + + def check_for_extra_actual_arguments( + self, + callee: CallableType, + actual_types: list[Type], + actual_kinds: list[ArgKind], + actual_names: Sequence[str | None] | None, + all_actuals: dict[int, int], + context: Context, + ) -> tuple[bool, bool]: + """Check for extra actual arguments. + + Return tuple (was everything ok, + was there an extra keyword argument error [used to avoid duplicate errors]). + """ + + is_unexpected_arg_error = False # Keep track of errors to avoid duplicate errors + ok = True # False if we've found any error + + for i, kind in enumerate(actual_kinds): + if ( + i not in all_actuals + and + # We accept the other iterables than tuple (including Any) + # as star arguments because they could be empty, resulting no arguments. + (kind != nodes.ARG_STAR or is_non_empty_tuple(actual_types[i])) + and + # Accept all types for double-starred arguments, because they could be empty + # dictionaries and we can't tell it from their types + kind != nodes.ARG_STAR2 + ): + # Extra actual: not matched by a formal argument. + ok = False + if kind != nodes.ARG_NAMED: + self.msg.too_many_arguments(callee, context) + else: + assert actual_names, "Internal error: named kinds without names given" + act_name = actual_names[i] + assert act_name is not None + act_type = actual_types[i] + self.msg.unexpected_keyword_argument(callee, act_name, act_type, context) + is_unexpected_arg_error = True + elif ( + kind == nodes.ARG_STAR and nodes.ARG_STAR not in callee.arg_kinds + ) or kind == nodes.ARG_STAR2: + actual_type = get_proper_type(actual_types[i]) + if isinstance(actual_type, (TupleType, TypedDictType)): + if all_actuals.get(i, 0) < len(actual_type.items): + # Too many tuple/dict items as some did not match. + if kind != nodes.ARG_STAR2 or not isinstance(actual_type, TypedDictType): + self.msg.too_many_arguments(callee, context) + else: + self.msg.too_many_arguments_from_typed_dict( + callee, actual_type, context + ) + is_unexpected_arg_error = True + ok = False + # *args/**kwargs can be applied even if the function takes a fixed + # number of positional arguments. This may succeed at runtime. + + return ok, is_unexpected_arg_error + + def missing_classvar_callable_note( + self, object_type: Type, callable_name: str, context: Context + ) -> None: + if isinstance(object_type, ProperType) and isinstance(object_type, Instance): + _, var_name = callable_name.rsplit(".", maxsplit=1) + node = object_type.type.get(var_name) + if node is not None and isinstance(node.node, Var): + if not node.node.is_inferred and not node.node.is_classvar: + self.msg.note( + f'"{var_name}" is considered instance variable,' + " to make it class variable use ClassVar[...]", + context, + ) + + def check_var_args_kwargs( + self, arg_types: list[Type], arg_kinds: list[ArgKind], context: Context + ) -> None: + for arg_type, arg_kind in zip(arg_types, arg_kinds): + arg_type = get_proper_type(arg_type) + if arg_kind == nodes.ARG_STAR and not self.is_valid_var_arg(arg_type): + self.msg.invalid_var_arg(arg_type, context) + if arg_kind == nodes.ARG_STAR2 and not self.is_valid_keyword_var_arg(arg_type): + is_mapping = is_subtype( + arg_type, self.chk.named_type("_typeshed.SupportsKeysAndGetItem") + ) + self.msg.invalid_keyword_var_arg(arg_type, is_mapping, context) + + def check_argument_types( + self, + arg_types: list[Type], + arg_kinds: list[ArgKind], + args: list[Expression], + callee: CallableType, + formal_to_actual: list[list[int]], + context: Context, + check_arg: ArgChecker | None = None, + object_type: Type | None = None, + ) -> None: + """Check argument types against a callable type. + + Report errors if the argument types are not compatible. + + The check_call docstring describes some of the arguments. + """ + self.check_var_args_kwargs(arg_types, arg_kinds, context) + + check_arg = check_arg or self.check_arg + # Keep track of consumed tuple *arg items. + mapper = ArgTypeExpander(self.argument_infer_context()) + + for i, actuals in enumerate(formal_to_actual): + orig_callee_arg_type = get_proper_type(callee.arg_types[i]) + + # Checking the case that we have more than one item but the first argument + # is an unpack, so this would be something like: + # [Tuple[Unpack[Ts]], int] + # + # In this case we have to check everything together, we do this by re-unifying + # the suffices to the tuple, e.g. a single actual like + # Tuple[Unpack[Ts], int] + expanded_tuple = False + actual_kinds = [arg_kinds[a] for a in actuals] + if len(actuals) > 1: + p_actual_type = get_proper_type(arg_types[actuals[0]]) + if ( + isinstance(p_actual_type, TupleType) + and len(p_actual_type.items) == 1 + and isinstance(p_actual_type.items[0], UnpackType) + and actual_kinds == [nodes.ARG_STAR] + [nodes.ARG_POS] * (len(actuals) - 1) + ): + actual_types = [p_actual_type.items[0]] + [arg_types[a] for a in actuals[1:]] + if isinstance(orig_callee_arg_type, UnpackType): + p_callee_type = get_proper_type(orig_callee_arg_type.type) + if isinstance(p_callee_type, TupleType): + assert p_callee_type.items + callee_arg_types = p_callee_type.items + callee_arg_kinds = [nodes.ARG_STAR] + [nodes.ARG_POS] * ( + len(p_callee_type.items) - 1 + ) + expanded_tuple = True + + if not expanded_tuple: + actual_types = [arg_types[a] for a in actuals] + if isinstance(orig_callee_arg_type, UnpackType): + unpacked_type = get_proper_type(orig_callee_arg_type.type) + if isinstance(unpacked_type, TupleType): + inner_unpack_index = find_unpack_in_list(unpacked_type.items) + if inner_unpack_index is None: + callee_arg_types = unpacked_type.items + callee_arg_kinds = [ARG_POS] * len(actuals) + else: + inner_unpack = unpacked_type.items[inner_unpack_index] + assert isinstance(inner_unpack, UnpackType) + inner_unpacked_type = get_proper_type(inner_unpack.type) + if isinstance(inner_unpacked_type, TypeVarTupleType): + # This branch mimics the expanded_tuple case above but for + # the case where caller passed a single * unpacked tuple argument. + callee_arg_types = unpacked_type.items + callee_arg_kinds = [ + ARG_POS if i != inner_unpack_index else ARG_STAR + for i in range(len(unpacked_type.items)) + ] + else: + # We assume heterogeneous tuples are desugared earlier. + assert isinstance(inner_unpacked_type, Instance) + assert inner_unpacked_type.type.fullname == "builtins.tuple" + callee_arg_types = ( + unpacked_type.items[:inner_unpack_index] + + [inner_unpacked_type.args[0]] + * (len(actuals) - len(unpacked_type.items) + 1) + + unpacked_type.items[inner_unpack_index + 1 :] + ) + callee_arg_kinds = [ARG_POS] * len(actuals) + elif isinstance(unpacked_type, TypeVarTupleType): + callee_arg_types = [orig_callee_arg_type] + callee_arg_kinds = [ARG_STAR] + else: + assert isinstance(unpacked_type, Instance) + assert unpacked_type.type.fullname == "builtins.tuple" + callee_arg_types = [unpacked_type.args[0]] * len(actuals) + callee_arg_kinds = [ARG_POS] * len(actuals) + else: + callee_arg_types = [orig_callee_arg_type] * len(actuals) + callee_arg_kinds = [callee.arg_kinds[i]] * len(actuals) + + assert len(actual_types) == len(actuals) == len(actual_kinds) + + if len(callee_arg_types) != len(actual_types): + if len(actual_types) > len(callee_arg_types): + self.chk.msg.too_many_arguments(callee, context) + else: + self.chk.msg.too_few_arguments(callee, context, None) + continue + + assert len(callee_arg_types) == len(actual_types) + assert len(callee_arg_types) == len(callee_arg_kinds) + for actual, actual_type, actual_kind, callee_arg_type, callee_arg_kind in zip( + actuals, actual_types, actual_kinds, callee_arg_types, callee_arg_kinds + ): + # Check that a *arg is valid as varargs. + expanded_actual = mapper.expand_actual_type( + actual_type, + actual_kind, + callee.arg_names[i], + callee_arg_kind, + allow_unpack=isinstance(callee_arg_type, UnpackType), + ) + check_arg( + expanded_actual, + actual_type, + actual_kind, + callee_arg_type, + actual + 1, + i + 1, + callee, + object_type, + args[actual], + context, + ) + + def check_arg( + self, + caller_type: Type, + original_caller_type: Type, + caller_kind: ArgKind, + callee_type: Type, + n: int, + m: int, + callee: CallableType, + object_type: Type | None, + context: Context, + outer_context: Context, + ) -> None: + """Check the type of a single argument in a call.""" + caller_type = get_proper_type(caller_type) + original_caller_type = get_proper_type(original_caller_type) + callee_type = get_proper_type(callee_type) + + if isinstance(caller_type, DeletedType): + self.msg.deleted_as_rvalue(caller_type, context) + # Only non-abstract non-protocol class can be given where Type[...] is expected... + elif self.has_abstract_type_part(caller_type, callee_type): + self.msg.concrete_only_call(callee_type, context) + elif not is_subtype(caller_type, callee_type, options=self.chk.options): + error = self.msg.incompatible_argument( + n, + m, + callee, + original_caller_type, + caller_kind, + object_type=object_type, + context=context, + outer_context=outer_context, + ) + if not caller_kind.is_star(): + # For *args and **kwargs this note would be incorrect - we're comparing + # iterable/mapping type with union of relevant arg types. + self.msg.incompatible_argument_note( + original_caller_type, callee_type, context, parent_error=error + ) + if not self.msg.prefer_simple_messages(): + self.chk.check_possible_missing_await( + caller_type, callee_type, context, error.code + ) + + def check_overload_call( + self, + callee: Overloaded, + args: list[Expression], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + callable_name: str | None, + object_type: Type | None, + context: Context, + ) -> tuple[Type, Type]: + """Checks a call to an overloaded function.""" + # Normalize unpacked kwargs before checking the call. + callee = callee.with_unpacked_kwargs() + arg_types = self.infer_arg_types_in_empty_context(args) + # Step 1: Filter call targets to remove ones where the argument counts don't match + plausible_targets = self.plausible_overload_call_targets( + arg_types, arg_kinds, arg_names, callee + ) + + # Step 2: If the arguments contain a union, we try performing union math first, + # instead of picking the first matching overload. + # This is because picking the first overload often ends up being too greedy: + # for example, when we have a fallback alternative that accepts an unrestricted + # typevar. See https://github.com/python/mypy/issues/4063 for related discussion. + erased_targets: list[CallableType] | None = None + inferred_types: list[Type] | None = None + unioned_result: tuple[Type, Type] | None = None + + # Determine whether we need to encourage union math. This should be generally safe, + # as union math infers better results in the vast majority of cases, but it is very + # computationally intensive. + none_type_var_overlap = self.possible_none_type_var_overlap(arg_types, plausible_targets) + union_interrupted = False # did we try all union combinations? + if any(self.real_union(arg) for arg in arg_types): + try: + with self.msg.filter_errors(): + unioned_return = self.union_overload_result( + plausible_targets, + args, + arg_types, + arg_kinds, + arg_names, + callable_name, + object_type, + none_type_var_overlap, + context, + ) + except TooManyUnions: + union_interrupted = True + else: + # Record if we succeeded. Next we need to see if maybe normal procedure + # gives a narrower type. + if unioned_return: + returns = [u[0] for u in unioned_return] + inferred_types = [u[1] for u in unioned_return] + # Note that we use `combine_function_signatures` instead of just returning + # a union of inferred callables because for example a call + # Union[int -> int, str -> str](Union[int, str]) is invalid and + # we don't want to introduce internal inconsistencies. + unioned_result = ( + make_simplified_union(returns, context.line, context.column), + self.combine_function_signatures(get_proper_types(inferred_types)), + ) + + # Step 3: We try checking each branch one-by-one. + inferred_result = self.infer_overload_return_type( + plausible_targets, + args, + arg_types, + arg_kinds, + arg_names, + callable_name, + object_type, + context, + ) + # If any of checks succeed, perform deprecation tests and stop early. + if inferred_result is not None and unioned_result is not None: + # Both unioned and direct checks succeeded, choose the more precise type. + if ( + is_subtype(inferred_result[0], unioned_result[0]) + and not isinstance(get_proper_type(inferred_result[0]), AnyType) + and not none_type_var_overlap + ): + unioned_result = None + else: + inferred_result = None + if unioned_result is not None: + if inferred_types is not None: + for inferred_type in inferred_types: + if isinstance(c := get_proper_type(inferred_type), CallableType): + self.chk.warn_deprecated(c.definition, context) + return unioned_result + if inferred_result is not None: + if isinstance(c := get_proper_type(inferred_result[1]), CallableType): + self.chk.warn_deprecated(c.definition, context) + return inferred_result + + # Step 4: Failure. At this point, we know there is no match. We fall back to trying + # to find a somewhat plausible overload target using the erased types + # so we can produce a nice error message. + # + # For example, suppose the user passes a value of type 'List[str]' into an + # overload with signatures f(x: int) -> int and f(x: List[int]) -> List[int]. + # + # Neither alternative matches, but we can guess the user probably wants the + # second one. + erased_targets = self.overload_erased_call_targets( + plausible_targets, arg_types, arg_kinds, arg_names, args, context + ) + + # Step 5: We try and infer a second-best alternative if possible. If not, fall back + # to using 'Any'. + if len(erased_targets) > 0: + # Pick the first plausible erased target as the fallback + # TODO: Adjust the error message here to make it clear there was no match. + # In order to do this, we need to find a clean way of associating + # a note with whatever error message 'self.check_call' will generate. + # In particular, the note's line and column numbers need to be the same + # as the error's. + target: Type = erased_targets[0] + else: + # There was no plausible match: give up + target = AnyType(TypeOfAny.from_error) + if not is_operator_method(callable_name): + code = None + else: + code = codes.OPERATOR + self.msg.no_variant_matches_arguments(callee, arg_types, context, code=code) + + result = self.check_call( + target, + args, + arg_kinds, + context, + arg_names, + callable_name=callable_name, + object_type=object_type, + ) + # Do not show the extra error if the union math was forced. + if union_interrupted and not none_type_var_overlap: + self.chk.fail(message_registry.TOO_MANY_UNION_COMBINATIONS, context) + return result + + def plausible_overload_call_targets( + self, + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + overload: Overloaded, + ) -> list[CallableType]: + """Returns all overload call targets that having matching argument counts. + + If the given args contains a star-arg (*arg or **kwarg argument, except for + ParamSpec), this method will ensure all star-arg overloads appear at the start + of the list, instead of their usual location. + + The only exception is if the starred argument is something like a Tuple or a + NamedTuple, which has a definitive "shape". If so, we don't move the corresponding + alternative to the front since we can infer a more precise match using the original + order.""" + + def has_shape(typ: Type) -> bool: + typ = get_proper_type(typ) + return isinstance(typ, (TupleType, TypedDictType)) or ( + isinstance(typ, Instance) and typ.type.is_named_tuple + ) + + matches: list[CallableType] = [] + star_matches: list[CallableType] = [] + + args_have_var_arg = False + args_have_kw_arg = False + for kind, typ in zip(arg_kinds, arg_types): + if kind == ARG_STAR and not has_shape(typ): + args_have_var_arg = True + if kind == ARG_STAR2 and not has_shape(typ): + args_have_kw_arg = True + + for typ in overload.items: + formal_to_actual = map_actuals_to_formals( + arg_kinds, arg_names, typ.arg_kinds, typ.arg_names, lambda i: arg_types[i] + ) + with self.msg.filter_errors(): + if typ.param_spec() is not None: + # ParamSpec can be expanded in a lot of different ways. We may try + # to expand it here instead, but picking an impossible overload + # is safe: it will be filtered out later. + # Unlike other var-args signatures, ParamSpec produces essentially + # a fixed signature, so there's no need to push them to the top. + matches.append(typ) + elif self.check_argument_count( + typ, arg_types, arg_kinds, arg_names, formal_to_actual, None + ): + if args_have_var_arg and typ.is_var_arg: + star_matches.append(typ) + elif args_have_kw_arg and typ.is_kw_arg: + star_matches.append(typ) + else: + matches.append(typ) + + return star_matches + matches + + def infer_overload_return_type( + self, + plausible_targets: list[CallableType], + args: list[Expression], + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + callable_name: str | None, + object_type: Type | None, + context: Context, + ) -> tuple[Type, Type] | None: + """Attempts to find the first matching callable from the given list. + + If a match is found, returns a tuple containing the result type and the inferred + callee type. (This tuple is meant to be eventually returned by check_call.) + If multiple targets match due to ambiguous Any parameters, returns (AnyType, AnyType). + If no targets match, returns None. + + Assumes all of the given targets have argument counts compatible with the caller. + """ + + matches: list[CallableType] = [] + return_types: list[Type] = [] + inferred_types: list[Type] = [] + args_contain_any = any(map(has_any_type, arg_types)) + type_maps: list[dict[Expression, Type]] = [] + + for typ in plausible_targets: + assert self.msg is self.chk.msg + with self.msg.filter_errors(filter_revealed_type=True) as w: + with self.chk.local_type_map as m: + ret_type, infer_type = self.check_call( + callee=typ, + args=args, + arg_kinds=arg_kinds, + arg_names=arg_names, + context=context, + callable_name=callable_name, + object_type=object_type, + ) + is_match = not w.has_new_errors() + if is_match: + # Return early if possible; otherwise record info, so we can + # check for ambiguity due to 'Any' below. + if not args_contain_any: + self.chk.store_types(m) + return ret_type, infer_type + p_infer_type = get_proper_type(infer_type) + if isinstance(p_infer_type, CallableType): + # Prefer inferred types if possible, this will avoid false triggers for + # Any-ambiguity caused by arguments with Any passed to generic overloads. + matches.append(p_infer_type) + else: + matches.append(typ) + return_types.append(ret_type) + inferred_types.append(infer_type) + type_maps.append(m) + + if not matches: + return None + elif any_causes_overload_ambiguity(matches, return_types, arg_types, arg_kinds, arg_names): + # An argument of type or containing the type 'Any' caused ambiguity. + # We try returning a precise type if we can. If not, we give up and just return 'Any'. + if all_same_types(return_types): + self.chk.store_types(type_maps[0]) + return return_types[0], inferred_types[0] + elif all_same_types([erase_type(typ) for typ in return_types]): + self.chk.store_types(type_maps[0]) + return erase_type(return_types[0]), erase_type(inferred_types[0]) + else: + return self.check_call( + callee=AnyType(TypeOfAny.special_form), + args=args, + arg_kinds=arg_kinds, + arg_names=arg_names, + context=context, + callable_name=callable_name, + object_type=object_type, + ) + else: + # Success! No ambiguity; return the first match. + self.chk.store_types(type_maps[0]) + return return_types[0], inferred_types[0] + + def overload_erased_call_targets( + self, + plausible_targets: list[CallableType], + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + args: list[Expression], + context: Context, + ) -> list[CallableType]: + """Returns a list of all targets that match the caller after erasing types. + + Assumes all of the given targets have argument counts compatible with the caller. + """ + matches: list[CallableType] = [] + for typ in plausible_targets: + if self.erased_signature_similarity( + arg_types, arg_kinds, arg_names, args, typ, context + ): + matches.append(typ) + return matches + + def possible_none_type_var_overlap( + self, arg_types: list[Type], plausible_targets: list[CallableType] + ) -> bool: + """Heuristic to determine whether we need to try forcing union math. + + This is needed to avoid greedy type variable match in situations like this: + @overload + def foo(x: None) -> None: ... + @overload + def foo(x: T) -> list[T]: ... + + x: int | None + foo(x) + we want this call to infer list[int] | None, not list[int | None]. + """ + if not plausible_targets or not arg_types: + return False + has_optional_arg = False + for arg_type in get_proper_types(arg_types): + if not isinstance(arg_type, UnionType): + continue + for item in get_proper_types(arg_type.items): + if isinstance(item, NoneType): + has_optional_arg = True + break + if not has_optional_arg: + return False + + min_prefix = min(len(c.arg_types) for c in plausible_targets) + for i in range(min_prefix): + if any( + isinstance(get_proper_type(c.arg_types[i]), NoneType) for c in plausible_targets + ) and any( + isinstance(get_proper_type(c.arg_types[i]), TypeVarType) for c in plausible_targets + ): + return True + return False + + def union_overload_result( + self, + plausible_targets: list[CallableType], + args: list[Expression], + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + callable_name: str | None, + object_type: Type | None, + none_type_var_overlap: bool, + context: Context, + level: int = 0, + ) -> list[tuple[Type, Type]] | None: + """Accepts a list of overload signatures and attempts to match calls by destructuring + the first union. + + Return a list of (, ) if call succeeds for every + item of the desctructured union. Returns None if there is no match. + """ + # Step 1: If we are already too deep, then stop immediately. Otherwise mypy might + # hang for long time because of a weird overload call. The caller will get + # the exception and generate an appropriate note message, if needed. + if level >= MAX_UNIONS: + raise TooManyUnions + + # Step 2: Find position of the first union in arguments. Return the normal inferred + # type if no more unions left. + for idx, typ in enumerate(arg_types): + if self.real_union(typ): + break + else: + # No unions in args, just fall back to normal inference + with self.type_overrides_set(args, arg_types): + res = self.infer_overload_return_type( + plausible_targets, + args, + arg_types, + arg_kinds, + arg_names, + callable_name, + object_type, + context, + ) + if res is not None: + return [res] + return None + + # Step 3: Try a direct match before splitting to avoid unnecessary union splits + # and save performance. + if not none_type_var_overlap: + with self.type_overrides_set(args, arg_types): + direct = self.infer_overload_return_type( + plausible_targets, + args, + arg_types, + arg_kinds, + arg_names, + callable_name, + object_type, + context, + ) + if direct is not None and not isinstance( + get_proper_type(direct[0]), (UnionType, AnyType) + ): + # We only return non-unions soon, to avoid greedy match. + return [direct] + + # Step 4: Split the first remaining union type in arguments into items and + # try to match each item individually (recursive). + first_union = get_proper_type(arg_types[idx]) + assert isinstance(first_union, UnionType) + res_items = [] + for item in first_union.relevant_items(): + new_arg_types = arg_types.copy() + new_arg_types[idx] = item + sub_result = self.union_overload_result( + plausible_targets, + args, + new_arg_types, + arg_kinds, + arg_names, + callable_name, + object_type, + none_type_var_overlap, + context, + level + 1, + ) + if sub_result is not None: + res_items.extend(sub_result) + else: + # Some item doesn't match, return soon. + return None + + # Step 5: If splitting succeeded, then filter out duplicate items before returning. + seen: set[tuple[Type, Type]] = set() + result = [] + for pair in res_items: + if pair not in seen: + seen.add(pair) + result.append(pair) + return result + + def real_union(self, typ: Type) -> bool: + typ = get_proper_type(typ) + return isinstance(typ, UnionType) and len(typ.relevant_items()) > 1 + + @contextmanager + def type_overrides_set( + self, exprs: Sequence[Expression], overrides: Sequence[Type] + ) -> Iterator[None]: + """Set _temporary_ type overrides for given expressions.""" + assert len(exprs) == len(overrides) + for expr, typ in zip(exprs, overrides): + self.type_overrides[expr] = typ + try: + yield + finally: + for expr in exprs: + del self.type_overrides[expr] + + def combine_function_signatures(self, types: list[ProperType]) -> AnyType | CallableType: + """Accepts a list of function signatures and attempts to combine them together into a + new CallableType consisting of the union of all of the given arguments and return types. + + If there is at least one non-callable type, return Any (this can happen if there is + an ambiguity because of Any in arguments). + """ + assert types, "Trying to merge no callables" + if not all(isinstance(c, CallableType) for c in types): + return AnyType(TypeOfAny.special_form) + callables = cast("list[CallableType]", types) + if len(callables) == 1: + return callables[0] + + # Note: we are assuming here that if a user uses some TypeVar 'T' in + # two different functions, they meant for that TypeVar to mean the + # same thing. + # + # This function will make sure that all instances of that TypeVar 'T' + # refer to the same underlying TypeVarType objects to simplify the union-ing + # logic below. + # + # (If the user did *not* mean for 'T' to be consistently bound to the + # same type in their overloads, well, their code is probably too + # confusing and ought to be re-written anyways.) + callables, variables = merge_typevars_in_callables_by_name(callables) + + new_args: list[list[Type]] = [[] for _ in range(len(callables[0].arg_types))] + new_kinds = list(callables[0].arg_kinds) + new_returns: list[Type] = [] + + too_complex = False + for target in callables: + # We fall back to Callable[..., Union[]] if the functions do not have + # the exact same signature. The only exception is if one arg is optional and + # the other is positional: in that case, we continue unioning (and expect a + # positional arg). + # TODO: Enhance the merging logic to handle a wider variety of signatures. + if len(new_kinds) != len(target.arg_kinds): + too_complex = True + break + for i, (new_kind, target_kind) in enumerate(zip(new_kinds, target.arg_kinds)): + if new_kind == target_kind: + continue + elif new_kind.is_positional() and target_kind.is_positional(): + new_kinds[i] = ARG_POS + else: + too_complex = True + break + + if too_complex: + break # outer loop + + for i, arg in enumerate(target.arg_types): + new_args[i].append(arg) + new_returns.append(target.ret_type) + + union_return = make_simplified_union(new_returns) + if too_complex: + any = AnyType(TypeOfAny.special_form) + return callables[0].copy_modified( + arg_types=[any, any], + arg_kinds=[ARG_STAR, ARG_STAR2], + arg_names=[None, None], + ret_type=union_return, + variables=variables, + implicit=True, + ) + + final_args = [] + for args_list in new_args: + new_type = make_simplified_union(args_list) + final_args.append(new_type) + + return callables[0].copy_modified( + arg_types=final_args, + arg_kinds=new_kinds, + ret_type=union_return, + variables=variables, + implicit=True, + ) + + def erased_signature_similarity( + self, + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + args: list[Expression], + callee: CallableType, + context: Context, + ) -> bool: + """Determine whether arguments could match the signature at runtime, after + erasing types.""" + formal_to_actual = map_actuals_to_formals( + arg_kinds, arg_names, callee.arg_kinds, callee.arg_names, lambda i: arg_types[i] + ) + + with self.msg.filter_errors(): + if not self.check_argument_count( + callee, arg_types, arg_kinds, arg_names, formal_to_actual, None + ): + # Too few or many arguments -> no match. + return False + + def check_arg( + caller_type: Type, + original_ccaller_type: Type, + caller_kind: ArgKind, + callee_type: Type, + n: int, + m: int, + callee: CallableType, + object_type: Type | None, + context: Context, + outer_context: Context, + ) -> None: + if not arg_approximate_similarity(caller_type, callee_type): + # No match -- exit early since none of the remaining work can change + # the result. + raise Finished + + try: + self.check_argument_types( + arg_types, + arg_kinds, + args, + callee, + formal_to_actual, + context=context, + check_arg=check_arg, + ) + return True + except Finished: + return False + + def apply_generic_arguments( + self, + callable: CallableType, + types: Sequence[Type | None], + context: Context, + skip_unsatisfied: bool = False, + ) -> CallableType: + """Simple wrapper around mypy.applytype.apply_generic_arguments.""" + return applytype.apply_generic_arguments( + callable, + types, + self.msg.incompatible_typevar_value, + context, + skip_unsatisfied=skip_unsatisfied, + ) + + def check_any_type_call( + self, args: list[Expression], arg_kinds: list[ArgKind], callee: Type, context: Context + ) -> tuple[Type, Type]: + arg_types = self.infer_arg_types_in_empty_context(args) + self.check_var_args_kwargs(arg_types, arg_kinds, context) + + callee = get_proper_type(callee) + if isinstance(callee, AnyType): + return ( + AnyType(TypeOfAny.from_another_any, source_any=callee), + AnyType(TypeOfAny.from_another_any, source_any=callee), + ) + else: + return AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form) + + def check_union_call( + self, + callee: UnionType, + args: list[Expression], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + context: Context, + ) -> tuple[Type, Type]: + with self.msg.disable_type_names(): + results = [ + self.check_call(subtype, args, arg_kinds, context, arg_names) + for subtype in callee.relevant_items() + ] + + return (make_simplified_union([res[0] for res in results]), callee) + + def visit_member_expr(self, e: MemberExpr, is_lvalue: bool = False) -> Type: + """Visit member expression (of form e.id).""" + result = self.analyze_ordinary_member_access(e, is_lvalue) + narrowed = self.narrow_type_from_binder(e, result) + self.chk.warn_deprecated(e.node, e) + return narrowed + + def analyze_ordinary_member_access( + self, e: MemberExpr, is_lvalue: bool, rvalue: Expression | None = None + ) -> Type: + """Analyse member expression or member lvalue. + + An rvalue can be provided optionally to infer better setter type when is_lvalue is True. + """ + if e.kind is not None: + # This is a reference to a module attribute. + return self.analyze_ref_expr(e) + else: + # This is a reference to a non-module attribute. + original_type = self.accept(e.expr, is_callee=self.is_callee) + base = e.expr + module_symbol_table = None + + if isinstance(base, RefExpr) and isinstance(base.node, MypyFile): + module_symbol_table = base.node.names + if isinstance(base, RefExpr) and isinstance(base.node, Var): + # This is needed to special case self-types, so we don't need to track + # these flags separately in checkmember.py. + is_self = base.node.is_self or base.node.is_cls + else: + is_self = False + + member_type = analyze_member_access( + e.name, + original_type, + e, + is_lvalue=is_lvalue, + is_super=False, + is_operator=False, + original_type=original_type, + chk=self.chk, + in_literal_context=self.is_literal_context(), + module_symbol_table=module_symbol_table, + is_self=is_self, + rvalue=rvalue, + ) + + return member_type + + def analyze_external_member_access( + self, member: str, base_type: Type, context: Context + ) -> Type: + """Analyse member access that is external, i.e. it cannot + refer to private definitions. Return the result type. + """ + # TODO remove; no private definitions in mypy + return analyze_member_access( + member, + base_type, + context, + is_lvalue=False, + is_super=False, + is_operator=False, + original_type=base_type, + chk=self.chk, + in_literal_context=self.is_literal_context(), + ) + + def is_literal_context(self) -> bool: + return is_literal_type_like(self.type_context[-1]) + + def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type: + """Analyzes the given literal expression and determines if we should be + inferring an Instance type, a Literal[...] type, or an Instance that + remembers the original literal. We... + + 1. ...Infer a normal Instance in most circumstances. + + 2. ...Infer a Literal[...] if we're in a literal context. For example, if we + were analyzing the "3" in "foo(3)" where "foo" has a signature of + "def foo(Literal[3]) -> None", we'd want to infer that the "3" has a + type of Literal[3] instead of Instance. + + 3. ...Infer an Instance that remembers the original Literal if we're declaring + a Final variable with an inferred type -- for example, "bar" in "bar: Final = 3" + would be assigned an Instance that remembers it originated from a '3'. See + the comments in Instance's constructor for more details. + """ + typ = self.named_type(fallback_name) + if self.is_literal_context(): + return LiteralType(value=value, fallback=typ) + else: + if value is True: + if self._literal_true is None: + self._literal_true = typ.copy_modified( + last_known_value=LiteralType(value=value, fallback=typ) + ) + return self._literal_true + if value is False: + if self._literal_false is None: + self._literal_false = typ.copy_modified( + last_known_value=LiteralType(value=value, fallback=typ) + ) + return self._literal_false + return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ)) + + def concat_tuples(self, left: TupleType, right: TupleType) -> TupleType: + """Concatenate two fixed length tuples.""" + assert not (find_unpack_in_list(left.items) and find_unpack_in_list(right.items)) + return TupleType( + items=left.items + right.items, fallback=self.named_type("builtins.tuple") + ) + + def visit_int_expr(self, e: IntExpr) -> Type: + """Type check an integer literal (trivial).""" + return self.infer_literal_expr_type(e.value, "builtins.int") + + def visit_str_expr(self, e: StrExpr) -> Type: + """Type check a string literal (trivial).""" + return self.infer_literal_expr_type(e.value, "builtins.str") + + def visit_bytes_expr(self, e: BytesExpr) -> Type: + """Type check a bytes literal (trivial).""" + return self.infer_literal_expr_type(e.value, "builtins.bytes") + + def visit_float_expr(self, e: FloatExpr) -> Type: + """Type check a float literal (trivial).""" + return self.named_type("builtins.float") + + def visit_complex_expr(self, e: ComplexExpr) -> Type: + """Type check a complex literal.""" + return self.named_type("builtins.complex") + + def visit_ellipsis(self, e: EllipsisExpr) -> Type: + """Type check '...'.""" + return self.named_type("builtins.ellipsis") + + def visit_op_expr(self, e: OpExpr) -> Type: + """Type check a binary operator expression.""" + if e.analyzed: + # It's actually a type expression X | Y. + return self.accept(e.analyzed) + if e.op == "and" or e.op == "or": + return self.check_boolean_op(e) + if e.op == "*" and isinstance(e.left, ListExpr): + # Expressions of form [...] * e get special type inference. + return self.check_list_multiply(e) + if e.op == "%": + if isinstance(e.left, BytesExpr): + return self.strfrm_checker.check_str_interpolation(e.left, e.right) + if isinstance(e.left, StrExpr): + return self.strfrm_checker.check_str_interpolation(e.left, e.right) + left_type = self.accept(e.left) + + proper_left_type = get_proper_type(left_type) + if isinstance(proper_left_type, TupleType) and e.op == "+": + left_add_method = proper_left_type.partial_fallback.type.get("__add__") + if left_add_method and left_add_method.fullname == "builtins.tuple.__add__": + proper_right_type = get_proper_type(self.accept(e.right)) + if isinstance(proper_right_type, TupleType): + right_radd_method = proper_right_type.partial_fallback.type.get("__radd__") + if right_radd_method is None: + # One cannot have two variadic items in the same tuple. + if ( + find_unpack_in_list(proper_left_type.items) is None + or find_unpack_in_list(proper_right_type.items) is None + ): + return self.concat_tuples(proper_left_type, proper_right_type) + elif ( + PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature + and isinstance(proper_right_type, Instance) + and self.chk.type_is_iterable(proper_right_type) + ): + # Handle tuple[X, Y] + tuple[Z, ...] = tuple[X, Y, *tuple[Z, ...]]. + right_radd_method = proper_right_type.type.get("__radd__") + if ( + right_radd_method is None + and proper_left_type.partial_fallback.type.fullname == "builtins.tuple" + and find_unpack_in_list(proper_left_type.items) is None + ): + item_type = self.chk.iterable_item_type(proper_right_type, e) + mapped = self.chk.named_generic_type("builtins.tuple", [item_type]) + return proper_left_type.copy_modified( + items=proper_left_type.items + [UnpackType(mapped)] + ) + + use_reverse: UseReverse = USE_REVERSE_DEFAULT + if e.op == "|": + if is_named_instance(proper_left_type, "builtins.dict"): + # This is a special case for `dict | TypedDict`. + # 1. Find `dict | TypedDict` case + # 2. Switch `dict.__or__` to `TypedDict.__ror__` (the same from both runtime and typing perspective) + proper_right_type = get_proper_type(self.accept(e.right)) + if isinstance(proper_right_type, TypedDictType): + use_reverse = USE_REVERSE_ALWAYS + if isinstance(proper_left_type, TypedDictType): + # This is the reverse case: `TypedDict | dict`, + # simply do not allow the reverse checking: + # do not call `__dict__.__ror__`. + proper_right_type = get_proper_type(self.accept(e.right)) + if is_named_instance(proper_right_type, "builtins.dict"): + use_reverse = USE_REVERSE_NEVER + + if PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature: + # Handle tuple[X, ...] + tuple[Y, Z] = tuple[*tuple[X, ...], Y, Z]. + if ( + e.op == "+" + and isinstance(proper_left_type, Instance) + and proper_left_type.type.fullname == "builtins.tuple" + ): + proper_right_type = get_proper_type(self.accept(e.right)) + if ( + isinstance(proper_right_type, TupleType) + and proper_right_type.partial_fallback.type.fullname == "builtins.tuple" + and find_unpack_in_list(proper_right_type.items) is None + ): + return proper_right_type.copy_modified( + items=[UnpackType(proper_left_type)] + proper_right_type.items + ) + + if e.op in operators.op_methods: + method = operators.op_methods[e.op] + if use_reverse is UseReverse.DEFAULT or use_reverse is UseReverse.NEVER: + result, method_type = self.check_op( + method, + base_type=left_type, + arg=e.right, + context=e, + allow_reverse=use_reverse is UseReverse.DEFAULT, + ) + elif use_reverse is UseReverse.ALWAYS: + result, method_type = self.check_op( + # The reverse operator here gives better error messages: + operators.reverse_op_methods[method], + base_type=self.accept(e.right), + arg=e.left, + context=e, + allow_reverse=False, + ) + else: + assert_never(use_reverse) + e.method_type = method_type + return result + else: + raise RuntimeError(f"Unknown operator {e.op}") + + def visit_comparison_expr(self, e: ComparisonExpr) -> Type: + """Type check a comparison expression. + + Comparison expressions are type checked consecutive-pair-wise + That is, 'a < b > c == d' is check as 'a < b and b > c and c == d' + """ + result: Type | None = None + sub_result: Type + + # Check each consecutive operand pair and their operator + for left, right, operator in zip(e.operands, e.operands[1:], e.operators): + left_type = self.accept(left) + + if operator == "in" or operator == "not in": + # This case covers both iterables and containers, which have different meanings. + # For a container, the in operator calls the __contains__ method. + # For an iterable, the in operator iterates over the iterable, and compares each item one-by-one. + # We allow `in` for a union of containers and iterables as long as at least one of them matches the + # type of the left operand, as the operation will simply return False if the union's container/iterator + # type doesn't match the left operand. + + # If the right operand has partial type, look it up without triggering + # a "Need type annotation ..." message, as it would be noise. + right_type = self.find_partial_type_ref_fast_path(right) + if right_type is None: + right_type = self.accept(right) # Validate the right operand + + right_type = get_proper_type(right_type) + item_types: Sequence[Type] = [right_type] + if isinstance(right_type, UnionType): + item_types = list(right_type.relevant_items()) + + sub_result = self.bool_type() + + container_types: list[Type] = [] + iterable_types: list[Type] = [] + failed_out = False + encountered_partial_type = False + + for item_type in item_types: + # Keep track of whether we get type check errors (these won't be reported, they + # are just to verify whether something is valid typing wise). + with self.msg.filter_errors(save_filtered_errors=True) as container_errors: + _, method_type = self.check_method_call_by_name( + method="__contains__", + base_type=item_type, + args=[left], + arg_kinds=[ARG_POS], + context=e, + original_type=right_type, + ) + # Container item type for strict type overlap checks. Note: we need to only + # check for nominal type, because a usual "Unsupported operands for in" + # will be reported for types incompatible with __contains__(). + # See testCustomContainsCheckStrictEquality for an example. + cont_type = self.chk.analyze_container_item_type(item_type) + + if isinstance(item_type, PartialType): + # We don't really know if this is an error or not, so just shut up. + encountered_partial_type = True + pass + elif ( + container_errors.has_new_errors() + and + # is_valid_var_arg is True for any Iterable + self.is_valid_var_arg(item_type) + ): + # it's not a container, but it is an iterable + with self.msg.filter_errors(save_filtered_errors=True) as iterable_errors: + _, itertype = self.chk.analyze_iterable_item_type_without_expression( + item_type, e + ) + if iterable_errors.has_new_errors(): + self.msg.add_errors(iterable_errors.filtered_errors()) + failed_out = True + else: + method_type = CallableType( + [left_type], + [nodes.ARG_POS], + [None], + self.bool_type(), + self.named_type("builtins.function"), + ) + e.method_types.append(method_type) + iterable_types.append(itertype) + elif not container_errors.has_new_errors() and cont_type: + container_types.append(cont_type) + e.method_types.append(method_type) + else: + self.msg.add_errors(container_errors.filtered_errors()) + failed_out = True + + if not encountered_partial_type and not failed_out: + iterable_type = UnionType.make_union(iterable_types) + if not is_subtype(left_type, iterable_type): + if not container_types: + self.msg.unsupported_operand_types("in", left_type, right_type, e) + else: + container_type = UnionType.make_union(container_types) + if not self.chk.can_skip_diagnostics and self.dangerous_comparison( + left_type, + container_type, + original_container=right_type, + prefer_literal=False, + ): + self.msg.dangerous_comparison( + left_type, container_type, "container", e + ) + + elif operator in operators.op_methods: + method = operators.op_methods[operator] + + with ErrorWatcher(self.msg.errors) as w: + sub_result, method_type = self.check_op( + method, left_type, right, e, allow_reverse=True + ) + e.method_types.append(method_type) + + # Only show dangerous overlap if there are no other errors. See + # testCustomEqCheckStrictEquality for an example. + if not w.has_new_errors() and operator in ("==", "!="): + right_type = self.accept(right) + if not self.chk.can_skip_diagnostics and self.dangerous_comparison( + left_type, right_type + ): + # Show the most specific literal types possible + left_type = try_getting_literal(left_type) + right_type = try_getting_literal(right_type) + self.msg.dangerous_comparison(left_type, right_type, "equality", e) + + elif operator == "is" or operator == "is not": + right_type = self.accept(right) # validate the right operand + sub_result = self.bool_type() + if ( + not self.chk.can_skip_diagnostics + and self.dangerous_comparison(left_type, right_type, identity_check=True) + # Allow dangerous identity comparisons with objects explicitly typed as Any + and not ( + isinstance(left, NameExpr) + and isinstance(left.node, Var) + and not left.node.is_inferred + and isinstance(get_proper_type(left.node.type), AnyType) + ) + and not ( + isinstance(right, NameExpr) + and isinstance(right.node, Var) + and not right.node.is_inferred + and isinstance(get_proper_type(right.node.type), AnyType) + ) + ): + # Show the most specific literal types possible + left_type = try_getting_literal(left_type) + right_type = try_getting_literal(right_type) + self.msg.dangerous_comparison(left_type, right_type, "identity", e) + e.method_types.append(None) + else: + raise RuntimeError(f"Unknown comparison operator {operator}") + + # Determine type of boolean-and of result and sub_result + if result is None: + result = sub_result + else: + result = join.join_types(result, sub_result) + + assert result is not None + return result + + def find_partial_type_ref_fast_path(self, expr: Expression) -> Type | None: + """If expression has a partial generic type, return it without additional checks. + + In particular, this does not generate an error about a missing annotation. + + Otherwise, return None. + """ + if not isinstance(expr, RefExpr): + return None + if isinstance(expr.node, Var): + result = self.analyze_var_ref(expr.node, expr) + if isinstance(result, PartialType) and result.type is not None: + self.chk.store_type(expr, fixup_partial_type(result)) + return result + return None + + def dangerous_comparison( + self, + left: Type, + right: Type, + *, + original_container: Type | None = None, + seen_types: set[tuple[Type, Type]] | None = None, + prefer_literal: bool = True, + identity_check: bool = False, + ) -> bool: + """Check for dangerous non-overlapping comparisons like 42 == 'no'. + + The original_container is the original container type for 'in' checks + (and None for equality checks). + + Rules: + * X and None are overlapping even in strict-optional mode. This is to allow + 'assert x is not None' for x defined as 'x = None # type: str' in class body + (otherwise mypy itself would have couple dozen errors because of this). + * Optional[X] and Optional[Y] are non-overlapping if X and Y are + non-overlapping, although technically None is overlap, it is most + likely an error. + * Any overlaps with everything, i.e. always safe. + * Special case: b'abc' in b'cde' is safe. + """ + if not self.chk.options.strict_equality: + return False + + if seen_types is None: + seen_types = set() + if (left, right) in seen_types: + return False + seen_types.add((left, right)) + + left, right = get_proper_types((left, right)) + + # We suppress the error for equality and container checks if there is a custom __eq__() + # method on either side. User defined (or even standard library) classes can define this + # to return True for comparisons between non-overlapping types. + if ( + custom_special_method(left, "__eq__") or custom_special_method(right, "__eq__") + ) and not identity_check: + return False + + if prefer_literal: + # Also flag non-overlapping literals in situations like: + # x: Literal['a', 'b'] + # if x == 'c': + # ... + left = try_getting_literal(left) + right = try_getting_literal(right) + + if self.chk.binder.is_unreachable_warning_suppressed(): + # We are inside a function that contains type variables with value restrictions in + # its signature. In this case we just suppress all strict-equality checks to avoid + # false positives for code like: + # + # T = TypeVar('T', str, int) + # def f(x: T) -> T: + # if x == 0: + # ... + # return x + # + # TODO: find a way of disabling the check only for types resulted from the expansion. + return False + if self.chk.options.strict_equality_for_none: + if isinstance(left, NoneType) and isinstance(right, NoneType): + return False + elif isinstance(left, NoneType) or isinstance(right, NoneType): + return False + if isinstance(left, UnionType) and isinstance(right, UnionType): + left = remove_optional(left) + right = remove_optional(right) + left, right = get_proper_types((left, right)) + if ( + original_container + and has_bytes_component(original_container) + and has_bytes_component(left) + ): + # We need to special case bytes and bytearray, because 97 in b'abc', b'a' in b'abc', + # b'a' in bytearray(b'abc') etc. all return True (and we want to show the error only + # if the check can _never_ be True). + return False + if isinstance(left, Instance) and isinstance(right, Instance): + # Special case some builtin implementations of AbstractSet. + left_name = left.type.fullname + right_name = right.type.fullname + if ( + left_name in OVERLAPPING_TYPES_ALLOWLIST + and right_name in OVERLAPPING_TYPES_ALLOWLIST + ): + abstract_set = self.chk.lookup_typeinfo("typing.AbstractSet") + left = map_instance_to_supertype(left, abstract_set) + right = map_instance_to_supertype(right, abstract_set) + return self.dangerous_comparison( + left.args[0], right.args[0], seen_types=seen_types + ) + elif left.type.has_base("typing.Mapping") and right.type.has_base("typing.Mapping"): + # Similar to above: Mapping ignores the classes, it just compares items. + abstract_map = self.chk.lookup_typeinfo("typing.Mapping") + left = map_instance_to_supertype(left, abstract_map) + right = map_instance_to_supertype(right, abstract_map) + return self.dangerous_comparison( + left.args[0], right.args[0], seen_types=seen_types + ) or self.dangerous_comparison(left.args[1], right.args[1], seen_types=seen_types) + elif left_name in ("builtins.list", "builtins.tuple") and right_name == left_name: + return self.dangerous_comparison( + left.args[0], right.args[0], seen_types=seen_types + ) + elif left_name in OVERLAPPING_BYTES_ALLOWLIST and right_name in ( + OVERLAPPING_BYTES_ALLOWLIST + ): + return False + if isinstance(left, LiteralType) and isinstance(right, LiteralType): + if isinstance(left.value, bool) and isinstance(right.value, bool): + # Comparing different booleans is not dangerous. + return False + if isinstance(left, LiteralType) and isinstance(right, Instance): + # bytes/bytearray comparisons are supported + if left.fallback.type.fullname == "builtins.bytes" and right.type.has_base( + "builtins.bytearray" + ): + return False + if isinstance(right, LiteralType) and isinstance(left, Instance): + # bytes/bytearray comparisons are supported + if right.fallback.type.fullname == "builtins.bytes" and left.type.has_base( + "builtins.bytearray" + ): + return False + return not is_overlapping_types(left, right, ignore_promotions=False) + + def check_method_call_by_name( + self, + method: str, + base_type: Type, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + original_type: Type | None = None, + self_type: Type | None = None, + ) -> tuple[Type, Type]: + """Type check a call to a named method on an object. + + Return tuple (result type, inferred method type). The 'original_type' + is used for error messages. The self_type is to bind self in methods + (see analyze_member_access for more details). + """ + original_type = original_type or base_type + self_type = self_type or base_type + # Unions are special-cased to allow plugins to act on each element of the union. + base_type = get_proper_type(base_type) + if isinstance(base_type, UnionType): + return self.check_union_method_call_by_name( + method, base_type, args, arg_kinds, context, original_type + ) + + method_type = analyze_member_access( + method, + base_type, + context, + is_lvalue=False, + is_super=False, + is_operator=True, + original_type=original_type, + self_type=self_type, + chk=self.chk, + in_literal_context=self.is_literal_context(), + ) + return self.check_method_call(method, base_type, method_type, args, arg_kinds, context) + + def check_union_method_call_by_name( + self, + method: str, + base_type: UnionType, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + original_type: Type | None = None, + ) -> tuple[Type, Type]: + """Type check a call to a named method on an object with union type. + + This essentially checks the call using check_method_call_by_name() for each + union item and unions the result. We do this to allow plugins to act on + individual union items. + """ + res: list[Type] = [] + meth_res: list[Type] = [] + for typ in base_type.relevant_items(): + # Format error messages consistently with + # mypy.checkmember.analyze_union_member_access(). + with self.msg.disable_type_names(): + item, meth_item = self.check_method_call_by_name( + method, typ, args, arg_kinds, context, original_type + ) + res.append(item) + meth_res.append(meth_item) + return make_simplified_union(res), make_simplified_union(meth_res) + + def check_method_call( + self, + method_name: str, + base_type: Type, + method_type: Type, + args: list[Expression], + arg_kinds: list[ArgKind], + context: Context, + ) -> tuple[Type, Type]: + """Type check a call to a method with the given name and type on an object. + + Return tuple (result type, inferred method type). + """ + callable_name = self.method_fullname(base_type, method_name) + object_type = base_type if callable_name is not None else None + + # Try to refine the method signature using plugin hooks before checking the call. + method_type = self.transform_callee_type( + callable_name, method_type, args, arg_kinds, context, object_type=object_type + ) + + return self.check_call( + method_type, + args, + arg_kinds, + context, + callable_name=callable_name, + object_type=base_type, + ) + + def check_op_reversible( + self, + op_name: str, + left_type: Type, + left_expr: Expression, + right_type: Type, + right_expr: Expression, + context: Context, + ) -> tuple[Type, Type]: + def lookup_operator(op_name: str, base_type: Type) -> Type | None: + """Looks up the given operator and returns the corresponding type, + if it exists.""" + + # This check is an important performance optimization. + if not has_operator(base_type, op_name, self.named_type): + return None + + with self.msg.filter_errors() as w: + member = analyze_member_access( + name=op_name, + typ=base_type, + is_lvalue=False, + is_super=False, + is_operator=True, + original_type=base_type, + context=context, + chk=self.chk, + in_literal_context=self.is_literal_context(), + ) + return None if w.has_new_errors() else member + + def lookup_definer(typ: Instance, attr_name: str) -> str | None: + """Returns the name of the class that contains the actual definition of attr_name. + + So if class A defines foo and class B subclasses A, running + 'get_class_defined_in(B, "foo")` would return the full name of A. + + However, if B were to override and redefine foo, that method call would + return the full name of B instead. + + If the attr name is not present in the given class or its MRO, returns None. + """ + for cls in typ.type.mro: + if cls.names.get(attr_name): + return cls.fullname + return None + + left_type = get_proper_type(left_type) + right_type = get_proper_type(right_type) + + # If either the LHS or the RHS are Any, we can't really concluding anything + # about the operation since the Any type may or may not define an + # __op__ or __rop__ method. So, we punt and return Any instead. + + if isinstance(left_type, AnyType): + any_type = AnyType(TypeOfAny.from_another_any, source_any=left_type) + return any_type, any_type + if isinstance(right_type, AnyType): + any_type = AnyType(TypeOfAny.from_another_any, source_any=right_type) + return any_type, any_type + + # STEP 1: + # We start by getting the __op__ and __rop__ methods, if they exist. + + rev_op_name = operators.reverse_op_methods[op_name] + + left_op = lookup_operator(op_name, left_type) + right_op = lookup_operator(rev_op_name, right_type) + + # STEP 2a: + # We figure out in which order Python will call the operator methods. As it + # turns out, it's not as simple as just trying to call __op__ first and + # __rop__ second. + # + # We store the determined order inside the 'variants_raw' variable, + # which records tuples containing the method, base type, and the argument. + + if op_name in operators.op_methods_that_shortcut and is_same_type(left_type, right_type): + # When we do "A() + A()", for example, Python will only call the __add__ method, + # never the __radd__ method. + # + # This is the case even if the __add__ method is completely missing and the __radd__ + # method is defined. + + variants_raw = [(op_name, left_op, left_type, right_expr)] + elif ( + ( + # Checking (A implies B) using the logically equivalent (not A or B), where + # A: left and right are both `Instance` objects + # B: right's __rop__ method is different from left's __op__ method + not (isinstance(left_type, Instance) and isinstance(right_type, Instance)) + or ( + lookup_definer(left_type, op_name) != lookup_definer(right_type, rev_op_name) + and ( + left_type.type.alt_promote is None + or left_type.type.alt_promote.type is not right_type.type + ) + ) + ) + # Note: use `covers_at_runtime` instead of `is_subtype` (#19006) + and covers_at_runtime(right_type, left_type) + ): + # When we do "A() + B()" where B is a subclass of A, we'll actually try calling + # B's __radd__ method first, but ONLY if B explicitly defines or overrides the + # __radd__ method. + # + # This mechanism lets subclasses "refine" the expected outcome of the operation, even + # if they're located on the RHS. + # + # As a special case, the alt_promote check makes sure that we don't use the + # __radd__ method of int if the LHS is a native int type. + + variants_raw = [ + (rev_op_name, right_op, right_type, left_expr), + (op_name, left_op, left_type, right_expr), + ] + else: + # In all other cases, we do the usual thing and call __add__ first and + # __radd__ second when doing "A() + B()". + + variants_raw = [ + (op_name, left_op, left_type, right_expr), + (rev_op_name, right_op, right_type, left_expr), + ] + + # STEP 3: + # We now filter out all non-existent operators. The 'variants' list contains + # all operator methods that are actually present, in the order that Python + # attempts to invoke them. + + variants = [(na, op, obj, arg) for (na, op, obj, arg) in variants_raw if op is not None] + + # STEP 4: + # We now try invoking each one. If an operation succeeds, end early and return + # the corresponding result. Otherwise, return the result and errors associated + # with the first entry. + + errors = [] + results = [] + for name, method, obj, arg in variants: + with self.msg.filter_errors(save_filtered_errors=True) as local_errors: + result = self.check_method_call(name, obj, method, [arg], [ARG_POS], context) + if local_errors.has_new_errors(): + errors.append(local_errors.filtered_errors()) + results.append(result) + else: + return result + + # We finish invoking above operators and no early return happens. Therefore, + # we check if either the LHS or the RHS is Instance and fallbacks to Any, + # if so, we also return Any + if (isinstance(left_type, Instance) and left_type.type.fallback_to_any) or ( + isinstance(right_type, Instance) and right_type.type.fallback_to_any + ): + any_type = AnyType(TypeOfAny.special_form) + return any_type, any_type + + # STEP 4b: + # Sometimes, the variants list is empty. In that case, we fall-back to attempting to + # call the __op__ method (even though it's missing). + + if not variants: + with self.msg.filter_errors(save_filtered_errors=True) as local_errors: + result = self.check_method_call_by_name( + op_name, left_type, [right_expr], [ARG_POS], context + ) + + if local_errors.has_new_errors(): + errors.append(local_errors.filtered_errors()) + results.append(result) + else: + # Although we should not need this case anymore, we keep it just in case, as + # otherwise we will get a crash if we introduce inconsistency in checkmember.py + return result + + self.msg.add_errors(errors[0]) + if len(results) == 1: + return results[0] + else: + error_any = AnyType(TypeOfAny.from_error) + result = error_any, error_any + return result + + def check_op( + self, + method: str, + base_type: Type, + arg: Expression, + context: Context, + allow_reverse: bool = False, + ) -> tuple[Type, Type]: + """Type check a binary operation which maps to a method call. + + Return tuple (result type, inferred operator method type). + """ + + if allow_reverse: + left_variants = [base_type] + base_type = get_proper_type(base_type) + if isinstance(base_type, UnionType): + left_variants = list(flatten_nested_unions(base_type.relevant_items())) + right_type = self.accept(arg) + + # Step 1: We first try leaving the right arguments alone and destructure + # just the left ones. (Mypy can sometimes perform some more precise inference + # if we leave the right operands a union -- see testOperatorWithEmptyListAndSum.) + all_results = [] + all_inferred = [] + + with self.msg.filter_errors() as local_errors: + for left_possible_type in left_variants: + result, inferred = self.check_op_reversible( + op_name=method, + left_type=left_possible_type, + left_expr=TempNode(left_possible_type, context=context), + right_type=right_type, + right_expr=arg, + context=context, + ) + all_results.append(result) + all_inferred.append(inferred) + + if not local_errors.has_new_errors(): + results_final = make_simplified_union(all_results) + inferred_final = make_simplified_union(all_inferred) + return results_final, inferred_final + + # Step 2: If that fails, we try again but also destructure the right argument. + # This is also necessary to make certain edge cases work -- see + # testOperatorDoubleUnionInterwovenUnionAdd, for example. + + # Note: We want to pass in the original 'arg' for 'left_expr' and 'right_expr' + # whenever possible so that plugins and similar things can introspect on the original + # node if possible. + # + # We don't do the same for the base expression because it could lead to weird + # type inference errors -- e.g. see 'testOperatorDoubleUnionSum'. + # TODO: Can we use `type_overrides_set()` here? + right_variants = [(right_type, arg)] + right_type = get_proper_type(right_type) + if isinstance(right_type, UnionType): + right_variants = [ + (item, TempNode(item, context=context)) + for item in flatten_nested_unions(right_type.relevant_items()) + ] + + all_results = [] + all_inferred = [] + + with self.msg.filter_errors(save_filtered_errors=True) as local_errors: + for left_possible_type in left_variants: + for right_possible_type, right_expr in right_variants: + result, inferred = self.check_op_reversible( + op_name=method, + left_type=left_possible_type, + left_expr=TempNode(left_possible_type, context=context), + right_type=right_possible_type, + right_expr=right_expr, + context=context, + ) + all_results.append(result) + all_inferred.append(inferred) + + if local_errors.has_new_errors(): + self.msg.add_errors(local_errors.filtered_errors()) + # Point any notes to the same location as an existing message. + err = local_errors.filtered_errors()[-1] + recent_context = TempNode(NoneType()) + recent_context.line = err.line + recent_context.column = err.column + if len(left_variants) >= 2 and len(right_variants) >= 2: + self.msg.warn_both_operands_are_from_unions(recent_context) + elif len(left_variants) >= 2: + self.msg.warn_operand_was_from_union("Left", base_type, context=recent_context) + elif len(right_variants) >= 2: + self.msg.warn_operand_was_from_union( + "Right", right_type, context=recent_context + ) + + # See the comment in 'check_overload_call' for more details on why + # we call 'combine_function_signature' instead of just unioning the inferred + # callable types. + results_final = make_simplified_union(all_results) + inferred_final = self.combine_function_signatures(get_proper_types(all_inferred)) + return results_final, inferred_final + else: + return self.check_method_call_by_name( + method=method, + base_type=base_type, + args=[arg], + arg_kinds=[ARG_POS], + context=context, + ) + + def check_boolean_op(self, e: OpExpr) -> Type: + """Type check a boolean operation ('and' or 'or').""" + + # A boolean operation can evaluate to either of the operands. + + # We use the current type context to guide the type inference of + # the left operand. We also use the left operand type to guide the type + # inference of the right operand so that expressions such as + # '[1] or []' are inferred correctly. + ctx = self.type_context[-1] + left_type = self.accept(e.left, ctx) + expanded_left_type = try_expanding_sum_type_to_union(left_type, "builtins.bool") + + assert e.op in ("and", "or") # Checked by visit_op_expr + + left_map: mypy.checker.TypeMap + right_map: mypy.checker.TypeMap + if e.right_always: + left_map, right_map = {e.left: UninhabitedType()}, {} + elif e.right_unreachable: + left_map, right_map = {}, {e.right: UninhabitedType()} + elif e.op == "and": + right_map, left_map = self.chk.find_isinstance_check(e.left) + elif e.op == "or": + left_map, right_map = self.chk.find_isinstance_check(e.left) + + # If left_map is unreachable then we know mypy considers the left expression + # to be redundant. + left_unreachable = mypy.checker.is_unreachable_map(left_map) + if ( + codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes + and left_unreachable + # don't report an error if it's intentional + and not e.right_always + ): + self.msg.redundant_left_operand(e.op, e.left) + + right_unreachable = mypy.checker.is_unreachable_map(right_map) + if ( + self.chk.should_report_unreachable_issues() + and right_unreachable + # don't report an error if it's intentional + and not e.right_unreachable + ): + self.msg.unreachable_right_operand(e.op, e.right) + + right_type = self.analyze_cond_branch( + right_map, e.right, self._combined_context(expanded_left_type) + ) + + if left_unreachable and right_unreachable: + return UninhabitedType() + + if right_unreachable: + # The boolean expression is statically known to be the left value + return left_type + if left_unreachable: + # The boolean expression is statically known to be the right value + return right_type + + if e.op == "and": + restricted_left_type = false_only(expanded_left_type) + result_is_left = not expanded_left_type.can_be_true + elif e.op == "or": + restricted_left_type = true_only(expanded_left_type) + result_is_left = not expanded_left_type.can_be_false + + if isinstance(restricted_left_type, UninhabitedType): + # The left operand can never be the result + return right_type + elif result_is_left: + # The left operand is always the result + return left_type + else: + return make_simplified_union([restricted_left_type, right_type]) + + def check_list_multiply(self, e: OpExpr) -> Type: + """Type check an expression of form '[...] * e'. + + Type inference is special-cased for this common construct. + """ + right_type = self.accept(e.right) + if is_subtype(right_type, self.named_type("builtins.int")): + # Special case: [...] * . Use the type context of the + # OpExpr, since the multiplication does not affect the type. + left_type = self.accept(e.left, type_context=self.type_context[-1]) + else: + left_type = self.accept(e.left) + result, method_type = self.check_op("__mul__", left_type, e.right, e) + e.method_type = method_type + return result + + def visit_assignment_expr(self, e: AssignmentExpr) -> Type: + value = self.accept(e.value) + self.chk.check_assignment(e.target, e.value) + self.chk.check_final(e) + if not has_uninhabited_component(value): + # TODO: can we get rid of this extra store_type()? + # Usually, check_assignment() already stores the lvalue type correctly. + self.chk.store_type(e.target, value) + self.find_partial_type_ref_fast_path(e.target) + return value + + def visit_unary_expr(self, e: UnaryExpr) -> Type: + """Type check an unary operation ('not', '-', '+' or '~').""" + operand_type = self.accept(e.expr) + op = e.op + if op == "not": + result: Type = self.bool_type() + self.chk.check_for_truthy_type(operand_type, e.expr) + else: + method = operators.unary_op_methods[op] + result, method_type = self.check_method_call_by_name(method, operand_type, [], [], e) + e.method_type = method_type + return result + + def visit_index_expr(self, e: IndexExpr) -> Type: + """Type check an index expression (base[index]). + + It may also represent type application. + """ + result = self.visit_index_expr_helper(e) + result = self.narrow_type_from_binder(e, result) + p_result = get_proper_type(result) + if ( + self.is_literal_context() + and isinstance(p_result, Instance) + and p_result.last_known_value is not None + ): + result = p_result.last_known_value + return result + + def visit_index_expr_helper(self, e: IndexExpr) -> Type: + if e.analyzed: + # It's actually a type application. + return self.accept(e.analyzed) + left_type = self.accept(e.base) + return self.visit_index_with_type(left_type, e) + + def visit_index_with_type( + self, + left_type: Type, + e: IndexExpr, + original_type: ProperType | None = None, + self_type: Type | None = None, + ) -> Type: + """Analyze type of an index expression for a given type of base expression. + + The 'original_type' is used for error messages (currently used for union types). The + 'self_type' is to bind self in methods (see analyze_member_access for more details). + """ + index = e.index + self_type = self_type or left_type + left_type = get_proper_type(left_type) + + # Visit the index, just to make sure we have a type for it available + self.accept(index) + + if isinstance(left_type, TupleType) and any( + isinstance(it, UnpackType) for it in left_type.items + ): + # Normalize variadic tuples for consistency. + left_type = expand_type(left_type, {}) + + if isinstance(left_type, UnionType): + original_type = original_type or left_type + # Don't combine literal types, since we may need them for type narrowing. + return make_simplified_union( + [ + self.visit_index_with_type(typ, e, original_type) + for typ in left_type.relevant_items() + ], + contract_literals=False, + ) + elif isinstance(left_type, TupleType) and self.chk.in_checked_function(): + # Special case for tuples. They return a more specific type when + # indexed by an integer literal. + if isinstance(index, SliceExpr): + return self.visit_tuple_slice_helper(left_type, index) + + ns = self.try_getting_int_literals(index) + if ns is not None: + out = [] + for n in ns: + item = self.visit_tuple_index_helper(left_type, n) + if item is not None: + out.append(item) + else: + self.chk.fail(message_registry.TUPLE_INDEX_OUT_OF_RANGE, e) + if any(isinstance(t, UnpackType) for t in left_type.items): + min_len = self.min_tuple_length(left_type) + self.chk.note(f"Variadic tuple can have length {min_len}", e) + return AnyType(TypeOfAny.from_error) + return make_simplified_union(out) + else: + return self.nonliteral_tuple_index_helper(left_type, index) + elif isinstance(left_type, TypedDictType): + return self.visit_typeddict_index_expr(left_type, e.index)[0] + elif isinstance(left_type, FunctionLike) and left_type.is_type_obj(): + if left_type.type_object().is_enum: + return self.visit_enum_index_expr(left_type.type_object(), e.index, e) + elif ( + left_type.type_object().type_vars + or left_type.type_object().fullname == "builtins.type" + ): + return self.named_type("types.GenericAlias") + + if isinstance(left_type, TypeVarType): + return self.visit_index_with_type( + left_type.values_or_bound(), e, original_type, left_type + ) + elif isinstance(left_type, Instance) and left_type.type.fullname == "typing._SpecialForm": + # Allow special forms to be indexed and used to create union types + return self.named_type("typing._SpecialForm") + else: + result, method_type = self.check_method_call_by_name( + "__getitem__", + left_type, + [e.index], + [ARG_POS], + e, + original_type=original_type, + self_type=self_type, + ) + e.method_type = method_type + return result + + def min_tuple_length(self, left: TupleType) -> int: + unpack_index = find_unpack_in_list(left.items) + if unpack_index is None: + return left.length() + unpack = left.items[unpack_index] + assert isinstance(unpack, UnpackType) + if isinstance(unpack.type, TypeVarTupleType): + return left.length() - 1 + unpack.type.min_len + return left.length() - 1 + + def visit_tuple_index_helper(self, left: TupleType, n: int) -> Type | None: + unpack_index = find_unpack_in_list(left.items) + if unpack_index is None: + if n < 0: + n += len(left.items) + if 0 <= n < len(left.items): + return left.items[n] + return None + unpack = left.items[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + if isinstance(unpacked, TypeVarTupleType): + # Usually we say that TypeVarTuple can't be split, be in case of + # indexing it seems benign to just return the upper bound item, similar + # to what we do when indexing a regular TypeVar. + bound = get_proper_type(unpacked.upper_bound) + assert isinstance(bound, Instance) + assert bound.type.fullname == "builtins.tuple" + middle = bound.args[0] + else: + assert isinstance(unpacked, Instance) + assert unpacked.type.fullname == "builtins.tuple" + middle = unpacked.args[0] + + extra_items = self.min_tuple_length(left) - left.length() + 1 + if n >= 0: + if n >= self.min_tuple_length(left): + # For tuple[int, *tuple[str, ...], int] we allow either index 0 or 1, + # since variadic item may have zero items. + return None + if n < unpack_index: + return left.items[n] + return UnionType.make_union( + [middle] + + left.items[unpack_index + 1 : max(n - extra_items + 2, unpack_index + 1)], + left.line, + left.column, + ) + n += self.min_tuple_length(left) + if n < 0: + # Similar to above, we only allow -1, and -2 for tuple[int, *tuple[str, ...], int] + return None + if n >= unpack_index + extra_items: + return left.items[n - extra_items + 1] + return UnionType.make_union( + left.items[min(n, unpack_index) : unpack_index] + [middle], left.line, left.column + ) + + def visit_tuple_slice_helper(self, left_type: TupleType, slic: SliceExpr) -> Type: + begin: Sequence[int | None] = [None] + end: Sequence[int | None] = [None] + stride: Sequence[int | None] = [None] + + if slic.begin_index: + begin_raw = self.try_getting_int_literals(slic.begin_index) + if begin_raw is None: + return self.nonliteral_tuple_index_helper(left_type, slic) + begin = begin_raw + + if slic.end_index: + end_raw = self.try_getting_int_literals(slic.end_index) + if end_raw is None: + return self.nonliteral_tuple_index_helper(left_type, slic) + end = end_raw + + if slic.stride: + stride_raw = self.try_getting_int_literals(slic.stride) + if stride_raw is None: + return self.nonliteral_tuple_index_helper(left_type, slic) + stride = stride_raw + + items: list[Type] = [] + for b, e, s in itertools.product(begin, end, stride): + item = left_type.slice(b, e, s, fallback=self.named_type("builtins.tuple")) + if item is None: + self.chk.fail(message_registry.AMBIGUOUS_SLICE_OF_VARIADIC_TUPLE, slic) + return AnyType(TypeOfAny.from_error) + items.append(item) + return make_simplified_union(items) + + def try_getting_int_literals(self, index: Expression) -> list[int] | None: + """If the given expression or type corresponds to an int literal + or a union of int literals, returns a list of the underlying ints. + Otherwise, returns None. + + Specifically, this function is guaranteed to return a list with + one or more ints if one the following is true: + + 1. 'expr' is a IntExpr or a UnaryExpr backed by an IntExpr + 2. 'typ' is a LiteralType containing an int + 3. 'typ' is a UnionType containing only LiteralType of ints + """ + if isinstance(index, IntExpr): + return [index.value] + elif isinstance(index, UnaryExpr): + if index.op == "-": + operand = index.expr + if isinstance(operand, IntExpr): + return [-1 * operand.value] + if index.op == "+": + operand = index.expr + if isinstance(operand, IntExpr): + return [operand.value] + typ = get_proper_type(self.accept(index)) + if isinstance(typ, Instance) and typ.last_known_value is not None: + typ = typ.last_known_value + if isinstance(typ, LiteralType) and isinstance(typ.value, int): + return [typ.value] + if isinstance(typ, UnionType): + out = [] + for item in get_proper_types(typ.items): + if isinstance(item, LiteralType) and isinstance(item.value, int): + out.append(item.value) + else: + return None + return out + return None + + def nonliteral_tuple_index_helper(self, left_type: TupleType, index: Expression) -> Type: + self.check_method_call_by_name("__getitem__", left_type, [index], [ARG_POS], context=index) + # We could return the return type from above, but unions are often better than the join + union = self.union_tuple_fallback_item(left_type) + if isinstance(index, SliceExpr): + return self.chk.named_generic_type("builtins.tuple", [union]) + return union + + def union_tuple_fallback_item(self, left_type: TupleType) -> Type: + # TODO: this duplicates logic in typeops.tuple_fallback(). + items = [] + for item in left_type.items: + if isinstance(item, UnpackType): + unpacked_type = get_proper_type(item.type) + if isinstance(unpacked_type, TypeVarTupleType): + unpacked_type = get_proper_type(unpacked_type.upper_bound) + if ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ): + items.append(unpacked_type.args[0]) + else: + raise NotImplementedError + else: + items.append(item) + return make_simplified_union(items) + + def visit_typeddict_index_expr( + self, td_type: TypedDictType, index: Expression, setitem: bool = False + ) -> tuple[Type, set[str]]: + if isinstance(index, StrExpr): + key_names = [index.value] + else: + typ = get_proper_type(self.accept(index)) + if isinstance(typ, UnionType): + key_types: list[Type] = list(typ.items) + else: + key_types = [typ] + + key_names = [] + for key_type in get_proper_types(key_types): + if isinstance(key_type, Instance) and key_type.last_known_value is not None: + key_type = key_type.last_known_value + + if ( + isinstance(key_type, LiteralType) + and isinstance(key_type.value, str) + and key_type.fallback.type.fullname != "builtins.bytes" + ): + key_names.append(key_type.value) + else: + self.msg.typeddict_key_must_be_string_literal(td_type, index) + return AnyType(TypeOfAny.from_error), set() + + value_types = [] + for key_name in key_names: + value_type = td_type.items.get(key_name) + if value_type is None: + self.msg.typeddict_key_not_found(td_type, key_name, index, setitem) + return AnyType(TypeOfAny.from_error), set() + else: + value_types.append(value_type) + return make_simplified_union(value_types), set(key_names) + + def visit_enum_index_expr( + self, enum_type: TypeInfo, index: Expression, context: Context + ) -> Type: + string_type: Type = self.named_type("builtins.str") + self.chk.check_subtype( + self.accept(index), + string_type, + context, + "Enum index should be a string", + "actual index type", + ) + return Instance(enum_type, []) + + def visit_cast_expr(self, expr: CastExpr) -> Type: + """Type check a cast expression.""" + source_type = self.accept( + expr.expr, + type_context=AnyType(TypeOfAny.special_form), + allow_none_return=True, + always_allow_any=True, + ) + target_type = expr.type + options = self.chk.options + if ( + options.warn_redundant_casts + and not is_same_type(target_type, AnyType(TypeOfAny.special_form)) + and is_same_type(source_type, target_type) + ): + self.msg.redundant_cast(target_type, expr) + if options.disallow_any_unimported and has_any_from_unimported_type(target_type): + self.msg.unimported_type_becomes_any("Target type of cast", target_type, expr) + check_for_explicit_any( + target_type, self.chk.options, self.chk.is_typeshed_stub, self.msg, context=expr + ) + return target_type + + def visit_type_form_expr(self, expr: TypeFormExpr) -> Type: + typ = expr.type + return TypeType.make_normalized(typ, line=typ.line, column=typ.column, is_type_form=True) + + def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type: + source_type = self.accept( + expr.expr, + type_context=self.type_context[-1], + allow_none_return=True, + always_allow_any=True, + ) + if self.chk.current_node_deferred: + return source_type + + target_type = expr.type + proper_source_type = get_proper_type(source_type) + if ( + isinstance(proper_source_type, mypy.types.Instance) + and proper_source_type.last_known_value is not None + ): + source_type = proper_source_type.last_known_value + if not is_same_type(source_type, target_type): + if not self.chk.in_checked_function(): + self.msg.note( + '"assert_type" expects everything to be "Any" in unchecked functions', + expr.expr, + ) + self.msg.assert_type_fail(source_type, target_type, expr) + return source_type + + def visit_reveal_expr(self, expr: RevealExpr) -> Type: + """Type check a reveal_type expression.""" + if expr.kind == REVEAL_TYPE: + assert expr.expr is not None + revealed_type = self.accept( + expr.expr, type_context=self.type_context[-1], allow_none_return=True + ) + if not self.chk.current_node_deferred: + self.msg.reveal_type(revealed_type, expr.expr) + if not self.chk.in_checked_function(): + self.msg.note( + "'reveal_type' always outputs 'Any' in unchecked functions", expr.expr + ) + self.check_reveal_imported(expr) + return revealed_type + else: + # REVEAL_LOCALS + if not self.chk.current_node_deferred: + # the RevealExpr contains a local_nodes attribute, + # calculated at semantic analysis time. Use it to pull out the + # corresponding subset of variables in self.chk.type_map + names_to_types = ( + {var_node.name: var_node.type for var_node in expr.local_nodes} + if expr.local_nodes is not None + else {} + ) + + self.msg.reveal_locals(names_to_types, expr) + self.check_reveal_imported(expr) + return NoneType() + + def check_reveal_imported(self, expr: RevealExpr) -> None: + if codes.UNIMPORTED_REVEAL not in self.chk.options.enabled_error_codes: + return + + name = "" + if expr.kind == REVEAL_LOCALS: + name = "reveal_locals" + elif expr.kind == REVEAL_TYPE and not expr.is_imported: + name = "reveal_type" + else: + return + + self.chk.fail(f'Name "{name}" is not defined', expr, code=codes.UNIMPORTED_REVEAL) + if name == "reveal_type": + module = ( + "typing" if self.chk.options.python_version >= (3, 11) else "typing_extensions" + ) + hint = ( + 'Did you forget to import it from "{module}"?' + ' (Suggestion: "from {module} import {name}")' + ).format(module=module, name=name) + self.chk.note(hint, expr, code=codes.UNIMPORTED_REVEAL) + + def visit_type_application(self, tapp: TypeApplication) -> Type: + """Type check a type application (expr[type, ...]). + + There are two different options here, depending on whether expr refers + to a type alias or directly to a generic class. In the first case we need + to use a dedicated function typeanal.instantiate_type_alias(). This + is due to slight differences in how type arguments are applied and checked. + """ + if isinstance(tapp.expr, RefExpr) and isinstance(tapp.expr.node, TypeAlias): + if tapp.expr.node.python_3_12_type_alias: + return self.type_alias_type_type() + # Subscription of a (generic) alias in runtime context, expand the alias. + item = instantiate_type_alias( + tapp.expr.node, + tapp.types, + self.chk.fail, + tapp.expr.node.no_args, + tapp, + self.chk.options, + ) + item = get_proper_type(item) + if isinstance(item, Instance): + tp = type_object_type(item.type, self.named_type) + return self.apply_type_arguments_to_callable(tp, item.args, tapp) + elif isinstance(item, TupleType) and item.partial_fallback.type.is_named_tuple: + tp = type_object_type(item.partial_fallback.type, self.named_type) + return self.apply_type_arguments_to_callable(tp, item.partial_fallback.args, tapp) + elif isinstance(item, TypedDictType): + return self.typeddict_callable_from_context(item) + else: + self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp) + return AnyType(TypeOfAny.from_error) + # Type application of a normal generic class in runtime context. + # This is typically used as `x = G[int]()`. + tp = get_proper_type(self.accept(tapp.expr)) + if isinstance(tp, (CallableType, Overloaded)): + if not tp.is_type_obj(): + self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp) + return self.apply_type_arguments_to_callable(tp, tapp.types, tapp) + if isinstance(tp, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=tp) + return AnyType(TypeOfAny.special_form) + + def visit_type_alias_expr(self, alias: TypeAliasExpr) -> Type: + """Right hand side of a type alias definition. + + It has the same type as if the alias itself was used in a runtime context. + For example, here: + + A = reveal_type(List[T]) + reveal_type(A) + + both `reveal_type` instances will reveal the same type `def (...) -> builtins.list[Any]`. + Note that type variables are implicitly substituted with `Any`. + """ + return self.alias_type_in_runtime_context(alias.node, ctx=alias, alias_definition=True) + + def alias_type_in_runtime_context( + self, alias: TypeAlias, *, ctx: Context, alias_definition: bool = False + ) -> Type: + """Get type of a type alias (could be generic) in a runtime expression. + + Note that this function can be called only if the alias appears _not_ + as a target of type application, which is treated separately in the + visit_type_application method. Some examples where this method is called are + casts and instantiation: + + class LongName(Generic[T]): ... + A = LongName[int] + + x = A() + y = cast(A, ...) + """ + if alias.python_3_12_type_alias: + return self.type_alias_type_type() + # If this is a generic alias, we set all variables to `Any`. + # For example: + # A = List[Tuple[T, T]] + # x = A() <- same as List[Tuple[Any, Any]], see PEP 484. + disallow_any = self.chk.options.disallow_any_generics and self.is_callee + item = get_proper_type( + set_any_tvars( + alias, + [], + ctx.line, + ctx.column, + self.chk.options, + disallow_any=disallow_any, + fail=self.msg.fail, + ) + ) + if isinstance(item, Instance): + # Normally we get a callable type (or overloaded) with .is_type_obj() true + # representing the class's constructor + tp = type_object_type(item.type, self.named_type) + if alias.no_args: + return tp + return self.apply_type_arguments_to_callable(tp, item.args, ctx) + elif ( + isinstance(item, TupleType) + and + # Tuple[str, int]() fails at runtime, only named tuples and subclasses work. + tuple_fallback(item).type.fullname != "builtins.tuple" + ): + return type_object_type(tuple_fallback(item).type, self.named_type) + elif isinstance(item, TypedDictType): + return self.typeddict_callable_from_context(item) + elif isinstance(item, NoneType): + return TypeType(item, line=item.line, column=item.column) + elif isinstance(item, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=item) + elif ( + isinstance(item, UnionType) + and item.uses_pep604_syntax + and self.chk.options.python_version >= (3, 10) + ): + return self.chk.named_generic_type("types.UnionType", item.items) + else: + if alias_definition: + return AnyType(TypeOfAny.special_form) + # The _SpecialForm type can be used in some runtime contexts (e.g. it may have __or__). + return self.named_type("typing._SpecialForm") + + def split_for_callable( + self, t: CallableType, args: Sequence[Type], ctx: Context + ) -> list[Type]: + """Handle directly applying type arguments to a variadic Callable. + + This is needed in situations where e.g. variadic class object appears in + runtime context. For example: + class C(Generic[T, Unpack[Ts]]): ... + x = C[int, str]() + + We simply group the arguments that need to go into Ts variable into a TupleType, + similar to how it is done in other places using split_with_prefix_and_suffix(). + """ + if t.is_type_obj(): + # Type arguments must map to class type variables, ignoring constructor vars. + vars = t.type_object().defn.type_vars + else: + vars = list(t.variables) + args = flatten_nested_tuples(args) + + # TODO: this logic is duplicated with semanal_typeargs. + for tv, arg in zip(t.variables, args): + if isinstance(tv, ParamSpecType): + if not isinstance( + get_proper_type(arg), (Parameters, ParamSpecType, AnyType, UnboundType) + ): + self.chk.fail( + "Can only replace ParamSpec with a parameter types list or" + f" another ParamSpec, got {format_type(arg, self.chk.options)}", + ctx, + ) + return [AnyType(TypeOfAny.from_error)] * len(vars) + + # TODO: in future we may want to support type application to variadic functions. + if ( + not vars + or not any(isinstance(v, TypeVarTupleType) for v in vars) + or not t.is_type_obj() + ): + return list(args) + info = t.type_object() + # We reuse the logic from semanal phase to reduce code duplication. + fake = Instance(info, args, line=ctx.line, column=ctx.column) + # This code can be only called either from checking a type application, or from + # checking a type alias (after the caller handles no_args aliases), so we know it + # was initially an IndexExpr, and we allow empty tuple type arguments. + if not validate_instance(fake, self.chk.fail, indexed=True): + fix_instance( + fake, self.chk.fail, self.chk.note, disallow_any=False, options=self.chk.options + ) + args = list(fake.args) + + prefix = next(i for (i, v) in enumerate(vars) if isinstance(v, TypeVarTupleType)) + suffix = len(vars) - prefix - 1 + tvt = vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + start, middle, end = split_with_prefix_and_suffix(tuple(args), prefix, suffix) + return list(start) + [TupleType(list(middle), tvt.tuple_fallback)] + list(end) + + def apply_type_arguments_to_callable( + self, tp: Type, args: Sequence[Type], ctx: Context + ) -> Type: + """Apply type arguments to a generic callable type coming from a type object. + + This will first perform type arguments count checks, report the + error as needed, and return the correct kind of Any. As a special + case this returns Any for non-callable types, because if type object type + is not callable, then an error should be already reported. + """ + tp = get_proper_type(tp) + + if isinstance(tp, CallableType): + if tp.is_type_obj(): + # If we have a class object in runtime context, then the available type + # variables are those of the class, we don't include additional variables + # of the constructor. So that with + # class C(Generic[T]): + # def __init__(self, f: Callable[[S], T], x: S) -> None + # C[int] is valid + # C[int, str] is invalid (although C as a callable has 2 type variables) + # Note: various logic below and in applytype.py relies on the fact that + # class type variables appear *before* constructor variables. + type_vars = tp.type_object().defn.type_vars + else: + type_vars = list(tp.variables) + min_arg_count = sum(not v.has_default() for v in type_vars) + has_type_var_tuple = any(isinstance(v, TypeVarTupleType) for v in type_vars) + if ( + len(args) < min_arg_count or len(args) > len(type_vars) + ) and not has_type_var_tuple: + if tp.is_type_obj() and tp.type_object().fullname == "builtins.tuple": + # e.g. expression tuple[X, Y] + # - want the type of the expression i.e. a function with that as its return type + # - tp is type of tuple (note it won't have params as we are only called + # with generic callable type) + # - tuple[X, Y]() takes a single arg that is a tuple containing an X and a Y + return CallableType( + [TupleType(list(args), self.chk.named_type("tuple"))], + [ARG_POS], + [None], + TupleType(list(args), self.chk.named_type("tuple")), + tp.fallback, + name="tuple", + definition=tp.definition, + is_bound=tp.is_bound, + ) + self.msg.incompatible_type_application( + min_arg_count, len(type_vars), len(args), ctx + ) + return AnyType(TypeOfAny.from_error) + return self.apply_generic_arguments(tp, self.split_for_callable(tp, args, ctx), ctx) + if isinstance(tp, Overloaded): + for it in tp.items: + if tp.is_type_obj(): + # Same as above. + type_vars = tp.type_object().defn.type_vars + else: + type_vars = list(it.variables) + min_arg_count = sum(not v.has_default() for v in type_vars) + has_type_var_tuple = any(isinstance(v, TypeVarTupleType) for v in type_vars) + if ( + len(args) < min_arg_count or len(args) > len(type_vars) + ) and not has_type_var_tuple: + self.msg.incompatible_type_application( + min_arg_count, len(type_vars), len(args), ctx + ) + return AnyType(TypeOfAny.from_error) + return Overloaded( + [ + self.apply_generic_arguments(it, self.split_for_callable(it, args, ctx), ctx) + for it in tp.items + ] + ) + return AnyType(TypeOfAny.special_form) + + def visit_list_expr(self, e: ListExpr) -> Type: + """Type check a list expression [...].""" + return self.check_lst_expr(e, "builtins.list", "") + + def visit_set_expr(self, e: SetExpr) -> Type: + return self.check_lst_expr(e, "builtins.set", "") + + def fast_container_type( + self, e: ListExpr | SetExpr | TupleExpr, container_fullname: str + ) -> Type | None: + """ + Fast path to determine the type of a list or set literal, + based on the list of entries. This mostly impacts large + module-level constant definitions. + + Limitations: + + - no active type context + - at least one item + - no star expressions + - not after deferral + - either exactly one distinct type inside, + or the joined type of all entries is an Instance or Tuple type, + """ + ctx = self.type_context[-1] + if ctx or not e.items: + return None + if self.chk.current_node_deferred: + # Guarantees that all items will be Any, we'll reject it anyway. + return None + values: list[Type] = [] + # Preserve join order while avoiding O(n) lookups at every iteration + values_set: set[Type] = set() + for item in e.items: + if isinstance(item, StarExpr): + # fallback to slow path + return None + + typ = self.accept(item) + if typ not in values_set: + values.append(typ) + values_set.add(typ) + + vt = self._first_or_join_fast_item(values) + if vt is None: + return None + return self.chk.named_generic_type(container_fullname, [vt]) + + def _first_or_join_fast_item(self, items: list[Type]) -> Type | None: + if len(items) == 1 and not self.chk.current_node_deferred: + return items[0] + typ = join.join_type_list(items) + if not allow_fast_container_literal(typ): + # TODO: This is overly strict, many other types can be joined safely here. + # However, our join implementation isn't bug-free, and some joins may produce + # undesired `Any`s or even more surprising results. + return None + return typ + + def check_lst_expr(self, e: ListExpr | SetExpr | TupleExpr, fullname: str, tag: str) -> Type: + # fast path + t = self.fast_container_type(e, fullname) + if t: + return t + + # Translate into type checking a generic function call. + # Used for list and set expressions, as well as for tuples + # containing star expressions that don't refer to a + # Tuple. (Note: "lst" stands for list-set-tuple. :-) + tv = TypeVarType( + "T", + "T", + id=TypeVarId(-1, namespace=""), + values=[], + upper_bound=self.object_type(), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + constructor = CallableType( + [tv], + [nodes.ARG_STAR], + [None], + self.chk.named_generic_type(fullname, [tv]), + self.named_type("builtins.function"), + name=tag, + variables=[tv], + ) + out = self.check_call( + constructor, + [(i.expr if isinstance(i, StarExpr) else i) for i in e.items], + [(nodes.ARG_STAR if isinstance(i, StarExpr) else nodes.ARG_POS) for i in e.items], + e, + )[0] + return remove_instance_last_known_values(out) + + def tuple_context_matches(self, expr: TupleExpr, ctx: TupleType) -> bool: + ctx_unpack_index = find_unpack_in_list(ctx.items) + if ctx_unpack_index is None: + # For fixed tuples accept everything that can possibly match, even if this + # requires all star items to be empty. + return len([e for e in expr.items if not isinstance(e, StarExpr)]) <= len(ctx.items) + # For variadic context, the only easy case is when structure matches exactly. + # TODO: try using tuple type context in more cases. + if len([e for e in expr.items if isinstance(e, StarExpr)]) != 1: + return False + expr_star_index = next(i for i, lv in enumerate(expr.items) if isinstance(lv, StarExpr)) + return len(expr.items) == len(ctx.items) and ctx_unpack_index == expr_star_index + + def visit_tuple_expr(self, e: TupleExpr) -> Type: + """Type check a tuple expression.""" + # Try to determine type context for type inference. + type_context = get_proper_type(self.type_context[-1]) + type_context_items = None + if isinstance(type_context, UnionType): + tuples_in_context = [ + t + for t in get_proper_types(type_context.items) + if (isinstance(t, TupleType) and self.tuple_context_matches(e, t)) + or is_named_instance(t, TUPLE_LIKE_INSTANCE_NAMES) + ] + if len(tuples_in_context) == 1: + type_context = tuples_in_context[0] + else: + # There are either no relevant tuples in the Union, or there is + # more than one. Either way, we can't decide on a context. + pass + + if isinstance(type_context, TupleType) and self.tuple_context_matches(e, type_context): + type_context_items = type_context.items + elif type_context and is_named_instance(type_context, TUPLE_LIKE_INSTANCE_NAMES): + assert isinstance(type_context, Instance) + if type_context.args: + type_context_items = [type_context.args[0]] * len(e.items) + # NOTE: it's possible for the context to have a different + # number of items than e. In that case we use those context + # items that match a position in e, and we'll worry about type + # mismatches later. + + unpack_in_context = False + if type_context_items is not None: + unpack_in_context = find_unpack_in_list(type_context_items) is not None + seen_unpack_in_items = False + allow_precise_tuples = ( + unpack_in_context or PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature + ) + + # Infer item types. Give up if there's a star expression + # that's not a Tuple. + items: list[Type] = [] + j = 0 # Index into type_context_items; irrelevant if type_context_items is none + for i in range(len(e.items)): + item = e.items[i] + if isinstance(item, StarExpr): + # Special handling for star expressions. + # TODO: If there's a context, and item.expr is a + # TupleExpr, flatten it, so we can benefit from the + # context? Counterargument: Why would anyone write + # (1, *(2, 3)) instead of (1, 2, 3) except in a test? + if unpack_in_context: + # Note: this logic depends on full structure match in tuple_context_matches(). + assert type_context_items + ctx_item = type_context_items[j] + assert isinstance(ctx_item, UnpackType) + ctx = ctx_item.type + else: + ctx = None + tt = self.accept(item.expr, ctx) + tt = get_proper_type(tt) + if isinstance(tt, TupleType): + if find_unpack_in_list(tt.items) is not None: + if seen_unpack_in_items: + # Multiple unpack items are not allowed in tuples, + # fall back to instance type. + return self.check_lst_expr(e, "builtins.tuple", "") + else: + seen_unpack_in_items = True + items.extend(tt.items) + # Note: this logic depends on full structure match in tuple_context_matches(). + if unpack_in_context: + j += 1 + else: + # If there is an unpack in expressions, but not in context, this will + # result in an error later, just do something predictable here. + j += len(tt.items) + else: + if allow_precise_tuples and not seen_unpack_in_items: + # Handle (x, *y, z), where y is e.g. tuple[Y, ...]. + if isinstance(tt, Instance) and self.chk.type_is_iterable(tt): + item_type = self.chk.iterable_item_type(tt, e) + mapped = self.chk.named_generic_type("builtins.tuple", [item_type]) + items.append(UnpackType(mapped)) + seen_unpack_in_items = True + continue + # A star expression that's not a Tuple. + # Treat the whole thing as a variable-length tuple. + return self.check_lst_expr(e, "builtins.tuple", "") + else: + if not type_context_items or j >= len(type_context_items): + tt = self.accept(item) + else: + tt = self.accept(item, type_context_items[j]) + j += 1 + items.append(tt) + # This is a partial fallback item type. A precise type will be calculated on demand. + fallback_item = AnyType(TypeOfAny.special_form) + result: ProperType = TupleType( + items, self.chk.named_generic_type("builtins.tuple", [fallback_item]) + ) + if seen_unpack_in_items: + # Return already normalized tuple type just in case. + result = expand_type(result, {}) + return result + + def fast_dict_type(self, e: DictExpr) -> Type | None: + """ + Fast path to determine the type of a dict literal, + based on the list of entries. This mostly impacts large + module-level constant definitions. + + Limitations: + + - no active type context + - at least one item + - only supported star expressions are other dict instances + - either exactly one distinct type (keys and values separately) inside, + or the joined type of all entries is an Instance or Tuple type + """ + ctx = self.type_context[-1] + if ctx or not e.items: + return None + + if self.chk.current_node_deferred: + # Guarantees that all items will be Any, we'll reject it anyway. + return None + + keys: list[Type] = [] + values: list[Type] = [] + # Preserve join order while avoiding O(n) lookups at every iteration + keys_set: set[Type] = set() + values_set: set[Type] = set() + stargs: tuple[Type, Type] | None = None + for key, value in e.items: + if key is None: + st = get_proper_type(self.accept(value)) + if ( + isinstance(st, Instance) + and st.type.fullname == "builtins.dict" + and len(st.args) == 2 + ): + stargs = (st.args[0], st.args[1]) + else: + return None + else: + key_t = self.accept(key) + if key_t not in keys_set: + keys.append(key_t) + keys_set.add(key_t) + value_t = self.accept(value) + if value_t not in values_set: + values.append(value_t) + values_set.add(value_t) + + kt = self._first_or_join_fast_item(keys) + if kt is None: + return None + + vt = self._first_or_join_fast_item(values) + if vt is None: + return None + + if stargs and (stargs[0] != kt or stargs[1] != vt): + return None + return self.chk.named_generic_type("builtins.dict", [kt, vt]) + + def check_typeddict_literal_in_context( + self, e: DictExpr, typeddict_context: TypedDictType + ) -> Type: + orig_ret_type = self.check_typeddict_call_with_dict( + callee=typeddict_context, kwargs=e.items, context=e, orig_callee=None + ) + ret_type = get_proper_type(orig_ret_type) + if isinstance(ret_type, TypedDictType): + return ret_type.copy_modified() + return typeddict_context.copy_modified() + + def visit_dict_expr(self, e: DictExpr) -> Type: + """Type check a dict expression. + + Translate it into a call to dict(), with provisions for **expr. + """ + # if the dict literal doesn't match TypedDict, check_typeddict_call_with_dict reports + # an error, but returns the TypedDict type that matches the literal it found + # that would cause a second error when that TypedDict type is returned upstream + # to avoid the second error, we always return TypedDict type that was requested + typeddict_contexts, exhaustive = self.find_typeddict_context(self.type_context[-1], e) + if typeddict_contexts: + if len(typeddict_contexts) == 1 and exhaustive: + return self.check_typeddict_literal_in_context(e, typeddict_contexts[0]) + # Multiple items union, check if at least one of them matches cleanly. + for typeddict_context in typeddict_contexts: + with self.msg.filter_errors() as err, self.chk.local_type_map as tmap: + ret_type = self.check_typeddict_literal_in_context(e, typeddict_context) + if err.has_new_errors(): + continue + self.chk.store_types(tmap) + return ret_type + # No item matched without an error, so we can't unambiguously choose the item. + if exhaustive: + self.msg.typeddict_context_ambiguous(typeddict_contexts, e) + + # fast path attempt + dt = self.fast_dict_type(e) + if dt: + return dt + + # Define type variables (used in constructors below). + kt = TypeVarType( + "KT", + "KT", + id=TypeVarId(-1, namespace=""), + values=[], + upper_bound=self.object_type(), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + vt = TypeVarType( + "VT", + "VT", + id=TypeVarId(-2, namespace=""), + values=[], + upper_bound=self.object_type(), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + + # Collect function arguments, watching out for **expr. + args: list[Expression] = [] + expected_types: list[Type] = [] + for key, value in e.items: + if key is None: + args.append(value) + expected_types.append( + self.chk.named_generic_type("_typeshed.SupportsKeysAndGetItem", [kt, vt]) + ) + else: + tup = TupleExpr([key, value]) + if key.line >= 0: + tup.line = key.line + tup.column = key.column + else: + tup.line = value.line + tup.column = value.column + tup.end_line = value.end_line + tup.end_column = value.end_column + args.append(tup) + expected_types.append(TupleType([kt, vt], self.named_type("builtins.tuple"))) + + # The callable type represents a function like this (except we adjust for **expr): + # def (*v: Tuple[kt, vt]) -> Dict[kt, vt]: ... + constructor = CallableType( + expected_types, + [nodes.ARG_POS] * len(expected_types), + [None] * len(expected_types), + self.chk.named_generic_type("builtins.dict", [kt, vt]), + self.named_type("builtins.function"), + name="", + variables=[kt, vt], + ) + return self.check_call(constructor, args, [nodes.ARG_POS] * len(args), e)[0] + + def find_typeddict_context( + self, context: Type | None, dict_expr: DictExpr + ) -> tuple[list[TypedDictType], bool]: + """Extract `TypedDict` members of the enclosing context. + + Returns: + a 2-tuple, (found_candidates, is_exhaustive) + """ + context = get_proper_type(context) + if isinstance(context, TypedDictType): + return [context], True + elif isinstance(context, UnionType): + items = [] + exhaustive = True + for item in context.items: + item_contexts, item_exhaustive = self.find_typeddict_context(item, dict_expr) + for item_context in item_contexts: + if self.match_typeddict_call_with_dict( + item_context, dict_expr.items, dict_expr + ): + items.append(item_context) + exhaustive = exhaustive and item_exhaustive + return items, exhaustive + # No TypedDict type in context. + return [], False + + def visit_template_str_expr(self, e: TemplateStrExpr) -> Type: + """Type check a template string expression (t-string). + + Type-checks all interpolated expressions but the result is always + string.templatelib.Template. + """ + for item in e.items: + if isinstance(item, tuple): + value_expr, _source, _conversion, format_spec = item + self.accept(value_expr) + if format_spec is not None: + self.accept(format_spec) + sym = lookup_fully_qualified("string.templatelib.Template", self.chk.modules) + if sym is not None and isinstance(sym.node, TypeInfo): + return Instance(sym.node, []) + return AnyType(TypeOfAny.from_error) + + def visit_lambda_expr(self, e: LambdaExpr) -> Type: + """Type check lambda expression.""" + old_in_lambda = self.in_lambda_expr + self.in_lambda_expr = True + self.chk.check_default_params(e, body_is_trivial=False) + inferred_type, type_override = self.infer_lambda_type_using_context(e) + if not inferred_type: + self.chk.return_types.append(AnyType(TypeOfAny.special_form)) + # Type check everything in the body except for the final return + # statement (it can contain tuple unpacking before return). + with ( + self.chk.binder.frame_context(can_skip=True, fall_through=0), + self.chk.scope.push_function(e), + ): + # Lambdas can have more than one element in body, + # when we add "fictional" AssignmentStatement nodes, like in: + # `lambda (a, b): a` + for stmt in e.body.body[:-1]: + stmt.accept(self.chk) + # Only type check the return expression, not the return statement. + # There's no useful type context. + ret_type = self.accept(e.expr(), allow_none_return=True) + fallback = self.named_type("builtins.function") + self.chk.return_types.pop() + self.in_lambda_expr = old_in_lambda + return callable_type(e, fallback, ret_type) + else: + # Type context available. + self.chk.return_types.append(inferred_type.ret_type) + with self.chk.tscope.function_scope(e): + self.chk.check_func_item(e, type_override=type_override) + if not self.chk.has_type(e.expr()): + # TODO: return expression must be accepted before exiting function scope. + with self.chk.binder.frame_context(can_skip=True, fall_through=0): + self.accept(e.expr(), allow_none_return=True) + ret_type = self.chk.lookup_type(e.expr()) + self.chk.return_types.pop() + self.in_lambda_expr = old_in_lambda + return replace_callable_return_type(inferred_type, ret_type) + + def infer_lambda_type_using_context( + self, e: LambdaExpr + ) -> tuple[CallableType | None, CallableType | None]: + """Try to infer lambda expression type using context. + + Return None if could not infer type. + The second item in the return type is the type_override parameter for check_func_item. + """ + # TODO also accept 'Any' context + ctx = get_proper_type(self.type_context[-1]) + + if isinstance(ctx, UnionType): + callables = [ + t for t in get_proper_types(ctx.relevant_items()) if isinstance(t, CallableType) + ] + if len(callables) == 1: + ctx = callables[0] + + if not ctx or not isinstance(ctx, CallableType): + return None, None + + # The context may have function type variables in it. We replace them + # since these are the type variables we are ultimately trying to infer; + # they must be considered as indeterminate. We use ErasedType since it + # does not affect type inference results (it is for purposes like this + # only). + if not self.chk.options.old_type_inference: + # With new type inference we can preserve argument types even if they + # are generic, since new inference algorithm can handle constraints + # like S <: T (we still erase return type since it's ultimately unknown). + extra_vars = [] + for arg in ctx.arg_types: + meta_vars = [tv for tv in get_all_type_vars(arg) if tv.id.is_meta_var()] + extra_vars.extend([tv for tv in meta_vars if tv not in extra_vars]) + callable_ctx = ctx.copy_modified( + ret_type=replace_meta_vars(ctx.ret_type, ErasedType()), + variables=list(ctx.variables) + extra_vars, + ) + else: + erased_ctx = replace_meta_vars(ctx, ErasedType()) + assert isinstance(erased_ctx, ProperType) and isinstance(erased_ctx, CallableType) + callable_ctx = erased_ctx + + # The callable_ctx may have a fallback of builtins.type if the context + # is a constructor -- but this fallback doesn't make sense for lambdas. + callable_ctx = callable_ctx.copy_modified(fallback=self.named_type("builtins.function")) + + if callable_ctx.type_guard is not None or callable_ctx.type_is is not None: + # Lambda's return type cannot be treated as a `TypeGuard`, + # because it is implicit. And `TypeGuard`s must be explicit. + # See https://github.com/python/mypy/issues/9927 + return None, None + + arg_kinds = [arg.kind for arg in e.arguments] + + if callable_ctx.is_ellipsis_args or ctx.param_spec() is not None: + # Fill in Any arguments to match the arguments of the lambda. + callable_ctx = callable_ctx.copy_modified( + is_ellipsis_args=False, + arg_types=[AnyType(TypeOfAny.special_form)] * len(arg_kinds), + arg_kinds=arg_kinds, + arg_names=e.arg_names.copy(), + ) + + if ARG_STAR in arg_kinds or ARG_STAR2 in arg_kinds: + # TODO treat this case appropriately + return callable_ctx, None + + if callable_ctx.arg_kinds != arg_kinds: + # Incompatible context; cannot use it to infer types. + self.chk.fail(message_registry.CANNOT_INFER_LAMBDA_TYPE, e) + return None, None + + # Type of lambda must have correct argument names, to prevent false + # negatives when lambdas appear in `ParamSpec` context. + return callable_ctx.copy_modified(arg_names=e.arg_names), callable_ctx + + def visit_super_expr(self, e: SuperExpr) -> Type: + """Type check a super expression (non-lvalue).""" + + # We have an expression like super(T, var).member + + # First compute the types of T and var + types = self._super_arg_types(e) + if isinstance(types, tuple): + type_type, instance_type = types + else: + return types + + # Now get the MRO + type_info = type_info_from_type(type_type) + if type_info is None: + self.chk.fail(message_registry.UNSUPPORTED_ARG_1_FOR_SUPER, e) + return AnyType(TypeOfAny.from_error) + + instance_info = type_info_from_type(instance_type) + if instance_info is None: + self.chk.fail(message_registry.UNSUPPORTED_ARG_2_FOR_SUPER, e) + return AnyType(TypeOfAny.from_error) + + mro = instance_info.mro + + # The base is the first MRO entry *after* type_info that has a member + # with the right name + index = None + if type_info in mro: + index = mro.index(type_info) + else: + method = self.chk.scope.current_function() + # Mypy explicitly allows supertype upper bounds (and no upper bound at all) + # for annotating self-types. However, if such an annotation is used for + # checking super() we will still get an error. So to be consistent, we also + # allow such imprecise annotations for use with super(), where we fall back + # to the current class MRO instead. This works only from inside a method. + if method is not None and is_self_type_like( + instance_type, is_classmethod=method.is_class + ): + if e.info and type_info in e.info.mro: + mro = e.info.mro + index = mro.index(type_info) + if index is None: + if ( + instance_info.is_protocol + and instance_info != type_info + and not type_info.is_protocol + ): + # A special case for mixins, in this case super() should point + # directly to the host protocol, this is not safe, since the real MRO + # is not known yet for mixin, but this feature is more like an escape hatch. + index = -1 + else: + self.chk.fail(message_registry.SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1, e) + return AnyType(TypeOfAny.from_error) + + if len(mro) == index + 1: + self.chk.fail(message_registry.TARGET_CLASS_HAS_NO_BASE_CLASS, e) + return AnyType(TypeOfAny.from_error) + + for base in mro[index + 1 :]: + if e.name in base.names or base == mro[-1]: + if e.info and e.info.fallback_to_any and base == mro[-1]: + # There's an undefined base class, and we're at the end of the + # chain. That's not an error. + return AnyType(TypeOfAny.special_form) + + return analyze_member_access( + name=e.name, + typ=instance_type, + is_lvalue=False, + is_super=True, + is_operator=False, + original_type=instance_type, + override_info=base, + context=e, + chk=self.chk, + in_literal_context=self.is_literal_context(), + ) + + assert False, "unreachable" + + def _super_arg_types(self, e: SuperExpr) -> Type | tuple[Type, Type]: + """ + Computes the types of the type and instance expressions in super(T, instance), or the + implicit ones for zero-argument super() expressions. Returns a single type for the whole + super expression when possible (for errors, anys), otherwise the pair of computed types. + """ + + if not self.chk.in_checked_function(): + return AnyType(TypeOfAny.unannotated) + elif len(e.call.args) == 0: + if not e.info: + # This has already been reported by the semantic analyzer. + return AnyType(TypeOfAny.from_error) + elif self.chk.scope.active_class(): + self.chk.fail(message_registry.SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED, e) + return AnyType(TypeOfAny.from_error) + + # Zero-argument super() is like super(, ) + current_type = fill_typevars(e.info) + type_type: ProperType = TypeType(current_type) + + # Use the type of the self argument, in case it was annotated + method = self.chk.scope.current_function() + assert method is not None + if method.arguments: + instance_type: Type = method.arguments[0].variable.type or current_type + else: + self.chk.fail(message_registry.SUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED, e) + return AnyType(TypeOfAny.from_error) + elif ARG_STAR in e.call.arg_kinds: + self.chk.fail(message_registry.SUPER_VARARGS_NOT_SUPPORTED, e) + return AnyType(TypeOfAny.from_error) + elif set(e.call.arg_kinds) != {ARG_POS}: + self.chk.fail(message_registry.SUPER_POSITIONAL_ARGS_REQUIRED, e) + return AnyType(TypeOfAny.from_error) + elif len(e.call.args) == 1: + self.chk.fail(message_registry.SUPER_WITH_SINGLE_ARG_NOT_SUPPORTED, e) + return AnyType(TypeOfAny.from_error) + elif len(e.call.args) == 2: + type_type = get_proper_type(self.accept(e.call.args[0])) + instance_type = self.accept(e.call.args[1]) + else: + self.chk.fail(message_registry.TOO_MANY_ARGS_FOR_SUPER, e) + return AnyType(TypeOfAny.from_error) + + # Imprecisely assume that the type is the current class + if isinstance(type_type, AnyType): + if e.info: + type_type = TypeType(fill_typevars(e.info)) + else: + return AnyType(TypeOfAny.from_another_any, source_any=type_type) + elif isinstance(type_type, TypeType): + type_item = type_type.item + if isinstance(type_item, AnyType): + if e.info: + type_type = TypeType(fill_typevars(e.info)) + else: + return AnyType(TypeOfAny.from_another_any, source_any=type_item) + + if not isinstance(type_type, TypeType) and not ( + isinstance(type_type, FunctionLike) and type_type.is_type_obj() + ): + self.msg.first_argument_for_super_must_be_type(type_type, e) + return AnyType(TypeOfAny.from_error) + + # Imprecisely assume that the instance is of the current class + instance_type = get_proper_type(instance_type) + if isinstance(instance_type, AnyType): + if e.info: + instance_type = fill_typevars(e.info) + else: + return AnyType(TypeOfAny.from_another_any, source_any=instance_type) + elif isinstance(instance_type, TypeType): + instance_item = instance_type.item + if isinstance(instance_item, AnyType): + if e.info: + instance_type = TypeType(fill_typevars(e.info)) + else: + return AnyType(TypeOfAny.from_another_any, source_any=instance_item) + + return type_type, instance_type + + def visit_slice_expr(self, e: SliceExpr) -> Type: + try: + supports_index = self.chk.named_type("typing_extensions.SupportsIndex") + except KeyError: + supports_index = self.chk.named_type("builtins.int") # thanks, fixture life + expected = make_optional_type(supports_index) + type_args = [] + for index in [e.begin_index, e.end_index, e.stride]: + if index: + t = self.accept(index) + self.chk.check_subtype(t, expected, index, message_registry.INVALID_SLICE_INDEX) + type_args.append(t) + else: + type_args.append(NoneType()) + return self.chk.named_generic_type("builtins.slice", type_args) + + def visit_list_comprehension(self, e: ListComprehension) -> Type: + return self.check_generator_or_comprehension( + e.generator, "builtins.list", "" + ) + + def visit_set_comprehension(self, e: SetComprehension) -> Type: + return self.check_generator_or_comprehension( + e.generator, "builtins.set", "" + ) + + def visit_generator_expr(self, e: GeneratorExpr) -> Type: + # If any of the comprehensions use async for, the expression will return an async generator + # object, or await is used anywhere but in the leftmost sequence. + if ( + any(e.is_async) + or has_await_expression(e.left_expr) + or any(has_await_expression(sequence) for sequence in e.sequences[1:]) + or any(has_await_expression(cond) for condlist in e.condlists for cond in condlist) + ): + typ = "typing.AsyncGenerator" + # received type is always None in async generator expressions + additional_args: list[Type] = [NoneType()] + else: + typ = "typing.Generator" + # received type and returned type are None + additional_args = [NoneType(), NoneType()] + return self.check_generator_or_comprehension( + e, typ, "", additional_args=additional_args + ) + + def check_generator_or_comprehension( + self, + gen: GeneratorExpr, + type_name: str, + id_for_messages: str, + additional_args: list[Type] | None = None, + ) -> Type: + """Type check a generator expression or a list comprehension.""" + additional_args = additional_args or [] + with self.chk.binder.frame_context(can_skip=True, fall_through=0): + self.check_for_comp(gen) + + # Infer the type of the list comprehension by using a synthetic generic + # callable type. + tv = TypeVarType( + "T", + "T", + id=TypeVarId(-1, namespace=""), + values=[], + upper_bound=self.object_type(), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + tv_list: list[Type] = [tv] + constructor = CallableType( + tv_list, + [nodes.ARG_POS], + [None], + self.chk.named_generic_type(type_name, tv_list + additional_args), + self.chk.named_type("builtins.function"), + name=id_for_messages, + variables=[tv], + ) + return self.check_call(constructor, [gen.left_expr], [nodes.ARG_POS], gen)[0] + + def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type: + """Type check a dictionary comprehension.""" + with self.chk.binder.frame_context(can_skip=True, fall_through=0): + self.check_for_comp(e) + + # Infer the type of the list comprehension by using a synthetic generic + # callable type. + ktdef = TypeVarType( + "KT", + "KT", + id=TypeVarId(-1, namespace=""), + values=[], + upper_bound=self.object_type(), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + vtdef = TypeVarType( + "VT", + "VT", + id=TypeVarId(-2, namespace=""), + values=[], + upper_bound=self.object_type(), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + constructor = CallableType( + [ktdef, vtdef], + [nodes.ARG_POS, nodes.ARG_POS], + [None, None], + self.chk.named_generic_type("builtins.dict", [ktdef, vtdef]), + self.chk.named_type("builtins.function"), + name="", + variables=[ktdef, vtdef], + ) + return self.check_call( + constructor, [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e + )[0] + + def check_for_comp(self, e: GeneratorExpr | DictionaryComprehension) -> None: + """Check the for_comp part of comprehensions. That is the part from 'for': + ... for x in y if z + + Note: This adds the type information derived from the condlists to the current binder. + """ + for index, sequence, conditions, is_async in zip( + e.indices, e.sequences, e.condlists, e.is_async + ): + if is_async: + _, sequence_type = self.chk.analyze_async_iterable_item_type(sequence) + else: + _, sequence_type = self.chk.analyze_iterable_item_type(sequence) + if ( + isinstance(get_proper_type(sequence_type), UninhabitedType) + and isinstance(index, NameExpr) + and index.name == "_" + ): + # To preserve backward compatibility, avoid inferring Never for "_" + sequence_type = AnyType(TypeOfAny.special_form) + + self.chk.analyze_index_variables(index, sequence_type, True, e) + for condition in conditions: + self.accept(condition) + + # values are only part of the comprehension when all conditions are true + true_map, false_map = self.chk.find_isinstance_check(condition) + self.chk.push_type_map(true_map) + + if codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes: + if mypy.checker.is_unreachable_map(true_map): + self.msg.redundant_condition_in_comprehension(False, condition) + elif mypy.checker.is_unreachable_map(false_map): + self.msg.redundant_condition_in_comprehension(True, condition) + + def visit_conditional_expr(self, e: ConditionalExpr, allow_none_return: bool = False) -> Type: + self.accept(e.cond) + ctx: Type | None = self.type_context[-1] + + # Gain type information from isinstance if it is there + # but only for the current expression + if_map, else_map = self.chk.find_isinstance_check(e.cond) + if codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes: + if mypy.checker.is_unreachable_map(if_map): + self.msg.redundant_condition_in_if(False, e.cond) + elif mypy.checker.is_unreachable_map(else_map): + self.msg.redundant_condition_in_if(True, e.cond) + + if ctx is None: + # When no context is provided, compute each branch individually, and + # use the union of the results as artificial context. Important for: + # - testUnificationDict + # - testConditionalExpressionWithEmpty + ctx_if_type = self.analyze_cond_branch( + if_map, e.if_expr, context=ctx, allow_none_return=allow_none_return + ) + ctx_else_type = self.analyze_cond_branch( + else_map, e.else_expr, context=ctx, allow_none_return=allow_none_return + ) + if has_ambiguous_uninhabited_component(ctx_if_type): + ctx = ctx_else_type + elif has_ambiguous_uninhabited_component(ctx_else_type): + ctx = ctx_if_type + else: + ctx = make_simplified_union([ctx_if_type, ctx_else_type]) + + if_type = self.analyze_cond_branch( + if_map, e.if_expr, context=ctx, allow_none_return=allow_none_return + ) + else_type = self.analyze_cond_branch( + else_map, e.else_expr, context=ctx, allow_none_return=allow_none_return + ) + + res: Type = make_simplified_union([if_type, else_type]) + if has_uninhabited_component(res) and not isinstance( + get_proper_type(self.type_context[-1]), UnionType + ): + # In rare cases with empty collections join may give a better result. + alternative = join.join_types(if_type, else_type) + p_alt = get_proper_type(alternative) + if not isinstance(p_alt, Instance) or p_alt.type.fullname != "builtins.object": + res = alternative + return res + + def analyze_cond_branch( + self, + map: dict[Expression, Type], + node: Expression, + context: Type | None, + allow_none_return: bool = False, + suppress_unreachable_errors: bool = True, + ) -> Type: + with self.chk.binder.frame_context(can_skip=True, fall_through=0): + if mypy.checker.is_unreachable_map(map): + # We still need to type check node, in case we want to + # process it for isinstance checks later. Since the branch was + # determined to be unreachable, any errors should be suppressed. + with self.msg.filter_errors(filter_errors=suppress_unreachable_errors): + self.accept(node, type_context=context, allow_none_return=allow_none_return) + return UninhabitedType() + self.chk.push_type_map(map) + return self.accept(node, type_context=context, allow_none_return=allow_none_return) + + def _combined_context(self, ty: Type | None) -> Type | None: + ctx_items = [] + if ty is not None: + if has_any_type(ty): + # HACK: Any should be contagious, `dict[str, Any] or ` should still + # infer Any in x. + return ty + ctx_items.append(ty) + if self.type_context and self.type_context[-1] is not None: + ctx_items.append(self.type_context[-1]) + if ctx_items: + return make_simplified_union(ctx_items) + return None + + # + # Helpers + # + + def accept( + self, + node: Expression, + type_context: Type | None = None, + allow_none_return: bool = False, + always_allow_any: bool = False, + is_callee: bool = False, + ) -> Type: + """Type check a node in the given type context. If allow_none_return + is True and this expression is a call, allow it to return None. This + applies only to this expression and not any subexpressions. + """ + if node in self.type_overrides: + # This branch is very fast, there is no point timing it. + return self.type_overrides[node] + # We don't use context manager here to get most precise data (and avoid overhead). + record_time = False + if self.collect_line_checking_stats and not self.in_expression: + t0 = time.perf_counter_ns() + self.in_expression = True + record_time = True + self.type_context.append(type_context) + old_is_callee = self.is_callee + self.is_callee = is_callee + try: + p_type_context = get_proper_type(type_context) + if allow_none_return and isinstance(node, CallExpr): + typ = self.visit_call_expr(node, allow_none_return=True) + elif allow_none_return and isinstance(node, YieldFromExpr): + typ = self.visit_yield_from_expr(node, allow_none_return=True) + elif allow_none_return and isinstance(node, ConditionalExpr): + typ = self.visit_conditional_expr(node, allow_none_return=True) + elif allow_none_return and isinstance(node, AwaitExpr): + typ = self.visit_await_expr(node, allow_none_return=True) + + elif ( + isinstance(p_type_context, TypeType) + and p_type_context.is_type_form + and (node_as_type := self.try_parse_as_type_expression(node)) is not None + ): + typ = TypeType.make_normalized( + node_as_type, + line=node_as_type.line, + column=node_as_type.column, + is_type_form=True, + ) # r-value type, when interpreted as a type expression + elif ( + isinstance(p_type_context, UnionType) + and any( + isinstance(p_item := get_proper_type(item), TypeType) and p_item.is_type_form + for item in p_type_context.items + ) + and (node_as_type := self.try_parse_as_type_expression(node)) is not None + ): + typ1 = TypeType.make_normalized( + node_as_type, + line=node_as_type.line, + column=node_as_type.column, + is_type_form=True, + ) + if is_subtype(typ1, p_type_context): + typ = typ1 # r-value type, when interpreted as a type expression + else: + typ2 = node.accept(self) + typ = typ2 # r-value type, when interpreted as a value expression + # Deeply nested generic calls can deteriorate performance dramatically. + # Although in most cases caching makes little difference, in worst case + # it avoids exponential complexity. + # We cannot use cache inside lambdas, because they skip immediate type + # context, and use enclosing one, see infer_lambda_type_using_context(). + # TODO: consider using cache for more expression kinds. + elif ( + isinstance(node, (CallExpr, ListExpr, TupleExpr, DictExpr, OpExpr)) + and not (self.in_lambda_expr or self.chk.current_node_deferred) + and not self.chk.options.disable_expression_cache + ): + if (node, type_context) in self.expr_cache: + binder_version, typ, messages, type_map = self.expr_cache[(node, type_context)] + if binder_version == self.chk.binder.version: + self.chk.store_types(type_map) + self.msg.add_errors(messages) + else: + typ = self.accept_maybe_cache(node, type_context=type_context) + else: + typ = self.accept_maybe_cache(node, type_context=type_context) + else: + typ = node.accept(self) # r-value type, when interpreted as a value expression + except Exception as err: + report_internal_error( + err, self.chk.errors.file, node.line, self.chk.errors, self.chk.options + ) + self.is_callee = old_is_callee + self.type_context.pop() + assert typ is not None + self.chk.store_type(node, typ) + + if ( + self.chk.options.disallow_any_expr + and not always_allow_any + and not self.chk.is_stub + and self.chk.in_checked_function() + and has_any_type(typ) + and not self.chk.current_node_deferred + ): + self.msg.disallowed_any_type(typ, node) + + if not self.chk.in_checked_function() or self.chk.current_node_deferred: + result: Type = AnyType(TypeOfAny.unannotated) + else: + result = typ + if record_time: + self.per_line_checking_time_ns[node.line] += time.perf_counter_ns() - t0 + self.in_expression = False + return result + + def accept_maybe_cache(self, node: Expression, type_context: Type | None = None) -> Type: + binder_version = self.chk.binder.version + with self.msg.filter_errors(filter_errors=True, save_filtered_errors=True) as msg: + with self.chk.local_type_map as type_map: + typ = node.accept(self) + messages = msg.filtered_errors() + if binder_version == self.chk.binder.version and not self.chk.current_node_deferred: + self.expr_cache[(node, type_context)] = (binder_version, typ, messages, type_map) + self.chk.store_types(type_map) + self.msg.add_errors(messages) + return typ + + def named_type(self, name: str) -> Instance: + """Return an instance type with type given by the name and no type + arguments. Alias for TypeChecker.named_type. + """ + return self.chk.named_type(name) + + def type_alias_type_type(self) -> Instance: + """Returns a `typing.TypeAliasType` or `typing_extensions.TypeAliasType`.""" + if self.chk.options.python_version >= (3, 12): + return self.named_type("typing.TypeAliasType") + return self.named_type("typing_extensions.TypeAliasType") + + def is_valid_var_arg(self, typ: Type) -> bool: + """Is a type valid as a *args argument?""" + typ = get_proper_type(typ) + return isinstance(typ, (TupleType, AnyType, ParamSpecType, UnpackType)) or is_subtype( + typ, self.chk.named_generic_type("typing.Iterable", [AnyType(TypeOfAny.special_form)]) + ) + + def is_valid_keyword_var_arg(self, typ: Type) -> bool: + """Is a type valid as a **kwargs argument?""" + typ = get_proper_type(typ) + return ( + ( + # This is a little ad hoc, ideally we would have a map_instance_to_supertype + # that worked for protocols + isinstance(typ, Instance) + and typ.type.fullname == "builtins.dict" + and is_subtype(typ.args[0], self.named_type("builtins.str")) + ) + or isinstance(typ, ParamSpecType) + or is_subtype( + typ, + self.chk.named_generic_type( + "_typeshed.SupportsKeysAndGetItem", + [self.named_type("builtins.str"), AnyType(TypeOfAny.special_form)], + ), + ) + or is_subtype( + typ, + self.chk.named_generic_type( + "_typeshed.SupportsKeysAndGetItem", [UninhabitedType(), UninhabitedType()] + ), + ) + ) + + def not_ready_callback(self, name: str, context: Context) -> None: + """Called when we can't infer the type of a variable because it's not ready yet. + + Either defer type checking of the enclosing function to the next + pass or report an error. + """ + self.chk.handle_cannot_determine_type(name, context) + + def visit_yield_expr(self, e: YieldExpr) -> Type: + return_type = self.chk.return_types[-1] + expected_item_type = self.chk.get_generator_yield_type(return_type, False) + if e.expr is None: + if ( + not isinstance(get_proper_type(expected_item_type), (NoneType, AnyType)) + and self.chk.in_checked_function() + ): + self.chk.fail(message_registry.YIELD_VALUE_EXPECTED, e) + else: + actual_item_type = self.accept(e.expr, expected_item_type) + self.chk.check_subtype( + actual_item_type, + expected_item_type, + e, + message_registry.INCOMPATIBLE_TYPES_IN_YIELD, + "actual type", + "expected type", + ) + return self.chk.get_generator_receive_type(return_type, False) + + def visit_await_expr(self, e: AwaitExpr, allow_none_return: bool = False) -> Type: + expected_type = self.type_context[-1] + if expected_type is not None: + expected_type = self.chk.named_generic_type("typing.Awaitable", [expected_type]) + actual_type = get_proper_type(self.accept(e.expr, expected_type)) + if isinstance(actual_type, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=actual_type) + ret = self.check_awaitable_expr( + actual_type, e, message_registry.INCOMPATIBLE_TYPES_IN_AWAIT + ) + if not allow_none_return and isinstance(get_proper_type(ret), NoneType): + self.chk.msg.does_not_return_value(None, e) + return ret + + def check_awaitable_expr( + self, t: Type, ctx: Context, msg: str | ErrorMessage, ignore_binder: bool = False + ) -> Type: + """Check the argument to `await` and extract the type of value. + + Also used by `async for` and `async with`. + """ + if not self.chk.check_subtype( + t, self.named_type("typing.Awaitable"), ctx, msg, "actual type", "expected type" + ): + return AnyType(TypeOfAny.special_form) + else: + generator = self.check_method_call_by_name("__await__", t, [], [], ctx)[0] + ret_type = self.chk.get_generator_return_type(generator, False) + ret_type = get_proper_type(ret_type) + if ( + not ignore_binder + and isinstance(ret_type, UninhabitedType) + and not ret_type.ambiguous + ): + self.chk.binder.unreachable() + return ret_type + + def visit_yield_from_expr(self, e: YieldFromExpr, allow_none_return: bool = False) -> Type: + # NOTE: Whether `yield from` accepts an `async def` decorated + # with `@types.coroutine` (or `@asyncio.coroutine`) depends on + # whether the generator containing the `yield from` is itself + # thus decorated. But it accepts a generator regardless of + # how it's decorated. + return_type = self.chk.return_types[-1] + # TODO: What should the context for the sub-expression be? + # If the containing function has type Generator[X, Y, ...], + # the context should be Generator[X, Y, T], where T is the + # context of the 'yield from' itself (but it isn't known). + subexpr_type = get_proper_type(self.accept(e.expr)) + + # Check that the expr is an instance of Iterable and get the type of the iterator produced + # by __iter__. + if isinstance(subexpr_type, AnyType): + iter_type: Type = AnyType(TypeOfAny.from_another_any, source_any=subexpr_type) + elif self.chk.type_is_iterable(subexpr_type): + if is_async_def(subexpr_type) and not has_coroutine_decorator(return_type): + self.chk.msg.yield_from_invalid_operand_type(subexpr_type, e) + + any_type = AnyType(TypeOfAny.special_form) + generic_generator_type = self.chk.named_generic_type( + "typing.Generator", [any_type, any_type, any_type] + ) + generic_generator_type.set_line(e) + iter_type, _ = self.check_method_call_by_name( + "__iter__", subexpr_type, [], [], context=generic_generator_type + ) + else: + if not (is_async_def(subexpr_type) and has_coroutine_decorator(return_type)): + self.chk.msg.yield_from_invalid_operand_type(subexpr_type, e) + iter_type = AnyType(TypeOfAny.from_error) + else: + iter_type = self.check_awaitable_expr( + subexpr_type, e, message_registry.INCOMPATIBLE_TYPES_IN_YIELD_FROM + ) + + # Check that the iterator's item type matches the type yielded by the Generator function + # containing this `yield from` expression. + expected_item_type = self.chk.get_generator_yield_type(return_type, False) + actual_item_type = self.chk.get_generator_yield_type(iter_type, False) + + self.chk.check_subtype( + actual_item_type, + expected_item_type, + e, + message_registry.INCOMPATIBLE_TYPES_IN_YIELD_FROM, + "actual type", + "expected type", + ) + + # Determine the type of the entire yield from expression. + iter_type = get_proper_type(iter_type) + expr_type = self.chk.get_generator_return_type(iter_type, is_coroutine=False) + + if not allow_none_return and isinstance(get_proper_type(expr_type), NoneType): + self.chk.msg.does_not_return_value(None, e) + return expr_type + + def visit_temp_node(self, e: TempNode) -> Type: + return e.type + + def visit_type_var_expr(self, e: TypeVarExpr) -> Type: + p_default = get_proper_type(e.default) + if not ( + isinstance(p_default, AnyType) + and p_default.type_of_any == TypeOfAny.from_omitted_generics + ): + if not is_subtype(p_default, e.upper_bound): + self.chk.fail("TypeVar default must be a subtype of the bound type", e) + if e.values and not any(is_same_type(p_default, value) for value in e.values): + self.chk.fail("TypeVar default must be one of the constraint types", e) + return AnyType(TypeOfAny.special_form) + + def visit_paramspec_expr(self, e: ParamSpecExpr) -> Type: + return AnyType(TypeOfAny.special_form) + + def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> Type: + return AnyType(TypeOfAny.special_form) + + def visit_newtype_expr(self, e: NewTypeExpr) -> Type: + return AnyType(TypeOfAny.special_form) + + def visit_namedtuple_expr(self, e: NamedTupleExpr) -> Type: + tuple_type = e.info.tuple_type + if tuple_type: + if self.chk.options.disallow_any_unimported and has_any_from_unimported_type( + tuple_type + ): + self.msg.unimported_type_becomes_any("NamedTuple type", tuple_type, e) + check_for_explicit_any( + tuple_type, self.chk.options, self.chk.is_typeshed_stub, self.msg, context=e + ) + return AnyType(TypeOfAny.special_form) + + def visit_enum_call_expr(self, e: EnumCallExpr) -> Type: + for name, value in zip(e.items, e.values): + if value is not None: + typ = self.accept(value) + if not isinstance(get_proper_type(typ), AnyType): + var = e.info.names[name].node + if isinstance(var, Var): + # Inline TypeChecker.set_inferred_type(), + # without the lvalue. (This doesn't really do + # much, since the value attribute is defined + # to have type Any in the typeshed stub.) + var.type = typ + var.is_inferred = True + return AnyType(TypeOfAny.special_form) + + def visit_typeddict_expr(self, e: TypedDictExpr) -> Type: + return AnyType(TypeOfAny.special_form) + + def visit__promote_expr(self, e: PromoteExpr) -> Type: + return e.type + + def visit_star_expr(self, e: StarExpr) -> Type: + # TODO: should this ever be called (see e.g. mypyc visitor)? + return self.accept(e.expr) + + def object_type(self) -> Instance: + """Return instance type 'object'.""" + return self.named_type("builtins.object") + + def bool_type(self) -> Instance: + """Return instance type 'bool'.""" + return self.named_type("builtins.bool") + + @overload + def narrow_type_from_binder(self, expr: Expression, known_type: Type) -> Type: ... + + @overload + def narrow_type_from_binder( + self, expr: Expression, known_type: Type, skip_non_overlapping: bool + ) -> Type | None: ... + + def narrow_type_from_binder( + self, expr: Expression, known_type: Type, skip_non_overlapping: bool = False + ) -> Type | None: + """Narrow down a known type of expression using information in conditional type binder. + + If 'skip_non_overlapping' is True, return None if the type and restriction are + non-overlapping. + """ + if literal(expr) >= LITERAL_TYPE: + restriction = self.chk.binder.get(expr) + # If the current node is deferred, some variables may get Any types that they + # otherwise wouldn't have. We don't want to narrow down these since it may + # produce invalid inferred Optional[Any] types, at least. + if restriction and not ( + isinstance(get_proper_type(known_type), AnyType) and self.chk.current_node_deferred + ): + # Note: this call should match the one in narrow_declared_type(). + if skip_non_overlapping and not is_overlapping_types(known_type, restriction): + return None + narrowed = narrow_declared_type(known_type, restriction) + if isinstance(get_proper_type(narrowed), UninhabitedType): + # If we hit this case, it means that we can't reliably mark the code as + # unreachable, but the resulting type can't be expressed in type system. + # Falling back to restriction is more intuitive in most cases. + return restriction + return narrowed + return known_type + + def has_abstract_type_part(self, caller_type: ProperType, callee_type: ProperType) -> bool: + # TODO: support other possible types here + if isinstance(caller_type, TupleType) and isinstance(callee_type, TupleType): + return any( + self.has_abstract_type(get_proper_type(caller), get_proper_type(callee)) + for caller, callee in zip(caller_type.items, callee_type.items) + ) + return self.has_abstract_type(caller_type, callee_type) + + def has_abstract_type(self, caller_type: ProperType, callee_type: ProperType) -> bool: + return ( + isinstance(caller_type, FunctionLike) + and isinstance(callee_type, TypeType) + and caller_type.is_type_obj() + and (caller_type.type_object().is_abstract or caller_type.type_object().is_protocol) + and isinstance(callee_type.item, Instance) + and (callee_type.item.type.is_abstract or callee_type.item.type.is_protocol) + and not self.chk.allow_abstract_call + ) + + def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> Type | None: + """Try to parse a value Expression as a type expression. + If success then return the type that it spells. + If fails then return None. + + A value expression that is parsable as a type expression may be used + where a TypeForm is expected to represent the spelled type. + + Unlike SemanticAnalyzer.try_parse_as_type_expression() + (used in the earlier SemanticAnalyzer pass), this function can only + recognize type expressions which contain no string annotations.""" + if not isinstance(maybe_type_expr, MaybeTypeExpression): + return None + + # Check whether has already been parsed as a type expression + # by SemanticAnalyzer.try_parse_as_type_expression(), + # perhaps containing a string annotation + if ( + isinstance(maybe_type_expr, (StrExpr, IndexExpr, OpExpr)) + and maybe_type_expr.as_type != NotParsed.VALUE + ): + return maybe_type_expr.as_type + + # If is potentially a type expression containing a string annotation, + # don't try to parse it because there isn't enough information + # available to the TypeChecker pass to resolve string annotations + if has_str_expression(maybe_type_expr): + self.chk.fail( + "TypeForm containing a string annotation cannot be recognized here. " + "Surround with TypeForm(...) to recognize.", + maybe_type_expr, + code=codes.MAYBE_UNRECOGNIZED_STR_TYPEFORM, + ) + return None + + # Collect symbols targeted by NameExprs and MemberExprs, + # to be looked up by TypeAnalyser when binding the + # UnboundTypes corresponding to those expressions. + name_exprs, member_exprs = all_name_and_member_expressions(maybe_type_expr) + sym_for_name = {e.name: SymbolTableNode(UNBOUND_IMPORTED, e.node) for e in name_exprs} | { + e_name: SymbolTableNode(UNBOUND_IMPORTED, e.node) + for e in member_exprs + if (e_name := get_member_expr_fullname(e)) is not None + } + + chk_sem = mypy.checker.TypeCheckerAsSemanticAnalyzer(self.chk, sym_for_name) + tpan = TypeAnalyser( + chk_sem, + # NOTE: Will never need to lookup type vars in this scope because + # SemanticAnalyzer.try_parse_as_type_expression() will have + # already recognized any type var referenced in a NameExpr. + # String annotations (which may also reference type vars) + # can't be resolved in the TypeChecker pass anyway. + TypeVarLikeScope(), # empty scope + self.plugin, + self.chk.options, + self.chk.tree, + self.chk.is_typeshed_stub, + ) + + try: + typ1 = expr_to_unanalyzed_type( + maybe_type_expr, self.chk.options, self.chk.is_typeshed_stub + ) + typ2 = typ1.accept(tpan) + if chk_sem.did_fail: + return None + return typ2 + except TypeTranslationError: + return None + + +def has_any_type(t: Type, ignore_in_type_obj: bool = False) -> bool: + """Whether t contains an Any type""" + return t.accept(HasAnyType(ignore_in_type_obj)) + + +class HasAnyType(types.BoolTypeQuery): + def __init__(self, ignore_in_type_obj: bool) -> None: + super().__init__(types.ANY_STRATEGY) + self.ignore_in_type_obj = ignore_in_type_obj + + def visit_any(self, t: AnyType) -> bool: + return t.type_of_any != TypeOfAny.special_form # special forms are not real Any types + + def visit_callable_type(self, t: CallableType) -> bool: + if self.ignore_in_type_obj and t.is_type_obj(): + return False + return super().visit_callable_type(t) + + def visit_type_var(self, t: TypeVarType) -> bool: + default = [t.default] if t.has_default() else [] + return self.query_types([t.upper_bound, *default] + t.values) + + def visit_param_spec(self, t: ParamSpecType) -> bool: + default = [t.default] if t.has_default() else [] + return self.query_types([t.upper_bound, *default, t.prefix]) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool: + default = [t.default] if t.has_default() else [] + return self.query_types([t.upper_bound, *default]) + + +def has_coroutine_decorator(t: Type) -> bool: + """Whether t came from a function decorated with `@coroutine`.""" + t = get_proper_type(t) + return isinstance(t, Instance) and t.type.fullname == "typing.AwaitableGenerator" + + +def is_async_def(t: Type) -> bool: + """Whether t came from a function defined using `async def`.""" + # In check_func_def(), when we see a function decorated with + # `@typing.coroutine` or `@async.coroutine`, we change the + # return type to typing.AwaitableGenerator[...], so that its + # type is compatible with either Generator or Awaitable. + # But for the check here we need to know whether the original + # function (before decoration) was an `async def`. The + # AwaitableGenerator type conveniently preserves the original + # type as its 4th parameter (3rd when using 0-origin indexing + # :-), so that we can recover that information here. + # (We really need to see whether the original, undecorated + # function was an `async def`, which is orthogonal to its + # decorations.) + t = get_proper_type(t) + if ( + isinstance(t, Instance) + and t.type.fullname == "typing.AwaitableGenerator" + and len(t.args) >= 4 + ): + t = get_proper_type(t.args[3]) + return isinstance(t, Instance) and t.type.fullname == "typing.Coroutine" + + +def is_non_empty_tuple(t: Type) -> bool: + t = get_proper_type(t) + return isinstance(t, TupleType) and bool(t.items) + + +def is_duplicate_mapping( + mapping: list[int], actual_types: list[Type], actual_kinds: list[ArgKind] +) -> bool: + return ( + len(mapping) > 1 + # Multiple actuals can map to the same formal if they both come from + # varargs (*args and **kwargs); in this case at runtime it is possible + # that here are no duplicates. We need to allow this, as the convention + # f(..., *args, **kwargs) is common enough. + and not ( + len(mapping) == 2 + and actual_kinds[mapping[0]] == nodes.ARG_STAR + and actual_kinds[mapping[1]] == nodes.ARG_STAR2 + ) + # Multiple actuals can map to the same formal if there are multiple + # **kwargs which cannot be mapped with certainty (non-TypedDict + # **kwargs). + and not all( + actual_kinds[m] == nodes.ARG_STAR2 + and not isinstance(get_proper_type(actual_types[m]), TypedDictType) + for m in mapping + ) + ) + + +def replace_callable_return_type(c: CallableType, new_ret_type: Type) -> CallableType: + """Return a copy of a callable type with a different return type.""" + return c.copy_modified(ret_type=new_ret_type) + + +class ArgInferSecondPassQuery(types.BoolTypeQuery): + """Query whether an argument type should be inferred in the second pass. + + The result is True if the type has a type variable in a callable return + type anywhere. For example, the result for Callable[[], T] is True if t is + a type variable. + """ + + def __init__(self) -> None: + super().__init__(types.ANY_STRATEGY) + + def visit_callable_type(self, t: CallableType) -> bool: + # TODO: we need to check only for type variables of original callable. + return self.query_types(t.arg_types) or has_type_vars(t) + + +def has_erased_component(t: Type | None) -> bool: + return t is not None and t.accept(HasErasedComponentsQuery()) + + +class HasErasedComponentsQuery(types.BoolTypeQuery): + """Visitor for querying whether a type has an erased component.""" + + def __init__(self) -> None: + super().__init__(types.ANY_STRATEGY) + + def visit_erased_type(self, t: ErasedType) -> bool: + return True + + +def has_uninhabited_component(t: Type | None) -> bool: + return t is not None and t.accept(HasUninhabitedComponentsQuery()) + + +class HasUninhabitedComponentsQuery(types.BoolTypeQuery): + """Visitor for querying whether a type has an UninhabitedType component.""" + + def __init__(self) -> None: + super().__init__(types.ANY_STRATEGY) + + def visit_uninhabited_type(self, t: UninhabitedType) -> bool: + return True + + +def has_ambiguous_uninhabited_component(t: Type) -> bool: + return t.accept(HasAmbiguousUninhabitedComponentsQuery()) + + +class HasAmbiguousUninhabitedComponentsQuery(types.BoolTypeQuery): + """Visitor for querying whether a type has an ambiguous UninhabitedType component.""" + + def __init__(self) -> None: + super().__init__(types.ANY_STRATEGY) + + def visit_uninhabited_type(self, t: UninhabitedType) -> bool: + return t.ambiguous + + +def arg_approximate_similarity(actual: Type, formal: Type) -> bool: + """Return if caller argument (actual) is roughly compatible with signature arg (formal). + + This function is deliberately loose and will report two types are similar + as long as their "shapes" are plausibly the same. + + This is useful when we're doing error reporting: for example, if we're trying + to select an overload alternative and there's no exact match, we can use + this function to help us identify which alternative the user might have + *meant* to match. + """ + actual = get_proper_type(actual) + formal = get_proper_type(formal) + + # Erase typevars: we'll consider them all to have the same "shape". + if isinstance(actual, TypeVarType): + actual = erase_to_union_or_bound(actual) + if isinstance(formal, TypeVarType): + formal = erase_to_union_or_bound(formal) + + # Callable or Type[...]-ish types + def is_typetype_like(typ: ProperType) -> bool: + return ( + isinstance(typ, TypeType) + or (isinstance(typ, FunctionLike) and typ.is_type_obj()) + or (isinstance(typ, Instance) and typ.type.fullname == "builtins.type") + ) + + if isinstance(formal, CallableType): + if isinstance(actual, (CallableType, Overloaded, TypeType)): + return True + if is_typetype_like(actual) and is_typetype_like(formal): + return True + + # Unions + if isinstance(actual, UnionType): + return any(arg_approximate_similarity(item, formal) for item in actual.relevant_items()) + if isinstance(formal, UnionType): + return any(arg_approximate_similarity(actual, item) for item in formal.relevant_items()) + + # TypedDicts + if isinstance(actual, TypedDictType): + if isinstance(formal, TypedDictType): + return True + return arg_approximate_similarity(actual.fallback, formal) + + # Instances + # For instances, we mostly defer to the existing is_subtype check. + if isinstance(formal, Instance): + if isinstance(actual, CallableType): + actual = actual.fallback + if isinstance(actual, Overloaded): + actual = actual.items[0].fallback + if isinstance(actual, TupleType): + actual = tuple_fallback(actual) + if isinstance(actual, Instance) and formal.type in actual.type.mro: + # Try performing a quick check as an optimization + return True + + # Fall back to a standard subtype check for the remaining kinds of type. + return is_subtype(erasetype.erase_type(actual), erasetype.erase_type(formal)) + + +def any_causes_overload_ambiguity( + items: list[CallableType], + return_types: list[Type], + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, +) -> bool: + """May an argument containing 'Any' cause ambiguous result type on call to overloaded function? + + Note that this sometimes returns True even if there is no ambiguity, since a correct + implementation would be complex (and the call would be imprecisely typed due to Any + types anyway). + + Args: + items: Overload items matching the actual arguments + arg_types: Actual argument types + arg_kinds: Actual argument kinds + arg_names: Actual argument names + """ + if all_same_types(return_types): + return False + + actual_to_formal = [ + map_formals_to_actuals( + arg_kinds, arg_names, item.arg_kinds, item.arg_names, lambda i: arg_types[i] + ) + for item in items + ] + + for arg_idx, arg_type in enumerate(arg_types): + # We ignore Anys in type object callables as ambiguity + # creators, since that can lead to falsely claiming ambiguity + # for overloads between Type and Callable. + if has_any_type(arg_type, ignore_in_type_obj=True): + matching_formals_unfiltered = [ + (item_idx, lookup[arg_idx]) + for item_idx, lookup in enumerate(actual_to_formal) + if lookup[arg_idx] + ] + + matching_returns = [] + matching_formals = [] + for item_idx, formals in matching_formals_unfiltered: + matched_callable = items[item_idx] + matching_returns.append(matched_callable.ret_type) + + # Note: if an actual maps to multiple formals of differing types within + # a single callable, then we know at least one of those formals must be + # a different type then the formal(s) in some other callable. + # So it's safe to just append everything to the same list. + for formal in formals: + matching_formals.append(matched_callable.arg_types[formal]) + if not all_same_types(matching_formals) and not all_same_types(matching_returns): + # Any maps to multiple different types, and the return types of these items differ. + return True + return False + + +def all_same_types(types: list[Type]) -> bool: + if not types: + return True + return all(is_same_type(t, types[0]) for t in types[1:]) + + +def merge_typevars_in_callables_by_name( + callables: Sequence[CallableType], +) -> tuple[list[CallableType], list[TypeVarType]]: + """Takes all the typevars present in the callables and 'combines' the ones with the same name. + + For example, suppose we have two callables with signatures "f(x: T, y: S) -> T" and + "f(x: List[Tuple[T, S]]) -> Tuple[T, S]". Both callables use typevars named "T" and + "S", but we treat them as distinct, unrelated typevars. (E.g. they could both have + distinct ids.) + + If we pass in both callables into this function, it returns a list containing two + new callables that are identical in signature, but use the same underlying TypeVarType + for T and S. + + This is useful if we want to take the output lists and "merge" them into one callable + in some way -- for example, when unioning together overloads. + + Returns both the new list of callables and a list of all distinct TypeVarType objects used. + """ + output: list[CallableType] = [] + unique_typevars: dict[str, TypeVarType] = {} + variables: list[TypeVarType] = [] + + for target in callables: + if target.is_generic(): + target = freshen_function_type_vars(target) + + rename = {} # Dict[TypeVarId, TypeVar] + for tv in target.variables: + name = tv.fullname + if name not in unique_typevars: + # TODO: support ParamSpecType and TypeVarTuple. + if isinstance(tv, (ParamSpecType, TypeVarTupleType)): + continue + assert isinstance(tv, TypeVarType) + unique_typevars[name] = tv + variables.append(tv) + rename[tv.id] = unique_typevars[name] + + target = expand_type(target, rename) + output.append(target) + + return output, variables + + +def try_getting_literal(typ: Type) -> ProperType: + """If possible, get a more precise literal type for a given type.""" + typ = get_proper_type(typ) + if isinstance(typ, Instance) and typ.last_known_value is not None: + return typ.last_known_value + return typ + + +def is_expr_literal_type(node: Expression) -> bool: + """Returns 'true' if the given node is a Literal""" + if isinstance(node, IndexExpr): + base = node.base + return isinstance(base, RefExpr) and base.fullname in LITERAL_TYPE_NAMES + if isinstance(node, NameExpr): + underlying = node.node + return isinstance(underlying, TypeAlias) and isinstance( + get_proper_type(underlying.target), LiteralType + ) + return False + + +def has_bytes_component(typ: Type) -> bool: + """Is this one of builtin byte types, or a union that contains it?""" + typ = get_proper_type(typ) + byte_types = {"builtins.bytes", "builtins.bytearray"} + if isinstance(typ, UnionType): + return any(has_bytes_component(t) for t in typ.items) + if isinstance(typ, Instance) and typ.type.fullname in byte_types: + return True + return False + + +def type_info_from_type(typ: Type) -> TypeInfo | None: + """Gets the TypeInfo for a type, indirecting through things like type variables and tuples.""" + typ = get_proper_type(typ) + if isinstance(typ, FunctionLike) and typ.is_type_obj(): + return typ.type_object() + if isinstance(typ, TypeType): + typ = typ.item + if isinstance(typ, TypeVarType): + typ = get_proper_type(typ.upper_bound) + if isinstance(typ, TupleType): + typ = tuple_fallback(typ) + if isinstance(typ, Instance): + return typ.type + + # A complicated type. Too tricky, give up. + # TODO: Do something more clever here. + return None + + +def is_operator_method(fullname: str | None) -> bool: + if not fullname: + return False + short_name = fullname.split(".")[-1] + return ( + short_name in operators.op_methods.values() + or short_name in operators.reverse_op_methods.values() + or short_name in operators.unary_op_methods.values() + ) + + +def get_partial_instance_type(t: Type | None) -> PartialType | None: + if t is None or not isinstance(t, PartialType) or t.type is None: + return None + return t + + +def is_type_type_context(context: Type | None) -> bool: + context = get_proper_type(context) + if isinstance(context, TypeType): + return True + if isinstance(context, UnionType): + return any(is_type_type_context(item) for item in context.items) + return False diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..514f42a9977c0ea4885ed0ac4979cd077da28857 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.py new file mode 100644 index 0000000000000000000000000000000000000000..3359190092aff37284e254d2de7f71b7fbb02ec4 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.py @@ -0,0 +1,1588 @@ +"""Type checking of attribute access""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import TypeVar, cast + +from mypy import message_registry, state +from mypy.checker_shared import TypeCheckerSharedApi +from mypy.erasetype import erase_typevars +from mypy.expandtype import ( + expand_self_type, + expand_type_by_instance, + freshen_all_functions_type_vars, +) +from mypy.maptype import map_instance_to_supertype +from mypy.meet import is_overlapping_types +from mypy.messages import MessageBuilder +from mypy.nodes import ( + ARG_POS, + ARG_STAR, + ARG_STAR2, + EXCLUDED_ENUM_ATTRIBUTES, + SYMBOL_FUNCBASE_TYPES, + Context, + Decorator, + Expression, + FuncBase, + FuncDef, + IndexExpr, + MypyFile, + NameExpr, + OverloadedFuncDef, + SymbolTable, + TempNode, + TypeAlias, + TypeInfo, + TypeVarLikeExpr, + Var, + is_final_node, +) +from mypy.plugin import AttributeContext +from mypy.subtypes import is_subtype +from mypy.typeops import ( + bind_self, + erase_to_bound, + freeze_all_type_vars, + function_type, + get_all_type_vars, + make_simplified_union, + supported_self_type, + tuple_fallback, +) +from mypy.types import ( + AnyType, + CallableType, + DeletedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UninhabitedType, + UnionType, + get_proper_type, +) + + +class MemberContext: + """Information and objects needed to type check attribute access. + + Look at the docstring of analyze_member_access for more information. + """ + + def __init__( + self, + *, + is_lvalue: bool, + is_super: bool, + is_operator: bool, + original_type: Type, + context: Context, + chk: TypeCheckerSharedApi, + self_type: Type | None = None, + module_symbol_table: SymbolTable | None = None, + no_deferral: bool = False, + is_self: bool = False, + rvalue: Expression | None = None, + suppress_errors: bool = False, + preserve_type_var_ids: bool = False, + ) -> None: + self.is_lvalue = is_lvalue + self.is_super = is_super + self.is_operator = is_operator + self.original_type = original_type + self.self_type = self_type or original_type + self.context = context # Error context + self.chk = chk + self.msg = chk.msg + self.module_symbol_table = module_symbol_table + self.no_deferral = no_deferral + self.is_self = is_self + if rvalue is not None: + assert is_lvalue + self.rvalue = rvalue + self.suppress_errors = suppress_errors + # This attribute is only used to preserve old protocol member access logic. + # It is needed to avoid infinite recursion in cases involving self-referential + # generic methods, see find_member() for details. Do not use for other purposes! + self.preserve_type_var_ids = preserve_type_var_ids + + def named_type(self, name: str) -> Instance: + return self.chk.named_type(name) + + def not_ready_callback(self, name: str, context: Context) -> None: + self.chk.handle_cannot_determine_type(name, context) + + def fail(self, msg: str) -> None: + if not self.suppress_errors: + self.msg.fail(msg, self.context) + + def copy_modified( + self, + *, + self_type: Type | None = None, + is_lvalue: bool | None = None, + original_type: Type | None = None, + ) -> MemberContext: + mx = MemberContext( + is_lvalue=self.is_lvalue, + is_super=self.is_super, + is_operator=self.is_operator, + original_type=self.original_type, + context=self.context, + chk=self.chk, + self_type=self.self_type, + module_symbol_table=self.module_symbol_table, + no_deferral=self.no_deferral, + rvalue=self.rvalue, + suppress_errors=self.suppress_errors, + preserve_type_var_ids=self.preserve_type_var_ids, + ) + if self_type is not None: + mx.self_type = self_type + if is_lvalue is not None: + mx.is_lvalue = is_lvalue + if original_type is not None: + mx.original_type = original_type + return mx + + +def analyze_member_access( + name: str, + typ: Type, + context: Context, + *, + is_lvalue: bool, + is_super: bool, + is_operator: bool, + original_type: Type, + chk: TypeCheckerSharedApi, + override_info: TypeInfo | None = None, + in_literal_context: bool = False, + self_type: Type | None = None, + module_symbol_table: SymbolTable | None = None, + no_deferral: bool = False, + is_self: bool = False, + rvalue: Expression | None = None, + suppress_errors: bool = False, +) -> Type: + """Return the type of attribute 'name' of 'typ'. + + The actual implementation is in '_analyze_member_access' and this docstring + also applies to it. + + This is a general operation that supports various different variations: + + 1. lvalue or non-lvalue access (setter or getter access) + 2. supertype access when using super() (is_super == True and + 'override_info' should refer to the supertype) + + 'original_type' is the most precise inferred or declared type of the base object + that we have available. When looking for an attribute of 'typ', we may perform + recursive calls targeting the fallback type, and 'typ' may become some supertype + of 'original_type'. 'original_type' is always preserved as the 'typ' type used in + the initial, non-recursive call. The 'self_type' is a component of 'original_type' + to which generic self should be bound (a narrower type that has a fallback to instance). + Currently, this is used only for union types. + + 'module_symbol_table' is passed to this function if 'typ' is actually a module, + and we want to keep track of the available attributes of the module (since they + are not available via the type object directly) + + 'rvalue' can be provided optionally to infer better setter type when is_lvalue is True, + most notably this helps for descriptors with overloaded __set__() method. + + 'suppress_errors' will skip any logic that is only needed to generate error messages. + Note that this more of a performance optimization, one should not rely on this to not + show any messages, as some may be show e.g. by callbacks called here, + use msg.filter_errors(), if needed. + """ + mx = MemberContext( + is_lvalue=is_lvalue, + is_super=is_super, + is_operator=is_operator, + original_type=original_type, + context=context, + chk=chk, + self_type=self_type, + module_symbol_table=module_symbol_table, + no_deferral=no_deferral, + is_self=is_self, + rvalue=rvalue, + suppress_errors=suppress_errors, + ) + result = _analyze_member_access(name, typ, mx, override_info) + possible_literal = get_proper_type(result) + if ( + in_literal_context + and isinstance(possible_literal, Instance) + and possible_literal.last_known_value is not None + ): + return possible_literal.last_known_value + else: + return result + + +def _analyze_member_access( + name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None +) -> Type: + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return analyze_instance_member_access(name, typ, mx, override_info) + elif isinstance(typ, AnyType): + # The base object has dynamic type. + return AnyType(TypeOfAny.from_another_any, source_any=typ) + elif isinstance(typ, UnionType): + return analyze_union_member_access(name, typ, mx) + elif isinstance(typ, FunctionLike) and typ.is_type_obj(): + return analyze_type_callable_member_access(name, typ, mx) + elif isinstance(typ, TypeType): + return analyze_type_type_member_access(name, typ, mx, override_info) + elif isinstance(typ, TupleType): + # Actually look up from the fallback instance type. + return _analyze_member_access(name, tuple_fallback(typ), mx, override_info) + elif isinstance(typ, (LiteralType, FunctionLike)): + # Actually look up from the fallback instance type. + return _analyze_member_access(name, typ.fallback, mx, override_info) + elif isinstance(typ, TypedDictType): + return analyze_typeddict_access(name, typ, mx, override_info) + elif isinstance(typ, NoneType): + return analyze_none_member_access(name, typ, mx) + elif isinstance(typ, TypeVarLikeType): + if isinstance(typ, TypeVarType) and typ.values: + return _analyze_member_access( + name, make_simplified_union(typ.values), mx, override_info + ) + return _analyze_member_access(name, typ.upper_bound, mx, override_info) + elif isinstance(typ, DeletedType): + if not mx.suppress_errors: + mx.msg.deleted_as_rvalue(typ, mx.context) + return AnyType(TypeOfAny.from_error) + elif isinstance(typ, UninhabitedType): + attr_type = UninhabitedType() + attr_type.ambiguous = typ.ambiguous + return attr_type + return report_missing_attribute(mx.original_type, typ, name, mx) + + +def may_be_awaitable_attribute( + name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None +) -> bool: + """Check if the given type has the attribute when awaited.""" + if mx.chk.checking_missing_await: + # Avoid infinite recursion. + return False + with mx.chk.checking_await_set(), mx.msg.filter_errors() as local_errors: + aw_type = mx.chk.get_precise_awaitable_type(typ, local_errors) + if aw_type is None: + return False + _ = _analyze_member_access( + name, aw_type, mx.copy_modified(self_type=aw_type), override_info + ) + return not local_errors.has_new_errors() + + +def report_missing_attribute( + original_type: Type, + typ: Type, + name: str, + mx: MemberContext, + override_info: TypeInfo | None = None, +) -> Type: + if mx.suppress_errors: + return AnyType(TypeOfAny.from_error) + error_code = mx.msg.has_no_attr(original_type, typ, name, mx.context, mx.module_symbol_table) + if not mx.msg.prefer_simple_messages(): + if may_be_awaitable_attribute(name, typ, mx, override_info): + mx.msg.possible_missing_await(mx.context, error_code) + return AnyType(TypeOfAny.from_error) + + +# The several functions that follow implement analyze_member_access for various +# types and aren't documented individually. + + +def analyze_instance_member_access( + name: str, typ: Instance, mx: MemberContext, override_info: TypeInfo | None +) -> Type: + info = typ.type + if override_info: + info = override_info + + method = info.get_method(name) + + if name == "__init__" and not mx.is_super and not info.is_final: + if not method or not method.is_final: + # Accessing __init__ in statically typed code would compromise + # type safety unless used via super() or the method/class is final. + mx.fail(message_registry.CANNOT_ACCESS_INIT) + return AnyType(TypeOfAny.from_error) + + # The base object has an instance type. + + if ( + state.find_occurrences + and info.name == state.find_occurrences[0] + and name == state.find_occurrences[1] + and not mx.suppress_errors + ): + mx.msg.note("Occurrence of '{}.{}'".format(*state.find_occurrences), mx.context) + + # Look up the member. First look up the method dictionary. + if method and not isinstance(method, Decorator): + if mx.is_super and not mx.suppress_errors: + validate_super_call(method, mx) + + if method.is_property: + assert isinstance(method, OverloadedFuncDef) + getter = method.items[0] + assert isinstance(getter, Decorator) + if mx.is_lvalue and getter.var.is_settable_property: + mx.chk.warn_deprecated(method.setter, mx.context) + return analyze_var(name, getter.var, typ, mx) + + if mx.is_lvalue and not mx.suppress_errors: + mx.msg.cant_assign_to_method(mx.context) + if not isinstance(method, OverloadedFuncDef): + signature = function_type(method, mx.named_type("builtins.function")) + else: + if method.type is None: + # Overloads may be not ready if they are decorated. Handle this in same + # manner as we would handle a regular decorated function: defer if possible. + if not mx.no_deferral and method.items: + mx.not_ready_callback(method.name, mx.context) + return AnyType(TypeOfAny.special_form) + assert isinstance(method.type, Overloaded) + signature = method.type + if not mx.preserve_type_var_ids: + signature = freshen_all_functions_type_vars(signature) + if not method.is_static: + if isinstance(method, (FuncDef, OverloadedFuncDef)) and method.is_trivial_self: + signature = bind_self_fast(signature, mx.self_type) + else: + signature = check_self_arg( + signature, mx.self_type, method.is_class, mx.context, name, mx.msg + ) + signature = bind_self(signature, mx.self_type, is_classmethod=method.is_class) + typ = map_instance_to_supertype(typ, method.info) + member_type = expand_type_by_instance(signature, typ) + freeze_all_type_vars(member_type) + return member_type + else: + # Not a method. + return analyze_member_var_access(name, typ, info, mx) + + +def validate_super_call(node: FuncBase, mx: MemberContext) -> None: + unsafe_super = False + if isinstance(node, FuncDef) and node.is_trivial_body: + unsafe_super = True + elif isinstance(node, OverloadedFuncDef): + if node.impl: + impl = node.impl if isinstance(node.impl, FuncDef) else node.impl.func + unsafe_super = impl.is_trivial_body + elif not node.is_property and node.items: + assert isinstance(node.items[0], Decorator) + unsafe_super = node.items[0].func.is_trivial_body + if unsafe_super: + mx.msg.unsafe_super(node.name, node.info.name, mx.context) + + +def analyze_type_callable_member_access(name: str, typ: FunctionLike, mx: MemberContext) -> Type: + # Class attribute. + # TODO super? + ret_type = typ.items[0].ret_type + assert isinstance(ret_type, ProperType) + if isinstance(ret_type, TupleType): + ret_type = tuple_fallback(ret_type) + if isinstance(ret_type, TypedDictType): + ret_type = ret_type.fallback + if isinstance(ret_type, LiteralType): + ret_type = ret_type.fallback + if isinstance(ret_type, Instance): + if not mx.is_operator: + # When Python sees an operator (eg `3 == 4`), it automatically translates that + # into something like `int.__eq__(3, 4)` instead of `(3).__eq__(4)` as an + # optimization. + # + # While it normally it doesn't matter which of the two versions are used, it + # does cause inconsistencies when working with classes. For example, translating + # `int == int` to `int.__eq__(int)` would not work since `int.__eq__` is meant to + # compare two int _instances_. What we really want is `type(int).__eq__`, which + # is meant to compare two types or classes. + # + # This check makes sure that when we encounter an operator, we skip looking up + # the corresponding method in the current instance to avoid this edge case. + # See https://github.com/python/mypy/pull/1787 for more info. + # TODO: do not rely on same type variables being present in all constructor overloads. + result = analyze_class_attribute_access( + ret_type, name, mx, original_vars=typ.items[0].variables, mcs_fallback=typ.fallback + ) + if result: + return result + # Look up from the 'type' type. + return _analyze_member_access(name, typ.fallback, mx) + else: + assert False, f"Unexpected type {ret_type!r}" + + +def analyze_type_type_member_access( + name: str, typ: TypeType, mx: MemberContext, override_info: TypeInfo | None +) -> Type: + # Similar to analyze_type_callable_attribute_access. + item = None + fallback = mx.named_type("builtins.type") + if isinstance(typ.item, Instance): + item = typ.item + elif isinstance(typ.item, AnyType): + with mx.msg.filter_errors(): + return _analyze_member_access(name, fallback, mx, override_info) + elif isinstance(typ.item, TypeVarType): + upper_bound = get_proper_type(typ.item.upper_bound) + if isinstance(upper_bound, Instance): + item = upper_bound + elif isinstance(upper_bound, UnionType): + return _analyze_member_access( + name, + TypeType.make_normalized(upper_bound, line=typ.line, column=typ.column), + mx, + override_info, + ) + elif isinstance(upper_bound, TupleType): + item = tuple_fallback(upper_bound) + elif isinstance(upper_bound, AnyType): + with mx.msg.filter_errors(): + return _analyze_member_access(name, fallback, mx, override_info) + elif isinstance(typ.item, TupleType): + item = tuple_fallback(typ.item) + elif isinstance(typ.item, FunctionLike) and typ.item.is_type_obj(): + item = typ.item.fallback + elif isinstance(typ.item, TypeType): + # Access member on metaclass object via Type[Type[C]] + if isinstance(typ.item.item, Instance): + item = typ.item.item.type.metaclass_type + ignore_messages = False + + if item is not None: + fallback = item.type.metaclass_type or fallback + + if item and not mx.is_operator: + # See comment above for why operators are skipped + result = analyze_class_attribute_access( + item, name, mx, mcs_fallback=fallback, override_info=override_info + ) + if result: + if not (isinstance(get_proper_type(result), AnyType) and item.type.fallback_to_any): + return result + else: + # We don't want errors on metaclass lookup for classes with Any fallback + ignore_messages = True + + with mx.msg.filter_errors(filter_errors=ignore_messages): + return _analyze_member_access(name, fallback, mx, override_info) + + +def analyze_union_member_access(name: str, typ: UnionType, mx: MemberContext) -> Type: + with mx.msg.disable_type_names(): + results = [] + for subtype in typ.relevant_items(): + # Self types should be bound to every individual item of a union. + item_mx = mx.copy_modified(self_type=subtype) + results.append(_analyze_member_access(name, subtype, item_mx)) + return make_simplified_union(results) + + +def analyze_none_member_access(name: str, typ: NoneType, mx: MemberContext) -> Type: + if name == "__bool__": + literal_false = LiteralType(False, fallback=mx.named_type("builtins.bool")) + return CallableType( + arg_types=[], + arg_kinds=[], + arg_names=[], + ret_type=literal_false, + fallback=mx.named_type("builtins.function"), + ) + else: + return _analyze_member_access(name, mx.named_type("builtins.object"), mx) + + +def analyze_member_var_access( + name: str, itype: Instance, info: TypeInfo, mx: MemberContext +) -> Type: + """Analyse attribute access that does not target a method. + + This is logically part of analyze_member_access and the arguments are similar. + + original_type is the type of E in the expression E.var + """ + # It was not a method. Try looking up a variable. + node = info.get(name) + v = node.node if node else None + + mx.chk.warn_deprecated(v, mx.context) + + vv = v + is_trivial_self = False + if isinstance(vv, Decorator): + # The associated Var node of a decorator contains the type. + v = vv.var + is_trivial_self = vv.func.is_trivial_self and not vv.decorators + if mx.is_super and not mx.suppress_errors: + validate_super_call(vv.func, mx) + if isinstance(v, FuncDef): + assert False, "Did not expect a function" + if isinstance(v, MypyFile): + # Special case: accessing module on instances is allowed, but will not + # be recorded by semantic analyzer. + mx.chk.module_refs.add(v.fullname) + + if isinstance(vv, (TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)): + # If the associated variable is a TypeInfo synthesize a Var node for + # the purposes of type checking. This enables us to type check things + # like accessing class attributes on an inner class. Similar we allow + # using qualified type aliases in runtime context. For example: + # class C: + # A = List[int] + # x = C.A() <- this is OK + typ = mx.chk.expr_checker.analyze_static_reference(vv, mx.context, mx.is_lvalue) + v = Var(name, type=typ) + v.info = info + + if isinstance(v, Var): + implicit = info[name].implicit + + # An assignment to final attribute is always an error, + # independently of types. + if mx.is_lvalue and not mx.chk.get_final_context(): + check_final_member(name, info, mx.msg, mx.context) + + return analyze_var(name, v, itype, mx, implicit=implicit, is_trivial_self=is_trivial_self) + elif ( + not v + and name not in ["__getattr__", "__setattr__", "__getattribute__"] + and not mx.is_operator + and mx.module_symbol_table is None + ): + # Above we skip ModuleType.__getattr__ etc. if we have a + # module symbol table, since the symbol table allows precise + # checking. + if not mx.is_lvalue: + for method_name in ("__getattribute__", "__getattr__"): + method = info.get_method(method_name) + + # __getattribute__ is defined on builtins.object and returns Any, so without + # the guard this search will always find object.__getattribute__ and conclude + # that the attribute exists + if method and method.info.fullname != "builtins.object": + bound_method = analyze_decorator_or_funcbase_access( + defn=method, itype=itype, name=method_name, mx=mx + ) + typ = map_instance_to_supertype(itype, method.info) + getattr_type = get_proper_type(expand_type_by_instance(bound_method, typ)) + if isinstance(getattr_type, CallableType): + result = getattr_type.ret_type + else: + result = getattr_type + + # Call the attribute hook before returning. + fullname = f"{method.info.fullname}.{name}" + hook = mx.chk.plugin.get_attribute_hook(fullname) + if hook: + result = hook( + AttributeContext( + get_proper_type(mx.original_type), + result, + mx.is_lvalue, + mx.context, + mx.chk, + ) + ) + return result + else: + setattr_meth = info.get_method("__setattr__") + if setattr_meth and setattr_meth.info.fullname != "builtins.object": + bound_type = analyze_decorator_or_funcbase_access( + defn=setattr_meth, + itype=itype, + name="__setattr__", + mx=mx.copy_modified(is_lvalue=False), + ) + typ = map_instance_to_supertype(itype, setattr_meth.info) + setattr_type = get_proper_type(expand_type_by_instance(bound_type, typ)) + if isinstance(setattr_type, CallableType) and len(setattr_type.arg_types) > 0: + return setattr_type.arg_types[-1] + + if itype.type.fallback_to_any: + return AnyType(TypeOfAny.special_form) + + # Could not find the member. + if itype.extra_attrs and name in itype.extra_attrs.attrs: + # For modules use direct symbol table lookup. + if not itype.extra_attrs.mod_name: + return itype.extra_attrs.attrs[name] + + if mx.is_super and not mx.suppress_errors: + mx.msg.undefined_in_superclass(name, mx.context) + return AnyType(TypeOfAny.from_error) + else: + ret = report_missing_attribute(mx.original_type, itype, name, mx) + # Avoid paying double jeopardy if we can't find the member due to --no-implicit-reexport + if ( + mx.module_symbol_table is not None + and name in mx.module_symbol_table + and not mx.module_symbol_table[name].module_public + ): + v = mx.module_symbol_table[name].node + e = NameExpr(name) + e.set_line(mx.context) + e.node = v + return mx.chk.expr_checker.analyze_ref_expr(e, lvalue=mx.is_lvalue) + return ret + + +def check_final_member(name: str, info: TypeInfo, msg: MessageBuilder, ctx: Context) -> None: + """Give an error if the name being assigned was declared as final.""" + for base in info.mro: + sym = base.names.get(name) + if sym and is_final_node(sym.node): + msg.cant_assign_to_final(name, attr_assign=True, ctx=ctx) + + +def analyze_descriptor_access(descriptor_type: Type, mx: MemberContext) -> Type: + """Type check descriptor access. + + Arguments: + descriptor_type: The type of the descriptor attribute being accessed + (the type of ``f`` in ``a.f`` when ``f`` is a descriptor). + mx: The current member access context. + Return: + The return type of the appropriate ``__get__/__set__`` overload for the descriptor. + """ + instance_type = get_proper_type(mx.self_type) + orig_descriptor_type = descriptor_type + descriptor_type = get_proper_type(descriptor_type) + + if isinstance(descriptor_type, UnionType): + # Map the access over union types + return make_simplified_union( + [analyze_descriptor_access(typ, mx) for typ in descriptor_type.items] + ) + elif not isinstance(descriptor_type, Instance): + return orig_descriptor_type + + if not mx.is_lvalue and not descriptor_type.type.has_readable_member("__get__"): + return orig_descriptor_type + + # We do this check first to accommodate for descriptors with only __set__ method. + # If there is no __set__, we type-check that the assigned value matches + # the return type of __get__. This doesn't match the python semantics, + # (which allow you to override the descriptor with any value), but preserves + # the type of accessing the attribute (even after the override). + if mx.is_lvalue and descriptor_type.type.has_readable_member("__set__"): + return analyze_descriptor_assign(descriptor_type, mx) + + if mx.is_lvalue and not descriptor_type.type.has_readable_member("__get__"): + # This turned out to be not a descriptor after all. + return orig_descriptor_type + + dunder_get = descriptor_type.type.get_method("__get__") + if dunder_get is None: + mx.fail( + message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format( + descriptor_type.str_with_options(mx.msg.options) + ) + ) + return AnyType(TypeOfAny.from_error) + + bound_method = analyze_decorator_or_funcbase_access( + defn=dunder_get, + itype=descriptor_type, + name="__get__", + mx=mx.copy_modified(self_type=descriptor_type), + ) + + typ = map_instance_to_supertype(descriptor_type, dunder_get.info) + dunder_get_type = expand_type_by_instance(bound_method, typ) + + if isinstance(instance_type, FunctionLike) and instance_type.is_type_obj(): + owner_type = instance_type.items[0].ret_type + instance_type = NoneType() + elif isinstance(instance_type, TypeType): + owner_type = instance_type.item + instance_type = NoneType() + else: + owner_type = instance_type + + callable_name = mx.chk.expr_checker.method_fullname(descriptor_type, "__get__") + dunder_get_type = mx.chk.expr_checker.transform_callee_type( + callable_name, + dunder_get_type, + [ + TempNode(instance_type, context=mx.context), + TempNode(TypeType.make_normalized(owner_type), context=mx.context), + ], + [ARG_POS, ARG_POS], + mx.context, + object_type=descriptor_type, + ) + + _, inferred_dunder_get_type = mx.chk.expr_checker.check_call( + dunder_get_type, + [ + TempNode(instance_type, context=mx.context), + TempNode(TypeType.make_normalized(owner_type), context=mx.context), + ], + [ARG_POS, ARG_POS], + mx.context, + object_type=descriptor_type, + callable_name=callable_name, + ) + + # Search for possible deprecations: + mx.chk.warn_deprecated(dunder_get, mx.context) + + inferred_dunder_get_type = get_proper_type(inferred_dunder_get_type) + if isinstance(inferred_dunder_get_type, AnyType): + # check_call failed, and will have reported an error + return inferred_dunder_get_type + + if not isinstance(inferred_dunder_get_type, CallableType): + mx.fail( + message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format( + descriptor_type.str_with_options(mx.msg.options) + ) + ) + return AnyType(TypeOfAny.from_error) + + return inferred_dunder_get_type.ret_type + + +def analyze_descriptor_assign(descriptor_type: Instance, mx: MemberContext) -> Type: + instance_type = get_proper_type(mx.self_type) + dunder_set = descriptor_type.type.get_method("__set__") + if dunder_set is None: + mx.fail( + message_registry.DESCRIPTOR_SET_NOT_CALLABLE.format( + descriptor_type.str_with_options(mx.msg.options) + ).value + ) + return AnyType(TypeOfAny.from_error) + + bound_method = analyze_decorator_or_funcbase_access( + defn=dunder_set, + itype=descriptor_type, + name="__set__", + mx=mx.copy_modified(is_lvalue=False, self_type=descriptor_type), + ) + typ = map_instance_to_supertype(descriptor_type, dunder_set.info) + dunder_set_type = expand_type_by_instance(bound_method, typ) + + callable_name = mx.chk.expr_checker.method_fullname(descriptor_type, "__set__") + rvalue = mx.rvalue or TempNode(AnyType(TypeOfAny.special_form), context=mx.context) + dunder_set_type = mx.chk.expr_checker.transform_callee_type( + callable_name, + dunder_set_type, + [TempNode(instance_type, context=mx.context), rvalue], + [ARG_POS, ARG_POS], + mx.context, + object_type=descriptor_type, + ) + + # For non-overloaded setters, the result should be type-checked like a regular assignment. + # Hence, we first only try to infer the type by using the rvalue as type context. + type_context = rvalue + with mx.msg.filter_errors(): + _, inferred_dunder_set_type = mx.chk.expr_checker.check_call( + dunder_set_type, + [TempNode(instance_type, context=mx.context), type_context], + [ARG_POS, ARG_POS], + mx.context, + object_type=descriptor_type, + callable_name=callable_name, + ) + + # And now we in fact type check the call, to show errors related to wrong arguments + # count, etc., replacing the type context for non-overloaded setters only. + inferred_dunder_set_type = get_proper_type(inferred_dunder_set_type) + if isinstance(inferred_dunder_set_type, CallableType): + type_context = TempNode(AnyType(TypeOfAny.special_form), context=mx.context) + mx.chk.expr_checker.check_call( + dunder_set_type, + [TempNode(instance_type, context=mx.context), type_context], + [ARG_POS, ARG_POS], + mx.context, + object_type=descriptor_type, + callable_name=callable_name, + ) + + # Search for possible deprecations: + mx.chk.warn_deprecated(dunder_set, mx.context) + + # In the following cases, a message already will have been recorded in check_call. + if (not isinstance(inferred_dunder_set_type, CallableType)) or ( + len(inferred_dunder_set_type.arg_types) < 2 + ): + return AnyType(TypeOfAny.from_error) + return inferred_dunder_set_type.arg_types[1] + + +def is_instance_var(var: Var) -> bool: + """Return if var is an instance variable according to PEP 526.""" + return ( + # check the type_info node is the var (not a decorated function, etc.) + var.name in var.info.names + and var.info.names[var.name].node is var + and not var.is_classvar + # variables without annotations are treated as classvar + and not var.is_inferred + ) + + +def analyze_var( + name: str, + var: Var, + itype: Instance, + mx: MemberContext, + *, + implicit: bool = False, + is_trivial_self: bool = False, +) -> Type: + """Analyze access to an attribute via a Var node. + + This is conceptually part of analyze_member_access and the arguments are similar. + itype is the instance type in which attribute should be looked up + original_type is the type of E in the expression E.var + if implicit is True, the original Var was created as an assignment to self + if is_trivial_self is True, we can use fast path for bind_self(). + """ + # Found a member variable. + original_itype = itype + itype = map_instance_to_supertype(itype, var.info) + if var.is_settable_property and mx.is_lvalue: + typ: Type | None = var.setter_type + if typ is None and var.is_ready: + # Existing synthetic properties may not set setter type. Fall back to getter. + typ = var.type + else: + typ = var.type + if typ: + if isinstance(typ, PartialType): + return mx.chk.handle_partial_var_type(typ, mx.is_lvalue, var, mx.context) + if mx.is_lvalue and not mx.suppress_errors: + if var.is_property and not var.is_settable_property: + mx.msg.read_only_property(name, itype.type, mx.context) + if var.is_classvar: + mx.msg.cant_assign_to_classvar(name, mx.context) + # This is the most common case for variables, so start with this. + result = expand_without_binding(typ, var, itype, original_itype, mx) + + # A non-None value indicates that we should actually bind self for this variable. + call_type: ProperType | None = None + if var.is_initialized_in_class and (not is_instance_var(var) or mx.is_operator): + typ = get_proper_type(typ) + if isinstance(typ, FunctionLike) and not typ.is_type_obj(): + call_type = typ + elif var.is_property: + deco_mx = mx.copy_modified(original_type=typ, self_type=typ, is_lvalue=False) + call_type = get_proper_type(_analyze_member_access("__call__", typ, deco_mx)) + else: + call_type = typ + + # Bound variables with callable types are treated like methods + # (these are usually method aliases like __rmul__ = __mul__). + if isinstance(call_type, FunctionLike) and not call_type.is_type_obj(): + if mx.is_lvalue and not var.is_property and not mx.suppress_errors: + mx.msg.cant_assign_to_method(mx.context) + + # Bind the self type for each callable component (when needed). + if call_type and not var.is_staticmethod: + bound_items = [] + for ct in call_type.items if isinstance(call_type, UnionType) else [call_type]: + p_ct = get_proper_type(ct) + if isinstance(p_ct, FunctionLike) and (not p_ct.bound() or var.is_property): + item = expand_and_bind_callable(p_ct, var, itype, name, mx, is_trivial_self) + else: + item = expand_without_binding(ct, var, itype, original_itype, mx) + bound_items.append(item) + result = UnionType.make_union(bound_items) + else: + if not var.is_ready and not mx.no_deferral: + mx.not_ready_callback(var.name, mx.context) + # Implicit 'Any' type. + result = AnyType(TypeOfAny.special_form) + fullname = f"{var.info.fullname}.{name}" + hook = mx.chk.plugin.get_attribute_hook(fullname) + + if var.info.is_enum and not mx.is_lvalue: + if name in var.info.enum_members and name not in {"name", "value"}: + enum_literal = LiteralType(name, fallback=itype) + result = itype.copy_modified(last_known_value=enum_literal) + elif ( + isinstance(p_result := get_proper_type(result), Instance) + and p_result.type.fullname == "enum.nonmember" + and p_result.args + ): + # Unwrap nonmember similar to class-level access + result = p_result.args[0] + if result and not (implicit or var.info.is_protocol and is_instance_var(var)): + result = analyze_descriptor_access(result, mx) + if hook: + result = hook( + AttributeContext( + get_proper_type(mx.original_type), result, mx.is_lvalue, mx.context, mx.chk + ) + ) + return result + + +def expand_without_binding( + typ: Type, var: Var, itype: Instance, original_itype: Instance, mx: MemberContext +) -> Type: + if not mx.preserve_type_var_ids: + typ = freshen_all_functions_type_vars(typ) + typ = expand_self_type_if_needed(typ, mx, var, original_itype) + expanded = expand_type_by_instance(typ, itype) + freeze_all_type_vars(expanded) + return expanded + + +def expand_and_bind_callable( + functype: FunctionLike, + var: Var, + itype: Instance, + name: str, + mx: MemberContext, + is_trivial_self: bool, +) -> Type: + if not mx.preserve_type_var_ids: + functype = freshen_all_functions_type_vars(functype) + typ = get_proper_type(expand_self_type(var, functype, mx.self_type)) + assert isinstance(typ, FunctionLike) + if is_trivial_self: + typ = bind_self_fast(typ, mx.self_type) + else: + typ = check_self_arg(typ, mx.self_type, var.is_classmethod, mx.context, name, mx.msg) + typ = bind_self(typ, mx.self_type, var.is_classmethod) + expanded = expand_type_by_instance(typ, itype) + freeze_all_type_vars(expanded) + if not var.is_property: + return expanded + if isinstance(expanded, Overloaded): + # Legacy way to store settable properties is with overloads. Also in case it is + # an actual overloaded property, selecting first item that passed check_self_arg() + # is a good approximation, long-term we should use check_call() inference below. + if not expanded.items: + # A broken overload, error should be already reported. + return AnyType(TypeOfAny.from_error) + expanded = expanded.items[0] + assert isinstance(expanded, CallableType), expanded + if var.is_settable_property and mx.is_lvalue and var.setter_type is not None: + if expanded.variables: + type_ctx = mx.rvalue or TempNode(AnyType(TypeOfAny.special_form), context=mx.context) + _, inferred_expanded = mx.chk.expr_checker.check_call( + expanded, [type_ctx], [ARG_POS], mx.context + ) + expanded = get_proper_type(inferred_expanded) + assert isinstance(expanded, CallableType) + if not expanded.arg_types: + # This can happen when accessing invalid property from its own body, + # error will be reported elsewhere. + return AnyType(TypeOfAny.from_error) + return expanded.arg_types[0] + else: + return expanded.ret_type + + +def expand_self_type_if_needed( + t: Type, mx: MemberContext, var: Var, itype: Instance, is_class: bool = False +) -> Type: + """Expand special Self type in a backwards compatible manner. + + This should ensure that mixing old-style and new-style self-types work + seamlessly. Also, re-bind new style self-types in subclasses if needed. + """ + original = get_proper_type(mx.self_type) + if not (mx.is_self or mx.is_super): + repl = mx.self_type + if is_class: + if isinstance(original, TypeType): + repl = original.item + elif isinstance(original, CallableType): + # Problematic access errors should have been already reported. + repl = erase_typevars(original.ret_type) + else: + repl = itype + return expand_self_type(var, t, repl) + elif supported_self_type( + # Support compatibility with plain old style T -> T and Type[T] -> T only. + get_proper_type(mx.self_type), + allow_instances=False, + allow_callable=False, + ): + repl = mx.self_type + if is_class and isinstance(original, TypeType): + repl = original.item + return expand_self_type(var, t, repl) + elif ( + mx.is_self + and itype.type != var.info + # If an attribute with Self-type was defined in a supertype, we need to + # rebind the Self type variable to Self type variable of current class... + and itype.type.self_type is not None + # ...unless `self` has an explicit non-trivial annotation. + and itype == mx.chk.scope.active_self_type() + ): + return expand_self_type(var, t, itype.type.self_type) + else: + return t + + +def check_self_arg( + functype: FunctionLike, + dispatched_arg_type: Type, + is_classmethod: bool, + context: Context, + name: str, + msg: MessageBuilder, +) -> FunctionLike: + """Check that an instance has a valid type for a method with annotated 'self'. + + For example if the method is defined as: + class A: + def f(self: S) -> T: ... + then for 'x.f' we check that type(x) <: S. If the method is overloaded, we select + only overloads items that satisfy this requirement. If there are no matching + overloads, an error is generated. + """ + items = functype.items + if not items: + return functype + new_items = [] + if is_classmethod: + dispatched_arg_type = TypeType.make_normalized(dispatched_arg_type) + p_dispatched_arg_type = get_proper_type(dispatched_arg_type) + + for item in items: + if not item.arg_types or item.arg_kinds[0] not in (ARG_POS, ARG_STAR): + # No positional first (self) argument (*args is okay). + msg.no_formal_self(name, item, context) + # This is pretty bad, so just return the original signature if + # there is at least one such error. + return functype + selfarg = get_proper_type(item.arg_types[0]) + if isinstance(selfarg, Instance) and isinstance(p_dispatched_arg_type, Instance): + if selfarg.type is p_dispatched_arg_type.type and selfarg.args: + if not is_overlapping_types(p_dispatched_arg_type, selfarg): + # This special casing is needed since `actual <: erased(template)` + # logic below doesn't always work, and a more correct approach may + # be tricky. + continue + new_items.append(item) + + if new_items: + items = new_items + new_items = [] + + for item in items: + selfarg = get_proper_type(item.arg_types[0]) + # This matches similar special-casing in bind_self(), see more details there. + self_callable = name == "__call__" and isinstance(selfarg, CallableType) + if self_callable or is_subtype( + dispatched_arg_type, + # This level of erasure matches the one in checker.check_func_def(), + # better keep these two checks consistent. + erase_typevars(erase_to_bound(selfarg)), + # This is to work around the fact that erased ParamSpec and TypeVarTuple + # callables are not always compatible with non-erased ones both ways. + always_covariant=any( + not isinstance(tv, TypeVarType) for tv in get_all_type_vars(selfarg) + ), + ignore_pos_arg_names=True, + ): + new_items.append(item) + elif isinstance(selfarg, ParamSpecType): + # TODO: This is not always right. What's the most reasonable thing to do here? + new_items.append(item) + elif isinstance(selfarg, TypeVarTupleType): + raise NotImplementedError + if not new_items: + # Choose first item for the message (it may be not very helpful for overloads). + msg.incompatible_self_argument( + name, dispatched_arg_type, items[0], is_classmethod, context + ) + return functype + if len(new_items) == 1: + return new_items[0] + return Overloaded(new_items) + + +def analyze_class_attribute_access( + itype: Instance, + name: str, + mx: MemberContext, + *, + mcs_fallback: Instance, + override_info: TypeInfo | None = None, + original_vars: Sequence[TypeVarLikeType] | None = None, +) -> Type | None: + """Analyze access to an attribute on a class object. + + itype is the return type of the class object callable, original_type is the type + of E in the expression E.var, original_vars are type variables of the class callable + (for generic classes). + """ + info = itype.type + if override_info: + info = override_info + + fullname = f"{info.fullname}.{name}" + hook = mx.chk.plugin.get_class_attribute_hook(fullname) + + node = info.get(name) + if not node: + if itype.extra_attrs and name in itype.extra_attrs.attrs: + # For modules use direct symbol table lookup. + if not itype.extra_attrs.mod_name: + return itype.extra_attrs.attrs[name] + if info.fallback_to_any or info.meta_fallback_to_any: + return apply_class_attr_hook(mx, hook, AnyType(TypeOfAny.special_form)) + return None + + if ( + isinstance(node.node, Var) + and not node.node.is_classvar + and not hook + and mcs_fallback.type.get(name) + ): + # If the same attribute is declared on the metaclass and the class but with different types, + # and the attribute on the class is not a ClassVar, + # the type of the attribute on the metaclass should take priority + # over the type of the attribute on the class, + # when the attribute is being accessed from the class object itself. + # + # Return `None` here to signify that the name should be looked up + # on the class object itself rather than the instance. + return None + + mx.chk.warn_deprecated(node.node, mx.context) + + is_decorated = isinstance(node.node, Decorator) + is_method = is_decorated or isinstance(node.node, FuncBase) + if mx.is_lvalue and not mx.suppress_errors: + if is_method: + mx.msg.cant_assign_to_method(mx.context) + if isinstance(node.node, TypeInfo): + mx.fail(message_registry.CANNOT_ASSIGN_TO_TYPE) + + # Refuse class attribute access if slot defined + if info.slots and name in info.slots: + mx.fail(message_registry.CLASS_VAR_CONFLICTS_SLOTS.format(name)) + + if node.implicit and isinstance(node.node, Var): + if node.node.is_final: + # If a final attribute was declared on `self` in `__init__`, then it + # can't be accessed on the class object. + mx.fail(message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR.format(node.node.name)) + elif not mx.is_lvalue and not defined_in_superclass(info, name): + mx.fail(message_registry.CANNOT_ACCESS_INSTANCE_ONLY_ATTR.format(node.node.name)) + + # An assignment to final attribute on class object is also always an error, + # independently of types. + if mx.is_lvalue and not mx.chk.get_final_context(): + check_final_member(name, info, mx.msg, mx.context) + + if info.is_enum and not (mx.is_lvalue or is_decorated or is_method): + enum_class_attribute_type = analyze_enum_class_attribute_access(itype, name, mx) + if enum_class_attribute_type: + return apply_class_attr_hook(mx, hook, enum_class_attribute_type) + + t = node.type + if t: + if isinstance(t, PartialType): + symnode = node.node + assert isinstance(symnode, Var) + return apply_class_attr_hook( + mx, hook, mx.chk.handle_partial_var_type(t, mx.is_lvalue, symnode, mx.context) + ) + + # Find the class where method/variable was defined. + if isinstance(node.node, Decorator): + super_info: TypeInfo | None = node.node.var.info + elif isinstance(node.node, (Var, SYMBOL_FUNCBASE_TYPES)): + super_info = node.node.info + else: + super_info = None + + # Map the type to how it would look as a defining class. For example: + # class C(Generic[T]): ... + # class D(C[Tuple[T, S]]): ... + # D[int, str].method() + # Here itype is D[int, str], isuper is C[Tuple[int, str]]. + if not super_info: + isuper = None + else: + isuper = map_instance_to_supertype(itype, super_info) + + if isinstance(node.node, Var): + assert isuper is not None + object_type = get_proper_type(mx.self_type) + # Check if original variable type has type variables. For example: + # class C(Generic[T]): + # x: T + # C.x # Error, ambiguous access + # C[int].x # Also an error, since C[int] is same as C at runtime + # Exception is Self type wrapped in ClassVar, that is safe. + prohibit_self = not node.node.is_classvar + def_vars = set(node.node.info.defn.type_vars) + if prohibit_self and node.node.info.self_type: + def_vars.add(node.node.info.self_type) + # Exception: access on Type[...], including first argument of class methods is OK. + prohibit_generic = not isinstance(object_type, TypeType) or node.implicit + if prohibit_generic and def_vars & set(get_all_type_vars(t)): + if node.node.is_classvar: + message = message_registry.GENERIC_CLASS_VAR_ACCESS + else: + message = message_registry.GENERIC_INSTANCE_VAR_CLASS_ACCESS + mx.fail(message) + t = expand_self_type_if_needed(t, mx, node.node, itype, is_class=True) + t = expand_type_by_instance(t, isuper) + # Erase non-mapped variables, but keep mapped ones, even if there is an error. + # In the above example this means that we infer following types: + # C.x -> Any + # C[int].x -> int + if prohibit_generic: + erase_vars = set(itype.type.defn.type_vars) + if prohibit_self and itype.type.self_type: + erase_vars.add(itype.type.self_type) + t = erase_typevars(t, {tv.id for tv in erase_vars}) + + is_classmethod = ( + (is_decorated and cast(Decorator, node.node).func.is_class) + or (isinstance(node.node, SYMBOL_FUNCBASE_TYPES) and node.node.is_class) + or isinstance(node.node, Var) + and node.node.is_classmethod + ) + t = get_proper_type(t) + is_trivial_self = False + if isinstance(node.node, Decorator): + # Use fast path if there are trivial decorators like @classmethod or @property + is_trivial_self = node.node.func.is_trivial_self and not node.node.decorators + elif isinstance(node.node, (FuncDef, OverloadedFuncDef)): + is_trivial_self = node.node.is_trivial_self + if ( + isinstance(t, FunctionLike) + and is_classmethod + and not is_trivial_self + and not t.bound() + ): + t = check_self_arg(t, mx.self_type, False, mx.context, name, mx.msg) + t = add_class_tvars( + t, + isuper, + is_classmethod, + mx, + original_vars=original_vars, + is_trivial_self=is_trivial_self, + ) + if is_decorated: + t = expand_self_type_if_needed( + t, mx, cast(Decorator, node.node).var, itype, is_class=is_classmethod + ) + + result = t + # __set__ is not called on class objects. + if not mx.is_lvalue: + result = analyze_descriptor_access(result, mx) + + return apply_class_attr_hook(mx, hook, result) + elif isinstance(node.node, Var): + mx.not_ready_callback(name, mx.context) + return AnyType(TypeOfAny.special_form) + + if isinstance(node.node, (TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)): + # TODO: should we apply class plugin here (similar to instance access)? + return mx.chk.expr_checker.analyze_static_reference(node.node, mx.context, mx.is_lvalue) + + if is_decorated: + assert isinstance(node.node, Decorator) + if node.node.type: + return apply_class_attr_hook(mx, hook, node.node.type) + else: + mx.not_ready_callback(name, mx.context) + return AnyType(TypeOfAny.from_error) + else: + assert isinstance(node.node, SYMBOL_FUNCBASE_TYPES) + typ = function_type(node.node, mx.named_type("builtins.function")) + # Note: if we are accessing class method on class object, the cls argument is bound. + # Annotated and/or explicit class methods go through other code paths above, for + # unannotated implicit class methods we do this here. + if node.node.is_class: + typ = bind_self_fast(typ) + return apply_class_attr_hook(mx, hook, typ) + + +def apply_class_attr_hook( + mx: MemberContext, hook: Callable[[AttributeContext], Type] | None, result: Type +) -> Type | None: + if hook: + result = hook( + AttributeContext( + get_proper_type(mx.original_type), result, mx.is_lvalue, mx.context, mx.chk + ) + ) + return result + + +def analyze_enum_class_attribute_access( + itype: Instance, name: str, mx: MemberContext +) -> Type | None: + # Skip these since Enum will remove it + if name in EXCLUDED_ENUM_ATTRIBUTES: + return report_missing_attribute(mx.original_type, itype, name, mx) + + node = itype.type.get(name) + if node and node.type: + proper = get_proper_type(node.type) + # Support `A = nonmember(1)` function call and decorator. + if ( + isinstance(proper, Instance) + and proper.type.fullname == "enum.nonmember" + and proper.args + ): + return proper.args[0] + + if name not in itype.type.enum_members: + return None + + enum_literal = LiteralType(name, fallback=itype) + return itype.copy_modified(last_known_value=enum_literal) + + +def analyze_typeddict_access( + name: str, typ: TypedDictType, mx: MemberContext, override_info: TypeInfo | None +) -> Type: + if name == "__setitem__": + if isinstance(mx.context, IndexExpr): + # Since we can get this during `a['key'] = ...` + # it is safe to assume that the context is `IndexExpr`. + item_type, key_names = mx.chk.expr_checker.visit_typeddict_index_expr( + typ, mx.context.index, setitem=True + ) + assigned_readonly_keys = typ.readonly_keys & key_names + if assigned_readonly_keys and not mx.suppress_errors: + mx.msg.readonly_keys_mutated(assigned_readonly_keys, context=mx.context) + else: + # It can also be `a.__setitem__(...)` direct call. + # In this case `item_type` can be `Any`, + # because we don't have args available yet. + # TODO: check in `default` plugin that `__setitem__` is correct. + item_type = AnyType(TypeOfAny.implementation_artifact) + return CallableType( + arg_types=[mx.chk.named_type("builtins.str"), item_type], + arg_kinds=[ARG_POS, ARG_POS], + arg_names=[None, None], + ret_type=NoneType(), + fallback=mx.chk.named_type("builtins.function"), + name=name, + ) + elif name == "__delitem__": + return CallableType( + arg_types=[mx.chk.named_type("builtins.str")], + arg_kinds=[ARG_POS], + arg_names=[None], + ret_type=NoneType(), + fallback=mx.chk.named_type("builtins.function"), + name=name, + ) + return _analyze_member_access(name, typ.fallback, mx, override_info) + + +def add_class_tvars( + t: ProperType, + isuper: Instance | None, + is_classmethod: bool, + mx: MemberContext, + original_vars: Sequence[TypeVarLikeType] | None = None, + is_trivial_self: bool = False, +) -> Type: + """Instantiate type variables during analyze_class_attribute_access, + e.g T and Q in the following: + + class A(Generic[T]): + @classmethod + def foo(cls: Type[Q]) -> Tuple[T, Q]: ... + + class B(A[str]): pass + B.foo() + + Args: + t: Declared type of the method (or property) + isuper: Current instance mapped to the superclass where method was defined, this + is usually done by map_instance_to_supertype() + is_classmethod: True if this method is decorated with @classmethod + original_vars: Type variables of the class callable on which the method was accessed + is_trivial_self: if True, we can use fast path for bind_self(). + Returns: + Expanded method type with added type variables (when needed). + """ + # TODO: verify consistency between Q and T + + # We add class type variables if the class method is accessed on class object + # without applied type arguments, this matches the behavior of __init__(). + # For example (continuing the example in docstring): + # A # The type of callable is def [T] () -> A[T], _not_ def () -> A[Any] + # A[int] # The type of callable is def () -> A[int] + # and + # A.foo # The type is generic def [T] () -> Tuple[T, A[T]] + # A[int].foo # The type is non-generic def () -> Tuple[int, A[int]] + # + # This behaviour is useful for defining alternative constructors for generic classes. + # To achieve such behaviour, we add the class type variables that are still free + # (i.e. appear in the return type of the class object on which the method was accessed). + if isinstance(t, CallableType): + tvars = original_vars if original_vars is not None else [] + if not mx.preserve_type_var_ids: + t = freshen_all_functions_type_vars(t) + if is_classmethod and not t.is_bound: + if is_trivial_self: + t = bind_self_fast(t, mx.self_type) + else: + t = bind_self(t, mx.self_type, is_classmethod=True) + if isuper is not None: + t = expand_type_by_instance(t, isuper) + freeze_all_type_vars(t) + return t.copy_modified(variables=list(tvars) + list(t.variables)) + elif isinstance(t, Overloaded): + return Overloaded( + [ + cast( + CallableType, + add_class_tvars(item, isuper, is_classmethod, mx, original_vars=original_vars), + ) + for item in t.items + ] + ) + if isuper is not None: + t = expand_type_by_instance(t, isuper) + return t + + +def analyze_decorator_or_funcbase_access( + defn: Decorator | FuncBase, itype: Instance, name: str, mx: MemberContext +) -> Type: + """Analyzes the type behind method access. + + The function itself can possibly be decorated. + See: https://github.com/python/mypy/issues/10409 + """ + if isinstance(defn, Decorator): + return analyze_var(name, defn.var, itype, mx) + typ = function_type(defn, mx.chk.named_type("builtins.function")) + if isinstance(defn, (FuncDef, OverloadedFuncDef)) and defn.is_trivial_self: + return bind_self_fast(typ, mx.self_type) + typ = check_self_arg(typ, mx.self_type, defn.is_class, mx.context, name, mx.msg) + return bind_self(typ, original_type=mx.self_type, is_classmethod=defn.is_class) + + +F = TypeVar("F", bound=FunctionLike) + + +def bind_self_fast(method: F, original_type: Type | None = None) -> F: + """Return a copy of `method`, with the type of its first parameter (usually + self or cls) bound to original_type. + + This is a faster version of mypy.typeops.bind_self() that can be used for methods + with trivial self/cls annotations. + """ + if isinstance(method, Overloaded): + items = [bind_self_fast(c, original_type) for c in method.items] + return cast(F, Overloaded(items)) + assert isinstance(method, CallableType) + if not method.arg_types: + # Invalid method, return something. + return method + if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2): + # See typeops.py for details. + return method + return method.copy_modified( + arg_types=method.arg_types[1:], + arg_kinds=method.arg_kinds[1:], + arg_names=method.arg_names[1:], + is_bound=True, + ) + + +def has_operator(typ: Type, op_method: str, named_type: Callable[[str], Instance]) -> bool: + """Does type have operator with the given name? + + Note: this follows the rules for operator access, in particular: + * __getattr__ is not considered + * for class objects we only look in metaclass + * instance level attributes (i.e. extra_attrs) are not considered + """ + # This is much faster than analyze_member_access, and so using + # it first as a filter is important for performance. This is mostly relevant + # in situations where we can't expect that method is likely present, + # e.g. for __OP__ vs __rOP__. + typ = get_proper_type(typ) + + if isinstance(typ, TypeVarLikeType): + typ = typ.values_or_bound() + if isinstance(typ, AnyType): + return True + if isinstance(typ, UnionType): + return all(has_operator(x, op_method, named_type) for x in typ.relevant_items()) + if isinstance(typ, FunctionLike) and typ.is_type_obj(): + return typ.fallback.type.has_readable_member(op_method) + if isinstance(typ, TypeType): + # Type[Union[X, ...]] is always normalized to Union[Type[X], ...], + # so we don't need to care about unions here, but we need to care about + # Type[T], where upper bound of T is a union. + item = typ.item + if isinstance(item, TypeVarType): + item = item.values_or_bound() + if isinstance(item, UnionType): + return all(meta_has_operator(x, op_method, named_type) for x in item.relevant_items()) + return meta_has_operator(item, op_method, named_type) + return instance_fallback(typ, named_type).type.has_readable_member(op_method) + + +def instance_fallback(typ: ProperType, named_type: Callable[[str], Instance]) -> Instance: + if isinstance(typ, Instance): + return typ + if isinstance(typ, TupleType): + return tuple_fallback(typ) + if isinstance(typ, (LiteralType, TypedDictType)): + return typ.fallback + return named_type("builtins.object") + + +def meta_has_operator(item: Type, op_method: str, named_type: Callable[[str], Instance]) -> bool: + item = get_proper_type(item) + if isinstance(item, AnyType): + return True + item = instance_fallback(item, named_type) + meta = item.type.metaclass_type or named_type("builtins.type") + return meta.type.has_readable_member(op_method) + + +def defined_in_superclass(info: TypeInfo, name: str) -> bool: + """Check if a variable has an explicit value at class level in any of superclasses.""" + for base in info.mro[1:]: + if (node := base.names.get(name)) is not None: + if not node.implicit and isinstance(node.node, Var) and node.node.has_explicit_value: + return True + return False diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..25300d1f0339ba665ce66f5e68e221e022ae5828 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.py new file mode 100644 index 0000000000000000000000000000000000000000..53fa75fa5ec389ace64b01e419ea38e1a5ad4b23 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.py @@ -0,0 +1,885 @@ +"""Pattern checker. This file is conceptually part of TypeChecker.""" + +from __future__ import annotations + +from collections import defaultdict +from typing import Final, NamedTuple + +from mypy import message_registry +from mypy.checker_shared import TypeCheckerSharedApi, TypeRange +from mypy.checkmember import analyze_member_access +from mypy.expandtype import expand_type_by_instance +from mypy.join import join_types +from mypy.literals import literal_hash +from mypy.maptype import map_instance_to_supertype +from mypy.meet import narrow_declared_type +from mypy.messages import MessageBuilder +from mypy.nodes import ARG_POS, Expression, NameExpr, TempNode, TypeAlias, Var +from mypy.options import Options +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + Pattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.plugin import Plugin +from mypy.subtypes import is_subtype +from mypy.typeops import ( + coerce_to_literal, + make_simplified_union, + try_getting_str_literals_from_type, + tuple_fallback, +) +from mypy.types import ( + AnyType, + FunctionLike, + Instance, + NoneType, + ProperType, + TupleType, + Type, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarTupleType, + TypeVarType, + UninhabitedType, + UnionType, + UnpackType, + callable_with_ellipsis, + find_unpack_in_list, + get_proper_type, + split_with_prefix_and_suffix, +) +from mypy.typevars import fill_typevars, fill_typevars_with_any +from mypy.visitor import PatternVisitor + +self_match_type_names: Final = [ + "builtins.bool", + "builtins.bytearray", + "builtins.bytes", + "builtins.dict", + "builtins.float", + "builtins.frozenset", + "builtins.int", + "builtins.list", + "builtins.set", + "builtins.str", + "builtins.tuple", +] + +non_sequence_match_type_names: Final = ["builtins.str", "builtins.bytes", "builtins.bytearray"] + + +# For every Pattern a PatternType can be calculated. This requires recursively calculating +# the PatternTypes of the sub-patterns first. +# Using the data in the PatternType the match subject and captured names can be narrowed/inferred. +class PatternType(NamedTuple): + type: Type # The type the match subject can be narrowed to + rest_type: Type # The remaining type if the pattern didn't match + captures: dict[Expression, Type] # The variables captured by the pattern + + +class PatternChecker(PatternVisitor[PatternType]): + """Pattern checker. + + This class checks if a pattern can match a type, what the type can be narrowed to, and what + type capture patterns should be inferred as. + """ + + # Some services are provided by a TypeChecker instance. + chk: TypeCheckerSharedApi + # This is shared with TypeChecker, but stored also here for convenience. + msg: MessageBuilder + # Currently unused + plugin: Plugin + # The expression being matched against the pattern + subject: Expression + + subject_type: Type + # Type of the subject to check the (sub)pattern against + type_context: list[Type] + # Types that match against self instead of their __match_args__ if used as a class pattern + # Filled in from self_match_type_names + self_match_types: list[Type] + # Types that are sequences, but don't match sequence patterns. Filled in from + # non_sequence_match_type_names + non_sequence_match_types: list[Type] + + options: Options + + def __init__( + self, chk: TypeCheckerSharedApi, msg: MessageBuilder, plugin: Plugin, options: Options + ) -> None: + self.chk = chk + self.msg = msg + self.plugin = plugin + + self.type_context = [] + self.self_match_types = self.generate_types_from_names(self_match_type_names) + self.non_sequence_match_types = self.generate_types_from_names( + non_sequence_match_type_names + ) + self.options = options + + def accept(self, o: Pattern, type_context: Type) -> PatternType: + self.type_context.append(type_context) + result = o.accept(self) + self.type_context.pop() + + return result + + def visit_as_pattern(self, o: AsPattern) -> PatternType: + current_type = self.type_context[-1] + if o.pattern is not None: + pattern_type = self.accept(o.pattern, current_type) + typ, rest_type, type_map = pattern_type + else: + typ, rest_type, type_map = current_type, UninhabitedType(), {} + + if not is_uninhabited(typ) and o.name is not None: + typ, _ = self.chk.conditional_types_with_intersection( + current_type, [get_type_range(typ)], o, default=current_type + ) + if not is_uninhabited(typ): + type_map[o.name] = typ + + return PatternType(typ, rest_type, type_map) + + def visit_or_pattern(self, o: OrPattern) -> PatternType: + current_type = self.type_context[-1] + + # + # Check all the subpatterns + # + pattern_types = [] + for pattern in o.patterns: + pattern_type = self.accept(pattern, current_type) + pattern_types.append(pattern_type) + if not is_uninhabited(pattern_type.type): + current_type = pattern_type.rest_type + + # + # Collect the final type + # + types = [] + for pattern_type in pattern_types: + if not is_uninhabited(pattern_type.type): + types.append(pattern_type.type) + + # + # Check the capture types + # + capture_types: dict[Var, list[tuple[Expression, Type]]] = defaultdict(list) + # Collect captures from the first subpattern + for expr, typ in pattern_types[0].captures.items(): + node = get_var(expr) + capture_types[node].append((expr, typ)) + + # Check if other subpatterns capture the same names + for i, pattern_type in enumerate(pattern_types[1:]): + vars = {get_var(expr) for expr, _ in pattern_type.captures.items()} + if capture_types.keys() != vars: + self.msg.fail(message_registry.OR_PATTERN_ALTERNATIVE_NAMES, o.patterns[i]) + for expr, typ in pattern_type.captures.items(): + node = get_var(expr) + capture_types[node].append((expr, typ)) + + captures: dict[Expression, Type] = {} + for capture_list in capture_types.values(): + typ = UninhabitedType() + for _, other in capture_list: + typ = make_simplified_union([typ, other]) + + captures[capture_list[0][0]] = typ + + union_type = make_simplified_union(types) + return PatternType(union_type, current_type, captures) + + def visit_value_pattern(self, o: ValuePattern) -> PatternType: + current_type = self.type_context[-1] + typ = self.chk.expr_checker.accept(o.expr) + typ = coerce_to_literal(typ) + node = TempNode(current_type) + # Value patterns are essentially a syntactic sugar on top of `if x == Value`. + # They should be treated equivalently. + ok_map, rest_map = self.chk.narrow_type_by_identity_equality( + "==", [node, TempNode(typ)], [current_type, typ], [0, 1], {0} + ) + ok_type = ok_map.get(node, current_type) if ok_map is not None else UninhabitedType() + rest_type = rest_map.get(node, current_type) if rest_map is not None else UninhabitedType() + return PatternType(ok_type, rest_type, {}) + + def visit_singleton_pattern(self, o: SingletonPattern) -> PatternType: + current_type = self.type_context[-1] + value: bool | None = o.value + if isinstance(value, bool): + typ = self.chk.expr_checker.infer_literal_expr_type(value, "builtins.bool") + elif value is None: + typ = NoneType() + else: + assert False + + narrowed_type, rest_type = self.chk.conditional_types_with_intersection( + current_type, [get_type_range(typ)], o, default=current_type + ) + return PatternType(narrowed_type, rest_type, {}) + + def visit_sequence_pattern(self, o: SequencePattern) -> PatternType: + # + # Step 1. Check for existence of a starred pattern + # + current_type = get_proper_type(self.type_context[-1]) + if not self.can_match_sequence(current_type): + return self.early_non_match() + + star_positions = [i for i, p in enumerate(o.patterns) if isinstance(p, StarredPattern)] + star_position: int | None = None + if len(star_positions) == 1: + star_position = star_positions[0] + elif len(star_positions) >= 2: + assert False, "Parser should prevent multiple starred patterns" + required_patterns = len(o.patterns) + if star_position is not None: + required_patterns -= 1 + + # + # Step 2. If we have a union, recurse and return the combined result + # + if isinstance(current_type, UnionType): + match_types: list[Type] = [] + rest_types: list[Type] = [] + captures_list: dict[Expression, list[Type]] = {} + + if star_position is not None: + star_pattern = o.patterns[star_position] + assert isinstance(star_pattern, StarredPattern) + star_expr = star_pattern.capture + else: + star_expr = None + + for t in current_type.items: + match_type, rest_type, captures = self.accept(o, t) + match_types.append(match_type) + rest_types.append(rest_type) + if not is_uninhabited(match_type): + for expr, typ in captures.items(): + p_typ = get_proper_type(typ) + if expr not in captures_list: + captures_list[expr] = [] + # Avoid adding in a list[Never] for empty list captures + if ( + expr == star_expr + and isinstance(p_typ, Instance) + and p_typ.type.fullname == "builtins.list" + and is_uninhabited(p_typ.args[0]) + ): + continue + captures_list[expr].append(typ) + + return PatternType( + make_simplified_union(match_types), + make_simplified_union(rest_types), + {expr: make_simplified_union(types) for expr, types in captures_list.items()}, + ) + + # + # Step 3. Get inner types of original type + # + unpack_index = None + if isinstance(current_type, TupleType): + inner_types: list[Type] = current_type.items + unpack_index = find_unpack_in_list(inner_types) + if unpack_index is None: + size_diff = len(inner_types) - required_patterns + if size_diff < 0: + return self.early_non_match() + elif size_diff > 0 and star_position is None: + return self.early_non_match() + else: + normalized_inner_types = [] + for it in inner_types: + # Unfortunately, it is not possible to "split" the TypeVarTuple + # into individual items, so we just use its upper bound for the whole + # analysis instead. + if isinstance(it, UnpackType) and isinstance(it.type, TypeVarTupleType): + it = UnpackType(it.type.upper_bound) + normalized_inner_types.append(it) + inner_types = normalized_inner_types + current_type = current_type.copy_modified(items=normalized_inner_types) + if len(inner_types) - 1 > required_patterns and star_position is None: + return self.early_non_match() + elif isinstance(current_type, AnyType): + inner_type = AnyType(TypeOfAny.from_another_any, current_type) + inner_types = [inner_type] * len(o.patterns) + elif isinstance(current_type, Instance) and self.chk.type_is_iterable(current_type): + inner_type = self.chk.iterable_item_type(current_type, o) + inner_types = [inner_type] * len(o.patterns) + else: + inner_type = self.chk.named_type("builtins.object") + inner_types = [inner_type] * len(o.patterns) + + # + # Step 4. Match inner patterns + # + contracted_new_inner_types: list[Type] = [] + contracted_rest_inner_types: list[Type] = [] + captures = {} # dict[Expression, Type] + + contracted_inner_types = self.contract_starred_pattern_types( + inner_types, star_position, required_patterns + ) + for p, t in zip(o.patterns, contracted_inner_types): + pattern_type = self.accept(p, t) + typ, rest, type_map = pattern_type + contracted_new_inner_types.append(typ) + contracted_rest_inner_types.append(rest) + self.update_type_map(captures, type_map) + + new_inner_types = self.expand_starred_pattern_types( + contracted_new_inner_types, star_position, len(inner_types), unpack_index is not None + ) + rest_inner_types = self.expand_starred_pattern_types( + contracted_rest_inner_types, star_position, len(inner_types), unpack_index is not None + ) + + # + # Step 5. Calculate new type + # + new_type: Type + rest_type = current_type + if isinstance(current_type, TupleType) and unpack_index is None: + if any(is_uninhabited(typ) for typ in new_inner_types): + new_type = UninhabitedType() + else: + new_type = TupleType(new_inner_types, current_type.partial_fallback) + + num_always_match = sum(is_uninhabited(typ) for typ in rest_inner_types) + if num_always_match == len(rest_inner_types): + # All subpatterns always match, so we can apply negative narrowing + rest_type = UninhabitedType() + elif num_always_match == len(rest_inner_types) - 1: + # Exactly one subpattern may conditionally match, the rest always match. + # We can apply negative narrowing to this one position. + rest_type = TupleType( + [ + curr if is_uninhabited(rest) else rest + for curr, rest in zip(inner_types, rest_inner_types) + ], + current_type.partial_fallback, + ) + elif isinstance(current_type, TupleType): + # For variadic tuples it is too tricky to match individual items like for fixed + # tuples, so we instead try to narrow the entire type. + # TODO: use more precise narrowing when possible (e.g. for identical shapes). + new_tuple_type = TupleType(new_inner_types, current_type.partial_fallback) + new_type, _ = self.chk.conditional_types_with_intersection( + new_tuple_type, [get_type_range(current_type)], o, default=new_tuple_type + ) + if ( + star_position is not None + and required_patterns <= len(inner_types) - 1 + and all(is_uninhabited(rest) for rest in rest_inner_types) + ): + rest_type = UninhabitedType() + else: + new_inner_type = UninhabitedType() + for typ in new_inner_types: + new_inner_type = join_types(new_inner_type, typ) + new_type = self.construct_sequence_child(current_type, new_inner_type) + new_type, possible_rest_type = self.chk.conditional_types_with_intersection( + current_type, [get_type_range(new_type)], o, default=current_type + ) + if star_position is not None and len(o.patterns) == 1: + # Match cannot be refuted, so narrow the remaining type + rest_type = possible_rest_type + + return PatternType(new_type, rest_type, captures) + + def contract_starred_pattern_types( + self, types: list[Type], star_pos: int | None, num_patterns: int + ) -> list[Type]: + """ + Contracts a list of types in a sequence pattern depending on the position of a starred + capture pattern. + + For example if the sequence pattern [a, *b, c] is matched against types [bool, int, str, + bytes] the contracted types are [bool, Union[int, str], bytes]. + + If star_pos in None the types are returned unchanged. + """ + unpack_index = find_unpack_in_list(types) + if unpack_index is not None: + # Variadic tuples require "re-shaping" to match the requested pattern. + unpack = types[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + # This should be guaranteed by the normalization in the caller. + assert isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple" + if star_pos is None: + missing = num_patterns - len(types) + 1 + new_types = types[:unpack_index] + new_types += [unpacked.args[0]] * missing + new_types += types[unpack_index + 1 :] + return new_types + prefix, middle, suffix = split_with_prefix_and_suffix( + tuple([UnpackType(unpacked) if isinstance(t, UnpackType) else t for t in types]), + star_pos, + num_patterns - star_pos, + ) + new_middle = [] + for m in middle: + # The existing code expects the star item type, rather than the type of + # the whole tuple "slice". + if isinstance(m, UnpackType): + new_middle.append(unpacked.args[0]) + else: + new_middle.append(m) + return list(prefix) + [make_simplified_union(new_middle)] + list(suffix) + else: + if star_pos is None: + return types + new_types = types[:star_pos] + star_length = len(types) - num_patterns + new_types.append(make_simplified_union(types[star_pos : star_pos + star_length])) + new_types += types[star_pos + star_length :] + return new_types + + def expand_starred_pattern_types( + self, types: list[Type], star_pos: int | None, num_types: int, original_unpack: bool + ) -> list[Type]: + """Undoes the contraction done by contract_starred_pattern_types. + + For example if the sequence pattern is [a, *b, c] and types [bool, int, str] are extended + to length 4 the result is [bool, int, int, str]. + """ + if star_pos is None: + return types + if original_unpack: + # In the case where original tuple type has an unpack item, it is not practical + # to coerce pattern type back to the original shape (and may not even be possible), + # so we only restore the type of the star item. + res = [] + for i, t in enumerate(types): + if i != star_pos or is_uninhabited(t): + res.append(t) + else: + res.append(UnpackType(self.chk.named_generic_type("builtins.tuple", [t]))) + return res + new_types = types[:star_pos] + star_length = num_types - len(types) + 1 + new_types += [types[star_pos]] * star_length + new_types += types[star_pos + 1 :] + + return new_types + + def visit_starred_pattern(self, o: StarredPattern) -> PatternType: + captures: dict[Expression, Type] = {} + if o.capture is not None: + list_type = self.chk.named_generic_type("builtins.list", [self.type_context[-1]]) + captures[o.capture] = list_type + return PatternType(self.type_context[-1], UninhabitedType(), captures) + + def visit_mapping_pattern(self, o: MappingPattern) -> PatternType: + current_type = get_proper_type(self.type_context[-1]) + can_match = True + captures: dict[Expression, Type] = {} + for key, value in zip(o.keys, o.values): + inner_type = self.get_mapping_item_type(o, current_type, key) + if inner_type is None: + can_match = False + inner_type = self.chk.named_type("builtins.object") + pattern_type = self.accept(value, inner_type) + if is_uninhabited(pattern_type.type): + can_match = False + else: + self.update_type_map(captures, pattern_type.captures) + + if o.rest is not None: + mapping = self.chk.named_type("typing.Mapping") + if is_subtype(current_type, mapping) and isinstance(current_type, Instance): + mapping_inst = map_instance_to_supertype(current_type, mapping.type) + dict_typeinfo = self.chk.lookup_typeinfo("builtins.dict") + rest_type = Instance(dict_typeinfo, mapping_inst.args) + else: + object_type = self.chk.named_type("builtins.object") + rest_type = self.chk.named_generic_type( + "builtins.dict", [object_type, object_type] + ) + + captures[o.rest] = rest_type + + else_type = current_type + if can_match: + # We can't narrow the type here, as Mapping key is invariant. + new_type = self.type_context[-1] + if not o.keys: + # Match cannot be refuted, so narrow the remaining type + mapping = self.chk.named_type("typing.Mapping") + if_type, else_type = self.chk.conditional_types_with_intersection( + current_type, + [TypeRange(mapping, is_upper_bound=False)], + o, + default=current_type, + ) + if not isinstance(current_type, AnyType): + new_type = if_type + else: + new_type = UninhabitedType() + return PatternType(new_type, else_type, captures) + + def get_mapping_item_type( + self, pattern: MappingPattern, mapping_type: Type, key: Expression + ) -> Type | None: + mapping_type = get_proper_type(mapping_type) + if isinstance(mapping_type, TypedDictType): + with self.msg.filter_errors() as local_errors: + result: Type | None = self.chk.expr_checker.visit_typeddict_index_expr( + mapping_type, key + )[0] + has_local_errors = local_errors.has_new_errors() + # If we can't determine the type statically fall back to treating it as a normal + # mapping + if has_local_errors: + with self.msg.filter_errors() as local_errors: + result = self.get_simple_mapping_item_type(pattern, mapping_type, key) + + if local_errors.has_new_errors(): + result = None + else: + with self.msg.filter_errors(): + result = self.get_simple_mapping_item_type(pattern, mapping_type, key) + return result + + def get_simple_mapping_item_type( + self, pattern: MappingPattern, mapping_type: Type, key: Expression + ) -> Type: + result, _ = self.chk.expr_checker.check_method_call_by_name( + "__getitem__", mapping_type, [key], [ARG_POS], pattern + ) + return result + + def visit_class_pattern(self, o: ClassPattern) -> PatternType: + current_type = get_proper_type(self.type_context[-1]) + + # + # Check class type + # + type_info = o.class_ref.node + if isinstance(type_info, TypeAlias) and not type_info.no_args: + self.msg.fail(message_registry.CLASS_PATTERN_GENERIC_TYPE_ALIAS, o) + return self.early_non_match() + + typ = self.chk.expr_checker.accept(o.class_ref) + type_ranges = self.get_class_pattern_type_ranges(typ, o) + if type_ranges is None: + return self.early_non_match() + typ = UnionType.make_union([t.item for t in type_ranges]) + + new_type, rest_type = self.chk.conditional_types_with_intersection( + current_type, type_ranges, o, default=current_type + ) + if is_uninhabited(new_type): + return self.early_non_match() + # TODO: Do I need this? + narrowed_type = narrow_declared_type(current_type, new_type) + + # + # Convert positional to keyword patterns + # + keyword_pairs: list[tuple[str | None, Pattern]] = [] + match_arg_set: set[str] = set() + + captures: dict[Expression, Type] = {} + + if len(o.positionals) != 0: + if self.should_self_match(typ): + if len(o.positionals) > 1: + self.msg.fail(message_registry.CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS, o) + pattern_type = self.accept(o.positionals[0], narrowed_type) + if not is_uninhabited(pattern_type.type): + return PatternType( + pattern_type.type, + join_types(rest_type, pattern_type.rest_type), + pattern_type.captures, + ) + captures = pattern_type.captures + else: + with self.msg.filter_errors() as local_errors: + match_args_type = analyze_member_access( + "__match_args__", + typ, + o, + is_lvalue=False, + is_super=False, + is_operator=False, + original_type=typ, + chk=self.chk, + ) + has_local_errors = local_errors.has_new_errors() + if has_local_errors: + self.msg.fail( + message_registry.MISSING_MATCH_ARGS.format( + typ.str_with_options(self.options) + ), + o, + ) + return self.early_non_match() + + proper_match_args_type = get_proper_type(match_args_type) + if isinstance(proper_match_args_type, TupleType): + match_arg_names = get_match_arg_names(proper_match_args_type) + + if len(o.positionals) > len(match_arg_names): + self.msg.fail(message_registry.CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS, o) + return self.early_non_match() + else: + match_arg_names = [None] * len(o.positionals) + + for arg_name, pos in zip(match_arg_names, o.positionals): + keyword_pairs.append((arg_name, pos)) + if arg_name is not None: + match_arg_set.add(arg_name) + + # + # Check for duplicate patterns + # + keyword_arg_set = set() + has_duplicates = False + for key, value in zip(o.keyword_keys, o.keyword_values): + keyword_pairs.append((key, value)) + if key in match_arg_set: + self.msg.fail( + message_registry.CLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL.format(key), value + ) + has_duplicates = True + elif key in keyword_arg_set: + self.msg.fail( + message_registry.CLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN.format(key), value + ) + has_duplicates = True + keyword_arg_set.add(key) + + if has_duplicates: + return self.early_non_match() + + # + # Check keyword patterns + # + can_match = True + for keyword, pattern in keyword_pairs: + key_type: Type | None = None + with self.msg.filter_errors() as local_errors: + if keyword is not None: + key_type = analyze_member_access( + keyword, + narrowed_type, + pattern, + is_lvalue=False, + is_super=False, + is_operator=False, + original_type=new_type, + chk=self.chk, + ) + else: + key_type = AnyType(TypeOfAny.from_error) + has_local_errors = local_errors.has_new_errors() + if has_local_errors or key_type is None: + key_type = AnyType(TypeOfAny.from_error) + if not (type_info and type_info.fullname == "builtins.object"): + self.msg.fail( + message_registry.CLASS_PATTERN_UNKNOWN_KEYWORD.format( + typ.str_with_options(self.options), keyword + ), + pattern, + ) + elif keyword is not None: + new_type = self.chk.add_any_attribute_to_type(new_type, keyword) + + inner_type, inner_rest_type, inner_captures = self.accept(pattern, key_type) + if is_uninhabited(inner_type): + can_match = False + else: + self.update_type_map(captures, inner_captures) + if not is_uninhabited(inner_rest_type): + rest_type = current_type + + if not can_match: + new_type = UninhabitedType() + return PatternType(new_type, rest_type, captures) + + def get_class_pattern_type_ranges(self, typ: Type, o: ClassPattern) -> list[TypeRange] | None: + p_typ = get_proper_type(typ) + + if isinstance(p_typ, UnionType): + type_ranges = [] + for item in p_typ.items: + type_range = self.get_class_pattern_type_ranges(item, o) + if type_range is not None: + type_ranges.extend(type_range) + if not type_ranges: + return None + return type_ranges + + if isinstance(p_typ, FunctionLike) and p_typ.is_type_obj(): + typ = fill_typevars_with_any(p_typ.type_object()) + return [TypeRange(typ, is_upper_bound=False)] + if ( + isinstance(o.class_ref.node, Var) + and o.class_ref.node.type is not None + and o.class_ref.node.fullname == "typing.Callable" + ): + # Create a `Callable[..., Any]` + fallback = self.chk.named_type("builtins.function") + any_type = AnyType(TypeOfAny.unannotated) + typ = callable_with_ellipsis(any_type, ret_type=any_type, fallback=fallback) + return [TypeRange(typ, is_upper_bound=False)] + if isinstance(p_typ, TypeType): + typ = p_typ.item + return [TypeRange(p_typ.item, is_upper_bound=True)] + if isinstance(p_typ, AnyType): + return [TypeRange(p_typ, is_upper_bound=False)] + + self.msg.fail( + message_registry.CLASS_PATTERN_TYPE_REQUIRED.format( + typ.str_with_options(self.options) + ), + o, + ) + return None + + def should_self_match(self, typ: Type) -> bool: + typ = get_proper_type(typ) + if isinstance(typ, TupleType): + typ = typ.partial_fallback + if isinstance(typ, AnyType): + return False + if isinstance(typ, Instance) and typ.type.get("__match_args__") is not None: + # Named tuples and other subtypes of builtins that define __match_args__ + # should not self match. + return False + for other in self.self_match_types: + if is_subtype(typ, other): + return True + return False + + def can_match_sequence(self, typ: ProperType) -> bool: + if isinstance(typ, AnyType): + return True + if isinstance(typ, UnionType): + return any(self.can_match_sequence(get_proper_type(item)) for item in typ.items) + for other in self.non_sequence_match_types: + # We have to ignore promotions, as memoryview should match, but bytes, + # which it can be promoted to, shouldn't + if is_subtype(typ, other, ignore_promotions=True): + return False + sequence = self.chk.named_type("typing.Sequence") + # If the static type is more general than sequence the actual type could still match + return is_subtype(typ, sequence) or is_subtype(sequence, typ) + + def generate_types_from_names(self, type_names: list[str]) -> list[Type]: + types: list[Type] = [] + for name in type_names: + try: + types.append(self.chk.named_type(name)) + except KeyError as e: + # Some built in types are not defined in all test cases + if not name.startswith("builtins."): + raise e + return types + + def update_type_map( + self, original_type_map: dict[Expression, Type], extra_type_map: dict[Expression, Type] + ) -> None: + # Calculating this would not be needed if TypeMap directly used literal hashes instead of + # expressions, as suggested in the TODO above it's definition + already_captured = {literal_hash(expr) for expr in original_type_map} + for expr, typ in extra_type_map.items(): + if literal_hash(expr) in already_captured: + node = get_var(expr) + self.msg.fail( + message_registry.MULTIPLE_ASSIGNMENTS_IN_PATTERN.format(node.name), expr + ) + else: + original_type_map[expr] = typ + + def construct_sequence_child(self, outer_type: Type, inner_type: Type) -> Type: + """ + If outer_type is a child class of typing.Sequence returns a new instance of + outer_type, that is a Sequence of inner_type. If outer_type is not a child class of + typing.Sequence just returns a Sequence of inner_type + + For example: + construct_sequence_child(List[int], str) = List[str] + + TODO: this doesn't make sense. For example if one has class S(Sequence[int], Generic[T]) + or class T(Sequence[Tuple[T, T]]), there is no way any of those can map to Sequence[str]. + """ + proper_type = get_proper_type(outer_type) + if isinstance(proper_type, TypeVarType): + new_bound = self.construct_sequence_child(proper_type.upper_bound, inner_type) + return proper_type.copy_modified(upper_bound=new_bound) + if isinstance(proper_type, AnyType): + return outer_type + if isinstance(proper_type, UnionType): + types = [ + self.construct_sequence_child(item, inner_type) + for item in proper_type.items + if self.can_match_sequence(get_proper_type(item)) + ] + return make_simplified_union(types) + sequence = self.chk.named_generic_type("typing.Sequence", [inner_type]) + if is_subtype(outer_type, self.chk.named_type("typing.Sequence")): + if isinstance(proper_type, TupleType): + proper_type = tuple_fallback(proper_type) + assert isinstance(proper_type, Instance) + empty_type = fill_typevars(proper_type.type) + partial_type = expand_type_by_instance(empty_type, sequence) + return expand_type_by_instance(partial_type, proper_type) + else: + return sequence + + def early_non_match(self) -> PatternType: + return PatternType(UninhabitedType(), self.type_context[-1], {}) + + +def get_match_arg_names(typ: TupleType) -> list[str | None]: + args: list[str | None] = [] + for item in typ.items: + values = try_getting_str_literals_from_type(item) + if values is None or len(values) != 1: + args.append(None) + else: + args.append(values[0]) + return args + + +def get_var(expr: Expression) -> Var: + """ + Warning: this in only true for expressions captured by a match statement. + Don't call it from anywhere else + """ + assert isinstance(expr, NameExpr), expr + node = expr.node + assert isinstance(node, Var), node + return node + + +def get_type_range(typ: Type) -> TypeRange: + typ = get_proper_type(typ) + if ( + isinstance(typ, Instance) + and typ.last_known_value + and isinstance(typ.last_known_value.value, bool) + ): + typ = typ.last_known_value + return TypeRange(typ, is_upper_bound=False) + + +def is_uninhabited(typ: Type) -> bool: + return isinstance(get_proper_type(typ), UninhabitedType) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f03fa6441c533d873b594028d1a2c6c11e9d77bf Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.py new file mode 100644 index 0000000000000000000000000000000000000000..55605274aa1f13fc8890353fd237bd3d3f324b2b --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.py @@ -0,0 +1,1099 @@ +""" +Format expression type checker. + +This file is conceptually part of ExpressionChecker and TypeChecker. Main functionality +is located in StringFormatterChecker.check_str_format_call() for '{}'.format(), and in +StringFormatterChecker.check_str_interpolation() for printf-style % interpolation. + +Note that although at runtime format strings are parsed using custom parsers, +here we use a regexp-based approach. This way we 99% match runtime behaviour while keeping +implementation simple. +""" + +from __future__ import annotations + +import re +from collections.abc import Callable +from re import Match, Pattern +from typing import Final, TypeAlias as _TypeAlias, cast + +import mypy.errorcodes as codes +from mypy import message_registry +from mypy.checker_shared import TypeCheckerSharedApi +from mypy.errors import Errors +from mypy.maptype import map_instance_to_supertype +from mypy.messages import MessageBuilder +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + ARG_STAR, + ARG_STAR2, + BytesExpr, + CallExpr, + Context, + DictExpr, + Expression, + ExpressionStmt, + IndexExpr, + IntExpr, + MemberExpr, + MypyFile, + NameExpr, + Node, + StarExpr, + StrExpr, + TempNode, + TupleExpr, +) +from mypy.parse import parse +from mypy.subtypes import is_subtype +from mypy.typeops import custom_special_method +from mypy.types import ( + AnyType, + Instance, + LiteralType, + TupleType, + Type, + TypeOfAny, + TypeVarTupleType, + TypeVarType, + UnionType, + UnpackType, + find_unpack_in_list, + get_proper_type, + get_proper_types, +) + +FormatStringExpr: _TypeAlias = StrExpr | BytesExpr +Checkers: _TypeAlias = tuple[Callable[[Expression], None], Callable[[Type], bool]] +MatchMap: _TypeAlias = dict[tuple[int, int], Match[str]] # span -> match + + +def compile_format_re() -> Pattern[str]: + """Construct regexp to match format conversion specifiers in % interpolation. + + See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting + The regexp is intentionally a bit wider to report better errors. + """ + key_re = r"(\((?P[^)]*)\))?" # (optional) parenthesised sequence of characters. + flags_re = r"(?P[#0\-+ ]*)" # (optional) sequence of flags. + width_re = r"(?P[1-9][0-9]*|\*)?" # (optional) minimum field width (* or numbers). + precision_re = r"(?:\.(?P\*|[0-9]+)?)?" # (optional) . followed by * of numbers. + length_mod_re = r"[hlL]?" # (optional) length modifier (unused). + type_re = r"(?P.)?" # conversion type. + format_re = "%" + key_re + flags_re + width_re + precision_re + length_mod_re + type_re + return re.compile(format_re) + + +def compile_new_format_re(custom_spec: bool) -> Pattern[str]: + """Construct regexps to match format conversion specifiers in str.format() calls. + + See After https://docs.python.org/3/library/string.html#formatspec for + specifications. The regexps are intentionally wider, to report better errors, + instead of just not matching. + """ + + # Field (optional) is an integer/identifier possibly followed by several .attr and [index]. + field = r"(?P(?P[^.[!:]*)([^:!]+)?)" + + # Conversion (optional) is ! followed by one of letters for forced repr(), str(), or ascii(). + conversion = r"(?P![^:])?" + + # Format specification (optional) follows its own mini-language: + if not custom_spec: + # Fill and align is valid for all builtin types. + fill_align = r"(?P.?[<>=^])?" + # Number formatting options are only valid for int, float, complex, and Decimal, + # except if only width is given (it is valid for all types). + # This contains sign, flags (sign, # and/or 0), width, grouping (_ or ,) and precision. + num_spec = r"(?P[+\- ]?#?0?)(?P\d+)?[_,]?(?P\.\d+)?" + # The last element is type. + conv_type = r"(?P.)?" # only some are supported, but we want to give a better error + format_spec = r"(?P:" + fill_align + num_spec + conv_type + r")?" + else: + # Custom types can define their own form_spec using __format__(). + format_spec = r"(?P:.*)?" + + return re.compile(field + conversion + format_spec) + + +FORMAT_RE: Final = compile_format_re() +FORMAT_RE_NEW: Final = compile_new_format_re(False) +FORMAT_RE_NEW_CUSTOM: Final = compile_new_format_re(True) +DUMMY_FIELD_NAME: Final = "__dummy_name__" + +# Types that require either int or float. +NUMERIC_TYPES_OLD: Final = {"d", "i", "o", "u", "x", "X", "e", "E", "f", "F", "g", "G"} +NUMERIC_TYPES_NEW: Final = {"b", "d", "o", "e", "E", "f", "F", "g", "G", "n", "x", "X", "%"} + +# These types accept _only_ int. +REQUIRE_INT_OLD: Final = {"o", "x", "X"} +REQUIRE_INT_NEW: Final = {"b", "d", "o", "x", "X"} + +# These types fall back to SupportsFloat with % (other fall back to SupportsInt) +FLOAT_TYPES: Final = {"e", "E", "f", "F", "g", "G"} + + +class ConversionSpecifier: + def __init__( + self, match: Match[str], start_pos: int = -1, non_standard_format_spec: bool = False + ) -> None: + self.whole_seq = match.group() + self.start_pos = start_pos + + m_dict = match.groupdict() + self.key = m_dict.get("key") + + # Replace unmatched optional groups with empty matches (for convenience). + self.conv_type = m_dict.get("type") or "" + self.flags = m_dict.get("flags") or "" + self.width = m_dict.get("width") or "" + self.precision = m_dict.get("precision") or "" + + # Used only for str.format() calls (it may be custom for types with __format__()). + self.format_spec = m_dict.get("format_spec") + self.non_standard_format_spec = non_standard_format_spec + # Used only for str.format() calls. + self.conversion = m_dict.get("conversion") + # Full formatted expression (i.e. key plus following attributes and/or indexes). + # Used only for str.format() calls. + self.field = m_dict.get("field") + + def has_key(self) -> bool: + return self.key is not None + + def has_star(self) -> bool: + return self.width == "*" or self.precision == "*" + + +def parse_conversion_specifiers(format_str: str) -> list[ConversionSpecifier]: + """Parse c-printf-style format string into list of conversion specifiers.""" + specifiers: list[ConversionSpecifier] = [] + for m in re.finditer(FORMAT_RE, format_str): + specifiers.append(ConversionSpecifier(m, start_pos=m.start())) + return specifiers + + +def parse_format_value( + format_value: str, ctx: Context, msg: MessageBuilder, nested: bool = False +) -> list[ConversionSpecifier] | None: + """Parse format string into list of conversion specifiers. + + The specifiers may be nested (two levels maximum), in this case they are ordered as + '{0:{1}}, {2:{3}{4}}'. Return None in case of an error. + """ + top_targets = find_non_escaped_targets(format_value, ctx, msg) + if top_targets is None: + return None + + result: list[ConversionSpecifier] = [] + for target, start_pos in top_targets: + match = FORMAT_RE_NEW.fullmatch(target) + if match: + conv_spec = ConversionSpecifier(match, start_pos=start_pos) + else: + custom_match = FORMAT_RE_NEW_CUSTOM.fullmatch(target) + if custom_match: + conv_spec = ConversionSpecifier( + custom_match, start_pos=start_pos, non_standard_format_spec=True + ) + else: + msg.fail( + "Invalid conversion specifier in format string", + ctx, + code=codes.STRING_FORMATTING, + ) + return None + + if conv_spec.key and ("{" in conv_spec.key or "}" in conv_spec.key): + msg.fail("Conversion value must not contain { or }", ctx, code=codes.STRING_FORMATTING) + return None + result.append(conv_spec) + + # Parse nested conversions that are allowed in format specifier. + if ( + conv_spec.format_spec + and conv_spec.non_standard_format_spec + and ("{" in conv_spec.format_spec or "}" in conv_spec.format_spec) + ): + if nested: + msg.fail( + "Formatting nesting must be at most two levels deep", + ctx, + code=codes.STRING_FORMATTING, + ) + return None + sub_conv_specs = parse_format_value(conv_spec.format_spec, ctx, msg, nested=True) + if sub_conv_specs is None: + return None + result.extend(sub_conv_specs) + return result + + +def find_non_escaped_targets( + format_value: str, ctx: Context, msg: MessageBuilder +) -> list[tuple[str, int]] | None: + """Return list of raw (un-parsed) format specifiers in format string. + + Format specifiers don't include enclosing braces. We don't use regexp for + this because they don't work well with nested/repeated patterns + (both greedy and non-greedy), and these are heavily used internally for + representation of f-strings. + + Return None in case of an error. + """ + result = [] + next_spec = "" + pos = 0 + nesting = 0 + while pos < len(format_value): + c = format_value[pos] + if not nesting: + # Skip any paired '{{' and '}}', enter nesting on '{', report error on '}'. + if c == "{": + if pos < len(format_value) - 1 and format_value[pos + 1] == "{": + pos += 1 + else: + nesting = 1 + if c == "}": + if pos < len(format_value) - 1 and format_value[pos + 1] == "}": + pos += 1 + else: + msg.fail( + "Invalid conversion specifier in format string: unexpected }", + ctx, + code=codes.STRING_FORMATTING, + ) + return None + else: + # Adjust nesting level, then either continue adding chars or move on. + if c == "{": + nesting += 1 + if c == "}": + nesting -= 1 + if nesting: + next_spec += c + else: + result.append((next_spec, pos - len(next_spec))) + next_spec = "" + pos += 1 + if nesting: + msg.fail( + "Invalid conversion specifier in format string: unmatched {", + ctx, + code=codes.STRING_FORMATTING, + ) + return None + return result + + +class StringFormatterChecker: + """String interpolation/formatter type checker. + + This class works closely together with checker.ExpressionChecker. + """ + + # Some services are provided by a TypeChecker instance. + chk: TypeCheckerSharedApi + # This is shared with TypeChecker, but stored also here for convenience. + msg: MessageBuilder + + def __init__(self, chk: TypeCheckerSharedApi, msg: MessageBuilder) -> None: + """Construct an expression type checker.""" + self.chk = chk + self.msg = msg + + def check_str_format_call(self, call: CallExpr, format_value: str) -> None: + """Perform more precise checks for str.format() calls when possible. + + Currently the checks are performed for: + * Actual string literals + * Literal types with string values + * Final names with string values + + The checks that we currently perform: + * Check generic validity (e.g. unmatched { or }, and {} in invalid positions) + * Check consistency of specifiers' auto-numbering + * Verify that replacements can be found for all conversion specifiers, + and all arguments were used + * Non-standard format specs are only allowed for types with custom __format__ + * Type check replacements with accessors applied (if any). + * Verify that specifier type is known and matches replacement type + * Perform special checks for some specifier types: + - 'c' requires a single character string + - 's' must not accept bytes + - non-empty flags are only allowed for numeric types + """ + conv_specs = parse_format_value(format_value, call, self.msg) + if conv_specs is None: + return + if not self.auto_generate_keys(conv_specs, call): + return + self.check_specs_in_format_call(call, conv_specs, format_value) + + def check_specs_in_format_call( + self, call: CallExpr, specs: list[ConversionSpecifier], format_value: str + ) -> None: + """Perform pairwise checks for conversion specifiers vs their replacements. + + The core logic for format checking is implemented in this method. + """ + assert all(s.key for s in specs), "Keys must be auto-generated first!" + replacements = self.find_replacements_in_call(call, [cast(str, s.key) for s in specs]) + assert len(replacements) == len(specs) + for spec, repl in zip(specs, replacements): + repl = self.apply_field_accessors(spec, repl, ctx=call) + actual_type = repl.type if isinstance(repl, TempNode) else self.chk.lookup_type(repl) + assert actual_type is not None + + # Special case custom formatting. + if ( + spec.format_spec + and spec.non_standard_format_spec + and + # Exclude "dynamic" specifiers (i.e. containing nested formatting). + not ("{" in spec.format_spec or "}" in spec.format_spec) + ): + if ( + not custom_special_method(actual_type, "__format__", check_all=True) + or spec.conversion + ): + # TODO: add support for some custom specs like datetime? + self.msg.fail( + f'Unrecognized format specification "{spec.format_spec[1:]}"', + call, + code=codes.STRING_FORMATTING, + ) + continue + # Adjust expected and actual types. + if not spec.conv_type: + expected_type: Type | None = AnyType(TypeOfAny.special_form) + else: + assert isinstance(call.callee, MemberExpr) + if isinstance(call.callee.expr, StrExpr): + format_str = call.callee.expr + else: + format_str = StrExpr(format_value) + expected_type = self.conversion_type( + spec.conv_type, call, format_str, format_call=True + ) + if spec.conversion is not None: + # If the explicit conversion is given, then explicit conversion is called _first_. + if spec.conversion[1] not in "rsa": + self.msg.fail( + ( + f'Invalid conversion type "{spec.conversion[1]}", ' + f'must be one of "r", "s" or "a"' + ), + call, + code=codes.STRING_FORMATTING, + ) + actual_type = self.named_type("builtins.str") + + # Perform the checks for given types. + if expected_type is None: + continue + + a_type = get_proper_type(actual_type) + actual_items = ( + get_proper_types(a_type.items) if isinstance(a_type, UnionType) else [a_type] + ) + for a_type in actual_items: + if custom_special_method(a_type, "__format__"): + continue + self.check_placeholder_type(a_type, expected_type, call) + self.perform_special_format_checks(spec, call, repl, a_type, expected_type) + + def perform_special_format_checks( + self, + spec: ConversionSpecifier, + call: CallExpr, + repl: Expression, + actual_type: Type, + expected_type: Type, + ) -> None: + # TODO: try refactoring to combine this logic with % formatting. + if spec.conv_type == "c": + if isinstance(repl, (StrExpr, BytesExpr)) and len(repl.value) != 1: + self.msg.requires_int_or_char(call, format_call=True) + c_typ = get_proper_type(self.chk.lookup_type(repl)) + if isinstance(c_typ, Instance) and c_typ.last_known_value: + c_typ = c_typ.last_known_value + if isinstance(c_typ, LiteralType) and isinstance(c_typ.value, str): + if len(c_typ.value) != 1: + self.msg.requires_int_or_char(call, format_call=True) + if (not spec.conv_type or spec.conv_type == "s") and not spec.conversion: + if has_type_component(actual_type, "builtins.bytes") and not custom_special_method( + actual_type, "__str__" + ): + self.msg.fail( + 'If x = b\'abc\' then f"{x}" or "{}".format(x) produces "b\'abc\'", ' + 'not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). ' + "Otherwise, decode the bytes", + call, + code=codes.STR_BYTES_PY3, + ) + if spec.flags: + numeric_types = UnionType( + [self.named_type("builtins.int"), self.named_type("builtins.float")] + ) + if ( + spec.conv_type + and spec.conv_type not in NUMERIC_TYPES_NEW + or not spec.conv_type + and not is_subtype(actual_type, numeric_types) + and not custom_special_method(actual_type, "__format__") + ): + self.msg.fail( + "Numeric flags are only allowed for numeric types", + call, + code=codes.STRING_FORMATTING, + ) + + def find_replacements_in_call(self, call: CallExpr, keys: list[str]) -> list[Expression]: + """Find replacement expression for every specifier in str.format() call. + + In case of an error use TempNode(AnyType). + """ + result: list[Expression] = [] + used: set[Expression] = set() + for key in keys: + if key.isdecimal(): + expr = self.get_expr_by_position(int(key), call) + if not expr: + self.msg.fail( + f"Cannot find replacement for positional format specifier {key}", + call, + code=codes.STRING_FORMATTING, + ) + expr = TempNode(AnyType(TypeOfAny.from_error)) + else: + expr = self.get_expr_by_name(key, call) + if not expr: + self.msg.fail( + f'Cannot find replacement for named format specifier "{key}"', + call, + code=codes.STRING_FORMATTING, + ) + expr = TempNode(AnyType(TypeOfAny.from_error)) + result.append(expr) + if not isinstance(expr, TempNode): + used.add(expr) + # Strictly speaking not using all replacements is not a type error, but most likely + # a typo in user code, so we show an error like we do for % formatting. + total_explicit = len([kind for kind in call.arg_kinds if kind in (ARG_POS, ARG_NAMED)]) + if len(used) < total_explicit: + self.msg.too_many_string_formatting_arguments(call) + return result + + def get_expr_by_position(self, pos: int, call: CallExpr) -> Expression | None: + """Get positional replacement expression from '{0}, {1}'.format(x, y, ...) call. + + If the type is from *args, return TempNode(). Return None in case of + an error. + """ + pos_args = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_POS] + if pos < len(pos_args): + return pos_args[pos] + star_args = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_STAR] + if not star_args: + return None + + # Fall back to *args when present in call. + star_arg = star_args[0] + varargs_type = get_proper_type(self.chk.lookup_type(star_arg)) + if not isinstance(varargs_type, Instance) or not varargs_type.type.has_base( + "typing.Sequence" + ): + # Error should be already reported. + return TempNode(AnyType(TypeOfAny.special_form)) + iter_info = self.chk.named_generic_type( + "typing.Sequence", [AnyType(TypeOfAny.special_form)] + ).type + return TempNode(map_instance_to_supertype(varargs_type, iter_info).args[0]) + + def get_expr_by_name(self, key: str, call: CallExpr) -> Expression | None: + """Get named replacement expression from '{name}'.format(name=...) call. + + If the type is from **kwargs, return TempNode(). Return None in case of + an error. + """ + named_args = [ + arg + for arg, kind, name in zip(call.args, call.arg_kinds, call.arg_names) + if kind == ARG_NAMED and name == key + ] + if named_args: + return named_args[0] + star_args_2 = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_STAR2] + if not star_args_2: + return None + star_arg_2 = star_args_2[0] + kwargs_type = get_proper_type(self.chk.lookup_type(star_arg_2)) + if not isinstance(kwargs_type, Instance) or not kwargs_type.type.has_base( + "typing.Mapping" + ): + # Error should be already reported. + return TempNode(AnyType(TypeOfAny.special_form)) + any_type = AnyType(TypeOfAny.special_form) + mapping_info = self.chk.named_generic_type("typing.Mapping", [any_type, any_type]).type + return TempNode(map_instance_to_supertype(kwargs_type, mapping_info).args[1]) + + def auto_generate_keys(self, all_specs: list[ConversionSpecifier], ctx: Context) -> bool: + """Translate '{} {name} {}' to '{0} {name} {1}'. + + Return True if generation was successful, otherwise report an error and return false. + """ + some_defined = any(s.key and s.key.isdecimal() for s in all_specs) + all_defined = all(bool(s.key) for s in all_specs) + if some_defined and not all_defined: + self.msg.fail( + "Cannot combine automatic field numbering and manual field specification", + ctx, + code=codes.STRING_FORMATTING, + ) + return False + if all_defined: + return True + next_index = 0 + for spec in all_specs: + if not spec.key: + str_index = str(next_index) + spec.key = str_index + # Update also the full field (i.e. turn {.x} into {0.x}). + if not spec.field: + spec.field = str_index + else: + spec.field = str_index + spec.field + next_index += 1 + return True + + def apply_field_accessors( + self, spec: ConversionSpecifier, repl: Expression, ctx: Context + ) -> Expression: + """Transform and validate expr in '{.attr[item]}'.format(expr) into expr.attr['item']. + + If validation fails, return TempNode(AnyType). + """ + assert spec.key, "Keys must be auto-generated first!" + if spec.field == spec.key: + return repl + assert spec.field + + temp_errors = Errors(self.chk.options) + dummy = DUMMY_FIELD_NAME + spec.field[len(spec.key) :] + temp_ast: Node = parse( + dummy, fnam="", module=None, options=self.chk.options, errors=temp_errors + ) + if temp_errors.is_errors(): + self.msg.fail( + f'Syntax error in format specifier "{spec.field}"', + ctx, + code=codes.STRING_FORMATTING, + ) + return TempNode(AnyType(TypeOfAny.from_error)) + + # These asserts are guaranteed by the original regexp. + assert isinstance(temp_ast, MypyFile) + temp_ast = temp_ast.defs[0] + assert isinstance(temp_ast, ExpressionStmt) + temp_ast = temp_ast.expr + if not self.validate_and_transform_accessors(temp_ast, repl, spec, ctx=ctx): + return TempNode(AnyType(TypeOfAny.from_error)) + + # Check if there are any other errors (like missing members). + # TODO: fix column to point to actual start of the format specifier _within_ string. + temp_ast.line = ctx.line + temp_ast.column = ctx.column + self.chk.expr_checker.accept(temp_ast) + return temp_ast + + def validate_and_transform_accessors( + self, + temp_ast: Expression, + original_repl: Expression, + spec: ConversionSpecifier, + ctx: Context, + ) -> bool: + """Validate and transform (in-place) format field accessors. + + On error, report it and return False. The transformations include replacing the dummy + variable with actual replacement expression and translating any name expressions in an + index into strings, so that this will work: + + class User(TypedDict): + name: str + id: int + u: User + '{[id]:d} -> {[name]}'.format(u) + """ + if not isinstance(temp_ast, (MemberExpr, IndexExpr)): + self.msg.fail( + "Only index and member expressions are allowed in" + ' format field accessors; got "{}"'.format(spec.field), + ctx, + code=codes.STRING_FORMATTING, + ) + return False + if isinstance(temp_ast, MemberExpr): + node = temp_ast.expr + else: + node = temp_ast.base + if not isinstance(temp_ast.index, (NameExpr, IntExpr)): + assert spec.key, "Call this method only after auto-generating keys!" + assert spec.field + self.msg.fail( + 'Invalid index expression in format field accessor "{}"'.format( + spec.field[len(spec.key) :] + ), + ctx, + code=codes.STRING_FORMATTING, + ) + return False + if isinstance(temp_ast.index, NameExpr): + temp_ast.index = StrExpr(temp_ast.index.name) + if isinstance(node, NameExpr) and node.name == DUMMY_FIELD_NAME: + # Replace it with the actual replacement expression. + assert isinstance(temp_ast, (IndexExpr, MemberExpr)) # XXX: this is redundant + if isinstance(temp_ast, IndexExpr): + temp_ast.base = original_repl + else: + temp_ast.expr = original_repl + return True + node.line = ctx.line + node.column = ctx.column + return self.validate_and_transform_accessors( + node, original_repl=original_repl, spec=spec, ctx=ctx + ) + + # TODO: In Python 3, the bytes formatting has a more restricted set of options + # compared to string formatting. + def check_str_interpolation(self, expr: FormatStringExpr, replacements: Expression) -> Type: + """Check the types of the 'replacements' in a string interpolation + expression: str % replacements. + """ + self.chk.expr_checker.accept(expr) + specifiers = parse_conversion_specifiers(expr.value) + has_mapping_keys = self.analyze_conversion_specifiers(specifiers, expr) + if has_mapping_keys is None: + pass # Error was reported + elif has_mapping_keys: + self.check_mapping_str_interpolation(specifiers, replacements, expr) + else: + self.check_simple_str_interpolation(specifiers, replacements, expr) + + if isinstance(expr, BytesExpr): + return self.named_type("builtins.bytes") + elif isinstance(expr, StrExpr): + return self.named_type("builtins.str") + else: + assert False + + def analyze_conversion_specifiers( + self, specifiers: list[ConversionSpecifier], context: Context + ) -> bool | None: + has_star = any(specifier.has_star() for specifier in specifiers) + has_key = any(specifier.has_key() for specifier in specifiers) + all_have_keys = all( + specifier.has_key() or specifier.conv_type == "%" for specifier in specifiers + ) + + if has_key and has_star: + self.msg.string_interpolation_with_star_and_key(context) + return None + if has_key and not all_have_keys: + self.msg.string_interpolation_mixing_key_and_non_keys(context) + return None + return has_key + + def check_simple_str_interpolation( + self, + specifiers: list[ConversionSpecifier], + replacements: Expression, + expr: FormatStringExpr, + ) -> None: + """Check % string interpolation with positional specifiers '%s, %d' % ('yes, 42').""" + checkers = self.build_replacement_checkers(specifiers, replacements, expr) + if checkers is None: + return + + rhs_type = get_proper_type(self.accept(replacements)) + rep_types: list[Type] = [] + if isinstance(rhs_type, TupleType): + rep_types = rhs_type.items + unpack_index = find_unpack_in_list(rep_types) + if unpack_index is not None: + # TODO: we should probably warn about potentially short tuple. + # However, without special-casing for tuple(f(i) for in other_tuple) + # this causes false positive on mypy self-check in report.py. + extras = max(0, len(checkers) - len(rep_types) + 1) + unpacked = rep_types[unpack_index] + assert isinstance(unpacked, UnpackType) + unpacked = get_proper_type(unpacked.type) + if isinstance(unpacked, TypeVarTupleType): + unpacked = get_proper_type(unpacked.upper_bound) + assert ( + isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple" + ) + unpack_items = [unpacked.args[0]] * extras + rep_types = rep_types[:unpack_index] + unpack_items + rep_types[unpack_index + 1 :] + elif isinstance(rhs_type, AnyType): + return + elif isinstance(rhs_type, Instance) and rhs_type.type.fullname == "builtins.tuple": + # Assume that an arbitrary-length tuple has the right number of items. + rep_types = [rhs_type.args[0]] * len(checkers) + elif isinstance(rhs_type, UnionType): + for typ in rhs_type.relevant_items(): + temp_node = TempNode(typ) + temp_node.line = replacements.line + self.check_simple_str_interpolation(specifiers, temp_node, expr) + return + else: + rep_types = [rhs_type] + + if len(checkers) > len(rep_types): + # Only check the fix-length Tuple type. Other Iterable types would skip. + if is_subtype(rhs_type, self.chk.named_type("typing.Iterable")) and not isinstance( + rhs_type, TupleType + ): + return + else: + self.msg.too_few_string_formatting_arguments(replacements) + elif len(checkers) < len(rep_types): + self.msg.too_many_string_formatting_arguments(replacements) + else: + if len(checkers) == 1: + check_node, check_type = checkers[0] + if isinstance(rhs_type, TupleType) and len(rhs_type.items) == 1: + check_type(rhs_type.items[0]) + else: + check_node(replacements) + elif isinstance(replacements, TupleExpr) and not any( + isinstance(item, StarExpr) for item in replacements.items + ): + for checks, rep_node in zip(checkers, replacements.items): + check_node, check_type = checks + check_node(rep_node) + else: + for checks, rep_type in zip(checkers, rep_types): + check_node, check_type = checks + check_type(rep_type) + + def check_mapping_str_interpolation( + self, + specifiers: list[ConversionSpecifier], + replacements: Expression, + expr: FormatStringExpr, + ) -> None: + """Check % string interpolation with names specifiers '%(name)s' % {'name': 'John'}.""" + if isinstance(replacements, DictExpr) and all( + isinstance(k, (StrExpr, BytesExpr)) for k, v in replacements.items + ): + mapping: dict[str, Type] = {} + for k, v in replacements.items: + if isinstance(expr, BytesExpr): + # Special case: for bytes formatting keys must be bytes. + if not isinstance(k, BytesExpr): + self.msg.fail( + "Dictionary keys in bytes formatting must be bytes, not strings", + expr, + code=codes.STRING_FORMATTING, + ) + key_str = cast(FormatStringExpr, k).value + mapping[key_str] = self.accept(v) + + for specifier in specifiers: + if specifier.conv_type == "%": + # %% is allowed in mappings, no checking is required + continue + assert specifier.key is not None + if specifier.key not in mapping: + self.msg.key_not_in_mapping(specifier.key, replacements) + return + rep_type = mapping[specifier.key] + assert specifier.conv_type is not None + expected_type = self.conversion_type(specifier.conv_type, replacements, expr) + if expected_type is None: + return + self.chk.check_subtype( + rep_type, + expected_type, + replacements, + message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION, + "expression has type", + f"placeholder with key '{specifier.key}' has type", + code=codes.STRING_FORMATTING, + ) + if specifier.conv_type == "s": + self.check_s_special_cases(expr, rep_type, expr) + else: + rep_type = self.accept(replacements) + dict_type = self.build_dict_type(expr) + self.chk.check_subtype( + rep_type, + dict_type, + replacements, + message_registry.FORMAT_REQUIRES_MAPPING, + "expression has type", + "expected type for mapping is", + code=codes.STRING_FORMATTING, + ) + + def build_dict_type(self, expr: FormatStringExpr) -> Type: + """Build expected mapping type for right operand in % formatting.""" + any_type = AnyType(TypeOfAny.special_form) + if isinstance(expr, BytesExpr): + bytes_type = self.chk.named_generic_type("builtins.bytes", []) + return self.chk.named_generic_type( + "_typeshed.SupportsKeysAndGetItem", [bytes_type, any_type] + ) + elif isinstance(expr, StrExpr): + str_type = self.chk.named_generic_type("builtins.str", []) + return self.chk.named_generic_type( + "_typeshed.SupportsKeysAndGetItem", [str_type, any_type] + ) + else: + assert False, "Unreachable" + + def build_replacement_checkers( + self, specifiers: list[ConversionSpecifier], context: Context, expr: FormatStringExpr + ) -> list[Checkers] | None: + checkers: list[Checkers] = [] + for specifier in specifiers: + checker = self.replacement_checkers(specifier, context, expr) + if checker is None: + return None + checkers.extend(checker) + return checkers + + def replacement_checkers( + self, specifier: ConversionSpecifier, context: Context, expr: FormatStringExpr + ) -> list[Checkers] | None: + """Returns a list of tuples of two functions that check whether a replacement is + of the right type for the specifier. The first function takes a node and checks + its type in the right type context. The second function just checks a type. + """ + checkers: list[Checkers] = [] + + if specifier.width == "*": + checkers.append(self.checkers_for_star(context)) + if specifier.precision == "*": + checkers.append(self.checkers_for_star(context)) + + if specifier.conv_type == "c": + c = self.checkers_for_c_type(specifier.conv_type, context, expr) + if c is None: + return None + checkers.append(c) + elif specifier.conv_type is not None and specifier.conv_type != "%": + c = self.checkers_for_regular_type(specifier.conv_type, context, expr) + if c is None: + return None + checkers.append(c) + return checkers + + def checkers_for_star(self, context: Context) -> Checkers: + """Returns a tuple of check functions that check whether, respectively, + a node or a type is compatible with a star in a conversion specifier. + """ + expected = self.named_type("builtins.int") + + def check_type(type: Type) -> bool: + expected = self.named_type("builtins.int") + return self.chk.check_subtype( + type, expected, context, "* wants int", code=codes.STRING_FORMATTING + ) + + def check_expr(expr: Expression) -> None: + type = self.accept(expr, expected) + check_type(type) + + return check_expr, check_type + + def check_placeholder_type(self, typ: Type, expected_type: Type, context: Context) -> bool: + return self.chk.check_subtype( + typ, + expected_type, + context, + message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION, + "expression has type", + "placeholder has type", + code=codes.STRING_FORMATTING, + ) + + def checkers_for_regular_type( + self, conv_type: str, context: Context, expr: FormatStringExpr + ) -> Checkers | None: + """Returns a tuple of check functions that check whether, respectively, + a node or a type is compatible with 'type'. Return None in case of an error. + """ + expected_type = self.conversion_type(conv_type, context, expr) + if expected_type is None: + return None + + def check_type(typ: Type) -> bool: + assert expected_type is not None + ret = self.check_placeholder_type(typ, expected_type, context) + if ret and conv_type == "s": + ret = self.check_s_special_cases(expr, typ, context) + return ret + + def check_expr(expr: Expression) -> None: + type = self.accept(expr, expected_type) + check_type(type) + + return check_expr, check_type + + def check_s_special_cases(self, expr: FormatStringExpr, typ: Type, context: Context) -> bool: + """Additional special cases for %s in bytes vs string context.""" + if isinstance(expr, StrExpr): + # Couple special cases for string formatting. + if has_type_component(typ, "builtins.bytes"): + self.msg.fail( + 'If x = b\'abc\' then "%s" % x produces "b\'abc\'", not "abc". ' + 'If this is desired behavior use "%r" % x. Otherwise, decode the bytes', + context, + code=codes.STR_BYTES_PY3, + ) + return False + if isinstance(expr, BytesExpr): + # A special case for bytes formatting: b'%s' actually requires bytes on Python 3. + if has_type_component(typ, "builtins.str"): + self.msg.fail( + "On Python 3 b'%s' requires bytes, not string", + context, + code=codes.STRING_FORMATTING, + ) + return False + return True + + def checkers_for_c_type( + self, type: str, context: Context, format_expr: FormatStringExpr + ) -> Checkers | None: + """Returns a tuple of check functions that check whether, respectively, + a node or a type is compatible with 'type' that is a character type. + """ + expected_type = self.conversion_type(type, context, format_expr) + if expected_type is None: + return None + + def check_type(type: Type) -> bool: + assert expected_type is not None + if isinstance(format_expr, BytesExpr): + err_msg = '"%c" requires an integer in range(256) or a single byte' + else: + err_msg = '"%c" requires int or char' + return self.chk.check_subtype( + type, + expected_type, + context, + err_msg, + "expression has type", + code=codes.STRING_FORMATTING, + ) + + def check_expr(expr: Expression) -> None: + """int, or str with length 1""" + type = self.accept(expr, expected_type) + # We need further check with expr to make sure that + # it has exact one char or one single byte. + if check_type(type): + # Python 3 doesn't support b'%c' % str + if ( + isinstance(format_expr, BytesExpr) + and isinstance(expr, BytesExpr) + and len(expr.value) != 1 + ): + self.msg.requires_int_or_single_byte(context) + elif isinstance(expr, (StrExpr, BytesExpr)) and len(expr.value) != 1: + self.msg.requires_int_or_char(context) + + return check_expr, check_type + + def conversion_type( + self, p: str, context: Context, expr: FormatStringExpr, format_call: bool = False + ) -> Type | None: + """Return the type that is accepted for a string interpolation conversion specifier type. + + Note that both Python's float (e.g. %f) and integer (e.g. %d) + specifier types accept both float and integers. + + The 'format_call' argument indicates whether this type came from % interpolation or from + a str.format() call, the meaning of few formatting types are different. + """ + NUMERIC_TYPES = NUMERIC_TYPES_NEW if format_call else NUMERIC_TYPES_OLD + INT_TYPES = REQUIRE_INT_NEW if format_call else REQUIRE_INT_OLD + if p == "b" and not format_call: + if not isinstance(expr, BytesExpr): + self.msg.fail( + 'Format character "b" is only supported on bytes patterns', + context, + code=codes.STRING_FORMATTING, + ) + return None + return self.named_type("builtins.bytes") + elif p == "a": + # TODO: return type object? + return AnyType(TypeOfAny.special_form) + elif p in ["s", "r"]: + return AnyType(TypeOfAny.special_form) + elif p in NUMERIC_TYPES: + if p in INT_TYPES: + numeric_types = [self.named_type("builtins.int")] + else: + numeric_types = [ + self.named_type("builtins.int"), + self.named_type("builtins.float"), + ] + if not format_call: + if p in FLOAT_TYPES: + numeric_types.append(self.named_type("typing.SupportsFloat")) + else: + numeric_types.append(self.named_type("typing.SupportsInt")) + return UnionType.make_union(numeric_types) + elif p in ["c"]: + if isinstance(expr, BytesExpr): + return UnionType( + [self.named_type("builtins.int"), self.named_type("builtins.bytes")] + ) + else: + return UnionType( + [self.named_type("builtins.int"), self.named_type("builtins.str")] + ) + else: + self.msg.unsupported_placeholder(p, context) + return None + + # + # Helpers + # + + def named_type(self, name: str) -> Instance: + """Return an instance type with type given by the name and no type + arguments. Alias for TypeChecker.named_type. + """ + return self.chk.named_type(name) + + def accept(self, expr: Expression, context: Type | None = None) -> Type: + """Type check a node. Alias for TypeChecker.accept.""" + return self.chk.expr_checker.accept(expr, context) + + +def has_type_component(typ: Type, fullname: str) -> bool: + """Is this a specific instance type, or a union that contains it? + + We use this ad-hoc function instead of a proper visitor or subtype check + because some str vs bytes errors are strictly speaking not runtime errors, + but rather highly counter-intuitive behavior. This is similar to what is used for + --strict-equality. + """ + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return typ.type.has_base(fullname) + elif isinstance(typ, TypeVarType): + return has_type_component(typ.upper_bound, fullname) or any( + has_type_component(v, fullname) for v in typ.values + ) + elif isinstance(typ, UnionType): + return any(has_type_component(t, fullname) for t in typ.relevant_items()) + return False diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f9423e479b152bdf848a770d50d107d8bd495b5e Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..747981916960d65f698cb46351f6a83e4b075063 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.py @@ -0,0 +1,734 @@ +from __future__ import annotations + +import argparse +import configparser +import glob as fileglob +import os +import re +import sys +from io import StringIO + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +from collections.abc import Callable, Mapping, MutableMapping, Sequence +from typing import Any, Final, TextIO, TypeAlias +from typing_extensions import Never + +from mypy import defaults +from mypy.options import PER_MODULE_OPTIONS, Options + +_CONFIG_VALUE_TYPES: TypeAlias = ( + str | bool | int | float | dict[str, str] | list[str] | tuple[int, int] +) +_INI_PARSER_CALLABLE: TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES] + + +class VersionTypeError(argparse.ArgumentTypeError): + """Provide a fallback value if the Python version is unsupported.""" + + def __init__(self, *args: Any, fallback: tuple[int, int]) -> None: + self.fallback = fallback + super().__init__(*args) + + +def parse_version(v: str | float) -> tuple[int, int]: + m = re.match(r"\A(\d)\.(\d+)\Z", str(v)) + if not m: + raise argparse.ArgumentTypeError(f"Invalid python version '{v}' (expected format: 'x.y')") + major, minor = int(m.group(1)), int(m.group(2)) + if major == 2 and minor == 7: + pass # Error raised elsewhere + elif major == 3: + if minor < defaults.PYTHON3_VERSION_MIN[1]: + msg = "Python 3.{} is not supported (must be {}.{} or higher)".format( + minor, *defaults.PYTHON3_VERSION_MIN + ) + + if isinstance(v, float): + msg += ". You may need to put quotes around your Python version" + + raise VersionTypeError(msg, fallback=defaults.PYTHON3_VERSION_MIN) + else: + raise argparse.ArgumentTypeError( + f"Python major version '{major}' out of range (must be 3)" + ) + return major, minor + + +def try_split(v: str | Sequence[str] | object, split_regex: str = ",") -> list[str]: + """Split and trim a str or sequence (eg: list) of str into a list of str. + If an element of the input is not str, a type error will be raised.""" + + def complain(x: object, additional_info: str = "") -> Never: + raise argparse.ArgumentTypeError( + f"Expected a list or a stringified version thereof, but got: '{x}', of type {type(x).__name__}.{additional_info}" + ) + + if isinstance(v, str): + items = [p.strip() for p in re.split(split_regex, v)] + if items and items[-1] == "": + items.pop(-1) + return items + elif isinstance(v, Sequence): + return [ + ( + p.strip() + if isinstance(p, str) + else complain(p, additional_info=" (As an element of the list.)") + ) + for p in v + ] + else: + complain(v) + + +def validate_package_allow_list(allow_list: list[str]) -> list[str]: + for p in allow_list: + msg = f"Invalid allow list entry: {p}" + if "*" in p: + raise argparse.ArgumentTypeError( + f"{msg} (entries are already prefixes so must not contain *)" + ) + if "\\" in p or "/" in p: + raise argparse.ArgumentTypeError( + f"{msg} (entries must be packages like foo.bar not directories or files)" + ) + return allow_list + + +def expand_path(path: str) -> str: + """Expand the user home directory and any environment variables contained within + the provided path. + """ + + return os.path.expandvars(os.path.expanduser(path)) + + +def str_or_array_as_list(v: str | Sequence[str]) -> list[str]: + if isinstance(v, str): + return [v.strip()] if v.strip() else [] + return [p.strip() for p in v if p.strip()] + + +def split_and_match_files_list(paths: Sequence[str]) -> list[str]: + """Take a list of files/directories (with support for globbing through the glob library). + + Where a path/glob matches no file, we still include the raw path in the resulting list. + + Returns a list of file paths + """ + expanded_paths = [] + + for path in paths: + path = expand_path(path.strip()) + globbed_files = fileglob.glob(path, recursive=True) + if globbed_files: + expanded_paths.extend(globbed_files) + else: + expanded_paths.append(path) + + return expanded_paths + + +def split_and_match_files(paths: str) -> list[str]: + """Take a string representing a list of files/directories (with support for globbing + through the glob library). + + Where a path/glob matches no file, we still include the raw path in the resulting list. + + Returns a list of file paths + """ + + return split_and_match_files_list(split_commas(paths)) + + +def check_follow_imports(choice: str) -> str: + choices = ["normal", "silent", "skip", "error"] + if choice not in choices: + raise argparse.ArgumentTypeError( + "invalid choice '{}' (choose from {})".format( + choice, ", ".join(f"'{x}'" for x in choices) + ) + ) + return choice + + +def check_junit_format(choice: str) -> str: + choices = ["global", "per_file"] + if choice not in choices: + raise argparse.ArgumentTypeError( + "invalid choice '{}' (choose from {})".format( + choice, ", ".join(f"'{x}'" for x in choices) + ) + ) + return choice + + +def split_commas(value: str) -> list[str]: + # Uses a bit smarter technique to allow last trailing comma + # and to remove last `""` item from the split. + items = value.split(",") + if items and items[-1] == "": + items.pop(-1) + return items + + +# For most options, the type of the default value set in options.py is +# sufficient, and we don't have to do anything here. This table +# exists to specify types for values initialized to None or container +# types. +ini_config_types: Final[dict[str, _INI_PARSER_CALLABLE]] = { + "python_version": parse_version, + "custom_typing_module": str, + "custom_typeshed_dir": expand_path, + "mypy_path": lambda s: [expand_path(p.strip()) for p in re.split("[,:]", s)], + "files": split_and_match_files, + "quickstart_file": expand_path, + "junit_xml": expand_path, + "junit_format": check_junit_format, + "follow_imports": check_follow_imports, + "no_site_packages": bool, + "plugins": lambda s: [p.strip() for p in split_commas(s)], + "always_true": lambda s: [p.strip() for p in split_commas(s)], + "always_false": lambda s: [p.strip() for p in split_commas(s)], + "untyped_calls_exclude": lambda s: validate_package_allow_list( + [p.strip() for p in split_commas(s)] + ), + "enable_incomplete_feature": lambda s: [p.strip() for p in split_commas(s)], + "disable_error_code": lambda s: [p.strip() for p in split_commas(s)], + "enable_error_code": lambda s: [p.strip() for p in split_commas(s)], + "package_root": lambda s: [p.strip() for p in split_commas(s)], + "cache_dir": expand_path, + "python_executable": expand_path, + "strict": bool, + "exclude": lambda s: [s.strip()], + "packages": try_split, + "modules": try_split, +} + +# Reuse the ini_config_types and overwrite the diff +toml_config_types: Final[dict[str, _INI_PARSER_CALLABLE]] = ini_config_types.copy() +toml_config_types.update( + { + "python_version": parse_version, + "mypy_path": lambda s: [expand_path(p) for p in try_split(s, "[,:]")], + "files": lambda s: split_and_match_files_list(try_split(s)), + "junit_format": lambda s: check_junit_format(str(s)), + "follow_imports": lambda s: check_follow_imports(str(s)), + "plugins": try_split, + "always_true": try_split, + "always_false": try_split, + "untyped_calls_exclude": lambda s: validate_package_allow_list(try_split(s)), + "enable_incomplete_feature": try_split, + "disable_error_code": lambda s: try_split(s), + "enable_error_code": lambda s: try_split(s), + "package_root": try_split, + "exclude": str_or_array_as_list, + "packages": try_split, + "modules": try_split, + } +) + + +def _parse_individual_file( + config_file: str, stderr: TextIO | None = None +) -> tuple[MutableMapping[str, Any], dict[str, _INI_PARSER_CALLABLE], str] | None: + + if not os.path.exists(config_file): + return None + + parser: MutableMapping[str, Any] + try: + if is_toml(config_file): + with open(config_file, "rb") as f: + toml_data = tomllib.load(f) + # Filter down to just mypy relevant toml keys + toml_data = toml_data.get("tool", {}) + if "mypy" not in toml_data: + return None + toml_data = {"mypy": toml_data["mypy"]} + parser = destructure_overrides(toml_data) + config_types = toml_config_types + else: + parser = configparser.RawConfigParser() + parser.read(config_file) + config_types = ini_config_types + + except (tomllib.TOMLDecodeError, configparser.Error, ConfigTOMLValueError) as err: + print(f"{config_file}: {err}", file=stderr) + return None + + if os.path.basename(config_file) in defaults.SHARED_CONFIG_NAMES and "mypy" not in parser: + return None + + return parser, config_types, config_file + + +def _find_config_file( + stderr: TextIO | None = None, +) -> tuple[MutableMapping[str, Any], dict[str, _INI_PARSER_CALLABLE], str] | None: + + current_dir = os.path.abspath(os.getcwd()) + + while True: + for name in defaults.CONFIG_NAMES + defaults.SHARED_CONFIG_NAMES: + config_file = os.path.relpath(os.path.join(current_dir, name)) + ret = _parse_individual_file(config_file, stderr) + if ret is None: + continue + return ret + + if any( + os.path.exists(os.path.join(current_dir, cvs_root)) for cvs_root in (".git", ".hg") + ): + break + parent_dir = os.path.dirname(current_dir) + if parent_dir == current_dir: + break + current_dir = parent_dir + + for config_file in defaults.USER_CONFIG_FILES: + ret = _parse_individual_file(config_file, stderr) + if ret is None: + continue + return ret + + return None + + +def parse_config_file( + options: Options, + set_strict_flags: Callable[[], None], + filename: str | None, + stdout: TextIO | None = None, + stderr: TextIO | None = None, +) -> None: + """Parse a config file into an Options object. + + Errors are written to stderr but are not fatal. + + If filename is None, fall back to default config files. + """ + stdout = stdout or sys.stdout + stderr = stderr or sys.stderr + + ret = ( + _parse_individual_file(filename, stderr) + if filename is not None + else _find_config_file(stderr) + ) + if ret is None: + return + parser, config_types, file_read = ret + + options.config_file = file_read + os.environ["MYPY_CONFIG_FILE_DIR"] = os.path.dirname(os.path.abspath(file_read)) + + if "mypy" not in parser: + if filename or os.path.basename(file_read) not in defaults.SHARED_CONFIG_NAMES: + print(f"{file_read}: No [mypy] section in config file", file=stderr) + else: + section = parser["mypy"] + prefix = f"{file_read}: [mypy]: " + updates, report_dirs = parse_section( + prefix, options, set_strict_flags, section, config_types, stderr + ) + for k, v in updates.items(): + setattr(options, k, v) + options.report_dirs.update(report_dirs) + + for name, section in parser.items(): + if name.startswith("mypy-"): + prefix = get_prefix(file_read, name) + updates, report_dirs = parse_section( + prefix, options, set_strict_flags, section, config_types, stderr + ) + if report_dirs: + print( + prefix, + "Per-module sections should not specify reports ({})".format( + ", ".join(s + "_report" for s in sorted(report_dirs)) + ), + file=stderr, + ) + if set(updates) - PER_MODULE_OPTIONS: + print( + prefix, + "Per-module sections should only specify per-module flags ({})".format( + ", ".join(sorted(set(updates) - PER_MODULE_OPTIONS)) + ), + file=stderr, + ) + updates = {k: v for k, v in updates.items() if k in PER_MODULE_OPTIONS} + + globs = name[5:] + for glob in globs.split(","): + # For backwards compatibility, replace (back)slashes with dots. + glob = glob.replace(os.sep, ".") + if os.altsep: + glob = glob.replace(os.altsep, ".") + + if any(c in glob for c in "?[]!") or any( + "*" in x and x != "*" for x in glob.split(".") + ): + print( + prefix, + "Patterns must be fully-qualified module names, optionally " + "with '*' in some components (e.g spam.*.eggs.*)", + file=stderr, + ) + else: + options.per_module_options[glob] = updates + + +def get_prefix(file_read: str, name: str) -> str: + if is_toml(file_read): + module_name_str = 'module = "%s"' % "-".join(name.split("-")[1:]) + else: + module_name_str = name + + return f"{file_read}: [{module_name_str}]:" + + +def is_toml(filename: str) -> bool: + return filename.lower().endswith(".toml") + + +def destructure_overrides(toml_data: dict[str, Any]) -> dict[str, Any]: + """Take the new [[tool.mypy.overrides]] section array in the pyproject.toml file, + and convert it back to a flatter structure that the existing config_parser can handle. + + E.g. the following pyproject.toml file: + + [[tool.mypy.overrides]] + module = [ + "a.b", + "b.*" + ] + disallow_untyped_defs = true + + [[tool.mypy.overrides]] + module = 'c' + disallow_untyped_defs = false + + Would map to the following config dict that it would have gotten from parsing an equivalent + ini file: + + { + "mypy-a.b": { + disallow_untyped_defs = true, + }, + "mypy-b.*": { + disallow_untyped_defs = true, + }, + "mypy-c": { + disallow_untyped_defs: false, + }, + } + """ + if "overrides" not in toml_data["mypy"]: + return toml_data + + if not isinstance(toml_data["mypy"]["overrides"], list): + raise ConfigTOMLValueError( + "tool.mypy.overrides sections must be an array. Please make " + "sure you are using double brackets like so: [[tool.mypy.overrides]]" + ) + + result = toml_data.copy() + for override in result["mypy"]["overrides"]: + if "module" not in override: + raise ConfigTOMLValueError( + "toml config file contains a [[tool.mypy.overrides]] " + "section, but no module to override was specified." + ) + + if isinstance(override["module"], str): + modules = [override["module"]] + elif isinstance(override["module"], list): + modules = override["module"] + else: + raise ConfigTOMLValueError( + "toml config file contains a [[tool.mypy.overrides]] " + "section with a module value that is not a string or a list of " + "strings" + ) + + for module in modules: + module_overrides = override.copy() + del module_overrides["module"] + old_config_name = f"mypy-{module}" + if old_config_name not in result: + result[old_config_name] = module_overrides + else: + for new_key, new_value in module_overrides.items(): + if ( + new_key in result[old_config_name] + and result[old_config_name][new_key] != new_value + ): + raise ConfigTOMLValueError( + "toml config file contains " + "[[tool.mypy.overrides]] sections with conflicting " + f"values. Module '{module}' has two different values for '{new_key}'" + ) + result[old_config_name][new_key] = new_value + + del result["mypy"]["overrides"] + return result + + +def parse_section( + prefix: str, + template: Options, + set_strict_flags: Callable[[], None], + section: Mapping[str, Any], + config_types: dict[str, Any], + stderr: TextIO = sys.stderr, +) -> tuple[dict[str, object], dict[str, str]]: + """Parse one section of a config file. + + Returns a dict of option values encountered, and a dict of report directories. + """ + results: dict[str, object] = {} + report_dirs: dict[str, str] = {} + + # Because these fields exist on Options, without proactive checking, we would accept them + # and crash later + invalid_options = { + "enabled_error_codes": "enable_error_code", + "disabled_error_codes": "disable_error_code", + } + + for key in section: + invert = False + # Here we use `key` for original config section key, and `options_key` for + # the corresponding Options attribute. + options_key = key + # Match aliasing for command line flag. + if key.endswith("allow_redefinition"): + options_key += "_old" + if key in config_types: + ct = config_types[key] + elif key in invalid_options: + print( + f"{prefix}Unrecognized option: {key} = {section[key]}" + f" (did you mean {invalid_options[key]}?)", + file=stderr, + ) + continue + else: + dv = getattr(template, options_key, None) + if dv is None: + if key.endswith("_report"): + report_type = key[:-7].replace("_", "-") + if report_type in defaults.REPORTER_NAMES: + report_dirs[report_type] = str(section[key]) + else: + print(f"{prefix}Unrecognized report type: {key}", file=stderr) + continue + if key.startswith("x_"): + pass # Don't complain about `x_blah` flags + elif key.startswith("no_") and hasattr(template, options_key[3:]): + options_key = options_key[3:] + invert = True + elif key.startswith("allow") and hasattr(template, "dis" + options_key): + options_key = "dis" + options_key + invert = True + elif key.startswith("disallow") and hasattr(template, options_key[3:]): + options_key = options_key[3:] + invert = True + elif key.startswith("show_") and hasattr(template, "hide_" + options_key[5:]): + options_key = "hide_" + options_key[5:] + invert = True + elif key == "strict": + pass # Special handling below + else: + print(f"{prefix}Unrecognized option: {key} = {section[key]}", file=stderr) + if invert: + dv = getattr(template, options_key, None) + else: + continue + ct = type(dv) if dv is not None else None + v: Any = None + try: + if ct is bool: + if isinstance(section, dict): + v = convert_to_boolean(section.get(key)) + else: + v = section.getboolean(key) # type: ignore[attr-defined] # Until better stub + if invert: + v = not v + elif callable(ct): + if invert: + print(f"{prefix}Can not invert non-boolean key {options_key}", file=stderr) + continue + try: + v = ct(section.get(key)) + except VersionTypeError as err_version: + print(f"{prefix}{key}: {err_version}", file=stderr) + v = err_version.fallback + except argparse.ArgumentTypeError as err: + print(f"{prefix}{key}: {err}", file=stderr) + continue + else: + print(f"{prefix}Don't know what type {key} should have", file=stderr) + continue + except ValueError as err: + print(f"{prefix}{key}: {err}", file=stderr) + continue + if key == "strict": + if v: + set_strict_flags() + continue + results[options_key] = v + + # These two flags act as per-module overrides, so store the empty defaults. + if "disable_error_code" not in results: + results["disable_error_code"] = [] + if "enable_error_code" not in results: + results["enable_error_code"] = [] + + return results, report_dirs + + +def convert_to_boolean(value: Any | None) -> bool: + """Return a boolean value translating from other types if necessary.""" + if isinstance(value, bool): + return value + if not isinstance(value, str): + value = str(value) + if value.lower() not in configparser.RawConfigParser.BOOLEAN_STATES: + raise ValueError(f"Not a boolean: {value}") + return configparser.RawConfigParser.BOOLEAN_STATES[value.lower()] + + +def split_directive(s: str) -> tuple[list[str], list[str]]: + """Split s on commas, except during quoted sections. + + Returns the parts and a list of error messages.""" + parts = [] + cur: list[str] = [] + errors = [] + i = 0 + while i < len(s): + if s[i] == ",": + parts.append("".join(cur).strip()) + cur = [] + elif s[i] == '"': + i += 1 + while i < len(s) and s[i] != '"': + cur.append(s[i]) + i += 1 + if i == len(s): + errors.append("Unterminated quote in configuration comment") + cur.clear() + else: + cur.append(s[i]) + i += 1 + if cur: + parts.append("".join(cur).strip()) + + return parts, errors + + +def mypy_comments_to_config_map(line: str, template: Options) -> tuple[dict[str, str], list[str]]: + """Rewrite the mypy comment syntax into ini file syntax.""" + options = {} + entries, errors = split_directive(line) + for entry in entries: + if "=" not in entry: + name = entry + value = None + else: + name, value = (x.strip() for x in entry.split("=", 1)) + + name = name.replace("-", "_") + if value is None: + value = "True" + options[name] = value + + return options, errors + + +def parse_mypy_comments( + args: list[tuple[int, str]], template: Options +) -> tuple[dict[str, object], list[tuple[int, str]]]: + """Parse a collection of inline mypy: configuration comments. + + Returns a dictionary of options to be applied and a list of error messages + generated. + """ + errors: list[tuple[int, str]] = [] + sections: dict[str, object] = {"enable_error_code": [], "disable_error_code": []} + + for lineno, line in args: + # In order to easily match the behavior for bools, we abuse configparser. + # Oddly, the only way to get the SectionProxy object with the getboolean + # method is to create a config parser. + parser = configparser.RawConfigParser() + options, parse_errors = mypy_comments_to_config_map(line, template) + if "python_version" in options: + errors.append((lineno, "python_version not supported in inline configuration")) + del options["python_version"] + + parser["dummy"] = options + errors.extend((lineno, x) for x in parse_errors) + + stderr = StringIO() + strict_found = False + + def set_strict_flags() -> None: + nonlocal strict_found + strict_found = True + + new_sections, reports = parse_section( + "", template, set_strict_flags, parser["dummy"], ini_config_types, stderr=stderr + ) + errors.extend((lineno, x) for x in stderr.getvalue().strip().split("\n") if x) + if reports: + errors.append((lineno, "Reports not supported in inline configuration")) + if strict_found: + errors.append( + ( + lineno, + 'Setting "strict" not supported in inline configuration: specify it in ' + "a configuration file instead, or set individual inline flags " + '(see "mypy -h" for the list of flags enabled in strict mode)', + ) + ) + # Because this is currently special-cased + # (the new_sections for an inline config *always* includes 'disable_error_code' and + # 'enable_error_code' fields, usually empty, which overwrite the old ones), + # we have to manipulate them specially. + # This could use a refactor, but so could the whole subsystem. + if ( + "enable_error_code" in new_sections + and isinstance(neec := new_sections["enable_error_code"], list) + and isinstance(eec := sections.get("enable_error_code", []), list) + ): + new_sections["enable_error_code"] = sorted(set(neec + eec)) + if ( + "disable_error_code" in new_sections + and isinstance(ndec := new_sections["disable_error_code"], list) + and isinstance(dec := sections.get("disable_error_code", []), list) + ): + new_sections["disable_error_code"] = sorted(set(ndec + dec)) + sections.update(new_sections) + return sections, errors + + +def get_config_module_names(filename: str | None, modules: list[str]) -> str: + if not filename or not modules: + return "" + + if not is_toml(filename): + return ", ".join(f"[mypy-{module}]" for module in modules) + + return "module = ['%s']" % ("', '".join(sorted(modules))) + + +class ConfigTOMLValueError(ValueError): + pass diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..442aa7ad3eb807fb96efef807c48845de9431019 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b915df229855b01dc737c564fff0596aa1e03e --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.py @@ -0,0 +1,187 @@ +"""Constant folding of expressions. + +For example, 3 + 5 can be constant folded into 8. +""" + +from __future__ import annotations + +from typing import Final + +from mypy.nodes import ( + ComplexExpr, + Expression, + FloatExpr, + IntExpr, + NameExpr, + OpExpr, + StrExpr, + UnaryExpr, + Var, +) + +# All possible result types of constant folding +ConstantValue = int | bool | float | complex | str +CONST_TYPES: Final = (int, bool, float, complex, str) + + +def constant_fold_expr(expr: Expression, cur_mod_id: str) -> ConstantValue | None: + """Return the constant value of an expression for supported operations. + + Among other things, support int arithmetic and string + concatenation. For example, the expression 3 + 5 has the constant + value 8. + + Also bind simple references to final constants defined in the + current module (cur_mod_id). Binding to references is best effort + -- we don't bind references to other modules. Mypyc trusts these + to be correct in compiled modules, so that it can replace a + constant expression (or a reference to one) with the statically + computed value. We don't want to infer constant values based on + stubs, in particular, as these might not match the implementation + (due to version skew, for example). + + Return None if unsuccessful. + """ + if isinstance(expr, IntExpr): + return expr.value + if isinstance(expr, StrExpr): + return expr.value + if isinstance(expr, FloatExpr): + return expr.value + if isinstance(expr, ComplexExpr): + return expr.value + elif isinstance(expr, NameExpr): + if expr.name == "True": + return True + elif expr.name == "False": + return False + node = expr.node + if ( + isinstance(node, Var) + and node.is_final + and node.fullname.rsplit(".", 1)[0] == cur_mod_id + ): + value = node.final_value + if isinstance(value, (CONST_TYPES)): + return value + elif isinstance(expr, OpExpr): + left = constant_fold_expr(expr.left, cur_mod_id) + right = constant_fold_expr(expr.right, cur_mod_id) + if left is not None and right is not None: + return constant_fold_binary_op(expr.op, left, right) + elif isinstance(expr, UnaryExpr): + value = constant_fold_expr(expr.expr, cur_mod_id) + if value is not None: + return constant_fold_unary_op(expr.op, value) + return None + + +def constant_fold_binary_op( + op: str, left: ConstantValue, right: ConstantValue +) -> ConstantValue | None: + if isinstance(left, int) and isinstance(right, int): + return constant_fold_binary_int_op(op, left, right) + + # Float and mixed int/float arithmetic. + if isinstance(left, float) and isinstance(right, float): + return constant_fold_binary_float_op(op, left, right) + elif isinstance(left, float) and isinstance(right, int): + return constant_fold_binary_float_op(op, left, right) + elif isinstance(left, int) and isinstance(right, float): + return constant_fold_binary_float_op(op, left, right) + + # String concatenation and multiplication. + if op == "+" and isinstance(left, str) and isinstance(right, str): + return left + right + elif op == "*" and isinstance(left, str) and isinstance(right, int): + return left * right + elif op == "*" and isinstance(left, int) and isinstance(right, str): + return left * right + + # Complex construction. + if op == "+" and isinstance(left, (int, float)) and isinstance(right, complex): + return left + right + elif op == "+" and isinstance(left, complex) and isinstance(right, (int, float)): + return left + right + elif op == "-" and isinstance(left, (int, float)) and isinstance(right, complex): + return left - right + elif op == "-" and isinstance(left, complex) and isinstance(right, (int, float)): + return left - right + + return None + + +def constant_fold_binary_int_op(op: str, left: int, right: int) -> int | float | None: + if op == "+": + return left + right + if op == "-": + return left - right + elif op == "*": + return left * right + elif op == "/": + if right != 0: + return left / right + elif op == "//": + if right != 0: + return left // right + elif op == "%": + if right != 0: + return left % right + elif op == "&": + return left & right + elif op == "|": + return left | right + elif op == "^": + return left ^ right + elif op == "<<": + if right >= 0: + return left << right + elif op == ">>": + if right >= 0: + return left >> right + elif op == "**": + if right >= 0: + ret = left**right + assert isinstance(ret, int) + return ret + return None + + +def constant_fold_binary_float_op(op: str, left: int | float, right: int | float) -> float | None: + assert not (isinstance(left, int) and isinstance(right, int)), (op, left, right) + if op == "+": + return left + right + elif op == "-": + return left - right + elif op == "*": + return left * right + elif op == "/": + if right != 0: + return left / right + elif op == "//": + if right != 0: + return left // right + elif op == "%": + if right != 0: + return left % right + elif op == "**": + if (left < 0 and isinstance(right, int)) or left > 0: + try: + ret = left**right + except OverflowError: + return None + else: + assert isinstance(ret, float), ret + return ret + + return None + + +def constant_fold_unary_op(op: str, value: ConstantValue) -> int | float | None: + if op == "-" and isinstance(value, (int, float)): + return -value + elif op == "~" and isinstance(value, int): + return ~value + elif op == "+" and isinstance(value, (int, float)): + return value + return None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..cb506573c7421850ce1841b82b68705fdb462008 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..df79fdae5456cf679e70a8131d6b9c79560957e4 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.py @@ -0,0 +1,1687 @@ +"""Type inference constraints.""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING, Final, TypeGuard, cast + +import mypy.subtypes +import mypy.typeops +from mypy.argmap import ArgTypeExpander +from mypy.erasetype import erase_typevars +from mypy.maptype import map_instance_to_supertype +from mypy.nodes import ( + ARG_OPT, + ARG_POS, + ARG_STAR, + ARG_STAR2, + CONTRAVARIANT, + COVARIANT, + ArgKind, + TypeInfo, +) +from mypy.types import ( + TUPLE_LIKE_INSTANCE_NAMES, + AnyType, + CallableType, + DeletedType, + ErasedType, + Instance, + LiteralType, + NoneType, + NormalizedCallableType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + flatten_nested_tuples, + get_proper_type, + has_recursive_types, + has_type_vars, + is_named_instance, + split_with_prefix_and_suffix, +) +from mypy.types_utils import is_union_with_any +from mypy.typestate import type_state + +if TYPE_CHECKING: + from mypy.infer import ArgumentInferContext + +SUBTYPE_OF: Final = 0 +SUPERTYPE_OF: Final = 1 + + +class Constraint: + """A representation of a type constraint. + + It can be either T <: type or T :> type (T is a type variable). + """ + + type_var: TypeVarId + op = 0 # SUBTYPE_OF or SUPERTYPE_OF + target: Type + + def __init__(self, type_var: TypeVarLikeType, op: int, target: Type) -> None: + self.type_var = type_var.id + self.op = op + # TODO: should we add "assert not isinstance(target, UnpackType)"? + # UnpackType is a synthetic type, and is never valid as a constraint target. + self.target = target + self.origin_type_var = type_var + # These are additional type variables that should be solved for together with type_var. + # TODO: A cleaner solution may be to modify the return type of infer_constraints() + # to include these instead, but this is a rather big refactoring. + self.extra_tvars: list[TypeVarLikeType] = [] + + def __repr__(self) -> str: + op_str = "<:" + if self.op == SUPERTYPE_OF: + op_str = ":>" + return f"{self.type_var} {op_str} {self.target}" + + def __hash__(self) -> int: + return hash((self.type_var, self.op, self.target)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Constraint): + return False + return (self.type_var, self.op, self.target) == (other.type_var, other.op, other.target) + + +def infer_constraints_for_callable( + callee: CallableType, + arg_types: Sequence[Type | None], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + formal_to_actual: list[list[int]], + context: ArgumentInferContext, +) -> list[Constraint]: + """Infer type variable constraints for a callable and actual arguments. + + Return a list of constraints. + """ + constraints: list[Constraint] = [] + mapper = ArgTypeExpander(context) + + param_spec = callee.param_spec() + param_spec_arg_types = [] + param_spec_arg_names = [] + param_spec_arg_kinds: list[ArgKind] = [] + + incomplete_star_mapping = False + for i, actuals in enumerate(formal_to_actual): # TODO: isn't this `enumerate(arg_types)`? + for actual in actuals: + if actual is None and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2): # type: ignore[unreachable] + # We can't use arguments to infer ParamSpec constraint, if only some + # are present in the current inference pass. + incomplete_star_mapping = True # type: ignore[unreachable] + break + + for i, actuals in enumerate(formal_to_actual): + if isinstance(callee.arg_types[i], UnpackType): + unpack_type = callee.arg_types[i] + assert isinstance(unpack_type, UnpackType) + + # In this case we are binding all the actuals to *args, + # and we want a constraint that the typevar tuple being unpacked + # is equal to a type list of all the actuals. + actual_types = [] + + unpacked_type = get_proper_type(unpack_type.type) + if isinstance(unpacked_type, TypeVarTupleType): + tuple_instance = unpacked_type.tuple_fallback + elif isinstance(unpacked_type, TupleType): + tuple_instance = unpacked_type.partial_fallback + else: + assert False, "mypy bug: unhandled constraint inference case" + + for actual in actuals: + actual_arg_type = arg_types[actual] + if actual_arg_type is None: + continue + + expanded_actual = mapper.expand_actual_type( + actual_arg_type, + arg_kinds[actual], + callee.arg_names[i], + callee.arg_kinds[i], + allow_unpack=True, + ) + + if arg_kinds[actual] != ARG_STAR or isinstance( + get_proper_type(actual_arg_type), TupleType + ): + actual_types.append(expanded_actual) + else: + # If we are expanding an iterable inside * actual, append a homogeneous item instead + actual_types.append( + UnpackType(tuple_instance.copy_modified(args=[expanded_actual])) + ) + + if isinstance(unpacked_type, TypeVarTupleType): + constraints.append( + Constraint( + unpacked_type, + SUPERTYPE_OF, + TupleType(actual_types, unpacked_type.tuple_fallback), + ) + ) + elif isinstance(unpacked_type, TupleType): + # Prefixes get converted to positional args, so technically the only case we + # should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out + # not to hold we can always handle the prefixes too. + inner_unpack = unpacked_type.items[0] + assert isinstance(inner_unpack, UnpackType) + inner_unpacked_type = get_proper_type(inner_unpack.type) + suffix_len = len(unpacked_type.items) - 1 + if isinstance(inner_unpacked_type, TypeVarTupleType): + # Variadic item can be either *Ts... + constraints.append( + Constraint( + inner_unpacked_type, + SUPERTYPE_OF, + TupleType( + actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback + ), + ) + ) + else: + # ...or it can be a homogeneous tuple. + assert ( + isinstance(inner_unpacked_type, Instance) + and inner_unpacked_type.type.fullname == "builtins.tuple" + ) + for at in actual_types[:-suffix_len]: + constraints.extend( + infer_constraints(inner_unpacked_type.args[0], at, SUPERTYPE_OF) + ) + # Now handle the suffix (if any). + if suffix_len: + for tt, at in zip(unpacked_type.items[1:], actual_types[-suffix_len:]): + constraints.extend(infer_constraints(tt, at, SUPERTYPE_OF)) + else: + assert False, "mypy bug: unhandled constraint inference case" + else: + for actual in actuals: + actual_arg_type = arg_types[actual] + if actual_arg_type is None: + continue + + if param_spec and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2): + # If actual arguments are mapped to ParamSpec type, we can't infer individual + # constraints, instead store them and infer single constraint at the end. + # It is impossible to map actual kind to formal kind, so use some heuristic. + # This inference is used as a fallback, so relying on heuristic should be OK. + if not incomplete_star_mapping: + param_spec_arg_types.append( + mapper.expand_actual_type( + actual_arg_type, arg_kinds[actual], None, arg_kinds[actual] + ) + ) + actual_kind = arg_kinds[actual] + param_spec_arg_kinds.append( + ARG_POS if actual_kind not in (ARG_STAR, ARG_STAR2) else actual_kind + ) + param_spec_arg_names.append(arg_names[actual] if arg_names else None) + else: + actual_type = mapper.expand_actual_type( + actual_arg_type, + arg_kinds[actual], + callee.arg_names[i], + callee.arg_kinds[i], + ) + c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF) + constraints.extend(c) + if ( + param_spec + and not any(c.type_var == param_spec.id for c in constraints) + and not incomplete_star_mapping + ): + # Use ParamSpec constraint from arguments only if there are no other constraints, + # since as explained above it is quite ad-hoc. + constraints.append( + Constraint( + param_spec, + SUPERTYPE_OF, + Parameters( + arg_types=param_spec_arg_types, + arg_kinds=param_spec_arg_kinds, + arg_names=param_spec_arg_names, + imprecise_arg_kinds=True, + ), + ) + ) + if any(isinstance(v, ParamSpecType) for v in callee.variables): + # As a perf optimization filter imprecise constraints only when we can have them. + constraints = filter_imprecise_kinds(constraints) + return constraints + + +def infer_constraints( + template: Type, actual: Type, direction: int, skip_neg_op: bool = False +) -> list[Constraint]: + """Infer type constraints. + + Match a template type, which may contain type variable references, + recursively against a type which does not contain (the same) type + variable references. The result is a list of type constrains of + form 'T is a supertype/subtype of x', where T is a type variable + present in the template and x is a type without reference to type + variables present in the template. + + Assume T and S are type variables. Now the following results can be + calculated (read as '(template, actual) --> result'): + + (T, X) --> T :> X + (X[T], X[Y]) --> T <: Y and T :> Y + ((T, T), (X, Y)) --> T :> X and T :> Y + ((T, S), (X, Y)) --> T :> X and S :> Y + (X[T], Any) --> T <: Any and T :> Any + + The constraints are represented as Constraint objects. If skip_neg_op == True, + then skip adding reverse (polymorphic) constraints (since this is already a call + to infer such constraints). + """ + if any( + get_proper_type(template) == get_proper_type(t) + and get_proper_type(actual) == get_proper_type(a) + for (t, a) in reversed(type_state.inferring) + ): + return [] + if has_recursive_types(template) or isinstance(get_proper_type(template), Instance): + # This case requires special care because it may cause infinite recursion. + # Note that we include Instances because the may be recursive as str(Sequence[str]). + if not has_type_vars(template): + # Return early on an empty branch. + return [] + type_state.inferring.append((template, actual)) + res = _infer_constraints(template, actual, direction, skip_neg_op) + type_state.inferring.pop() + return res + return _infer_constraints(template, actual, direction, skip_neg_op) + + +def _infer_constraints( + template: Type, actual: Type, direction: int, skip_neg_op: bool +) -> list[Constraint]: + orig_template = template + template = get_proper_type(template) + actual = get_proper_type(actual) + + # Type inference shouldn't be affected by whether union types have been simplified. + # We however keep any ErasedType items, so that the caller will see it when using + # checkexpr.has_erased_component(). + if isinstance(template, UnionType): + template = mypy.typeops.make_simplified_union(template.items, keep_erased=True) + if isinstance(actual, UnionType): + actual = mypy.typeops.make_simplified_union(actual.items, keep_erased=True) + + # Ignore Any types from the type suggestion engine to avoid them + # causing us to infer Any in situations where a better job could + # be done otherwise. (This can produce false positives but that + # doesn't really matter because it is all heuristic anyway.) + if isinstance(actual, AnyType) and actual.type_of_any == TypeOfAny.suggestion_engine: + return [] + + # type[A | B] is always represented as type[A] | type[B] internally. + # This makes our constraint solver choke on type[T] <: type[A] | type[B], + # solving T as generic meet(A, B) which is often `object`. Force unwrap such unions + # if both sides are type[...] or unions thereof. See `testTypeVarType` test + type_type_unwrapped = False + if _is_type_type(template) and _is_type_type(actual): + type_type_unwrapped = True + template = _unwrap_type_type(template) + actual = _unwrap_type_type(actual) + + # If the template is simply a type variable, emit a Constraint directly. + # We need to handle this case before handling Unions for two reasons: + # 1. "T <: Union[U1, U2]" is not equivalent to "T <: U1 or T <: U2", + # because T can itself be a union (notably, Union[U1, U2] itself). + # 2. "T :> Union[U1, U2]" is logically equivalent to "T :> U1 and + # T :> U2", but they are not equivalent to the constraint solver, + # which never introduces new Union types (it uses join() instead). + if isinstance(template, TypeVarType): + return [Constraint(template, direction, actual)] + + if ( + isinstance(actual, TypeVarType) + and not actual.id.is_meta_var() + and direction == SUPERTYPE_OF + ): + # Unless template is also a type variable (or a union that contains one), using the upper + # bound for inference will usually give better result for actual that is a type variable. + if not isinstance(template, UnionType) or not any( + isinstance(t, TypeVarType) for t in template.items + ): + actual = get_proper_type(actual.upper_bound) + + # Now handle the case of either template or actual being a Union. + # For a Union to be a subtype of another type, every item of the Union + # must be a subtype of that type, so concatenate the constraints. + if direction == SUBTYPE_OF and isinstance(template, UnionType): + res = [] + for t_item in template.items: + res.extend(infer_constraints(t_item, actual, direction)) + return res + if direction == SUPERTYPE_OF and isinstance(actual, UnionType): + res = [] + for a_item in actual.items: + # `orig_template` has to be preserved intact in case it's recursive. + # If we unwrapped ``type[...]`` previously, wrap the item back again, + # as ``type[...]`` can't be removed from `orig_template`. + if type_type_unwrapped: + a_item = TypeType.make_normalized(a_item) + res.extend(infer_constraints(orig_template, a_item, direction)) + return res + + # Now the potential subtype is known not to be a Union or a type + # variable that we are solving for. In that case, for a Union to + # be a supertype of the potential subtype, some item of the Union + # must be a supertype of it. + if direction == SUBTYPE_OF and isinstance(actual, UnionType): + # We infer constraints eagerly -- try to find constraints for a type + # variable if possible. This seems to help with some real-world + # use cases. + return any_constraints( + [ + infer_constraints_if_possible(template, a_item, direction) + for a_item in actual.items + ], + eager=True, + ) + if direction == SUPERTYPE_OF and isinstance(template, UnionType): + # When the template is a union, we are okay with leaving some + # type variables indeterminate. This helps with some special + # cases, though this isn't very principled. + result = any_constraints( + [ + infer_constraints_if_possible(t_item, actual, direction) + for t_item in template.items + ], + eager=isinstance(actual, AnyType), + ) + if result: + return result + elif has_recursive_types(template) and not has_recursive_types(actual): + return handle_recursive_union(template, actual, direction) + return [] + + # Remaining cases are handled by ConstraintBuilderVisitor. + return template.accept(ConstraintBuilderVisitor(actual, direction, skip_neg_op)) + + +def _is_type_type(tp: ProperType) -> TypeGuard[TypeType | UnionType]: + """Is ``tp`` a ``type[...]`` or a union thereof? + + ``Type[A | B]`` is internally represented as ``type[A] | type[B]``, and this + troubles the solver sometimes. + """ + return ( + isinstance(tp, TypeType) + or isinstance(tp, UnionType) + and all(isinstance(get_proper_type(o), TypeType) for o in tp.items) + ) + + +def _unwrap_type_type(tp: TypeType | UnionType) -> ProperType: + """Extract the inner type from ``type[...]`` expression or a union thereof.""" + if isinstance(tp, TypeType): + return tp.item + return UnionType.make_union([cast(TypeType, get_proper_type(o)).item for o in tp.items]) + + +def infer_constraints_if_possible( + template: Type, actual: Type, direction: int +) -> list[Constraint] | None: + """Like infer_constraints, but return None if the input relation is + known to be unsatisfiable, for example if template=List[T] and actual=int. + (In this case infer_constraints would return [], just like it would for + an automatically satisfied relation like template=List[T] and actual=object.) + """ + if direction == SUBTYPE_OF and not mypy.subtypes.is_subtype(erase_typevars(template), actual): + return None + if direction == SUPERTYPE_OF and not mypy.subtypes.is_subtype( + actual, erase_typevars(template) + ): + return None + if ( + direction == SUPERTYPE_OF + and isinstance(template, TypeVarType) + and not mypy.subtypes.is_subtype(actual, erase_typevars(template.upper_bound)) + ): + # This is not caught by the above branch because of the erase_typevars() call, + # that would return 'Any' for a type variable. + return None + return infer_constraints(template, actual, direction) + + +def select_trivial(options: Sequence[list[Constraint] | None]) -> list[list[Constraint]]: + """Select only those lists where each item is a constraint against Any.""" + res = [] + for option in options: + if option is None: + continue + if all(isinstance(get_proper_type(c.target), AnyType) for c in option): + res.append(option) + return res + + +def merge_with_any(constraint: Constraint) -> Constraint: + """Transform a constraint target into a union with given Any type.""" + target = constraint.target + if is_union_with_any(target): + # Do not produce redundant unions. + return constraint + # TODO: if we will support multiple sources Any, use this here instead. + any_type = AnyType(TypeOfAny.implementation_artifact) + return Constraint( + constraint.origin_type_var, + constraint.op, + UnionType.make_union([target, any_type], target.line, target.column), + ) + + +def handle_recursive_union(template: UnionType, actual: Type, direction: int) -> list[Constraint]: + # This is a hack to special-case things like Union[T, Inst[T]] in recursive types. Although + # it is quite arbitrary, it is a relatively common pattern, so we should handle it well. + # This function may be called when inferring against such union resulted in different + # constraints for each item. Normally we give up in such case, but here we instead split + # the union in two parts, and try inferring sequentially. + non_type_var_items = [t for t in template.items if not isinstance(t, TypeVarType)] + type_var_items = [t for t in template.items if isinstance(t, TypeVarType)] + return infer_constraints( + UnionType.make_union(non_type_var_items), actual, direction + ) or infer_constraints(UnionType.make_union(type_var_items), actual, direction) + + +def any_constraints(options: list[list[Constraint] | None], *, eager: bool) -> list[Constraint]: + """Deduce what we can from a collection of constraint lists. + + It's a given that at least one of the lists must be satisfied. A + None element in the list of options represents an unsatisfiable + constraint and is ignored. Ignore empty constraint lists if eager + is true -- they are always trivially satisfiable. + """ + if eager: + valid_options = [option for option in options if option] + else: + valid_options = [option for option in options if option is not None] + + if not valid_options: + return [] + + if len(valid_options) == 1: + return valid_options[0] + + if all(is_same_constraints(valid_options[0], c) for c in valid_options[1:]): + # Multiple sets of constraints that are all the same. Just pick any one of them. + return valid_options[0] + + if all(is_similar_constraints(valid_options[0], c) for c in valid_options[1:]): + # All options have same structure. In this case we can merge-in trivial + # options (i.e. those that only have Any) and try again. + # TODO: More generally, if a given (variable, direction) pair appears in + # every option, combine the bounds with meet/join always, not just for Any. + trivial_options = select_trivial(valid_options) + if trivial_options and len(trivial_options) < len(valid_options): + merged_options = [] + for option in valid_options: + if option in trivial_options: + continue + merged_options.append([merge_with_any(c) for c in option]) + return any_constraints(list(merged_options), eager=eager) + + # If normal logic didn't work, try excluding trivially unsatisfiable constraint (due to + # upper bounds) from each option, and comparing them again. + filtered_options = [filter_satisfiable(o) for o in options] + if filtered_options != options: + return any_constraints(filtered_options, eager=eager) + + # Try harder: if that didn't work, try to strip typevars that aren't meta vars. + # Note this is what we would always do, but unfortunately some callers may not + # set the meta var status correctly (for historical reasons), so we use this as + # a fallback only. + filtered_options = [exclude_non_meta_vars(o) for o in options] + if filtered_options != options: + return any_constraints(filtered_options, eager=eager) + + # Otherwise, there are either no valid options or multiple, inconsistent valid + # options. Give up and deduce nothing. + return [] + + +def filter_satisfiable(option: list[Constraint] | None) -> list[Constraint] | None: + """Keep only constraints that can possibly be satisfied. + + Currently, we filter out constraints where target is not a subtype of the upper bound. + Since those can be never satisfied. We may add more cases in future if it improves type + inference. + """ + if not option: + return option + + satisfiable = [] + for c in option: + if isinstance(c.origin_type_var, TypeVarType) and c.origin_type_var.values: + if any( + mypy.subtypes.is_subtype(c.target, value) for value in c.origin_type_var.values + ): + satisfiable.append(c) + elif mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound): + satisfiable.append(c) + if not satisfiable: + return None + return satisfiable + + +def exclude_non_meta_vars(option: list[Constraint] | None) -> list[Constraint] | None: + # If we had an empty list, keep it intact + if not option: + return option + # However, if none of the options actually references meta vars, better remove + # this constraint entirely. + return [c for c in option if c.type_var.is_meta_var()] or None + + +def is_same_constraints(x: list[Constraint], y: list[Constraint]) -> bool: + for c1 in x: + if not any(is_same_constraint(c1, c2) for c2 in y): + return False + for c1 in y: + if not any(is_same_constraint(c1, c2) for c2 in x): + return False + return True + + +def is_same_constraint(c1: Constraint, c2: Constraint) -> bool: + # Ignore direction when comparing constraints against Any. + skip_op_check = isinstance(get_proper_type(c1.target), AnyType) and isinstance( + get_proper_type(c2.target), AnyType + ) + return ( + c1.type_var == c2.type_var + and (c1.op == c2.op or skip_op_check) + and mypy.subtypes.is_same_type(c1.target, c2.target) + ) + + +def is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool: + """Check that two lists of constraints have similar structure. + + This means that each list has same type variable plus direction pairs (i.e we + ignore the target). Except for constraints where target is Any type, there + we ignore direction as well. + """ + return _is_similar_constraints(x, y) and _is_similar_constraints(y, x) + + +def _is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool: + """Check that every constraint in the first list has a similar one in the second. + + See docstring above for definition of similarity. + """ + for c1 in x: + has_similar = False + for c2 in y: + # Ignore direction when either constraint is against Any. + skip_op_check = isinstance(get_proper_type(c1.target), AnyType) or isinstance( + get_proper_type(c2.target), AnyType + ) + if c1.type_var == c2.type_var and (c1.op == c2.op or skip_op_check): + has_similar = True + break + if not has_similar: + return False + return True + + +class ConstraintBuilderVisitor(TypeVisitor[list[Constraint]]): + """Visitor class for inferring type constraints.""" + + # The type that is compared against a template + # TODO: The value may be None. Is that actually correct? + actual: ProperType + + def __init__(self, actual: ProperType, direction: int, skip_neg_op: bool) -> None: + # Direction must be SUBTYPE_OF or SUPERTYPE_OF. + self.actual = actual + self.direction = direction + # Whether to skip polymorphic inference (involves inference in opposite direction) + # this is used to prevent infinite recursion when both template and actual are + # generic callables. + self.skip_neg_op = skip_neg_op + + # Trivial leaf types + + def visit_unbound_type(self, template: UnboundType) -> list[Constraint]: + return [] + + def visit_any(self, template: AnyType) -> list[Constraint]: + return [] + + def visit_none_type(self, template: NoneType) -> list[Constraint]: + return [] + + def visit_uninhabited_type(self, template: UninhabitedType) -> list[Constraint]: + return [] + + def visit_erased_type(self, template: ErasedType) -> list[Constraint]: + return [] + + def visit_deleted_type(self, template: DeletedType) -> list[Constraint]: + return [] + + def visit_literal_type(self, template: LiteralType) -> list[Constraint]: + return [] + + # Errors + + def visit_partial_type(self, template: PartialType) -> list[Constraint]: + # We can't do anything useful with a partial type here. + assert False, "Internal error" + + # Non-trivial leaf type + + def visit_type_var(self, template: TypeVarType) -> list[Constraint]: + assert False, ( + "Unexpected TypeVarType in ConstraintBuilderVisitor" + " (should have been handled in infer_constraints)" + ) + + def visit_param_spec(self, template: ParamSpecType) -> list[Constraint]: + # Can't infer ParamSpecs from component values (only via Callable[P, T]). + return [] + + def visit_type_var_tuple(self, template: TypeVarTupleType) -> list[Constraint]: + raise NotImplementedError + + def visit_unpack_type(self, template: UnpackType) -> list[Constraint]: + raise RuntimeError("Mypy bug: unpack should be handled at a higher level.") + + def visit_parameters(self, template: Parameters) -> list[Constraint]: + # Constraining Any against C[P] turns into infer_against_any([P], Any) + if isinstance(self.actual, AnyType): + return self.infer_against_any(template.arg_types, self.actual) + if type_state.infer_polymorphic and isinstance(self.actual, Parameters): + # For polymorphic inference we need to be able to infer secondary constraints + # in situations like [x: T] <: P <: [x: int]. + return infer_callable_arguments_constraints(template, self.actual, self.direction) + if type_state.infer_polymorphic and isinstance(self.actual, ParamSpecType): + # Similar for [x: T] <: Q <: Concatenate[int, P]. + return infer_callable_arguments_constraints( + template, self.actual.prefix, self.direction + ) + # There also may be unpatched types after a user error, simply ignore them. + return [] + + # Non-leaf types + + def visit_instance(self, template: Instance) -> list[Constraint]: + original_actual = actual = self.actual + res: list[Constraint] = [] + if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol: + if "__call__" in template.type.protocol_members: + # Special case: a generic callback protocol + if not any(template == t for t in template.type.inferring): + template.type.inferring.append(template) + call = mypy.subtypes.find_member( + "__call__", template, actual, is_operator=True + ) + assert call is not None + if ( + self.direction == SUPERTYPE_OF + and mypy.subtypes.is_subtype(actual, erase_typevars(call)) + or self.direction == SUBTYPE_OF + and mypy.subtypes.is_subtype(erase_typevars(call), actual) + ): + res.extend(infer_constraints(call, actual, self.direction)) + template.type.inferring.pop() + if isinstance(actual, CallableType) and actual.fallback is not None: + if ( + actual.is_type_obj() + and template.type.is_protocol + and self.direction == SUPERTYPE_OF + ): + ret_type = get_proper_type(actual.ret_type) + if isinstance(ret_type, TupleType): + ret_type = mypy.typeops.tuple_fallback(ret_type) + if isinstance(ret_type, Instance): + res.extend( + self.infer_constraints_from_protocol_members( + ret_type, template, ret_type, template, class_obj=True + ) + ) + actual = actual.fallback + if isinstance(actual, TypeType) and template.type.is_protocol: + if self.direction == SUPERTYPE_OF: + a_item = actual.item + if isinstance(a_item, Instance): + res.extend( + self.infer_constraints_from_protocol_members( + a_item, template, a_item, template, class_obj=True + ) + ) + # Infer constraints for Type[T] via metaclass of T when it makes sense. + if isinstance(a_item, TypeVarType): + a_item = get_proper_type(a_item.upper_bound) + if isinstance(a_item, Instance) and a_item.type.metaclass_type: + res.extend( + self.infer_constraints_from_protocol_members( + a_item.type.metaclass_type, template, actual, template + ) + ) + + if isinstance(actual, Overloaded) and actual.fallback is not None: + actual = actual.fallback + if isinstance(actual, TypedDictType): + actual = actual.create_anonymous_fallback() + if isinstance(actual, LiteralType): + actual = actual.fallback + if isinstance(actual, Instance): + instance = actual + erased = erase_typevars(template) + assert isinstance(erased, Instance) # type: ignore[misc] + # We always try nominal inference if possible, + # it is much faster than the structural one. + if self.direction == SUBTYPE_OF and template.type.has_base(instance.type.fullname): + mapped = map_instance_to_supertype(template, instance.type) + tvars = mapped.type.defn.type_vars + + if instance.type.has_type_var_tuple_type: + # Variadic types need special handling to map each type argument to + # the correct corresponding type variable. + assert instance.type.type_var_tuple_prefix is not None + assert instance.type.type_var_tuple_suffix is not None + prefix_len = instance.type.type_var_tuple_prefix + suffix_len = instance.type.type_var_tuple_suffix + tvt = instance.type.defn.type_vars[prefix_len] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + i_prefix, i_middle, i_suffix = split_with_prefix_and_suffix( + instance.args, prefix_len, suffix_len + ) + m_prefix, m_middle, m_suffix = split_with_prefix_and_suffix( + mapped.args, prefix_len, suffix_len + ) + instance_args = i_prefix + (TupleType(list(i_middle), fallback),) + i_suffix + mapped_args = m_prefix + (TupleType(list(m_middle), fallback),) + m_suffix + else: + mapped_args = mapped.args + instance_args = instance.args + + # N.B: We use zip instead of indexing because the lengths might have + # mismatches during daemon reprocessing. + for tvar, mapped_arg, instance_arg in zip(tvars, mapped_args, instance_args): + if isinstance(tvar, TypeVarType): + # The constraints for generic type parameters depend on variance. + # Include constraints from both directions if invariant. + if tvar.variance != CONTRAVARIANT: + res.extend(infer_constraints(mapped_arg, instance_arg, self.direction)) + if tvar.variance != COVARIANT: + res.extend( + infer_constraints(mapped_arg, instance_arg, neg_op(self.direction)) + ) + elif isinstance(tvar, ParamSpecType) and isinstance(mapped_arg, ParamSpecType): + prefix = mapped_arg.prefix + if isinstance(instance_arg, Parameters): + # No such thing as variance for ParamSpecs, consider them invariant + # TODO: constraints between prefixes using + # infer_callable_arguments_constraints() + suffix: Type = instance_arg.copy_modified( + instance_arg.arg_types[len(prefix.arg_types) :], + instance_arg.arg_kinds[len(prefix.arg_kinds) :], + instance_arg.arg_names[len(prefix.arg_names) :], + ) + res.append(Constraint(mapped_arg, SUBTYPE_OF, suffix)) + res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix)) + elif isinstance(instance_arg, ParamSpecType): + suffix = instance_arg.copy_modified( + prefix=Parameters( + instance_arg.prefix.arg_types[len(prefix.arg_types) :], + instance_arg.prefix.arg_kinds[len(prefix.arg_kinds) :], + instance_arg.prefix.arg_names[len(prefix.arg_names) :], + ) + ) + res.append(Constraint(mapped_arg, SUBTYPE_OF, suffix)) + res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix)) + elif isinstance(tvar, TypeVarTupleType): + # Handle variadic type variables covariantly for consistency. + res.extend(infer_constraints(mapped_arg, instance_arg, self.direction)) + + return res + elif self.direction == SUPERTYPE_OF and instance.type.has_base(template.type.fullname): + mapped = map_instance_to_supertype(instance, template.type) + tvars = template.type.defn.type_vars + if template.type.has_type_var_tuple_type: + # Variadic types need special handling to map each type argument to + # the correct corresponding type variable. + assert template.type.type_var_tuple_prefix is not None + assert template.type.type_var_tuple_suffix is not None + prefix_len = template.type.type_var_tuple_prefix + suffix_len = template.type.type_var_tuple_suffix + tvt = template.type.defn.type_vars[prefix_len] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix( + template.args, prefix_len, suffix_len + ) + m_prefix, m_middle, m_suffix = split_with_prefix_and_suffix( + mapped.args, prefix_len, suffix_len + ) + template_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix + mapped_args = m_prefix + (TupleType(list(m_middle), fallback),) + m_suffix + else: + mapped_args = mapped.args + template_args = template.args + # N.B: We use zip instead of indexing because the lengths might have + # mismatches during daemon reprocessing. + for tvar, mapped_arg, template_arg in zip(tvars, mapped_args, template_args): + if isinstance(tvar, TypeVarType): + # The constraints for generic type parameters depend on variance. + # Include constraints from both directions if invariant. + if tvar.variance != CONTRAVARIANT: + res.extend(infer_constraints(template_arg, mapped_arg, self.direction)) + if tvar.variance != COVARIANT: + res.extend( + infer_constraints(template_arg, mapped_arg, neg_op(self.direction)) + ) + elif isinstance(tvar, ParamSpecType) and isinstance( + template_arg, ParamSpecType + ): + prefix = template_arg.prefix + if isinstance(mapped_arg, Parameters): + # No such thing as variance for ParamSpecs, consider them invariant + # TODO: constraints between prefixes using + # infer_callable_arguments_constraints() + suffix = mapped_arg.copy_modified( + mapped_arg.arg_types[len(prefix.arg_types) :], + mapped_arg.arg_kinds[len(prefix.arg_kinds) :], + mapped_arg.arg_names[len(prefix.arg_names) :], + ) + res.append(Constraint(template_arg, SUBTYPE_OF, suffix)) + res.append(Constraint(template_arg, SUPERTYPE_OF, suffix)) + elif isinstance(mapped_arg, ParamSpecType): + suffix = mapped_arg.copy_modified( + prefix=Parameters( + mapped_arg.prefix.arg_types[len(prefix.arg_types) :], + mapped_arg.prefix.arg_kinds[len(prefix.arg_kinds) :], + mapped_arg.prefix.arg_names[len(prefix.arg_names) :], + ) + ) + res.append(Constraint(template_arg, SUBTYPE_OF, suffix)) + res.append(Constraint(template_arg, SUPERTYPE_OF, suffix)) + elif isinstance(tvar, TypeVarTupleType): + # Consider variadic type variables to be invariant. + res.extend(infer_constraints(template_arg, mapped_arg, SUBTYPE_OF)) + res.extend(infer_constraints(template_arg, mapped_arg, SUPERTYPE_OF)) + return res + if ( + template.type.is_protocol + and self.direction == SUPERTYPE_OF + and + # We avoid infinite recursion for structural subtypes by checking + # whether this type already appeared in the inference chain. + # This is a conservative way to break the inference cycles. + # It never produces any "false" constraints but gives up soon + # on purely structural inference cycles, see #3829. + # Note that we use is_protocol_implementation instead of is_subtype + # because some type may be considered a subtype of a protocol + # due to _promote, but still not implement the protocol. + not any(template == t for t in reversed(template.type.inferring)) + and mypy.subtypes.is_protocol_implementation(instance, erased, skip=["__call__"]) + ): + template.type.inferring.append(template) + res.extend( + self.infer_constraints_from_protocol_members( + instance, template, original_actual, template + ) + ) + template.type.inferring.pop() + return res + elif ( + instance.type.is_protocol + and self.direction == SUBTYPE_OF + and + # We avoid infinite recursion for structural subtypes also here. + not any(instance == i for i in reversed(instance.type.inferring)) + and mypy.subtypes.is_protocol_implementation(erased, instance, skip=["__call__"]) + ): + instance.type.inferring.append(instance) + res.extend( + self.infer_constraints_from_protocol_members( + instance, template, template, instance + ) + ) + instance.type.inferring.pop() + return res + if res: + return res + + if isinstance(actual, AnyType): + return self.infer_against_any(template.args, actual) + if ( + isinstance(actual, TupleType) + and is_named_instance(template, TUPLE_LIKE_INSTANCE_NAMES) + and self.direction == SUPERTYPE_OF + ): + for item in actual.items: + if isinstance(item, UnpackType): + unpacked = get_proper_type(item.type) + if isinstance(unpacked, TypeVarTupleType): + # Cannot infer anything for T from [T, ...] <: *Ts + continue + assert ( + isinstance(unpacked, Instance) + and unpacked.type.fullname == "builtins.tuple" + ) + item = unpacked.args[0] + cb = infer_constraints(template.args[0], item, SUPERTYPE_OF) + res.extend(cb) + return res + elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF: + return infer_constraints(template, mypy.typeops.tuple_fallback(actual), self.direction) + elif isinstance(actual, TypeVarType): + if not actual.values and not actual.id.is_meta_var(): + return infer_constraints(template, actual.upper_bound, self.direction) + return [] + elif isinstance(actual, ParamSpecType): + return infer_constraints(template, actual.upper_bound, self.direction) + elif isinstance(actual, TypeVarTupleType): + raise NotImplementedError + else: + return [] + + def infer_constraints_from_protocol_members( + self, + instance: Instance, + template: Instance, + subtype: Type, + protocol: Instance, + class_obj: bool = False, + ) -> list[Constraint]: + """Infer constraints for situations where either 'template' or 'instance' is a protocol. + + The 'protocol' is the one of two that is an instance of protocol type, 'subtype' + is the type used to bind self during inference. Currently, we just infer constrains for + every protocol member type (both ways for settable members). + """ + res = [] + for member in protocol.type.protocol_members: + inst = mypy.subtypes.find_member(member, instance, subtype, class_obj=class_obj) + temp = mypy.subtypes.find_member(member, template, subtype) + if inst is None or temp is None: + if member == "__call__": + continue + return [] # See #11020 + # The above is safe since at this point we know that 'instance' is a subtype + # of (erased) 'template', therefore it defines all protocol members + if class_obj: + # For class objects we must only infer constraints if possible, otherwise it + # can lead to confusion between class and instance, for example StrEnum is + # Iterable[str] for an instance, but Iterable[StrEnum] for a class object. + if not mypy.subtypes.is_subtype( + inst, erase_typevars(temp), ignore_pos_arg_names=True + ): + continue + # This exception matches the one in typeops.py, see PR #14121 for context. + if member == "__call__" and instance.type.is_metaclass(precise=True): + continue + res.extend(infer_constraints(temp, inst, self.direction)) + if mypy.subtypes.IS_SETTABLE in mypy.subtypes.get_member_flags(member, protocol): + # Settable members are invariant, add opposite constraints + res.extend(infer_constraints(temp, inst, neg_op(self.direction))) + return res + + def visit_callable_type(self, template: CallableType) -> list[Constraint]: + # Normalize callables before matching against each other. + # Note that non-normalized callables can be created in annotations + # using e.g. callback protocols. + # TODO: check that callables match? Ideally we should not infer constraints + # callables that can never be subtypes of one another in given direction. + template = template.with_unpacked_kwargs().with_normalized_var_args() + extra_tvars = False + if isinstance(self.actual, CallableType): + res: list[Constraint] = [] + cactual = self.actual.with_unpacked_kwargs().with_normalized_var_args() + param_spec = template.param_spec() + + template_ret_type, cactual_ret_type = template.ret_type, cactual.ret_type + if template.type_guard is not None and cactual.type_guard is not None: + template_ret_type = template.type_guard + cactual_ret_type = cactual.type_guard + + if template.type_is is not None and cactual.type_is is not None: + template_ret_type = template.type_is + cactual_ret_type = cactual.type_is + + res.extend(infer_constraints(template_ret_type, cactual_ret_type, self.direction)) + + if param_spec is None: + # TODO: Erase template variables if it is generic? + if ( + type_state.infer_polymorphic + and cactual.variables + and not self.skip_neg_op + # Technically, the correct inferred type for application of e.g. + # Callable[..., T] -> Callable[..., T] (with literal ellipsis), to a generic + # like U -> U, should be Callable[..., Any], but if U is a self-type, we can + # allow it to leak, to be later bound to self. A bunch of existing code + # depends on this old behaviour. + and not ( + any(tv.id.is_self() for tv in cactual.variables) + and template.is_ellipsis_args + ) + ): + # If the actual callable is generic, infer constraints in the opposite + # direction, and indicate to the solver there are extra type variables + # to solve for (see more details in mypy/solve.py). + res.extend( + infer_constraints( + cactual, template, neg_op(self.direction), skip_neg_op=True + ) + ) + extra_tvars = True + + # We can't infer constraints from arguments if the template is Callable[..., T] + # (with literal '...'). + if not template.is_ellipsis_args: + unpack_present = find_unpack_in_list(template.arg_types) + # When both ParamSpec and TypeVarTuple are present, things become messy + # quickly. For now, we only allow ParamSpec to "capture" TypeVarTuple, + # but not vice versa. + # TODO: infer more from prefixes when possible. + if unpack_present is not None and not cactual.param_spec(): + # We need to re-normalize args to the form they appear in tuples, + # for callables we always pack the suffix inside another tuple. + unpack = template.arg_types[unpack_present] + assert isinstance(unpack, UnpackType) + tuple_type = get_tuple_fallback_from_unpack(unpack) + template_types = repack_callable_args(template, tuple_type) + actual_types = repack_callable_args(cactual, tuple_type) + # Now we can use the same general helper as for tuple types. + unpack_constraints = build_constraints_for_simple_unpack( + template_types, actual_types, neg_op(self.direction) + ) + res.extend(unpack_constraints) + else: + # TODO: do we need some special-casing when unpack is present in actual + # callable but not in template callable? + res.extend( + infer_callable_arguments_constraints(template, cactual, self.direction) + ) + else: + prefix = param_spec.prefix + prefix_len = len(prefix.arg_types) + cactual_ps = cactual.param_spec() + + if type_state.infer_polymorphic and cactual.variables and not self.skip_neg_op: + # Similar logic to the branch above. + res.extend( + infer_constraints( + cactual, template, neg_op(self.direction), skip_neg_op=True + ) + ) + extra_tvars = True + + # Compare prefixes as well + cactual_prefix = cactual.copy_modified( + arg_types=cactual.arg_types[:prefix_len], + arg_kinds=cactual.arg_kinds[:prefix_len], + arg_names=cactual.arg_names[:prefix_len], + ) + res.extend( + infer_callable_arguments_constraints(prefix, cactual_prefix, self.direction) + ) + + param_spec_target: Type | None = None + if not cactual_ps: + max_prefix_len = len([k for k in cactual.arg_kinds if k in (ARG_POS, ARG_OPT)]) + prefix_len = min(prefix_len, max_prefix_len) + param_spec_target = Parameters( + arg_types=cactual.arg_types[prefix_len:], + arg_kinds=cactual.arg_kinds[prefix_len:], + arg_names=cactual.arg_names[prefix_len:], + variables=cactual.variables if not type_state.infer_polymorphic else [], + imprecise_arg_kinds=cactual.imprecise_arg_kinds, + ) + else: + if len(param_spec.prefix.arg_types) <= len(cactual_ps.prefix.arg_types): + param_spec_target = cactual_ps.copy_modified( + prefix=Parameters( + arg_types=cactual_ps.prefix.arg_types[prefix_len:], + arg_kinds=cactual_ps.prefix.arg_kinds[prefix_len:], + arg_names=cactual_ps.prefix.arg_names[prefix_len:], + imprecise_arg_kinds=cactual_ps.prefix.imprecise_arg_kinds, + ) + ) + if param_spec_target is not None: + res.append(Constraint(param_spec, self.direction, param_spec_target)) + if extra_tvars: + for c in res: + c.extra_tvars += cactual.variables + return res + elif isinstance(self.actual, AnyType): + param_spec = template.param_spec() + any_type = AnyType(TypeOfAny.from_another_any, source_any=self.actual) + if param_spec is None: + # FIX what if generic + res = self.infer_against_any(template.arg_types, self.actual) + else: + res = [ + Constraint( + param_spec, + SUBTYPE_OF, + Parameters([any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None]), + ) + ] + res.extend(infer_constraints(template.ret_type, any_type, self.direction)) + return res + elif isinstance(self.actual, Overloaded): + return self.infer_against_overloaded(self.actual, template) + elif isinstance(self.actual, TypeType): + return infer_constraints(template.ret_type, self.actual.item, self.direction) + elif isinstance(self.actual, Instance): + # Instances with __call__ method defined are considered structural + # subtypes of Callable with a compatible signature. + call = mypy.subtypes.find_member( + "__call__", self.actual, self.actual, is_operator=True + ) + if call: + return infer_constraints(template, call, self.direction) + else: + return [] + else: + return [] + + def infer_against_overloaded( + self, overloaded: Overloaded, template: CallableType + ) -> list[Constraint]: + # Create constraints by matching an overloaded type against a template. + # This is tricky to do in general. We cheat by only matching against + # the first overload item that is callable compatible. This + # seems to work somewhat well, but we should really use a more + # reliable technique. + item = find_matching_overload_item(overloaded, template) + return infer_constraints(template, item, self.direction) + + def visit_tuple_type(self, template: TupleType) -> list[Constraint]: + actual = self.actual + unpack_index = find_unpack_in_list(template.items) + is_varlength_tuple = ( + isinstance(actual, Instance) and actual.type.fullname == "builtins.tuple" + ) + + if isinstance(actual, TupleType) or is_varlength_tuple: + res: list[Constraint] = [] + if unpack_index is not None: + if is_varlength_tuple: + # Variadic tuple can be only a supertype of a tuple type, but even if + # direction is opposite, inferring something may give better error messages. + unpack_type = template.items[unpack_index] + assert isinstance(unpack_type, UnpackType) + unpacked_type = get_proper_type(unpack_type.type) + if isinstance(unpacked_type, TypeVarTupleType): + res = [ + Constraint(type_var=unpacked_type, op=self.direction, target=actual) + ] + else: + assert ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ) + res = infer_constraints(unpacked_type, actual, self.direction) + assert isinstance(actual, Instance) # ensured by is_varlength_tuple == True + for i, ti in enumerate(template.items): + if i == unpack_index: + # This one we just handled above. + continue + # For Tuple[T, *Ts, S] <: tuple[X, ...] infer also T <: X and S <: X. + res.extend(infer_constraints(ti, actual.args[0], self.direction)) + return res + else: + assert isinstance(actual, TupleType) + unpack_constraints = build_constraints_for_simple_unpack( + template.items, actual.items, self.direction + ) + actual_items: tuple[Type, ...] = () + template_items: tuple[Type, ...] = () + res.extend(unpack_constraints) + elif isinstance(actual, TupleType): + a_unpack_index = find_unpack_in_list(actual.items) + if a_unpack_index is not None: + # The case where template tuple doesn't have an unpack, but actual tuple + # has an unpack. We can infer something if actual unpack is a variadic tuple. + # Tuple[T, S, U] <: tuple[X, *tuple[Y, ...], Z] => T <: X, S <: Y, U <: Z. + a_unpack = actual.items[a_unpack_index] + assert isinstance(a_unpack, UnpackType) + a_unpacked = get_proper_type(a_unpack.type) + if len(actual.items) + 1 <= len(template.items): + a_prefix_len = a_unpack_index + a_suffix_len = len(actual.items) - a_unpack_index - 1 + t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix( + tuple(template.items), a_prefix_len, a_suffix_len + ) + actual_items = tuple(actual.items[:a_prefix_len]) + if a_suffix_len: + actual_items += tuple(actual.items[-a_suffix_len:]) + template_items = t_prefix + t_suffix + if isinstance(a_unpacked, Instance): + assert a_unpacked.type.fullname == "builtins.tuple" + for tm in t_middle: + res.extend( + infer_constraints(tm, a_unpacked.args[0], self.direction) + ) + else: + actual_items = () + template_items = () + else: + actual_items = tuple(actual.items) + template_items = tuple(template.items) + else: + return res + + # Cases above will return if actual wasn't a TupleType. + assert isinstance(actual, TupleType) + if len(actual_items) == len(template_items): + if ( + actual.partial_fallback.type.is_named_tuple + and template.partial_fallback.type.is_named_tuple + ): + # For named tuples using just the fallbacks usually gives better results. + return res + infer_constraints( + template.partial_fallback, actual.partial_fallback, self.direction + ) + for i in range(len(template_items)): + res.extend( + infer_constraints(template_items[i], actual_items[i], self.direction) + ) + res.extend( + infer_constraints( + template.partial_fallback, actual.partial_fallback, self.direction + ) + ) + return res + elif isinstance(actual, AnyType): + return self.infer_against_any(template.items, actual) + else: + return [] + + def visit_typeddict_type(self, template: TypedDictType) -> list[Constraint]: + actual = self.actual + if isinstance(actual, TypedDictType): + res: list[Constraint] = [] + # NOTE: Non-matching keys are ignored. Compatibility is checked + # elsewhere so this shouldn't be unsafe. + for item_name, template_item_type, actual_item_type in template.zip(actual): + res.extend(infer_constraints(template_item_type, actual_item_type, self.direction)) + return res + elif isinstance(actual, AnyType): + return self.infer_against_any(template.items.values(), actual) + else: + return [] + + def visit_union_type(self, template: UnionType) -> list[Constraint]: + assert False, ( + "Unexpected UnionType in ConstraintBuilderVisitor" + " (should have been handled in infer_constraints)" + ) + + def visit_type_alias_type(self, template: TypeAliasType) -> list[Constraint]: + assert False, f"This should be never called, got {template}" + + def infer_against_any(self, types: Iterable[Type], any_type: AnyType) -> list[Constraint]: + res: list[Constraint] = [] + # Some items may be things like `*Tuple[*Ts, T]` for example from callable types with + # suffix after *arg, so flatten them. + for t in flatten_nested_tuples(types): + if isinstance(t, UnpackType): + if isinstance(t.type, TypeVarTupleType): + res.append(Constraint(t.type, self.direction, any_type)) + else: + unpacked = get_proper_type(t.type) + assert isinstance(unpacked, Instance) + res.extend(infer_constraints(unpacked, any_type, self.direction)) + else: + # Note that we ignore variance and simply always use the + # original direction. This is because for Any targets direction is + # irrelevant in most cases, see e.g. is_same_constraint(). + res.extend(infer_constraints(t, any_type, self.direction)) + return res + + def visit_overloaded(self, template: Overloaded) -> list[Constraint]: + if isinstance(self.actual, CallableType): + items = find_matching_overload_items(template, self.actual) + else: + items = template.items + res: list[Constraint] = [] + for t in items: + res.extend(infer_constraints(t, self.actual, self.direction)) + return res + + def visit_type_type(self, template: TypeType) -> list[Constraint]: + if isinstance(self.actual, CallableType): + return infer_constraints(template.item, self.actual.ret_type, self.direction) + elif isinstance(self.actual, Overloaded): + return infer_constraints(template.item, self.actual.items[0].ret_type, self.direction) + elif isinstance(self.actual, TypeType): + return infer_constraints(template.item, self.actual.item, self.direction) + elif isinstance(self.actual, AnyType): + return infer_constraints(template.item, self.actual, self.direction) + else: + return [] + + +def neg_op(op: int) -> int: + """Map SubtypeOf to SupertypeOf and vice versa.""" + + if op == SUBTYPE_OF: + return SUPERTYPE_OF + elif op == SUPERTYPE_OF: + return SUBTYPE_OF + else: + raise ValueError(f"Invalid operator {op}") + + +def find_matching_overload_item(overloaded: Overloaded, template: CallableType) -> CallableType: + """Disambiguate overload item against a template.""" + items = overloaded.items + for item in items: + # Return type may be indeterminate in the template, so ignore it when performing a + # subtype check. + if mypy.subtypes.is_callable_compatible( + item, + template, + is_compat=mypy.subtypes.is_subtype, + is_proper_subtype=False, + ignore_return=True, + ): + return item + # Fall back to the first item if we can't find a match. This is totally arbitrary -- + # maybe we should just bail out at this point. + return items[0] + + +def find_matching_overload_items( + overloaded: Overloaded, template: CallableType +) -> list[CallableType]: + """Like find_matching_overload_item, but return all matches, not just the first.""" + items = overloaded.items + res = [] + for item in items: + # Return type may be indeterminate in the template, so ignore it when performing a + # subtype check. + if mypy.subtypes.is_callable_compatible( + item, + template, + is_compat=mypy.subtypes.is_subtype, + is_proper_subtype=False, + ignore_return=True, + ): + res.append(item) + if not res: + # Falling back to all items if we can't find a match is pretty arbitrary, but + # it maintains backward compatibility. + res = items.copy() + return res + + +def get_tuple_fallback_from_unpack(unpack: UnpackType) -> TypeInfo: + """Get builtins.tuple type from available types to construct homogeneous tuples.""" + tp = get_proper_type(unpack.type) + if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple": + return tp.type + if isinstance(tp, TypeVarTupleType): + return tp.tuple_fallback.type + if isinstance(tp, TupleType): + for base in tp.partial_fallback.type.mro: + if base.fullname == "builtins.tuple": + return base + assert False, "Invalid unpack type" + + +def repack_callable_args(callable: CallableType, tuple_type: TypeInfo) -> list[Type]: + """Present callable with star unpack in a normalized form. + + Since positional arguments cannot follow star argument, they are packed in a suffix, + while prefix is represented as individual positional args. We want to put all in a single + list with unpack in the middle, and prefix/suffix on the sides (as they would appear + in e.g. a TupleType). + """ + if ARG_STAR not in callable.arg_kinds: + return callable.arg_types + star_index = callable.arg_kinds.index(ARG_STAR) + arg_types = callable.arg_types[:star_index] + star_type = callable.arg_types[star_index] + suffix_types = [] + if not isinstance(star_type, UnpackType): + # Re-normalize *args: X -> *args: *tuple[X, ...] + star_type = UnpackType(Instance(tuple_type, [star_type])) + else: + tp = get_proper_type(star_type.type) + if isinstance(tp, TupleType): + assert isinstance(tp.items[0], UnpackType) + star_type = tp.items[0] + suffix_types = tp.items[1:] + return arg_types + [star_type] + suffix_types + + +def build_constraints_for_simple_unpack( + template_args: list[Type], actual_args: list[Type], direction: int +) -> list[Constraint]: + """Infer constraints between two lists of types with variadic items. + + This function is only supposed to be called when a variadic item is present in templates. + If there is no variadic item the actuals, we simply use split_with_prefix_and_suffix() + and infer prefix <: prefix, suffix <: suffix, variadic <: middle. If there is a variadic + item in the actuals we need to be more careful, only common prefix/suffix can generate + constraints, also we can only infer constraints for variadic template item, if template + prefix/suffix are shorter that actual ones, otherwise there may be partial overlap + between variadic items, for example if template prefix is longer: + + templates: T1, T2, Ts, Ts, Ts, ... + actuals: A1, As, As, As, ... + + Note: this function can only be called for builtin variadic constructors: Tuple and Callable. + For instances, you should first find correct type argument mapping. + """ + template_unpack = find_unpack_in_list(template_args) + assert template_unpack is not None + template_prefix = template_unpack + template_suffix = len(template_args) - template_prefix - 1 + + t_unpack = None + res = [] + + actual_unpack = find_unpack_in_list(actual_args) + if actual_unpack is None: + t_unpack = template_args[template_unpack] + if template_prefix + template_suffix > len(actual_args): + # These can't be subtypes of each-other, return fast. + assert isinstance(t_unpack, UnpackType) + if isinstance(t_unpack.type, TypeVarTupleType): + # Set TypeVarTuple to empty to improve error messages. + return [ + Constraint( + t_unpack.type, direction, TupleType([], t_unpack.type.tuple_fallback) + ) + ] + else: + return [] + common_prefix = template_prefix + common_suffix = template_suffix + else: + actual_prefix = actual_unpack + actual_suffix = len(actual_args) - actual_prefix - 1 + common_prefix = min(template_prefix, actual_prefix) + common_suffix = min(template_suffix, actual_suffix) + if actual_prefix >= template_prefix and actual_suffix >= template_suffix: + # This is the only case where we can guarantee there will be no partial overlap + # (note however partial overlap is OK for variadic tuples, it is handled below). + t_unpack = template_args[template_unpack] + + # Handle constraints from prefixes/suffixes first. + start, middle, end = split_with_prefix_and_suffix( + tuple(actual_args), common_prefix, common_suffix + ) + for t, a in zip(template_args[:common_prefix], start): + res.extend(infer_constraints(t, a, direction)) + if common_suffix: + for t, a in zip(template_args[-common_suffix:], end): + res.extend(infer_constraints(t, a, direction)) + + if t_unpack is not None: + # Add constraint(s) for variadic item when possible. + assert isinstance(t_unpack, UnpackType) + tp = get_proper_type(t_unpack.type) + if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple": + # Homogeneous case *tuple[T, ...] <: [X, Y, Z, ...]. + for a in middle: + # TODO: should we use union instead of join here? + if not isinstance(a, UnpackType): + res.extend(infer_constraints(tp.args[0], a, direction)) + else: + a_tp = get_proper_type(a.type) + # This is the case *tuple[T, ...] <: *tuple[A, ...]. + if isinstance(a_tp, Instance) and a_tp.type.fullname == "builtins.tuple": + res.extend(infer_constraints(tp.args[0], a_tp.args[0], direction)) + elif isinstance(tp, TypeVarTupleType): + res.append(Constraint(tp, direction, TupleType(list(middle), tp.tuple_fallback))) + elif actual_unpack is not None: + # A special case for a variadic tuple unpack, we simply infer T <: X from + # Tuple[..., *tuple[T, ...], ...] <: Tuple[..., *tuple[X, ...], ...]. + actual_unpack_type = actual_args[actual_unpack] + assert isinstance(actual_unpack_type, UnpackType) + a_unpacked = get_proper_type(actual_unpack_type.type) + if isinstance(a_unpacked, Instance) and a_unpacked.type.fullname == "builtins.tuple": + t_unpack = template_args[template_unpack] + assert isinstance(t_unpack, UnpackType) + tp = get_proper_type(t_unpack.type) + if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple": + res.extend(infer_constraints(tp.args[0], a_unpacked.args[0], direction)) + return res + + +def infer_directed_arg_constraints(left: Type, right: Type, direction: int) -> list[Constraint]: + """Infer constraints between two arguments using direction between original callables.""" + if isinstance(left, (ParamSpecType, UnpackType)) or isinstance( + right, (ParamSpecType, UnpackType) + ): + # This avoids bogus constraints like T <: P.args + # TODO: can we infer something useful for *T vs P? + return [] + if direction == SUBTYPE_OF: + # We invert direction to account for argument contravariance. + return infer_constraints(left, right, neg_op(direction)) + else: + return infer_constraints(right, left, neg_op(direction)) + + +def infer_callable_arguments_constraints( + template: NormalizedCallableType | Parameters, + actual: NormalizedCallableType | Parameters, + direction: int, +) -> list[Constraint]: + """Infer constraints between argument types of two callables. + + This function essentially extracts four steps from are_parameters_compatible() in + subtypes.py that involve subtype checks between argument types. We keep the argument + matching logic, but ignore various strictness flags present there, and checks that + do not involve subtyping. Then in place of every subtype check we put an infer_constraints() + call for the same types. + """ + res = [] + if direction == SUBTYPE_OF: + left, right = template, actual + else: + left, right = actual, template + left_star = left.var_arg() + left_star2 = left.kw_arg() + right_star = right.var_arg() + right_star2 = right.kw_arg() + + # Numbering of steps below matches the one in are_parameters_compatible() for convenience. + # Phase 1a: compare star vs star arguments. + if left_star is not None and right_star is not None: + res.extend(infer_directed_arg_constraints(left_star.typ, right_star.typ, direction)) + if left_star2 is not None and right_star2 is not None: + res.extend(infer_directed_arg_constraints(left_star2.typ, right_star2.typ, direction)) + + # Phase 1b: compare left args with corresponding non-star right arguments. + for right_arg in right.formal_arguments(): + left_arg = mypy.typeops.callable_corresponding_argument(left, right_arg) + if left_arg is None: + continue + res.extend(infer_directed_arg_constraints(left_arg.typ, right_arg.typ, direction)) + + # Phase 1c: compare left args with right *args. + if right_star is not None: + right_by_position = right.try_synthesizing_arg_from_vararg(None) + assert right_by_position is not None + i = right_star.pos + assert i is not None + while i < len(left.arg_kinds) and left.arg_kinds[i].is_positional(): + left_by_position = left.argument_by_position(i) + assert left_by_position is not None + res.extend( + infer_directed_arg_constraints( + left_by_position.typ, right_by_position.typ, direction + ) + ) + i += 1 + + # Phase 1d: compare left args with right **kwargs. + if right_star2 is not None: + right_names = {name for name in right.arg_names if name is not None} + left_only_names = set() + for name, kind in zip(left.arg_names, left.arg_kinds): + if name is None or kind.is_star() or name in right_names: + continue + left_only_names.add(name) + + right_by_name = right.try_synthesizing_arg_from_kwarg(None) + assert right_by_name is not None + for name in left_only_names: + left_by_name = left.argument_by_name(name) + assert left_by_name is not None + res.extend( + infer_directed_arg_constraints(left_by_name.typ, right_by_name.typ, direction) + ) + return res + + +def filter_imprecise_kinds(cs: list[Constraint]) -> list[Constraint]: + """For each ParamSpec remove all imprecise constraints, if at least one precise available.""" + have_precise = set() + for c in cs: + if not isinstance(c.origin_type_var, ParamSpecType): + continue + if ( + isinstance(c.target, ParamSpecType) + or isinstance(c.target, Parameters) + and not c.target.imprecise_arg_kinds + ): + have_precise.add(c.type_var) + new_cs = [] + for c in cs: + if not isinstance(c.origin_type_var, ParamSpecType) or c.type_var not in have_precise: + new_cs.append(c) + if not isinstance(c.target, Parameters) or not c.target.imprecise_arg_kinds: + new_cs.append(c) + return new_cs diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..7220b5e9c09c80fe207737f058879ce07f34abf5 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.py new file mode 100644 index 0000000000000000000000000000000000000000..9a390a01bdbab4e385c4fc6687695d7d6cced3a6 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +from typing import Any, cast + +from mypy.types import ( + AnyType, + CallableType, + DeletedType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + TypeAliasType, + TypedDictType, + TypeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, +) + +# type_visitor needs to be imported after types +from mypy.type_visitor import TypeVisitor # ruff: isort: skip + + +def copy_type(t: ProperType) -> ProperType: + """Create a shallow copy of a type. + + This can be used to mutate the copy with truthiness information. + + Classes compiled with mypyc don't support copy.copy(), so we need + a custom implementation. + """ + return t.accept(TypeShallowCopier()) + + +class TypeShallowCopier(TypeVisitor[ProperType]): + def visit_unbound_type(self, t: UnboundType) -> ProperType: + return t + + def visit_any(self, t: AnyType) -> ProperType: + return self.copy_common(t, AnyType(t.type_of_any, t.source_any, t.missing_import_name)) + + def visit_none_type(self, t: NoneType) -> ProperType: + return self.copy_common(t, NoneType()) + + def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType: + dup = UninhabitedType() + dup.ambiguous = t.ambiguous + return self.copy_common(t, dup) + + def visit_erased_type(self, t: ErasedType) -> ProperType: + return self.copy_common(t, ErasedType()) + + def visit_deleted_type(self, t: DeletedType) -> ProperType: + return self.copy_common(t, DeletedType(t.source)) + + def visit_instance(self, t: Instance) -> ProperType: + dup = Instance(t.type, t.args, last_known_value=t.last_known_value) + return self.copy_common(t, dup) + + def visit_type_var(self, t: TypeVarType) -> ProperType: + return self.copy_common(t, t.copy_modified()) + + def visit_param_spec(self, t: ParamSpecType) -> ProperType: + dup = ParamSpecType( + t.name, t.fullname, t.id, t.flavor, t.upper_bound, t.default, prefix=t.prefix + ) + return self.copy_common(t, dup) + + def visit_parameters(self, t: Parameters) -> ProperType: + dup = Parameters( + t.arg_types, + t.arg_kinds, + t.arg_names, + variables=t.variables, + is_ellipsis_args=t.is_ellipsis_args, + ) + return self.copy_common(t, dup) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType: + dup = TypeVarTupleType( + t.name, t.fullname, t.id, t.upper_bound, t.tuple_fallback, t.default + ) + return self.copy_common(t, dup) + + def visit_unpack_type(self, t: UnpackType) -> ProperType: + dup = UnpackType(t.type) + return self.copy_common(t, dup) + + def visit_partial_type(self, t: PartialType) -> ProperType: + return self.copy_common(t, PartialType(t.type, t.var, t.value_type)) + + def visit_callable_type(self, t: CallableType) -> ProperType: + return self.copy_common(t, t.copy_modified()) + + def visit_tuple_type(self, t: TupleType) -> ProperType: + return self.copy_common(t, TupleType(t.items, t.partial_fallback, implicit=t.implicit)) + + def visit_typeddict_type(self, t: TypedDictType) -> ProperType: + return self.copy_common( + t, TypedDictType(t.items, t.required_keys, t.readonly_keys, t.fallback) + ) + + def visit_literal_type(self, t: LiteralType) -> ProperType: + return self.copy_common(t, LiteralType(value=t.value, fallback=t.fallback)) + + def visit_union_type(self, t: UnionType) -> ProperType: + return self.copy_common(t, UnionType(t.items)) + + def visit_overloaded(self, t: Overloaded) -> ProperType: + return self.copy_common(t, Overloaded(items=t.items)) + + def visit_type_type(self, t: TypeType) -> ProperType: + # Use cast since the type annotations in TypeType are imprecise. + return self.copy_common(t, TypeType(cast(Any, t.item), is_type_form=t.is_type_form)) + + def visit_type_alias_type(self, t: TypeAliasType) -> ProperType: + assert False, "only ProperTypes supported" + + def copy_common(self, t: ProperType, t2: ProperType) -> ProperType: + t2.line = t.line + t2.column = t.column + t2.can_be_false = t.can_be_false + t2.can_be_true = t.can_be_true + return t2 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..4cc6e3c5518560d2f15d1bcd549c14d83350a32a Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..a39a577d03ac6b680dc2a10cdb595742edab086e --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import os +from typing import Final + +# Earliest fully supported Python 3.x version. Used as the default Python +# version in tests. Mypy wheels should be built starting with this version, +# and CI tests should be run on this version (and later versions). +PYTHON3_VERSION: Final = (3, 10) + +# Earliest Python 3.x version supported via --python-version 3.x. To run +# mypy, at least version PYTHON3_VERSION is needed. +PYTHON3_VERSION_MIN: Final = (3, 9) # Keep in sync with typeshed's python support + +CACHE_DIR: Final = ".mypy_cache" + +CONFIG_NAMES: Final = ["mypy.ini", ".mypy.ini"] +SHARED_CONFIG_NAMES: Final = ["pyproject.toml", "setup.cfg"] + +USER_CONFIG_FILES: list[str] = ["~/.config/mypy/config", "~/.mypy.ini"] +if os.environ.get("XDG_CONFIG_HOME"): + USER_CONFIG_FILES.insert(0, os.path.join(os.environ["XDG_CONFIG_HOME"], "mypy/config")) +USER_CONFIG_FILES = [os.path.expanduser(f) for f in USER_CONFIG_FILES] + +# This must include all reporters defined in mypy.report. This is defined here +# to make reporter names available without importing mypy.report -- this speeds +# up startup. +REPORTER_NAMES: Final = [ + "linecount", + "any-exprs", + "linecoverage", + "memory-xml", + "cobertura-xml", + "xml", + "xslt-html", + "xslt-txt", + "html", + "txt", + "lineprecision", +] + +# Threshold after which we sometimes filter out most errors to avoid very +# verbose output. The default is to show all errors. +MANY_ERRORS_THRESHOLD: Final = -1 + +RECURSION_LIMIT: Final = 2**14 + +WORKER_START_INTERVAL: Final = 0.01 +WORKER_START_TIMEOUT: Final = 3 +WORKER_CONNECTION_TIMEOUT: Final = 10 +WORKER_DONE_TIMEOUT: Final = 600 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..63d2ae5e8b3a2aae47f637064474ea976d6e46cb Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.py new file mode 100644 index 0000000000000000000000000000000000000000..184015ffe7203d1ecd313586dccef953bb73621a --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import sys +from collections.abc import Callable +from typing import Any + +if sys.platform == "win32": + import ctypes + import subprocess + from ctypes.wintypes import DWORD, HANDLE + + PROCESS_QUERY_LIMITED_INFORMATION = ctypes.c_ulong(0x1000) + + kernel32 = ctypes.windll.kernel32 + OpenProcess: Callable[[DWORD, int, int], HANDLE] = kernel32.OpenProcess + GetExitCodeProcess: Callable[[HANDLE, Any], int] = kernel32.GetExitCodeProcess +else: + import os + import signal + + +def alive(pid: int) -> bool: + """Is the process alive?""" + if sys.platform == "win32": + # why can't anything be easy... + status = DWORD() + handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) + GetExitCodeProcess(handle, ctypes.byref(status)) + return status.value == 259 # STILL_ACTIVE + else: + try: + os.kill(pid, 0) + except OSError: + return False + return True + + +def kill(pid: int) -> None: + """Kill the process.""" + if sys.platform == "win32": + subprocess.check_output(f"taskkill /pid {pid} /f /t") + else: + os.kill(pid, signal.SIGKILL) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_server.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_server.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..6ef463454961fc8030c24254de99320d5e0162fe Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_server.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_server.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b0e03282a4a6a606af6f6b0ccf9596495f5f037 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_server.py @@ -0,0 +1,1126 @@ +"""Server for mypy daemon mode. + +This implements a daemon process which keeps useful state in memory +to enable fine-grained incremental reprocessing of changes. +""" + +from __future__ import annotations + +import argparse +import io +import json +import os +import pickle +import subprocess +import sys +import time +import traceback +from collections.abc import Callable, Sequence, Set as AbstractSet +from contextlib import redirect_stderr, redirect_stdout +from typing import Any, Final, TypeAlias as _TypeAlias + +from librt.base64 import b64encode + +import mypy.build +import mypy.errors +import mypy.main +from mypy.dmypy_util import WriteToConn, receive, send +from mypy.find_sources import InvalidSourceList, create_source_list +from mypy.fscache import FileSystemCache +from mypy.fswatcher import FileData, FileSystemWatcher +from mypy.inspections import InspectionEngine +from mypy.ipc import IPCServer +from mypy.modulefinder import BuildSource, FindModuleCache, SearchPaths, compute_search_paths +from mypy.options import Options +from mypy.server.update import FineGrainedBuildManager, refresh_suppressed_submodules +from mypy.suggestions import SuggestionEngine, SuggestionFailure +from mypy.typestate import reset_global_state +from mypy.util import FancyFormatter, count_stats +from mypy.version import __version__ + +MEM_PROFILE: Final = False # If True, dump memory profile after initialization + +if sys.platform == "win32": + from subprocess import STARTUPINFO + + def daemonize( + options: Options, status_file: str, timeout: int | None = None, log_file: str | None = None + ) -> int: + """Create the daemon process via "dmypy daemon" and pass options via command line + + When creating the daemon grandchild, we create it in a new console, which is + started hidden. We cannot use DETACHED_PROCESS since it will cause console windows + to pop up when starting. See + https://github.com/python/cpython/pull/4150#issuecomment-340215696 + for more on why we can't have nice things. + + It also pickles the options to be unpickled by mypy. + """ + command = [sys.executable, "-m", "mypy.dmypy", "--status-file", status_file, "daemon"] + pickled_options = pickle.dumps(options.snapshot()) + command.append(f'--options-data="{b64encode(pickled_options).decode()}"') + if timeout: + command.append(f"--timeout={timeout}") + if log_file: + command.append(f"--log-file={log_file}") + info = STARTUPINFO() + info.dwFlags = 0x1 # STARTF_USESHOWWINDOW aka use wShowWindow's value + info.wShowWindow = 0 # SW_HIDE aka make the window invisible + try: + subprocess.Popen(command, creationflags=0x10, startupinfo=info) # CREATE_NEW_CONSOLE + return 0 + except subprocess.CalledProcessError as e: + return e.returncode + +else: + + def _daemonize_cb(func: Callable[[], None], log_file: str | None = None) -> int: + """Arrange to call func() in a grandchild of the current process. + + Return 0 for success, exit status for failure, negative if + subprocess killed by signal. + """ + # See https://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python + sys.stdout.flush() + sys.stderr.flush() + pid = os.fork() + if pid: + # Parent process: wait for child in case things go bad there. + npid, sts = os.waitpid(pid, 0) + sig = sts & 0xFF + if sig: + print("Child killed by signal", sig) + return -sig + sts = sts >> 8 + if sts: + print("Child exit status", sts) + return sts + # Child process: do a bunch of UNIX stuff and then fork a grandchild. + try: + os.setsid() # Detach controlling terminal + os.umask(0o27) + devnull = os.open("/dev/null", os.O_RDWR) + os.dup2(devnull, 0) + os.dup2(devnull, 1) + os.dup2(devnull, 2) + os.close(devnull) + pid = os.fork() + if pid: + # Child is done, exit to parent. + os._exit(0) + # Grandchild: run the server. + if log_file: + sys.stdout = sys.stderr = open(log_file, "a", buffering=1) + fd = sys.stdout.fileno() + os.dup2(fd, 2) + os.dup2(fd, 1) + func() + finally: + # Make sure we never get back into the caller. + os._exit(1) + + def daemonize( + options: Options, status_file: str, timeout: int | None = None, log_file: str | None = None + ) -> int: + """Run the mypy daemon in a grandchild of the current process + + Return 0 for success, exit status for failure, negative if + subprocess killed by signal. + """ + return _daemonize_cb(Server(options, status_file, timeout).serve, log_file) + + +# Server code. + +CONNECTION_NAME: Final = "dmypy" + + +def process_start_options(flags: list[str], allow_sources: bool) -> Options: + _, options = mypy.main.process_options( + ["-i"] + flags, require_targets=False, server_options=True + ) + if options.report_dirs: + print("dmypy: Ignoring report generation settings. Start/restart cannot generate reports.") + if options.junit_xml: + print( + "dmypy: Ignoring report generation settings. " + "Start/restart does not support --junit-xml. Pass it to check/recheck instead" + ) + options.junit_xml = None + if not options.incremental: + sys.exit("dmypy: start/restart should not disable incremental mode") + if options.follow_imports not in ("skip", "error", "normal"): + sys.exit("dmypy: follow-imports=silent not supported") + return options + + +def ignore_suppressed_imports(module: str) -> bool: + """Can we skip looking for newly unsuppressed imports to module?""" + # Various submodules of 'encodings' can be suppressed, since it + # uses module-level '__getattr__'. Skip them since there are many + # of them, and following imports to them is kind of pointless. + return module.startswith("encodings.") + + +ModulePathPair: _TypeAlias = tuple[str, str] +ModulePathPairs: _TypeAlias = list[ModulePathPair] +ChangesAndRemovals: _TypeAlias = tuple[ModulePathPairs, ModulePathPairs] + + +class Server: + # NOTE: the instance is constructed in the parent process but + # serve() is called in the grandchild (by daemonize()). + + def __init__(self, options: Options, status_file: str, timeout: int | None = None) -> None: + """Initialize the server with the desired mypy flags.""" + self.options = options + # Snapshot the options info before we muck with it, to detect changes + self.options_snapshot = options.snapshot() + self.timeout = timeout + self.fine_grained_manager: FineGrainedBuildManager | None = None + + if os.path.isfile(status_file): + os.unlink(status_file) + + self.fscache = FileSystemCache() + + options.raise_exceptions = True + options.incremental = True + options.fine_grained_incremental = True + options.show_traceback = True + if options.use_fine_grained_cache: + # Using fine_grained_cache implies generating and caring + # about the fine grained cache + options.cache_fine_grained = True + else: + options.cache_dir = os.devnull + # Fine-grained incremental doesn't support general partial types + # (details in https://github.com/python/mypy/issues/4492) + options.local_partial_types = True + self.status_file = status_file + + # Since the object is created in the parent process we can check + # the output terminal options here. + self.formatter = FancyFormatter(sys.stdout, sys.stderr, options.hide_error_codes) + + def _response_metadata(self) -> dict[str, str]: + py_version = f"{self.options.python_version[0]}_{self.options.python_version[1]}" + return {"platform": self.options.platform, "python_version": py_version} + + def serve(self) -> None: + """Serve requests, synchronously (no thread or fork).""" + + command = None + server = IPCServer(CONNECTION_NAME, self.timeout) + orig_stdout = sys.stdout + orig_stderr = sys.stderr + + try: + with open(self.status_file, "w") as f: + json.dump({"pid": os.getpid(), "connection_name": server.connection_name}, f) + f.write("\n") # I like my JSON with a trailing newline + while True: + with server: + data = receive(server) + sys.stdout = WriteToConn(server, "stdout", sys.stdout.isatty()) + sys.stderr = WriteToConn(server, "stderr", sys.stderr.isatty()) + resp: dict[str, Any] = {} + if "command" not in data: + resp = {"error": "No command found in request"} + else: + command = data["command"] + if not isinstance(command, str): + resp = {"error": "Command is not a string"} + else: + command = data.pop("command") + try: + resp = self.run_command(command, data) + except Exception: + # If we are crashing, report the crash to the client + tb = traceback.format_exception(*sys.exc_info()) + resp = {"error": "Daemon crashed!\n" + "".join(tb)} + resp.update(self._response_metadata()) + resp["final"] = True + send(server, resp) + raise + resp["final"] = True + try: + resp.update(self._response_metadata()) + send(server, resp) + except OSError: + pass # Maybe the client hung up + if command == "stop": + reset_global_state() + sys.exit(0) + finally: + # Revert stdout/stderr so we can see any errors. + sys.stdout = orig_stdout + sys.stderr = orig_stderr + + # If the final command is something other than a clean + # stop, remove the status file. (We can't just + # simplify the logic and always remove the file, since + # that could cause us to remove a future server's + # status file.) + if command != "stop": + os.unlink(self.status_file) + try: + server.cleanup() # try to remove the socket dir on Linux + except OSError: + pass + exc_info = sys.exc_info() + if exc_info[0] and exc_info[0] is not SystemExit: + traceback.print_exception(*exc_info) + + def run_command(self, command: str, data: dict[str, object]) -> dict[str, object]: + """Run a specific command from the registry.""" + key = "cmd_" + command + method = getattr(self.__class__, key, None) + if method is None: + return {"error": f"Unrecognized command '{command}'"} + else: + if command not in {"check", "recheck", "run"}: + # Only the above commands use some error formatting. + del data["is_tty"] + del data["terminal_width"] + ret = method(self, **data) + assert isinstance(ret, dict) + return ret + + # Command functions (run in the server via RPC). + + def cmd_status(self, fswatcher_dump_file: str | None = None) -> dict[str, object]: + """Return daemon status.""" + res: dict[str, object] = {} + res.update(get_meminfo()) + if fswatcher_dump_file: + data = self.fswatcher.dump_file_data() if hasattr(self, "fswatcher") else {} + # Using .dumps and then writing was noticeably faster than using dump + s = json.dumps(data) + with open(fswatcher_dump_file, "w") as f: + f.write(s) + return res + + def cmd_stop(self) -> dict[str, object]: + """Stop daemon.""" + # We need to remove the status file *before* we complete the + # RPC. Otherwise a race condition exists where a subsequent + # command can see a status file from a dying server and think + # it is a live one. + os.unlink(self.status_file) + return {} + + def cmd_run( + self, + version: str, + args: Sequence[str], + export_types: bool, + is_tty: bool, + terminal_width: int, + ) -> dict[str, object]: + """Check a list of files, triggering a restart if needed.""" + stderr = io.StringIO() + stdout = io.StringIO() + try: + # Process options can exit on improper arguments, so we need to catch that and + # capture stderr so the client can report it + with redirect_stderr(stderr): + with redirect_stdout(stdout): + sources, options = mypy.main.process_options( + ["-i"] + list(args), + require_targets=True, + server_options=True, + fscache=self.fscache, + program="mypy-daemon", + header=argparse.SUPPRESS, + ) + # Signal that we need to restart if the options have changed + if not options.compare_stable(self.options_snapshot): + return {"restart": "configuration changed"} + if __version__ != version: + return {"restart": "mypy version changed"} + if self.fine_grained_manager: + manager = self.fine_grained_manager.manager + start_plugins_snapshot = manager.plugins_snapshot + _, current_plugins_snapshot = mypy.build.load_plugins( + options, manager.errors, sys.stdout, extra_plugins=() + ) + if current_plugins_snapshot != start_plugins_snapshot: + return {"restart": "plugins changed"} + except InvalidSourceList as err: + return {"out": "", "err": str(err), "status": 2} + except SystemExit as e: + return {"out": stdout.getvalue(), "err": stderr.getvalue(), "status": e.code} + return self.check(sources, export_types, is_tty, terminal_width) + + def cmd_check( + self, files: Sequence[str], export_types: bool, is_tty: bool, terminal_width: int + ) -> dict[str, object]: + """Check a list of files.""" + try: + sources = create_source_list(files, self.options, self.fscache) + except InvalidSourceList as err: + return {"out": "", "err": str(err), "status": 2} + return self.check(sources, export_types, is_tty, terminal_width) + + def cmd_recheck( + self, + is_tty: bool, + terminal_width: int, + export_types: bool, + remove: list[str] | None = None, + update: list[str] | None = None, + ) -> dict[str, object]: + """Check the same list of files we checked most recently. + + If remove/update is given, they modify the previous list; + if all are None, stat() is called for each file in the previous list. + """ + t0 = time.time() + if not self.fine_grained_manager: + return {"error": "Command 'recheck' is only valid after a 'check' command"} + sources = self.previous_sources + if remove: + removals = set(remove) + sources = [s for s in sources if s.path and s.path not in removals] + if update: + # Sort list of file updates by extension, so *.pyi files are first. + update.sort(key=lambda f: os.path.splitext(f)[1], reverse=True) + + known = {s.path for s in sources if s.path} + added = [p for p in update if p not in known] + try: + added_sources = create_source_list(added, self.options, self.fscache) + except InvalidSourceList as err: + return {"out": "", "err": str(err), "status": 2} + sources = sources + added_sources # Make a copy! + t1 = time.time() + manager = self.fine_grained_manager.manager + manager.log(f"fine-grained increment: cmd_recheck: {t1 - t0:.3f}s") + old_export_types = self.options.export_types + self.options.export_types = self.options.export_types or export_types + if not self.following_imports(): + messages = self.fine_grained_increment( + sources, remove, update, explicit_export_types=export_types + ) + else: + assert remove is None and update is None + messages = self.fine_grained_increment_follow_imports( + sources, explicit_export_types=export_types + ) + res = self.increment_output(messages, sources, is_tty, terminal_width) + self.flush_caches() + self.update_stats(res) + self.options.export_types = old_export_types + return res + + def check( + self, sources: list[BuildSource], export_types: bool, is_tty: bool, terminal_width: int + ) -> dict[str, Any]: + """Check using fine-grained incremental mode. + + If is_tty is True format the output nicely with colors and summary line + (unless disabled in self.options). Also pass the terminal_width to formatter. + """ + old_export_types = self.options.export_types + self.options.export_types = self.options.export_types or export_types + if not self.fine_grained_manager: + res = self.initialize_fine_grained(sources, is_tty, terminal_width) + else: + if not self.following_imports(): + messages = self.fine_grained_increment(sources, explicit_export_types=export_types) + else: + messages = self.fine_grained_increment_follow_imports( + sources, explicit_export_types=export_types + ) + res = self.increment_output(messages, sources, is_tty, terminal_width) + self.flush_caches() + self.update_stats(res) + self.options.export_types = old_export_types + return res + + def flush_caches(self) -> None: + self.fscache.flush() + if self.fine_grained_manager: + self.fine_grained_manager.flush_cache() + + def update_stats(self, res: dict[str, Any]) -> None: + if self.fine_grained_manager: + manager = self.fine_grained_manager.manager + manager.dump_stats() + res["stats"] = manager.stats + manager.stats = {} + + def following_imports(self) -> bool: + """Are we following imports?""" + # TODO: What about silent? + return self.options.follow_imports == "normal" + + def initialize_fine_grained( + self, sources: list[BuildSource], is_tty: bool, terminal_width: int + ) -> dict[str, Any]: + self.fswatcher = FileSystemWatcher(self.fscache) + t0 = time.time() + self.update_sources(sources) + t1 = time.time() + try: + result = mypy.build.build(sources=sources, options=self.options, fscache=self.fscache) + except mypy.errors.CompileError as e: + output = "".join(s + "\n" for s in e.messages) + if e.use_stdout: + out, err = output, "" + else: + out, err = "", output + return {"out": out, "err": err, "status": 2} + messages = result.errors + self.fine_grained_manager = FineGrainedBuildManager(result) + + original_sources_len = len(sources) + if self.following_imports(): + sources = find_all_sources_in_build(self.fine_grained_manager.graph, sources) + self.update_sources(sources) + + self.previous_sources = sources + + # If we are using the fine-grained cache, build hasn't actually done + # the typechecking on the updated files yet. + # Run a fine-grained update starting from the cached data + if result.used_cache: + t2 = time.time() + # Pull times and hashes out of the saved_cache and stick them into + # the fswatcher, so we pick up the changes. + for state in self.fine_grained_manager.graph.values(): + meta = state.meta + if meta is None: + continue + assert state.path is not None + self.fswatcher.set_file_data( + state.path, + FileData(st_mtime=float(meta.mtime), st_size=meta.size, hash=meta.hash), + ) + + changed, removed = self.find_changed(sources) + changed += self.find_added_suppressed( + self.fine_grained_manager.graph, + set(), + self.fine_grained_manager.manager.search_paths, + ) + + # Find anything that has had its dependency list change + for state in self.fine_grained_manager.graph.values(): + if not state.is_fresh(): + assert state.path is not None + changed.append((state.id, state.path)) + + t3 = time.time() + # Run an update + messages = self.fine_grained_manager.update(changed, removed) + + if self.following_imports(): + # We need to do another update to any new files found by following imports. + messages = self.fine_grained_increment_follow_imports(sources) + + t4 = time.time() + self.fine_grained_manager.manager.add_stats( + update_sources_time=t1 - t0, + build_time=t2 - t1, + find_changes_time=t3 - t2, + fg_update_time=t4 - t3, + files_changed=len(removed) + len(changed), + ) + + else: + # Stores the initial state of sources as a side effect. + self.fswatcher.find_changed() + + if MEM_PROFILE: + from mypy.memprofile import print_memory_profile + + print_memory_profile(run_gc=False) + + __, n_notes, __ = count_stats(messages) + status = 1 if messages and n_notes < len(messages) else 0 + # We use explicit sources length to match the logic in non-incremental mode. + messages = self.pretty_messages(messages, original_sources_len, is_tty, terminal_width) + return {"out": "".join(s + "\n" for s in messages), "err": "", "status": status} + + def fine_grained_increment( + self, + sources: list[BuildSource], + remove: list[str] | None = None, + update: list[str] | None = None, + explicit_export_types: bool = False, + ) -> list[str]: + """Perform a fine-grained type checking increment. + + If remove and update are None, determine changed paths by using + fswatcher. Otherwise, assume that only these files have changes. + + Args: + sources: sources passed on the command line + remove: paths of files that have been removed + update: paths of files that have been changed or created + explicit_export_types: --export-type was passed in a check command + (as opposite to being set in dmypy start) + """ + assert self.fine_grained_manager is not None + manager = self.fine_grained_manager.manager + + t0 = time.time() + if remove is None and update is None: + # Use the fswatcher to determine which files were changed + # (updated or added) or removed. + self.update_sources(sources) + changed, removed = self.find_changed(sources) + else: + # Use the remove/update lists to update fswatcher. + # This avoids calling stat() for unchanged files. + changed, removed = self.update_changed(sources, remove or [], update or []) + if explicit_export_types: + # If --export-types is given, we need to force full re-checking of all + # explicitly passed files, since we need to visit each expression. + add_all_sources_to_changed(sources, changed) + changed += self.find_added_suppressed( + self.fine_grained_manager.graph, set(), manager.search_paths + ) + manager.search_paths = compute_search_paths(sources, manager.options, manager.data_dir) + t1 = time.time() + manager.log(f"fine-grained increment: find_changed: {t1 - t0:.3f}s") + messages = self.fine_grained_manager.update(changed, removed) + t2 = time.time() + manager.log(f"fine-grained increment: update: {t2 - t1:.3f}s") + manager.add_stats( + find_changes_time=t1 - t0, + fg_update_time=t2 - t1, + files_changed=len(removed) + len(changed), + ) + + self.previous_sources = sources + return messages + + def fine_grained_increment_follow_imports( + self, sources: list[BuildSource], explicit_export_types: bool = False + ) -> list[str]: + """Like fine_grained_increment, but follow imports.""" + t0 = time.time() + + # TODO: Support file events + + assert self.fine_grained_manager is not None + fine_grained_manager = self.fine_grained_manager + graph = fine_grained_manager.graph + manager = fine_grained_manager.manager + + orig_modules = list(graph.keys()) + + self.update_sources(sources) + changed_paths = self.fswatcher.find_changed() + manager.search_paths = compute_search_paths(sources, manager.options, manager.data_dir) + + t1 = time.time() + manager.log(f"fine-grained increment: find_changed: {t1 - t0:.3f}s") + + # Track all modules encountered so far. New entries for all dependencies + # are added below by other module finding methods below. All dependencies + # in graph but not in `seen` are considered deleted at the end of this method. + seen = {source.module for source in sources} + + # Find changed modules reachable from roots (or in roots) already in graph. + changed, new_files = self.find_reachable_changed_modules( + sources, graph, seen, changed_paths + ) + # Same as in fine_grained_increment(). + self.add_explicitly_new(sources, changed) + if explicit_export_types: + # Same as in fine_grained_increment(). + add_all_sources_to_changed(sources, changed) + sources.extend(new_files) + + # Process changes directly reachable from roots. + messages = fine_grained_manager.update(changed, [], followed=True) + + # Follow deps from changed modules (still within graph). + worklist = changed.copy() + while worklist: + module = worklist.pop() + if module[0] not in graph: + continue + sources2 = self.direct_imports(module, graph) + # Filter anything already seen before. This prevents + # infinite looping if there are any self edges. (Self + # edges are maybe a bug, but...) + sources2 = [source for source in sources2 if source.module not in seen] + changed, new_files = self.find_reachable_changed_modules( + sources2, graph, seen, changed_paths + ) + self.update_sources(new_files) + messages = fine_grained_manager.update(changed, [], followed=True) + worklist.extend(changed) + + t2 = time.time() + + def refresh_file(module: str, path: str) -> list[str]: + return fine_grained_manager.update([(module, path)], [], followed=True) + + for module_id, state in list(graph.items()): + new_messages = refresh_suppressed_submodules( + module_id, state.path, fine_grained_manager.deps, graph, self.fscache, refresh_file + ) + if new_messages is not None: + messages = new_messages + + t3 = time.time() + + # There may be new files that became available, currently treated as + # suppressed imports. Process them. + while True: + new_unsuppressed = self.find_added_suppressed(graph, seen, manager.search_paths) + if not new_unsuppressed: + break + new_files = [BuildSource(mod[1], mod[0], followed=True) for mod in new_unsuppressed] + sources.extend(new_files) + self.update_sources(new_files) + messages = fine_grained_manager.update(new_unsuppressed, [], followed=True) + + for module_id, path in new_unsuppressed: + new_messages = refresh_suppressed_submodules( + module_id, path, fine_grained_manager.deps, graph, self.fscache, refresh_file + ) + if new_messages is not None: + messages = new_messages + + t4 = time.time() + + # Find all original modules in graph that were not reached -- they are deleted. + to_delete = [] + for module_id in orig_modules: + if module_id not in graph: + continue + if module_id not in seen: + module_path = graph[module_id].path + assert module_path is not None + to_delete.append((module_id, module_path)) + if to_delete: + messages = fine_grained_manager.update([], to_delete) + + fix_module_deps(graph) + + self.previous_sources = find_all_sources_in_build(graph) + self.update_sources(self.previous_sources) + + # Store current file state as side effect + self.fswatcher.find_changed() + + t5 = time.time() + + manager.log(f"fine-grained increment: update: {t5 - t1:.3f}s") + manager.add_stats( + find_changes_time=t1 - t0, + fg_update_time=t2 - t1, + refresh_suppressed_time=t3 - t2, + find_added_suppressed_time=t4 - t3, + cleanup_time=t5 - t4, + ) + + return messages + + def find_reachable_changed_modules( + self, + roots: list[BuildSource], + graph: mypy.build.Graph, + seen: set[str], + changed_paths: AbstractSet[str], + ) -> tuple[list[tuple[str, str]], list[BuildSource]]: + """Follow imports within graph from given sources until hitting changed modules. + + If we find a changed module, we can't continue following imports as the imports + may have changed. + + Args: + roots: modules where to start search from + graph: module graph to use for the search + seen: modules we've seen before that won't be visited (mutated here!!). + Needed to accumulate all modules encountered during update and remove + everything that no longer exists. + changed_paths: which paths have changed (stop search here and return any found) + + Return (encountered reachable changed modules, + unchanged files not in sources_set traversed). + """ + changed = [] + new_files = [] + worklist = roots.copy() + seen.update(source.module for source in worklist) + while worklist: + nxt = worklist.pop() + if nxt.module not in seen: + seen.add(nxt.module) + new_files.append(nxt) + if nxt.path in changed_paths: + assert nxt.path is not None # TODO + changed.append((nxt.module, nxt.path)) + elif nxt.module in graph: + state = graph[nxt.module] + ancestors = state.ancestors or [] + for dep in state.dependencies + ancestors: + if dep not in seen: + seen.add(dep) + worklist.append(BuildSource(graph[dep].path, graph[dep].id, followed=True)) + return changed, new_files + + def direct_imports( + self, module: tuple[str, str], graph: mypy.build.Graph + ) -> list[BuildSource]: + """Return the direct imports of module not included in seen.""" + state = graph[module[0]] + return [BuildSource(graph[dep].path, dep, followed=True) for dep in state.dependencies] + + def find_added_suppressed( + self, graph: mypy.build.Graph, seen: set[str], search_paths: SearchPaths + ) -> list[tuple[str, str]]: + """Find suppressed modules that have been added (and not included in seen). + + Args: + seen: reachable modules we've seen before (mutated here!!). + Needed to accumulate all modules encountered during update and remove + everything that no longer exists. + + Return suppressed, added modules. + """ + all_suppressed = set() + for state in graph.values(): + all_suppressed |= state.suppressed_set + + # Filter out things that shouldn't actually be considered suppressed. + # + # TODO: Figure out why these are treated as suppressed + all_suppressed = { + module + for module in all_suppressed + if module not in graph and not ignore_suppressed_imports(module) + } + + # Optimization: skip top-level packages that are obviously not + # there, to avoid calling the relatively slow find_module() + # below too many times. + packages = {module.split(".", 1)[0] for module in all_suppressed} + packages = filter_out_missing_top_level_packages(packages, search_paths, self.fscache) + + # TODO: Namespace packages + + finder = FindModuleCache(search_paths, self.fscache, self.options) + + found = [] + + for module in all_suppressed: + top_level_pkg = module.split(".", 1)[0] + if top_level_pkg not in packages: + # Fast path: non-existent top-level package + continue + result = finder.find_module(module, fast_path=True) + if isinstance(result, str) and module not in seen: + # When not following imports, we only follow imports to .pyi files. + if not self.following_imports() and not result.endswith(".pyi"): + continue + found.append((module, result)) + seen.add(module) + + return found + + def increment_output( + self, messages: list[str], sources: list[BuildSource], is_tty: bool, terminal_width: int + ) -> dict[str, Any]: + status = 1 if messages else 0 + messages = self.pretty_messages(messages, len(sources), is_tty, terminal_width) + return {"out": "".join(s + "\n" for s in messages), "err": "", "status": status} + + def pretty_messages( + self, + messages: list[str], + n_sources: int, + is_tty: bool = False, + terminal_width: int | None = None, + ) -> list[str]: + use_color = self.options.color_output and is_tty + fit_width = self.options.pretty and is_tty + if fit_width: + messages = self.formatter.fit_in_terminal( + messages, fixed_terminal_width=terminal_width + ) + if self.options.error_summary: + summary: str | None = None + n_errors, n_notes, n_files = count_stats(messages) + if n_errors: + summary = self.formatter.format_error( + n_errors, n_files, n_sources, use_color=use_color + ) + elif not messages or n_notes == len(messages): + summary = self.formatter.format_success(n_sources, use_color) + if summary: + # Create new list to avoid appending multiple summaries on successive runs. + messages = messages + [summary] + if use_color: + messages = [self.formatter.colorize(m) for m in messages] + return messages + + def update_sources(self, sources: list[BuildSource]) -> None: + paths = [source.path for source in sources if source.path is not None] + if self.following_imports(): + # Filter out directories (used for namespace packages). + paths = [path for path in paths if self.fscache.isfile(path)] + self.fswatcher.add_watched_paths(paths) + + def update_changed( + self, sources: list[BuildSource], remove: list[str], update: list[str] + ) -> ChangesAndRemovals: + changed_paths = self.fswatcher.update_changed(remove, update) + return self._find_changed(sources, changed_paths) + + def find_changed(self, sources: list[BuildSource]) -> ChangesAndRemovals: + changed_paths = self.fswatcher.find_changed() + return self._find_changed(sources, changed_paths) + + def _find_changed( + self, sources: list[BuildSource], changed_paths: AbstractSet[str] + ) -> ChangesAndRemovals: + # Find anything that has been added or modified + changed = [ + (source.module, source.path) + for source in sources + if source.path and source.path in changed_paths + ] + + # Now find anything that has been removed from the build + modules = {source.module for source in sources} + omitted = [source for source in self.previous_sources if source.module not in modules] + removed = [] + for source in omitted: + path = source.path + assert path + removed.append((source.module, path)) + + self.add_explicitly_new(sources, changed) + + # Find anything that has had its module path change because of added or removed __init__s + last = {s.path: s.module for s in self.previous_sources} + for s in sources: + assert s.path + if s.path in last and last[s.path] != s.module: + # Mark it as removed from its old name and changed at its new name + removed.append((last[s.path], s.path)) + changed.append((s.module, s.path)) + + return changed, removed + + def add_explicitly_new( + self, sources: list[BuildSource], changed: list[tuple[str, str]] + ) -> None: + # Always add modules that were (re-)added, since they may be detected as not changed by + # fswatcher (if they were actually not changed), but they may still need to be checked + # in case they had errors before they were deleted from sources on previous runs. + previous_modules = {source.module for source in self.previous_sources} + changed_set = set(changed) + changed.extend( + [ + (source.module, source.path) + for source in sources + if source.path + and source.module not in previous_modules + and (source.module, source.path) not in changed_set + ] + ) + + def cmd_inspect( + self, + show: str, + location: str, + verbosity: int = 0, + limit: int = 0, + include_span: bool = False, + include_kind: bool = False, + include_object_attrs: bool = False, + union_attrs: bool = False, + force_reload: bool = False, + ) -> dict[str, object]: + """Locate and inspect expression(s).""" + if not self.fine_grained_manager: + return { + "error": 'Command "inspect" is only valid after a "check" command' + " (that produces no parse errors)" + } + engine = InspectionEngine( + self.fine_grained_manager, + verbosity=verbosity, + limit=limit, + include_span=include_span, + include_kind=include_kind, + include_object_attrs=include_object_attrs, + union_attrs=union_attrs, + force_reload=force_reload, + ) + old_inspections = self.options.inspections + self.options.inspections = True + try: + if show == "type": + result = engine.get_type(location) + elif show == "attrs": + result = engine.get_attrs(location) + elif show == "definition": + result = engine.get_definition(location) + else: + assert False, "Unknown inspection kind" + finally: + self.options.inspections = old_inspections + if "out" in result: + assert isinstance(result["out"], str) + result["out"] += "\n" + return result + + def cmd_suggest(self, function: str, callsites: bool, **kwargs: Any) -> dict[str, object]: + """Suggest a signature for a function.""" + if not self.fine_grained_manager: + return { + "error": "Command 'suggest' is only valid after a 'check' command" + " (that produces no parse errors)" + } + engine = SuggestionEngine(self.fine_grained_manager, **kwargs) + try: + if callsites: + out = engine.suggest_callsites(function) + else: + out = engine.suggest(function) + except SuggestionFailure as err: + return {"error": str(err)} + else: + if not out: + out = "No suggestions\n" + elif not out.endswith("\n"): + out += "\n" + return {"out": out, "err": "", "status": 0} + finally: + self.flush_caches() + + def cmd_hang(self) -> dict[str, object]: + """Hang for 100 seconds, as a debug hack.""" + time.sleep(100) + return {} + + +# Misc utilities. + + +MiB: Final = 2**20 + + +def get_meminfo() -> dict[str, Any]: + res: dict[str, Any] = {} + try: + import psutil + except ImportError: + res["memory_psutil_missing"] = ( + "psutil not found, run pip install mypy[dmypy] " + "to install the needed components for dmypy" + ) + else: + process = psutil.Process() + meminfo = process.memory_info() + res["memory_rss_mib"] = meminfo.rss / MiB + res["memory_vms_mib"] = meminfo.vms / MiB + if sys.platform == "win32": + res["memory_maxrss_mib"] = meminfo.peak_wset / MiB + else: + # See https://stackoverflow.com/questions/938733/total-memory-used-by-python-process + import resource # Since it doesn't exist on Windows. + + rusage = resource.getrusage(resource.RUSAGE_SELF) + if sys.platform == "darwin": + factor = 1 + else: + factor = 1024 # Linux + res["memory_maxrss_mib"] = rusage.ru_maxrss * factor / MiB + return res + + +def find_all_sources_in_build( + graph: mypy.build.Graph, extra: Sequence[BuildSource] = () +) -> list[BuildSource]: + result = list(extra) + seen = {source.module for source in result} + for module, state in graph.items(): + if module not in seen: + result.append(BuildSource(state.path, module)) + return result + + +def add_all_sources_to_changed(sources: list[BuildSource], changed: list[tuple[str, str]]) -> None: + """Add all (explicit) sources to the list changed files in place. + + Use this when re-processing of unchanged files is needed (e.g. for + the purpose of exporting types for inspections). + """ + changed_set = set(changed) + changed.extend( + [ + (bs.module, bs.path) + for bs in sources + if bs.path and (bs.module, bs.path) not in changed_set + ] + ) + + +def fix_module_deps(graph: mypy.build.Graph) -> None: + """After an incremental update, update module dependencies to reflect the new state. + + This can make some suppressed dependencies non-suppressed, and vice versa (if modules + have been added to or removed from the build). + """ + for state in graph.values(): + new_suppressed = [] + new_dependencies = [] + for dep in state.dependencies + state.suppressed: + if dep in graph: + new_dependencies.append(dep) + else: + new_suppressed.append(dep) + state.dependencies = new_dependencies + state.dependencies_set = set(new_dependencies) + state.suppressed = new_suppressed + state.suppressed_set = set(new_suppressed) + + +def filter_out_missing_top_level_packages( + packages: set[str], search_paths: SearchPaths, fscache: FileSystemCache +) -> set[str]: + """Quickly filter out obviously missing top-level packages. + + Return packages with entries that can't be found removed. + + This is approximate: some packages that aren't actually valid may be + included. However, all potentially valid packages must be returned. + """ + # Start with a empty set and add all potential top-level packages. + found = set() + paths = ( + search_paths.python_path + + search_paths.mypy_path + + search_paths.package_path + + search_paths.typeshed_path + ) + for p in paths: + try: + entries = fscache.listdir(p) + except Exception: + entries = [] + for entry in entries: + # The code is hand-optimized for mypyc since this may be somewhat + # performance-critical. + if entry.endswith(".py"): + entry = entry[:-3] + elif entry.endswith(".pyi"): + entry = entry[:-4] + elif entry.endswith("-stubs"): + # Possible PEP 561 stub package + entry = entry[:-6] + if entry in packages: + found.add(entry) + return found diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_util.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_util.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..cc3b157a202487d57ec5764f72ad715640b3113f Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_util.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_util.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_util.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb918b7877e596a318af637ecf5c0597c1d388d --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_util.py @@ -0,0 +1,117 @@ +"""Shared code between dmypy.py and dmypy_server.py. + +This should be pretty lightweight and not depend on other mypy code (other than ipc). +""" + +from __future__ import annotations + +import io +import json +from collections.abc import Iterable, Iterator +from types import TracebackType +from typing import Any, Final, TextIO + +from mypy.ipc import IPCBase + +DEFAULT_STATUS_FILE: Final = ".dmypy.json" + + +def receive(connection: IPCBase) -> Any: + """Receive single JSON data frame from a connection. + + Raise OSError if the data received is not valid JSON or if it is + not a dict. + """ + bdata = connection.read() + if not bdata: + raise OSError("No data received") + try: + data = json.loads(bdata) + except Exception as e: + raise OSError("Data received is not valid JSON") from e + if not isinstance(data, dict): + raise OSError(f"Data received is not a dict ({type(data)})") + return data + + +def send(connection: IPCBase, data: Any) -> None: + """Send data to a connection encoded and framed. + + The data must be JSON-serializable. We assume that a single send call is a + single frame to be sent on the connect. + """ + connection.write(json.dumps(data)) + + +class WriteToConn(TextIO): + """Helper class to write to a connection instead of standard output.""" + + def __init__(self, server: IPCBase, output_key: str, isatty: bool) -> None: + self.server = server + self.output_key = output_key + self._isatty = isatty + + def __enter__(self) -> TextIO: + return self + + def __exit__( + self, + t: type[BaseException] | None, + value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + pass + + def __iter__(self) -> Iterator[str]: + raise io.UnsupportedOperation + + def __next__(self) -> str: + raise io.UnsupportedOperation + + def close(self) -> None: + pass + + def fileno(self) -> int: + raise OSError + + def flush(self) -> None: + pass + + def isatty(self) -> bool: + return self._isatty + + def read(self, n: int = 0) -> str: + raise io.UnsupportedOperation + + def readable(self) -> bool: + return False + + def readline(self, limit: int = 0) -> str: + raise io.UnsupportedOperation + + def readlines(self, hint: int = 0) -> list[str]: + raise io.UnsupportedOperation + + def seek(self, offset: int, whence: int = 0) -> int: + raise io.UnsupportedOperation + + def seekable(self) -> bool: + return False + + def tell(self) -> int: + raise io.UnsupportedOperation + + def truncate(self, size: int | None = 0) -> int: + raise io.UnsupportedOperation + + def write(self, output: str) -> int: + resp: dict[str, Any] = {self.output_key: output} + send(self.server, resp) + return len(output) + + def writable(self) -> bool: + return True + + def writelines(self, lines: Iterable[str]) -> None: + for s in lines: + self.write(s) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/erasetype.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/erasetype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..4c9f9e8f9aa68140d4e0ae940c42bdce79c1da06 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/erasetype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/erasetype.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/erasetype.py new file mode 100644 index 0000000000000000000000000000000000000000..cb8d66f292dd3157b781ad8aa3cc5ebdf3e3e6d2 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/erasetype.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +from collections.abc import Callable, Container +from typing import cast + +from mypy.nodes import ARG_STAR, ARG_STAR2 +from mypy.types import ( + AnyType, + CallableType, + DeletedType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeTranslator, + TypeType, + TypeVarId, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + get_proper_type, + get_proper_types, +) +from mypy.typevartuples import erased_vars + + +def erase_type(typ: Type) -> ProperType: + """Erase any type variables from a type. + + Also replace tuple types with the corresponding concrete types. + + Examples: + A -> A + B[X] -> B[Any] + Tuple[A, B] -> tuple + Callable[[A1, A2, ...], R] -> Callable[..., Any] + Type[X] -> Type[Any] + """ + typ = get_proper_type(typ) + return typ.accept(EraseTypeVisitor()) + + +class EraseTypeVisitor(TypeVisitor[ProperType]): + def visit_unbound_type(self, t: UnboundType) -> ProperType: + # TODO: replace with an assert after UnboundType can't leak from semantic analysis. + return AnyType(TypeOfAny.from_error) + + def visit_any(self, t: AnyType) -> ProperType: + return t + + def visit_none_type(self, t: NoneType) -> ProperType: + return t + + def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType: + return t + + def visit_erased_type(self, t: ErasedType) -> ProperType: + return t + + def visit_partial_type(self, t: PartialType) -> ProperType: + # Should not get here. + raise RuntimeError("Cannot erase partial types") + + def visit_deleted_type(self, t: DeletedType) -> ProperType: + return t + + def visit_instance(self, t: Instance) -> ProperType: + args = erased_vars(t.type.defn.type_vars, TypeOfAny.special_form) + return Instance(t.type, args, t.line) + + def visit_type_var(self, t: TypeVarType) -> ProperType: + return AnyType(TypeOfAny.special_form) + + def visit_param_spec(self, t: ParamSpecType) -> ProperType: + return AnyType(TypeOfAny.special_form) + + def visit_parameters(self, t: Parameters) -> ProperType: + raise RuntimeError("Parameters should have been bound to a class") + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType: + # Likely, we can never get here because of aggressive erasure of types that + # can contain this, but better still return a valid replacement. + return t.tuple_fallback.copy_modified(args=[AnyType(TypeOfAny.special_form)]) + + def visit_unpack_type(self, t: UnpackType) -> ProperType: + return AnyType(TypeOfAny.special_form) + + def visit_callable_type(self, t: CallableType) -> ProperType: + # We must preserve the fallback type for overload resolution to work. + any_type = AnyType(TypeOfAny.special_form) + return CallableType( + arg_types=[any_type, any_type], + arg_kinds=[ARG_STAR, ARG_STAR2], + arg_names=[None, None], + ret_type=any_type, + fallback=t.fallback, + is_ellipsis_args=True, + implicit=True, + ) + + def visit_overloaded(self, t: Overloaded) -> ProperType: + return t.fallback.accept(self) + + def visit_tuple_type(self, t: TupleType) -> ProperType: + return t.partial_fallback.accept(self) + + def visit_typeddict_type(self, t: TypedDictType) -> ProperType: + return t.fallback.accept(self) + + def visit_literal_type(self, t: LiteralType) -> ProperType: + # The fallback for literal types should always be either + # something like int or str, or an enum class -- types that + # don't contain any TypeVars. So there's no need to visit it. + return t + + def visit_union_type(self, t: UnionType) -> ProperType: + erased_items = [erase_type(item) for item in t.items] + from mypy.typeops import make_simplified_union + + return make_simplified_union(erased_items) + + def visit_type_type(self, t: TypeType) -> ProperType: + return TypeType.make_normalized( + t.item.accept(self), line=t.line, is_type_form=t.is_type_form + ) + + def visit_type_alias_type(self, t: TypeAliasType) -> ProperType: + raise RuntimeError("Type aliases should be expanded before accepting this visitor") + + +def erase_typevars(t: Type, ids_to_erase: Container[TypeVarId] | None = None) -> Type: + """Replace all type variables in a type with any, + or just the ones in the provided collection. + """ + + if ids_to_erase is None: + return t.accept(TypeVarEraser(None, AnyType(TypeOfAny.special_form))) + + def erase_id(id: TypeVarId) -> bool: + return id in ids_to_erase + + return t.accept(TypeVarEraser(erase_id, AnyType(TypeOfAny.special_form))) + + +def erase_meta_id(id: TypeVarId) -> bool: + return id.is_meta_var() + + +def replace_meta_vars(t: Type, target_type: Type) -> Type: + """Replace unification variables in a type with the target type.""" + return t.accept(TypeVarEraser(erase_meta_id, target_type)) + + +class TypeVarEraser(TypeTranslator): + """Implementation of type erasure""" + + def __init__(self, erase_id: Callable[[TypeVarId], bool] | None, replacement: Type) -> None: + super().__init__() + self.erase_id = erase_id + self.replacement = replacement + + def visit_type_var(self, t: TypeVarType) -> Type: + if self.erase_id is None or self.erase_id(t.id): + return self.replacement + return t + + # TODO: below two methods duplicate some logic with expand_type(). + # In fact, we may want to refactor this whole visitor to use expand_type(). + def visit_instance(self, t: Instance) -> Type: + result = super().visit_instance(t) + assert isinstance(result, ProperType) and isinstance(result, Instance) + if t.type.fullname == "builtins.tuple": + # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...] + arg = result.args[0] + if isinstance(arg, UnpackType): + unpacked = get_proper_type(arg.type) + if isinstance(unpacked, Instance): + assert unpacked.type.fullname == "builtins.tuple" + return unpacked + return result + + def visit_tuple_type(self, t: TupleType) -> Type: + result = super().visit_tuple_type(t) + assert isinstance(result, ProperType) and isinstance(result, TupleType) + if len(result.items) == 1: + # Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...] + item = result.items[0] + if isinstance(item, UnpackType): + unpacked = get_proper_type(item.type) + if isinstance(unpacked, Instance): + assert unpacked.type.fullname == "builtins.tuple" + if result.partial_fallback.type.fullname != "builtins.tuple": + # If it is a subtype (like named tuple) we need to preserve it, + # this essentially mimics the logic in tuple_fallback(). + return result.partial_fallback.accept(self) + return unpacked + return result + + def visit_callable_type(self, t: CallableType) -> Type: + result = super().visit_callable_type(t) + assert isinstance(result, ProperType) and isinstance(result, CallableType) + # Usually this is done in semanal_typeargs.py, but erasure can create + # a non-normal callable from normal one. + result.normalize_trivial_unpack() + return result + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + if self.erase_id is None or self.erase_id(t.id): + return t.tuple_fallback.copy_modified(args=[self.replacement]) + return t + + def visit_param_spec(self, t: ParamSpecType) -> Type: + # TODO: we should probably preserve prefix here. + if self.erase_id is None or self.erase_id(t.id): + return self.replacement + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # Type alias target can't contain bound type variables (not bound by the type + # alias itself), so it is safe to just erase the arguments. + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def remove_instance_last_known_values(t: Type) -> Type: + return t.accept(LastKnownValueEraser()) + + +class LastKnownValueEraser(TypeTranslator): + """Removes the Literal[...] type that may be associated with any + Instance types.""" + + def visit_instance(self, t: Instance) -> Type: + if not t.last_known_value and not t.args: + return t + return t.copy_modified(args=[a.accept(self) for a in t.args], last_known_value=None) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # Type aliases can't contain literal values, because they are + # always constructed as explicit types. + return t + + def visit_union_type(self, t: UnionType) -> Type: + new = cast(UnionType, super().visit_union_type(t)) + # Erasure can result in many duplicate items; merge them. + # Call make_simplified_union only on lists of instance types + # that all have the same fullname, to avoid simplifying too + # much. + instances = [item for item in new.items if isinstance(get_proper_type(item), Instance)] + # Avoid merge in simple cases such as optional types. + if len(instances) > 1: + instances_by_name: dict[str, list[Instance]] = {} + p_new_items = get_proper_types(new.items) + for p_item in p_new_items: + if isinstance(p_item, Instance) and not p_item.args: + instances_by_name.setdefault(p_item.type.fullname, []).append(p_item) + merged: list[Type] = [] + for item in new.items: + orig_item = item + item = get_proper_type(item) + if isinstance(item, Instance) and not item.args: + types = instances_by_name.get(item.type.fullname) + if types is not None: + if len(types) == 1: + merged.append(item) + else: + from mypy.typeops import make_simplified_union + + merged.append(make_simplified_union(types)) + del instances_by_name[item.type.fullname] + else: + merged.append(orig_item) + return UnionType.make_union(merged) + return new + + +def shallow_erase_type_for_equality(typ: Type) -> ProperType: + """Erase type variables from Instance's""" + p_typ = get_proper_type(typ) + if isinstance(p_typ, Instance): + if not p_typ.args: + return p_typ + args = erased_vars(p_typ.type.defn.type_vars, TypeOfAny.special_form) + return Instance(p_typ.type, args, p_typ.line) + if isinstance(p_typ, UnionType): + items = [shallow_erase_type_for_equality(item) for item in p_typ.items] + return UnionType.make_union(items) + return p_typ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/error_formatter.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/error_formatter.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..1cbe5e48725efa9f7771719eeb999caddc7a5d01 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/error_formatter.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/error_formatter.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/error_formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb962e4641fed59468eaa09e147111c63e03837 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/error_formatter.py @@ -0,0 +1,39 @@ +"""Defines the different custom formats in which mypy can output.""" + +import json +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mypy.errors import MypyError + + +class ErrorFormatter(ABC): + """Base class to define how errors are formatted before being printed.""" + + @abstractmethod + def report_error(self, error: "MypyError") -> str: + raise NotImplementedError + + +class JSONFormatter(ErrorFormatter): + """Formatter for basic JSON output format.""" + + def report_error(self, error: "MypyError") -> str: + """Prints out the errors as simple, static JSON lines.""" + return json.dumps( + { + "file": error.file_path, + "line": error.line, + "column": error.column, + "end_line": error.end_line, + "end_column": error.end_column, + "message": error.message, + "hint": None if len(error.hints) == 0 else "\n".join(error.hints), + "code": error.errorcode, + "severity": error.severity, + } + ) + + +OUTPUT_CHOICES = {"json": JSONFormatter()} diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errorcodes.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errorcodes.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ecf74de6283e4d0dc9ae94c7e1548301eb665111 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errorcodes.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errorcodes.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errorcodes.py new file mode 100644 index 0000000000000000000000000000000000000000..5c28e8332a76cdc75f2c84964ce7d2e95171696c --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errorcodes.py @@ -0,0 +1,333 @@ +"""Classification of possible errors mypy can detect. + +These can be used for filtering specific errors. +""" + +from __future__ import annotations + +from collections import defaultdict +from typing import Final + +from mypy_extensions import mypyc_attr + +error_codes: dict[str, ErrorCode] = {} +sub_code_map: dict[str, set[str]] = defaultdict(set) + + +@mypyc_attr(allow_interpreted_subclasses=True) +class ErrorCode: + def __init__( + self, + code: str, + description: str, + category: str, + default_enabled: bool = True, + sub_code_of: ErrorCode | None = None, + ) -> None: + self.code = code + self.description = description + self.category = category + self.default_enabled = default_enabled + self.sub_code_of = sub_code_of + if sub_code_of is not None: + assert sub_code_of.sub_code_of is None, "Nested subcategories are not supported" + sub_code_map[sub_code_of.code].add(code) + error_codes[code] = self + + def __str__(self) -> str: + return f"" + + def __repr__(self) -> str: + """This doesn't fulfill the goals of repr but it's better than the default view.""" + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ErrorCode): + return False + return self.code == other.code + + def __hash__(self) -> int: + return hash((self.code,)) + + +ATTR_DEFINED: Final = ErrorCode("attr-defined", "Check that attribute exists", "General") +NAME_DEFINED: Final = ErrorCode("name-defined", "Check that name is defined", "General") +CALL_ARG: Final = ErrorCode( + "call-arg", "Check number, names and kinds of arguments in calls", "General" +) +ARG_TYPE: Final = ErrorCode("arg-type", "Check argument types in calls", "General") +CALL_OVERLOAD: Final = ErrorCode( + "call-overload", "Check that an overload variant matches arguments", "General" +) +VALID_TYPE: Final = ErrorCode("valid-type", "Check that type (annotation) is valid", "General") +NONETYPE_TYPE: Final = ErrorCode( + "nonetype-type", "Check that type (annotation) is not NoneType", "General" +) +VAR_ANNOTATED: Final = ErrorCode( + "var-annotated", "Require variable annotation if type can't be inferred", "General" +) +OVERRIDE: Final = ErrorCode( + "override", "Check that method override is compatible with base class", "General" +) +RETURN: Final = ErrorCode("return", "Check that function always returns a value", "General") +RETURN_VALUE: Final = ErrorCode( + "return-value", "Check that return value is compatible with signature", "General" +) +ASSIGNMENT: Final = ErrorCode( + "assignment", "Check that assigned value is compatible with target", "General" +) +METHOD_ASSIGN: Final = ErrorCode( + "method-assign", + "Check that assignment target is not a method", + "General", + sub_code_of=ASSIGNMENT, +) +TYPE_ARG: Final = ErrorCode("type-arg", "Check that generic type arguments are present", "General") +TYPE_VAR: Final = ErrorCode("type-var", "Check that type variable values are valid", "General") +UNION_ATTR: Final = ErrorCode( + "union-attr", "Check that attribute exists in each item of a union", "General" +) +INDEX: Final = ErrorCode("index", "Check indexing operations", "General") +OPERATOR: Final = ErrorCode("operator", "Check that operator is valid for operands", "General") +LIST_ITEM: Final = ErrorCode( + "list-item", "Check list items in a list expression [item, ...]", "General" +) +DICT_ITEM: Final = ErrorCode( + "dict-item", "Check dict items in a dict expression {key: value, ...}", "General" +) +TYPEDDICT_ITEM: Final = ErrorCode( + "typeddict-item", "Check items when constructing TypedDict", "General" +) +TYPEDDICT_UNKNOWN_KEY: Final = ErrorCode( + "typeddict-unknown-key", + "Check unknown keys when constructing TypedDict", + "General", + sub_code_of=TYPEDDICT_ITEM, +) +HAS_TYPE: Final = ErrorCode( + "has-type", "Check that type of reference can be determined", "General" +) +IMPORT: Final = ErrorCode( + "import", "Require that imported module can be found or has stubs", "General" +) +IMPORT_NOT_FOUND: Final = ErrorCode( + "import-not-found", "Require that imported module can be found", "General", sub_code_of=IMPORT +) +IMPORT_UNTYPED: Final = ErrorCode( + "import-untyped", "Require that imported module has stubs", "General", sub_code_of=IMPORT +) +NO_REDEF: Final = ErrorCode("no-redef", "Check that each name is defined once", "General") +FUNC_RETURNS_VALUE: Final = ErrorCode( + "func-returns-value", "Check that called function returns a value in value context", "General" +) +ABSTRACT: Final = ErrorCode( + "abstract", "Prevent instantiation of classes with abstract attributes", "General" +) +TYPE_ABSTRACT: Final = ErrorCode( + "type-abstract", "Require only concrete classes where Type[...] is expected", "General" +) +VALID_NEWTYPE: Final = ErrorCode( + "valid-newtype", "Check that argument 2 to NewType is valid", "General" +) +STRING_FORMATTING: Final = ErrorCode( + "str-format", "Check that string formatting/interpolation is type-safe", "General" +) +STR_BYTES_PY3: Final = ErrorCode( + "str-bytes-safe", "Warn about implicit coercions related to bytes and string types", "General" +) +EXIT_RETURN: Final = ErrorCode( + "exit-return", "Warn about too general return type for '__exit__'", "General" +) +LITERAL_REQ: Final = ErrorCode("literal-required", "Check that value is a literal", "General") +UNUSED_COROUTINE: Final = ErrorCode( + "unused-coroutine", "Ensure that all coroutines are used", "General" +) +EMPTY_BODY: Final = ErrorCode( + "empty-body", + "A dedicated error code to opt out return errors for empty/trivial bodies", + "General", +) +SAFE_SUPER: Final = ErrorCode( + "safe-super", "Warn about calls to abstract methods with empty/trivial bodies", "General" +) +TOP_LEVEL_AWAIT: Final = ErrorCode( + "top-level-await", "Warn about top level await expressions", "General" +) +AWAIT_NOT_ASYNC: Final = ErrorCode( + "await-not-async", 'Warn about "await" outside coroutine ("async def")', "General" +) +# These error codes aren't enabled by default. +NO_UNTYPED_DEF: Final = ErrorCode( + "no-untyped-def", "Check that every function has an annotation", "General" +) +NO_UNTYPED_CALL: Final = ErrorCode( + "no-untyped-call", + "Disallow calling functions without type annotations from annotated functions", + "General", +) +REDUNDANT_CAST: Final = ErrorCode( + "redundant-cast", "Check that cast changes type of expression", "General" +) +ASSERT_TYPE: Final = ErrorCode("assert-type", "Check that assert_type() call succeeds", "General") +COMPARISON_OVERLAP: Final = ErrorCode( + "comparison-overlap", "Check that types in comparisons and 'in' expressions overlap", "General" +) +NO_ANY_UNIMPORTED: Final = ErrorCode( + "no-any-unimported", 'Reject "Any" types from unfollowed imports', "General" +) +NO_ANY_RETURN: Final = ErrorCode( + "no-any-return", + 'Reject returning value with "Any" type if return type is not "Any"', + "General", +) +UNREACHABLE: Final = ErrorCode( + "unreachable", "Warn about unreachable statements or expressions", "General" +) +ANNOTATION_UNCHECKED: Final = ErrorCode( + "annotation-unchecked", "Notify about type annotations in unchecked functions", "General" +) +TYPEDDICT_READONLY_MUTATED: Final = ErrorCode( + "typeddict-readonly-mutated", "TypedDict's ReadOnly key is mutated", "General" +) +POSSIBLY_UNDEFINED: Final = ErrorCode( + "possibly-undefined", + "Warn about variables that are defined only in some execution paths", + "General", + default_enabled=False, +) +REDUNDANT_EXPR: Final = ErrorCode( + "redundant-expr", "Warn about redundant expressions", "General", default_enabled=False +) +TRUTHY_BOOL: Final = ErrorCode( + "truthy-bool", + "Warn about expressions that could always evaluate to true in boolean contexts", + "General", + default_enabled=False, +) +TRUTHY_FUNCTION: Final = ErrorCode( + "truthy-function", + "Warn about function that always evaluate to true in boolean contexts", + "General", +) +TRUTHY_ITERABLE: Final = ErrorCode( + "truthy-iterable", + "Warn about Iterable expressions that could always evaluate to true in boolean contexts", + "General", + default_enabled=False, +) +STR_UNPACK: Final[ErrorCode] = ErrorCode( + "str-unpack", "Warn about expressions that unpack str", "General" +) +NAME_MATCH: Final = ErrorCode( + "name-match", "Check that type definition has consistent naming", "General" +) +NO_OVERLOAD_IMPL: Final = ErrorCode( + "no-overload-impl", + "Check that overloaded functions outside stub files have an implementation", + "General", +) +IGNORE_WITHOUT_CODE: Final = ErrorCode( + "ignore-without-code", + "Warn about '# type: ignore' comments which do not have error codes", + "General", + default_enabled=False, +) +UNUSED_AWAITABLE: Final = ErrorCode( + "unused-awaitable", + "Ensure that all awaitable values are used", + "General", + default_enabled=False, +) +REDUNDANT_SELF_TYPE: Final = ErrorCode( + "redundant-self", + "Warn about redundant Self type annotations on method first argument", + "General", + default_enabled=False, +) +USED_BEFORE_DEF: Final = ErrorCode( + "used-before-def", "Warn about variables that are used before they are defined", "General" +) +UNUSED_IGNORE: Final = ErrorCode( + "unused-ignore", "Ensure that all type ignores are used", "General", default_enabled=False +) +EXPLICIT_OVERRIDE_REQUIRED: Final = ErrorCode( + "explicit-override", + "Require @override decorator if method is overriding a base class method", + "General", + default_enabled=False, +) +UNIMPORTED_REVEAL: Final = ErrorCode( + "unimported-reveal", + "Require explicit import from typing or typing_extensions for reveal_type", + "General", + default_enabled=False, +) +MUTABLE_OVERRIDE: Final = ErrorCode( + "mutable-override", + "Reject covariant overrides for mutable attributes", + "General", + default_enabled=False, +) +EXHAUSTIVE_MATCH: Final = ErrorCode( + "exhaustive-match", + "Reject match statements that are not exhaustive", + "General", + default_enabled=False, +) +METACLASS: Final = ErrorCode("metaclass", "Ensure that metaclass is valid", "General") +MAYBE_UNRECOGNIZED_STR_TYPEFORM: Final = ErrorCode( + "maybe-unrecognized-str-typeform", + "Error when a string is used where a TypeForm is expected but a string annotation cannot be recognized", + "General", +) + +# Syntax errors are often blocking. +SYNTAX: Final = ErrorCode("syntax", "Report syntax errors", "General") + +# This is a catch-all for remaining uncategorized errors. +MISC: Final = ErrorCode("misc", "Miscellaneous other checks", "General") + +OVERLOAD_CANNOT_MATCH: Final = ErrorCode( + "overload-cannot-match", + "Warn if an @overload signature can never be matched", + "General", + sub_code_of=MISC, +) + +OVERLOAD_OVERLAP: Final = ErrorCode( + "overload-overlap", + "Warn if multiple @overload variants overlap in unsafe ways", + "General", + sub_code_of=MISC, +) + +PROPERTY_DECORATOR: Final = ErrorCode( + "prop-decorator", + "Decorators on top of @property are not supported", + "General", + sub_code_of=MISC, +) + +UNTYPED_DECORATOR: Final = ErrorCode( + "untyped-decorator", "Error if an untyped decorator makes a typed function untyped", "General" +) + +NARROWED_TYPE_NOT_SUBTYPE: Final = ErrorCode( + "narrowed-type-not-subtype", + "Warn if a TypeIs function's narrowed type is not a subtype of the original type", + "General", +) + +EXPLICIT_ANY: Final = ErrorCode( + "explicit-any", "Warn about explicit Any type annotations", "General" +) + +DEPRECATED: Final = ErrorCode( + "deprecated", + "Warn when importing or using deprecated (overloaded) functions, methods or classes", + "General", + default_enabled=False, +) + +# This copy will not include any error codes defined later in the plugins. +mypy_error_codes = error_codes.copy() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errors.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errors.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..d0f0b909771906717cc4497c469ca4a3edd45584 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errors.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errors.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..5ffada781b9ab156165eb14268654cb58163d1ea --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/errors.py @@ -0,0 +1,1471 @@ +from __future__ import annotations + +import os.path +import sys +import traceback +from collections import defaultdict +from collections.abc import Callable, Iterable, Iterator +from itertools import chain +from typing import Final, Literal, NoReturn, TextIO, TypeVar +from typing_extensions import Self + +from librt.internal import ( + ReadBuffer, + WriteBuffer, + read_bool, + read_int as read_int_bare, + write_bool, + write_int as write_int_bare, +) + +from mypy import errorcodes as codes +from mypy.cache import ( + ErrorTuple, + read_int, + read_int_list, + read_str, + read_str_opt, + write_int, + write_int_list, + write_str, + write_str_opt, +) +from mypy.error_formatter import ErrorFormatter +from mypy.errorcodes import IMPORT, IMPORT_NOT_FOUND, IMPORT_UNTYPED, ErrorCode, mypy_error_codes +from mypy.nodes import Context +from mypy.options import Options +from mypy.scope import Scope +from mypy.types import Type +from mypy.util import DEFAULT_SOURCE_OFFSET +from mypy.version import __version__ as mypy_version + +T = TypeVar("T") + +# Show error codes for some note-level messages (these usually appear alone +# and not as a comment for a previous error-level message). +SHOW_NOTE_CODES: Final = {codes.ANNOTATION_UNCHECKED.code, codes.DEPRECATED.code} + +# Do not add notes with links to error code docs to errors with these codes. +# We can tweak this set as we get more experience about what is helpful and what is not. +HIDE_LINK_CODES: Final = { + # This is a generic error code, so it has no useful docs + codes.MISC, + # These are trivial and have some custom notes (e.g. for list being invariant) + codes.ASSIGNMENT, + codes.ARG_TYPE, + codes.RETURN_VALUE, + # Undefined name/attribute errors are self-explanatory + codes.ATTR_DEFINED, + codes.NAME_DEFINED, + # Overrides have a custom link to docs + codes.OVERRIDE, +} + +BASE_RTD_URL: Final = "https://mypy.rtfd.io/en/stable/_refs.html#code" + +# Keep track of the original error code when the error code of a message is changed. +# This is used to give notes about out-of-date "type: ignore" comments. +original_error_codes: Final = {codes.LITERAL_REQ: codes.MISC, codes.TYPE_ABSTRACT: codes.MISC} + + +class ErrorInfo: + """Representation of a single error message.""" + + # Description of a sequence of imports that refer to the source file + # related to this error. Each item is a (path, line number) tuple. + import_ctx: list[tuple[str, int]] + # Type and function/method where this error occurred. Unqualified, may be None. + local_ctx: tuple[str | None, str | None] + + # The line number related to this error within file. + line = 0 # -1 if unknown + # The column number related to this error with file. + column = 0 # -1 if unknown + # The end line number related to this error within file. + end_line = 0 # -1 if unknown + # The end column number related to this error with file. + end_column = 0 # -1 if unknown + # Either 'error' or 'note' + severity = "" + # The error message. + message = "" + # The error code. + code: ErrorCode | None = None + + # If True, we should halt build after the file that generated this error. + blocker = False + # Only report this particular messages once per program. + only_once = False + + # These two are used by the daemon: + # The fully-qualified id of the source module for this error. + module: str | None + # Fine-grained incremental target where this was reported + target: str | None + + # Lines where `type: ignores` will have effect on this error, for most errors + # this is just [line]. But sometimes may be custom, e.g. for override errors + # in methods with multi-line definition. + origin_span: Iterable[int] + # For errors on the same line you can use this to customize their sorting + # (lower value means show first). + priority: int + # If True, don't show this message in output, but still record the error. + hidden = False + + # For notes, specifies (optionally) the error this note is attached to. This is used to + # simplify error code matching and de-duplication logic for complex multi-line notes. + parent_error: ErrorInfo | None = None + + def __init__( + self, + *, + import_ctx: list[tuple[str, int]], + local_ctx: tuple[str | None, str | None], + line: int, + column: int, + end_line: int, + end_column: int, + severity: str, + message: str, + code: ErrorCode | None, + blocker: bool, + only_once: bool, + module: str | None, + target: str | None, + origin_span: Iterable[int] | None = None, + priority: int = 0, + parent_error: ErrorInfo | None = None, + ) -> None: + self.import_ctx = import_ctx + self.module = module + self.local_ctx = local_ctx + self.line = line + self.column = column + self.end_line = end_line + self.end_column = end_column + self.severity = severity + self.message = message + self.code = code + self.blocker = blocker + self.only_once = only_once + self.origin_span = origin_span or [line] + self.target = target + self.priority = priority + if parent_error is not None: + assert severity == "note", "Only notes can specify parent errors" + self.parent_error = parent_error + + def write(self, buf: WriteBuffer) -> None: + assert self.parent_error is None, "Parent errors not supported yet" + write_int_bare(buf, len(self.import_ctx)) + for file, line in self.import_ctx: + write_str(buf, file) + write_int(buf, line) + type, function = self.local_ctx + write_str_opt(buf, type) + write_str_opt(buf, function) + write_int(buf, self.line) + write_int(buf, self.column) + write_int(buf, self.end_line) + write_int(buf, self.end_column) + write_str(buf, self.severity) + write_str(buf, self.message) + write_str_opt(buf, self.code.code if self.code else None) + write_bool(buf, self.blocker) + write_bool(buf, self.only_once) + write_str_opt(buf, self.module) + write_str_opt(buf, self.target) + write_int_list(buf, list(self.origin_span)) + write_int(buf, self.priority) + + @classmethod + def read(cls, buf: ReadBuffer) -> ErrorInfo: + return ErrorInfo( + import_ctx=[(read_str(buf), read_int(buf)) for _ in range(read_int_bare(buf))], + local_ctx=(read_str_opt(buf), read_str_opt(buf)), + line=read_int(buf), + column=read_int(buf), + end_line=read_int(buf), + end_column=read_int(buf), + severity=read_str(buf), + message=read_str(buf), + code=mypy_error_codes[code] if (code := read_str_opt(buf)) else None, + blocker=read_bool(buf), + only_once=read_bool(buf), + module=read_str_opt(buf), + target=read_str_opt(buf), + origin_span=read_int_list(buf), + priority=read_int(buf), + ) + + +class ErrorWatcher: + """Context manager that can be used to keep track of new errors recorded + around a given operation. + + Errors maintain a stack of such watchers. The handler is called starting + at the top of the stack, and is propagated down the stack unless filtered + out by one of the ErrorWatcher instances. + """ + + # public attribute for the special treatment of `reveal_type` by + # `MessageBuilder.reveal_type`: + filter_revealed_type: bool + + def __init__( + self, + errors: Errors, + *, + filter_errors: bool | Callable[[str, ErrorInfo], bool] = False, + save_filtered_errors: bool = False, + filter_deprecated: bool = False, + filter_revealed_type: bool = False, + ) -> None: + self.errors = errors + self._has_new_errors = False + self._filter = filter_errors + self._filter_deprecated = filter_deprecated + self.filter_revealed_type = filter_revealed_type + self._filtered: list[ErrorInfo] | None = [] if save_filtered_errors else None + + def __enter__(self) -> Self: + self.errors._watchers.append(self) + return self + + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]: + last = self.errors._watchers.pop() + assert last == self + return False + + def on_error(self, file: str, info: ErrorInfo) -> bool: + """Handler called when a new error is recorded. + + The default implementation just sets the has_new_errors flag + + Return True to filter out the error, preventing it from being seen by other + ErrorWatcher further down the stack and from being recorded by Errors + """ + if info.code == codes.DEPRECATED: + # Deprecated is not a type error, so it is handled on opt-in basis here. + if not self._filter_deprecated: + return False + + self._has_new_errors = True + if isinstance(self._filter, bool): + should_filter = self._filter + elif callable(self._filter): + should_filter = self._filter(file, info) + else: + raise AssertionError(f"invalid error filter: {type(self._filter)}") + if should_filter and self._filtered is not None: + self._filtered.append(info) + + return should_filter + + def has_new_errors(self) -> bool: + return self._has_new_errors + + def filtered_errors(self) -> list[ErrorInfo]: + assert self._filtered is not None + return self._filtered + + +class NonOverlapErrorInfo: + line: int + column: int + end_line: int | None + end_column: int | None + kind: str + + def __init__( + self, *, line: int, column: int, end_line: int | None, end_column: int | None, kind: str + ) -> None: + self.line = line + self.column = column + self.end_line = end_line + self.end_column = end_column + self.kind = kind + + def __eq__(self, other: object) -> bool: + if isinstance(other, NonOverlapErrorInfo): + return ( + self.line == other.line + and self.column == other.column + and self.end_line == other.end_line + and self.end_column == other.end_column + and self.kind == other.kind + ) + return False + + def __hash__(self) -> int: + return hash((self.line, self.column, self.end_line, self.end_column, self.kind)) + + +class IterationDependentErrors: + """An `IterationDependentErrors` instance serves to collect the `unreachable`, + `redundant-expr`, and `redundant-casts` errors, as well as the revealed types and + non-overlapping types, handled by the individual `IterationErrorWatcher` instances + sequentially applied to the same code section.""" + + # One set of `unreachable`, `redundant-expr`, and `redundant-casts` errors per + # iteration step. Meaning of the tuple items: ErrorCode, message, line, column, + # end_line, end_column. + uselessness_errors: list[set[tuple[ErrorCode, str, int, int, int, int]]] + + # One set of unreachable line numbers per iteration step. Not only the lines where + # the error report occurs but really all unreachable lines. + unreachable_lines: list[set[int]] + + # One list of revealed types for each `reveal_type` statement. Each created list + # can grow during the iteration. Meaning of the tuple items: line, column, + # end_line, end_column: + revealed_types: dict[tuple[int, int, int | None, int | None], list[Type]] + + # One dictionary of non-overlapping types per iteration step: + nonoverlapping_types: list[dict[NonOverlapErrorInfo, tuple[Type, Type]]] + + def __init__(self) -> None: + self.uselessness_errors = [] + self.unreachable_lines = [] + self.nonoverlapping_types = [] + self.revealed_types = defaultdict(list) + + def yield_uselessness_error_infos(self) -> Iterator[tuple[str, Context, ErrorCode]]: + """Report only those `unreachable`, `redundant-expr`, and `redundant-casts` + errors that could not be ruled out in any iteration step.""" + + persistent_uselessness_errors = set() + for candidate in set(chain(*self.uselessness_errors)): + if all( + (candidate in errors) or (candidate[2] in lines) + for errors, lines in zip(self.uselessness_errors, self.unreachable_lines) + ): + persistent_uselessness_errors.add(candidate) + for error_info in persistent_uselessness_errors: + context = Context(line=error_info[2], column=error_info[3]) + context.end_line = error_info[4] + context.end_column = error_info[5] + yield error_info[1], context, error_info[0] + + def yield_nonoverlapping_types( + self, + ) -> Iterator[tuple[tuple[list[Type], list[Type]], str, Context]]: + """Report expressions where non-overlapping types were detected for all iterations + were the expression was reachable.""" + + selected = set() + for candidate in set(chain.from_iterable(self.nonoverlapping_types)): + if all( + (candidate in nonoverlap) or (candidate.line in lines) + for nonoverlap, lines in zip(self.nonoverlapping_types, self.unreachable_lines) + ): + selected.add(candidate) + + persistent_nonoverlaps: dict[NonOverlapErrorInfo, tuple[list[Type], list[Type]]] = ( + defaultdict(lambda: ([], [])) + ) + for nonoverlaps in self.nonoverlapping_types: + for candidate, (left, right) in nonoverlaps.items(): + if candidate in selected: + types = persistent_nonoverlaps[candidate] + types[0].append(left) + types[1].append(right) + + for error_info, types in persistent_nonoverlaps.items(): + context = Context(line=error_info.line, column=error_info.column) + context.end_line = error_info.end_line + context.end_column = error_info.end_column + yield (types[0], types[1]), error_info.kind, context + + def yield_revealed_type_infos(self) -> Iterator[tuple[list[Type], Context]]: + """Yield all types revealed in at least one iteration step.""" + + for note_info, types in self.revealed_types.items(): + context = Context(line=note_info[0], column=note_info[1]) + context.end_line = note_info[2] + context.end_column = note_info[3] + yield types, context + + +class IterationErrorWatcher(ErrorWatcher): + """Error watcher that filters and separately collects `unreachable` errors, + `redundant-expr` and `redundant-casts` errors, and revealed types and + non-overlapping types when analysing code sections iteratively to help avoid + making too-hasty reports.""" + + iteration_dependent_errors: IterationDependentErrors + + def __init__( + self, + errors: Errors, + iteration_dependent_errors: IterationDependentErrors, + *, + filter_errors: bool | Callable[[str, ErrorInfo], bool] = False, + save_filtered_errors: bool = False, + filter_deprecated: bool = False, + ) -> None: + super().__init__( + errors, + filter_errors=filter_errors, + save_filtered_errors=save_filtered_errors, + filter_deprecated=filter_deprecated, + ) + self.iteration_dependent_errors = iteration_dependent_errors + iteration_dependent_errors.uselessness_errors.append(set()) + iteration_dependent_errors.nonoverlapping_types.append({}) + iteration_dependent_errors.unreachable_lines.append(set()) + + def on_error(self, file: str, info: ErrorInfo) -> bool: + """Filter out the "iteration-dependent" errors and notes and store their + information to handle them after iteration is completed.""" + + iter_errors = self.iteration_dependent_errors + + if info.code in (codes.UNREACHABLE, codes.REDUNDANT_EXPR, codes.REDUNDANT_CAST): + iter_errors.uselessness_errors[-1].add( + (info.code, info.message, info.line, info.column, info.end_line, info.end_column) + ) + if info.code == codes.UNREACHABLE: + iter_errors.unreachable_lines[-1].update(range(info.line, info.end_line + 1)) + return True + + return super().on_error(file, info) + + +class Errors: + """Container for compile errors. + + This class generates and keeps tracks of compile errors and the + current error context (nested imports). + """ + + # Map from files to generated error messages. Is an OrderedDict so + # that it can be used to order messages based on the order the + # files were processed. + error_info_map: dict[str, list[ErrorInfo]] + + # optimization for legacy codebases with many files with errors + has_blockers: set[str] + + # Files that we have reported the errors for + flushed_files: set[str] + + # Current error context: nested import context/stack, as a list of (path, line) pairs. + import_ctx: list[tuple[str, int]] + + # Path name prefix that is removed from all paths, if set. + ignore_prefix: str | None = None + + # Path to current file. + file: str = "" + + # Ignore some errors on these lines of each file + # (path -> line -> error-codes) + ignored_lines: dict[str, dict[int, list[str]]] + + # Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE, + # or platform/version checks. Those lines would not be type-checked. + skipped_lines: dict[str, set[int]] + + # Lines on which an error was actually ignored. + used_ignored_lines: dict[str, dict[int, list[str]]] + + # Files where all errors should be ignored. + ignored_files: set[str] + + # Collection of reported only_once messages. + only_once_messages: set[str] + + # State for keeping track of the current fine-grained incremental mode target. + # (See mypy.server.update for more about targets.) + # Current module id. + target_module: str | None = None + scope: Scope | None = None + + # Have we seen an import-related error so far? If yes, we filter out other messages + # in some cases to avoid reporting huge numbers of errors. + seen_import_error = False + + # Set this flag to record all raw report() calls. Recorded error (per file) can + # be replayed using by calling set_file() and add_error_info(). + global_watcher = False + recorded: dict[str, list[ErrorInfo]] + + _watchers: list[ErrorWatcher] + + def __init__( + self, + options: Options, + *, + read_source: Callable[[str], list[str] | None] | None = None, + hide_error_codes: bool | None = None, + ) -> None: + self.options = options + self.hide_error_codes = ( + hide_error_codes if hide_error_codes is not None else options.hide_error_codes + ) + # We use fscache to read source code when showing snippets. + self.read_source = read_source + self.initialize() + + def initialize(self) -> None: + self.error_info_map = {} + self.flushed_files = set() + self.import_ctx = [] + self.function_or_member = [None] + self.ignored_lines = {} + self.skipped_lines = {} + self.used_ignored_lines = defaultdict(lambda: defaultdict(list)) + self.ignored_files = set() + self.only_once_messages = set() + self.has_blockers = set() + self.scope = None + self.target_module = None + self.seen_import_error = False + self._watchers = [] + self.global_watcher = False + self.recorded = defaultdict(list) + + def reset(self) -> None: + self.initialize() + + def set_ignore_prefix(self, prefix: str) -> None: + """Set path prefix that will be removed from all paths.""" + prefix = os.path.normpath(prefix) + # Add separator to the end, if not given. + if os.path.basename(prefix) != "": + prefix += os.sep + self.ignore_prefix = prefix + + def simplify_path(self, file: str) -> str: + if self.options.show_absolute_path: + return os.path.abspath(file) + else: + file = os.path.normpath(file) + return remove_path_prefix(file, self.ignore_prefix) + + def set_file( + self, file: str, module: str | None, options: Options, scope: Scope | None = None + ) -> None: + """Set the path and module id of the current file.""" + # The path will be simplified later, in render_messages. That way + # * 'file' is always a key that uniquely identifies a source file + # that mypy read (simplified paths might not be unique); and + # * we only have to simplify in one place, while still supporting + # reporting errors for files other than the one currently being + # processed. + self.file = file + self.target_module = module + self.scope = scope + self.options = options + + def set_file_ignored_lines( + self, file: str, ignored_lines: dict[int, list[str]], ignore_all: bool = False + ) -> None: + self.ignored_lines[file] = ignored_lines + if ignore_all: + self.ignored_files.add(file) + + def set_skipped_lines(self, file: str, skipped_lines: set[int]) -> None: + self.skipped_lines[file] = skipped_lines + + def current_target(self) -> str | None: + """Retrieves the current target from the associated scope. + + If there is no associated scope, use the target module.""" + if self.scope is not None: + return self.scope.current_target() + return self.target_module + + def current_module(self) -> str | None: + return self.target_module + + def import_context(self) -> list[tuple[str, int]]: + """Return a copy of the import context.""" + return self.import_ctx.copy() + + def set_import_context(self, ctx: list[tuple[str, int]]) -> None: + """Replace the entire import context with a new value.""" + self.import_ctx = ctx.copy() + + def report( + self, + line: int, + column: int | None, + message: str, + code: ErrorCode | None = None, + *, + blocker: bool = False, + severity: str = "error", + only_once: bool = False, + origin_span: Iterable[int] | None = None, + offset: int = 0, + end_line: int | None = None, + end_column: int | None = None, + parent_error: ErrorInfo | None = None, + ) -> ErrorInfo: + """Report message at the given line using the current error context. + + Args: + line: line number of error + column: column number of error + message: message to report + code: error code (defaults to 'misc'; not shown for notes) + blocker: if True, don't continue analysis after this error + severity: 'error' or 'note' + only_once: if True, only report this exact message once per build + origin_span: lines where `type: ignore`s have effect for this error + (default is [line]) + offset: number of spaces to prefix this message + end_line: if known, end line of error location + end_column: if known, end column of error location + parent_error: an error this note is attached to (for notes only). + """ + if self.scope: + type = self.scope.current_type_name() + if self.scope.ignored > 0: + type = None # Omit type context if nested function + function = self.scope.current_function_name() + else: + type = None + function = None + + # It looks like there is a bug in how we parse f-strings, + # we cannot simply assert this yet. + if end_line is None or end_line < line: + end_line = line + + if column is None: + column = -1 + if end_column is None: + if column == -1: + end_column = -1 + else: + end_column = column + 1 + if line == end_line and end_column <= column: + # Be defensive, similar to the logic for lines above. + end_column = column + 1 + + if offset: + message = " " * offset + message + + code = code or (parent_error.code if parent_error else None) + if parent_error is not None: + assert code == parent_error.code, "Must have same error code as parent" + assert severity == "note", "Only notes can have parent errors" + code = code or (codes.MISC if not blocker else None) + + info = ErrorInfo( + import_ctx=self.import_context(), + local_ctx=(type, function), + line=line, + column=column, + end_line=end_line, + end_column=end_column, + severity=severity, + message=message, + code=code, + blocker=blocker, + only_once=only_once, + origin_span=origin_span, + module=self.current_module(), + target=self.current_target(), + parent_error=parent_error, + ) + if self.global_watcher: + self.recorded[self.file].append(info) + self.add_error_info(info) + return info + + def _add_error_info(self, file: str, info: ErrorInfo) -> None: + assert file not in self.flushed_files + # process the stack of ErrorWatchers before modifying any internal state + # in case we need to filter out the error entirely + if self._filter_error(file, info): + return + if file not in self.error_info_map: + self.error_info_map[file] = [] + self.error_info_map[file].append(info) + if info.blocker: + self.has_blockers.add(file) + if info.code in (IMPORT, IMPORT_UNTYPED, IMPORT_NOT_FOUND): + self.seen_import_error = True + + def note_for_info( + self, + file: str, + info: ErrorInfo, + message: str, + code: ErrorCode | None, + *, + only_once: bool = False, + priority: int = 0, + ) -> None: + """Generate an additional note for an existing ErrorInfo. + + This skip the logic in add_error_info() and goes to _add_error_info(). + """ + info = ErrorInfo( + import_ctx=info.import_ctx, + local_ctx=info.local_ctx, + line=info.line, + column=info.column, + end_line=info.end_line, + end_column=info.end_column, + severity="note", + message=message, + code=code, + blocker=False, + only_once=only_once, + module=info.module, + target=info.target, + origin_span=info.origin_span, + priority=priority, + ) + self._add_error_info(file, info) + + def report_simple_error( + self, file: str, line: int, message: str, code: ErrorCode | None + ) -> None: + """Generate a simple error in a module. + + This skip the logic in add_error_info() and goes to _add_error_info(). + """ + info = ErrorInfo( + import_ctx=self.import_context(), + local_ctx=(None, None), + line=line, + column=-1, + end_line=line, + end_column=-1, + severity="error", + message=message, + code=code, + blocker=False, + only_once=False, + module=self.current_module(), + # TODO: can we support more precise targets? + target=self.target_module, + ) + self._add_error_info(file, info) + + def get_watchers(self) -> Iterator[ErrorWatcher]: + """Yield the `ErrorWatcher` stack from top to bottom.""" + i = len(self._watchers) + while i > 0: + i -= 1 + yield self._watchers[i] + + def _filter_error(self, file: str, info: ErrorInfo) -> bool: + """ + process ErrorWatcher stack from top to bottom, + stopping early if error needs to be filtered out + """ + return any(w.on_error(file, info) for w in self.get_watchers()) + + def add_error_info(self, info: ErrorInfo, *, file: str | None = None) -> None: + lines = info.origin_span + file = file or self.file + # process the stack of ErrorWatchers before modifying any internal state + # in case we need to filter out the error entirely + # NB: we need to do this both here and in _add_error_info, otherwise we + # might incorrectly update the sets of ignored or only_once messages + if self._filter_error(file, info): + return + if not info.blocker: # Blockers cannot be ignored + if file in self.ignored_lines: + # Check each line in this context for "type: ignore" comments. + # line == end_line for most nodes, so we only loop once. + for scope_line in lines: + if self.is_ignored_error(scope_line, info, self.ignored_lines[file]): + err_code = info.code or codes.MISC + if not self.is_error_code_enabled(err_code): + # Error code is disabled - don't mark the current + # "type: ignore" comment as used. + return + # Annotation requests us to ignore all errors on this line. + self.used_ignored_lines[file][scope_line].append(err_code.code) + return + if file in self.ignored_files: + return + if info.only_once: + if info.message in self.only_once_messages: + return + self.only_once_messages.add(info.message) + if ( + self.seen_import_error + and info.code not in (IMPORT, IMPORT_UNTYPED, IMPORT_NOT_FOUND) + and self.has_many_errors() + ): + # Missing stubs can easily cause thousands of errors about + # Any types, especially when upgrading to mypy 0.900, + # which no longer bundles third-party library stubs. Avoid + # showing too many errors to make it easier to see + # import-related errors. + info.hidden = True + self.report_hidden_errors(file, info) + self._add_error_info(file, info) + ignored_codes = self.ignored_lines.get(file, {}).get(info.line, []) + if ignored_codes and info.code: + # Something is ignored on the line, but not this error, so maybe the error + # code is incorrect. + msg = f'Error code "{info.code.code}" not covered by "type: ignore" comment' + if info.code in original_error_codes: + # If there seems to be a "type: ignore" with a stale error + # code, report a more specific note. + old_code = original_error_codes[info.code].code + if old_code in ignored_codes: + msg = ( + f'Error code changed to {info.code.code}; "type: ignore" comment ' + + "may be out of date" + ) + self.note_for_info(file, info, msg, None, only_once=False) + if ( + self.options.show_error_code_links + and not self.options.hide_error_codes + and info.code is not None + and info.code not in HIDE_LINK_CODES + and info.code.code in mypy_error_codes + ): + message = f"See {BASE_RTD_URL}-{info.code.code} for more info" + if message in self.only_once_messages: + return + self.only_once_messages.add(message) + self.note_for_info(file, info, message, info.code, only_once=True, priority=20) + + def has_many_errors(self) -> bool: + if self.options.many_errors_threshold < 0: + return False + if len(self.error_info_map) >= self.options.many_errors_threshold: + return True + if ( + sum(len(errors) for errors in self.error_info_map.values()) + >= self.options.many_errors_threshold + ): + return True + return False + + def report_hidden_errors(self, file: str, info: ErrorInfo) -> None: + message = ( + "(Skipping most remaining errors due to unresolved imports or missing stubs; " + + "fix these first)" + ) + if message in self.only_once_messages: + return + self.only_once_messages.add(message) + self.note_for_info(file, info, message, None, only_once=True) + + def is_ignored_error(self, line: int, info: ErrorInfo, ignores: dict[int, list[str]]) -> bool: + if info.blocker: + # Blocking errors can never be ignored + return False + if info.code and not self.is_error_code_enabled(info.code): + return True + if line not in ignores: + return False + if not ignores[line]: + # Empty list means that we ignore all errors + return True + if info.code and self.is_error_code_enabled(info.code): + return ( + info.code.code in ignores[line] + or info.code.sub_code_of is not None + and info.code.sub_code_of.code in ignores[line] + ) + return False + + def is_error_code_enabled(self, error_code: ErrorCode) -> bool: + if self.options: + current_mod_disabled = self.options.disabled_error_codes + current_mod_enabled = self.options.enabled_error_codes + else: + current_mod_disabled = set() + current_mod_enabled = set() + + if error_code in current_mod_disabled: + return False + elif error_code in current_mod_enabled: + return True + elif error_code.sub_code_of is not None and error_code.sub_code_of in current_mod_disabled: + return False + else: + return error_code.default_enabled + + def clear_errors_in_targets(self, path: str, targets: set[str]) -> None: + """Remove errors in specific fine-grained targets within a file.""" + if path in self.error_info_map: + new_errors = [] + has_blocker = False + for info in self.error_info_map[path]: + if info.target not in targets: + new_errors.append(info) + has_blocker |= info.blocker + elif info.only_once: + self.only_once_messages.remove(info.message) + self.error_info_map[path] = new_errors + if not has_blocker and path in self.has_blockers: + self.has_blockers.remove(path) + + def generate_unused_ignore_errors(self, file: str, is_typeshed: bool = False) -> None: + if is_typeshed or file in self.ignored_files: + return + ignored_lines = self.ignored_lines[file] + used_ignored_lines = self.used_ignored_lines[file] + for line, ignored_codes in ignored_lines.items(): + if line in self.skipped_lines[file]: + continue + if codes.UNUSED_IGNORE.code in ignored_codes: + continue + used_ignored_codes = set(used_ignored_lines[line]) + unused_ignored_codes = [c for c in ignored_codes if c not in used_ignored_codes] + # `ignore` is used + if not ignored_codes and used_ignored_codes: + continue + # All codes appearing in `ignore[...]` are used + if ignored_codes and not unused_ignored_codes: + continue + # Display detail only when `ignore[...]` specifies more than one error code + unused_codes_message = "" + if len(ignored_codes) > 1 and unused_ignored_codes: + unused_codes_message = f"[{', '.join(unused_ignored_codes)}]" + message = f'Unused "type: ignore{unused_codes_message}" comment' + for unused in unused_ignored_codes: + narrower = set(used_ignored_codes) & codes.sub_code_map[unused] + if narrower: + message += f", use narrower [{', '.join(narrower)}] instead of [{unused}] code" + # Don't use report() since add_error_info will ignore the error! + self.report_simple_error(file, line, message, code=codes.UNUSED_IGNORE) + + def generate_ignore_without_code_errors( + self, file: str, is_warning_unused_ignores: bool, is_typeshed: bool = False + ) -> None: + if is_typeshed or file in self.ignored_files: + return + + used_ignored_lines = self.used_ignored_lines[file] + for line, ignored_codes in self.ignored_lines[file].items(): + if line in self.skipped_lines[file]: + continue + if ignored_codes: + continue + + # If the `type: ignore` is itself unused and that would be warned about, + # let that error stand alone + if is_warning_unused_ignores and not used_ignored_lines[line]: + continue + + codes_hint = "" + ignored_codes = sorted(set(used_ignored_lines[line])) + if ignored_codes: + codes_hint = f' (consider "type: ignore[{", ".join(ignored_codes)}]" instead)' + + message = f'"type: ignore" comment without error code{codes_hint}' + # Don't use report() since add_error_info will ignore the error! + self.report_simple_error(file, line, message, code=codes.IGNORE_WITHOUT_CODE) + + def num_messages(self) -> int: + """Return the number of generated messages.""" + return sum(len(x) for x in self.error_info_map.values()) + + def is_errors(self) -> bool: + """Are there any generated messages?""" + return bool(self.error_info_map) + + def is_blockers(self) -> bool: + """Are the any errors that are blockers?""" + return bool(self.has_blockers) + + def blocker_module(self) -> str | None: + """Return the module with a blocking error, or None if not possible.""" + for path in self.has_blockers: + for err in self.error_info_map[path]: + if err.blocker: + return err.module + return None + + def is_errors_for_file(self, file: str) -> bool: + """Are there any errors for the given file?""" + return file in self.error_info_map and file not in self.ignored_files + + def prefer_simple_messages(self) -> bool: + """Should we generate simple/fast error messages? + + Return True if errors are not shown to user, i.e. errors are ignored + or they are collected for internal use only. + + If True, we should prefer to generate a simple message quickly. + All normal errors should still be reported. + """ + if self.file in self.ignored_files: + # Errors ignored, so no point generating fancy messages + return True + if self.options.ignore_errors: + return True + if self._watchers: + _watcher = self._watchers[-1] + if _watcher._filter is True and _watcher._filtered is None: + # Errors are filtered + return True + return False + + def raise_error(self, use_stdout: bool = True) -> NoReturn: + """Raise a CompileError with the generated messages. + + Render the messages suitable for displaying. + """ + # self.new_messages() will format all messages that haven't already + # been returned from a file_messages() call. + raise CompileError( + self.new_messages(), use_stdout=use_stdout, module_with_blocker=self.blocker_module() + ) + + def format_messages_default( + self, error_tuples: list[ErrorTuple], source_lines: list[str] | None + ) -> list[str]: + """Return a string list that represents the error messages. + + Use a form suitable for displaying to the user. If self.pretty + is True also append a relevant trimmed source code line (only for + severity 'error'). + """ + a: list[str] = [] + for file, line, column, end_line, end_column, severity, message, code in error_tuples: + s = "" + if file is not None: + if self.options.show_column_numbers and line >= 0 and column >= 0: + srcloc = f"{file}:{line}:{1 + column}" + if self.options.show_error_end and end_line >= 0 and end_column >= 0: + srcloc += f":{end_line}:{end_column}" + elif line >= 0: + srcloc = f"{file}:{line}" + else: + srcloc = file + s = f"{srcloc}: {severity}: {message}" + else: + s = message + if ( + not self.hide_error_codes + and code + and (severity != "note" or code in SHOW_NOTE_CODES) + ): + # If note has an error code, it is related to a previous error. Avoid + # displaying duplicate error codes. + s = f"{s} [{code}]" + a.append(s) + if self.options.pretty: + # Add source code fragment and a location marker. + if severity == "error" and source_lines and line > 0: + source_line = source_lines[line - 1] + source_line_expanded = source_line.expandtabs() + min_column = len(source_line) - len(source_line.lstrip()) + if column < min_column: + # Something went wrong, take first non-empty column. + column = min_column + + # Shifts column after tab expansion + column = len(source_line[:column].expandtabs()) + end_column = len(source_line[:end_column].expandtabs()) + + # Note, currently coloring uses the offset to detect source snippets, + # so these offsets should not be arbitrary. + a.append(" " * DEFAULT_SOURCE_OFFSET + source_line_expanded) + marker = "^" + if end_line == line and end_column > column: + marker = f'^{"~" * (end_column - column - 1)}' + elif end_line != line: + # just highlight the first line instead + marker = f'^{"~" * (len(source_line_expanded) - column - 1)}' + a.append(" " * (DEFAULT_SOURCE_OFFSET + column) + marker) + return a + + def file_messages(self, path: str) -> list[ErrorTuple]: + """Return an error tuple list of new error messages from a given file.""" + if path not in self.error_info_map: + return [] + + error_info = self.error_info_map[path] + error_info = [info for info in error_info if not info.hidden] + error_info = self.remove_duplicates(self.sort_messages(error_info)) + return self.render_messages(path, error_info) + + def format_messages( + self, path: str, error_tuples: list[ErrorTuple], formatter: ErrorFormatter | None = None + ) -> list[str]: + """Return a string list of new error messages from a given file. + + Use a form suitable for displaying to the user. + """ + self.flushed_files.add(path) + if formatter is not None: + errors = create_errors(error_tuples) + return [formatter.report_error(err) for err in errors] + + source_lines = None + if self.options.pretty and self.read_source: + # Find shadow file mapping and read source lines if a shadow file exists for the given path. + # If shadow file mapping is not found, read source lines + mapped_path = self.find_shadow_file_mapping(path) + if mapped_path: + source_lines = self.read_source(mapped_path) + else: + source_lines = self.read_source(path) + return self.format_messages_default(error_tuples, source_lines) + + def find_shadow_file_mapping(self, path: str) -> str | None: + """Return the shadow file path for a given source file path or None.""" + if self.options.shadow_file is None: + return None + + for i in self.options.shadow_file: + if i[0] == path: + return i[1] + return None + + def new_messages(self) -> list[str]: + """Return a string list of new error messages. + + Use a form suitable for displaying to the user. + Errors from different files are ordered based on the order in which + they first generated an error. + """ + msgs = [] + for path in self.error_info_map.keys(): + if path not in self.flushed_files: + error_tuples = self.file_messages(path) + msgs.extend(self.format_messages(path, error_tuples)) + return msgs + + def targets(self) -> set[str]: + """Return a set of all targets that contain errors.""" + # TODO: Make sure that either target is always defined or that not being defined + # is okay for fine-grained incremental checking. + return { + info.target for errs in self.error_info_map.values() for info in errs if info.target + } + + def render_messages(self, file: str, errors: list[ErrorInfo]) -> list[ErrorTuple]: + """Translate the messages into a sequence of tuples. + + Each tuple is of form (path, line, col, severity, message, code). + The rendered sequence includes information about error contexts. + The path item may be None. If the line item is negative, the + line number is not defined for the tuple. + """ + file = self.simplify_path(file) + result: list[ErrorTuple] = [] + prev_import_context: list[tuple[str, int]] = [] + prev_function: str | None = None + prev_type: str | None = None + + for e in errors: + # Report module import context, if different from previous message. + if not self.options.show_error_context: + pass + elif e.import_ctx != prev_import_context: + last = len(e.import_ctx) - 1 + i = last + while i >= 0: + path, line = e.import_ctx[i] + fmt = "{}:{}: note: In module imported here" + if i < last: + fmt = "{}:{}: note: ... from here" + if i > 0: + fmt += "," + else: + fmt += ":" + # Remove prefix to ignore from path (if present) to + # simplify path. + path = remove_path_prefix(path, self.ignore_prefix) + result.append((None, -1, -1, -1, -1, "note", fmt.format(path, line), None)) + i -= 1 + + # Report context within a source file. + type, function = e.local_ctx + if not self.options.show_error_context: + pass + elif function != prev_function or type != prev_type: + if function is None: + if type is None: + result.append((file, -1, -1, -1, -1, "note", "At top level:", None)) + else: + result.append((file, -1, -1, -1, -1, "note", f'In class "{type}":', None)) + else: + + if type is None: + msg = f'In function "{function}":' + else: + msg = 'In member "{}" of class "{}":'.format(function, type) + result.append((file, -1, -1, -1, -1, "note", msg, None)) + + elif type != prev_type: + if type is None: + result.append((file, -1, -1, -1, -1, "note", "At top level:", None)) + else: + result.append((file, -1, -1, -1, -1, "note", f'In class "{type}":', None)) + + code = e.code.code if e.code is not None else None + result.append( + (file, e.line, e.column, e.end_line, e.end_column, e.severity, e.message, code) + ) + + prev_import_context = e.import_ctx + prev_function = function + prev_type = type + + return result + + def sort_messages(self, errors: list[ErrorInfo]) -> list[ErrorInfo]: + """Sort an array of error messages locally by line number. + + I.e., sort a run of consecutive messages with the same + context by line number, but otherwise retain the general + ordering of the messages. + """ + result: list[ErrorInfo] = [] + i = 0 + while i < len(errors): + i0 = i + # Find neighbouring errors with the same context and file. + while i + 1 < len(errors) and errors[i + 1].import_ctx == errors[i].import_ctx: + i += 1 + i += 1 + + # Sort the errors specific to a file according to line number and column. + a = sorted(errors[i0:i], key=lambda x: (x.line, x.column)) + a = self.sort_within_context(a) + result.extend(a) + return result + + def sort_within_context(self, errors: list[ErrorInfo]) -> list[ErrorInfo]: + """For the same location decide which messages to show first/last. + + Currently, we only compare within the same error code, to decide the + order of various additional notes. + """ + result = [] + i = 0 + while i < len(errors): + i0 = i + # Find neighbouring errors with the same position and error code. + while ( + i + 1 < len(errors) + and errors[i + 1].line == errors[i].line + and errors[i + 1].column == errors[i].column + and errors[i + 1].end_line == errors[i].end_line + and errors[i + 1].end_column == errors[i].end_column + and errors[i + 1].code == errors[i].code + ): + i += 1 + i += 1 + + # Sort the messages specific to a given error by priority. + a = sorted(errors[i0:i], key=lambda x: x.priority) + result.extend(a) + return result + + def remove_duplicates(self, errors: list[ErrorInfo]) -> list[ErrorInfo]: + filtered_errors = [] + seen_by_line: defaultdict[int, set[tuple[str, str]]] = defaultdict(set) + removed = set() + for err in errors: + if err.parent_error is not None: + # Notes with specified parent are removed together with error below. + filtered_errors.append(err) + elif (err.severity, err.message) not in seen_by_line[err.line]: + filtered_errors.append(err) + seen_by_line[err.line].add((err.severity, err.message)) + else: + removed.add(err) + return [ + err + for err in filtered_errors + if err.parent_error is None or err.parent_error not in removed + ] + + +class CompileError(Exception): + """Exception raised when there is a compile error. + + It can be a parse, semantic analysis, type check or other + compilation-related error. + + CompileErrors raised from an errors object carry all of the + messages that have not been reported out by error streaming. + This is patched up by build.build to contain either all error + messages (if errors were streamed) or none (if they were not). + + """ + + messages: list[str] + use_stdout = False + # Can be set in case there was a module with a blocking error + module_with_blocker: str | None = None + + def __init__( + self, messages: list[str], use_stdout: bool = False, module_with_blocker: str | None = None + ) -> None: + super().__init__("\n".join(messages)) + self.messages = messages + self.use_stdout = use_stdout + self.module_with_blocker = module_with_blocker + + +def remove_path_prefix(path: str, prefix: str | None) -> str: + """If path starts with prefix, return copy of path with the prefix removed. + Otherwise, return path. If path is None, return None. + """ + if prefix is not None and path.startswith(prefix): + return path[len(prefix) :] + else: + return path + + +def report_internal_error( + err: Exception, + file: str | None, + line: int, + errors: Errors | None, + options: Options, + stdout: TextIO | None = None, + stderr: TextIO | None = None, +) -> NoReturn: + """Report internal error and exit. + + This optionally starts pdb or shows a traceback. + """ + stdout = stdout or sys.stdout + stderr = stderr or sys.stderr + # Dump out errors so far, they often provide a clue. + # But catch unexpected errors rendering them. + if errors: + try: + for msg in errors.new_messages(): + print(msg) + except Exception as e: + print("Failed to dump errors:", repr(e), file=stderr) + + # Compute file:line prefix for official-looking error messages. + if file: + if line: + prefix = f"{file}:{line}: " + else: + prefix = f"{file}: " + else: + prefix = "" + + # Print "INTERNAL ERROR" message. + print( + f"{prefix}error: INTERNAL ERROR --", + "Please try using mypy master on GitHub:\n" + "https://mypy.readthedocs.io/en/stable/common_issues.html" + "#using-a-development-mypy-build", + file=stderr, + ) + if options.show_traceback: + print("Please report a bug at https://github.com/python/mypy/issues", file=stderr) + else: + print( + "If this issue continues with mypy master, " + "please report a bug at https://github.com/python/mypy/issues", + file=stderr, + ) + print(f"version: {mypy_version}", file=stderr) + + # If requested, drop into pdb. This overrides show_tb. + if options.pdb: + print("Dropping into pdb", file=stderr) + import pdb + + pdb.post_mortem(sys.exc_info()[2]) + + # If requested, print traceback, else print note explaining how to get one. + if options.raise_exceptions: + raise err + if not options.show_traceback: + if not options.pdb: + print( + "{}note: please use --show-traceback to print a traceback " + "when reporting a bug".format(prefix), + file=stderr, + ) + else: + tb = traceback.extract_stack()[:-2] + tb2 = traceback.extract_tb(sys.exc_info()[2]) + print("Traceback (most recent call last):") + for s in traceback.format_list(tb + tb2): + print(s.rstrip("\n")) + print(f"{type(err).__name__}: {err}", file=stdout) + print(f"{prefix}note: use --pdb to drop into pdb", file=stderr) + + # Exit. The caller has nothing more to say. + # We use exit code 2 to signal that this is no ordinary error. + raise SystemExit(2) + + +class MypyError: + def __init__( + self, + file_path: str, + line: int, + column: int, + end_line: int, + end_column: int, + message: str, + errorcode: str | None, + severity: Literal["error", "note"], + ) -> None: + self.file_path = file_path + self.line = line + self.column = column + self.end_line = end_line + self.end_column = end_column + self.message = message + self.errorcode = errorcode + self.severity = severity + self.hints: list[str] = [] + + +# (file_path, line, column) +_ErrorLocation = tuple[str, int, int] + + +def create_errors(error_tuples: list[ErrorTuple]) -> list[MypyError]: + errors: list[MypyError] = [] + latest_error_at_location: dict[_ErrorLocation, MypyError] = {} + + for error_tuple in error_tuples: + file_path, line, column, end_line, end_column, severity, message, errorcode = error_tuple + if file_path is None: + continue + + assert severity in ("error", "note") + if severity == "note": + error_location = (file_path, line, column) + error = latest_error_at_location.get(error_location) + if error is None: + # This is purely a note, with no error correlated to it + error = MypyError( + file_path, + line, + column, + end_line, + end_column, + message, + errorcode, + severity="note", + ) + errors.append(error) + continue + + error.hints.append(message) + + else: + error = MypyError( + file_path, line, column, end_line, end_column, message, errorcode, severity="error" + ) + errors.append(error) + error_location = (file_path, line, column) + latest_error_at_location[error_location] = error + + return errors diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0f740b5751a363f74710e9017816b900133b8839 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/evalexpr.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/evalexpr.py new file mode 100644 index 0000000000000000000000000000000000000000..f46e5c23c3e43f79899791e173d4ad9bf999daa9 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/evalexpr.py @@ -0,0 +1,211 @@ +""" + +Evaluate an expression. + +Used by stubtest; in a separate file because things break if we don't +put it in a mypyc-compiled file. + +""" + +import ast +from typing import Final + +import mypy.nodes +from mypy.visitor import ExpressionVisitor + +UNKNOWN = object() + + +class _NodeEvaluator(ExpressionVisitor[object]): + def visit_int_expr(self, o: mypy.nodes.IntExpr) -> int: + return o.value + + def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str: + return o.value + + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr) -> object: + # The value of a BytesExpr is a string created from the repr() + # of the bytes object. Get the original bytes back. + try: + return ast.literal_eval(f"b'{o.value}'") + except SyntaxError: + return ast.literal_eval(f'b"{o.value}"') + + def visit_float_expr(self, o: mypy.nodes.FloatExpr) -> float: + return o.value + + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr) -> object: + return o.value + + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr) -> object: + return Ellipsis + + def visit_star_expr(self, o: mypy.nodes.StarExpr) -> object: + return UNKNOWN + + def visit_name_expr(self, o: mypy.nodes.NameExpr) -> object: + if o.name == "True": + return True + elif o.name == "False": + return False + elif o.name == "None": + return None + # TODO: Handle more names by figuring out a way to hook into the + # symbol table. + return UNKNOWN + + def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> object: + return UNKNOWN + + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> object: + return UNKNOWN + + def visit_yield_expr(self, o: mypy.nodes.YieldExpr) -> object: + return UNKNOWN + + def visit_call_expr(self, o: mypy.nodes.CallExpr) -> object: + return UNKNOWN + + def visit_op_expr(self, o: mypy.nodes.OpExpr) -> object: + return UNKNOWN + + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr) -> object: + return UNKNOWN + + def visit_cast_expr(self, o: mypy.nodes.CastExpr) -> object: + return o.expr.accept(self) + + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr) -> object: + return UNKNOWN + + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr) -> object: + return o.expr.accept(self) + + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr) -> object: + return UNKNOWN + + def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> object: + return UNKNOWN + + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> object: + operand = o.expr.accept(self) + if operand is UNKNOWN: + return UNKNOWN + if o.op == "-": + if isinstance(operand, (int, float, complex)): + return -operand + elif o.op == "+": + if isinstance(operand, (int, float, complex)): + return +operand + elif o.op == "~": + if isinstance(operand, int): + return ~operand + elif o.op == "not": + if isinstance(operand, (bool, int, float, str, bytes)): + return not operand + return UNKNOWN + + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> object: + return o.value.accept(self) + + def visit_list_expr(self, o: mypy.nodes.ListExpr) -> object: + items = [item.accept(self) for item in o.items] + if all(item is not UNKNOWN for item in items): + return items + return UNKNOWN + + def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> object: + items = [ + (UNKNOWN if key is None else key.accept(self), value.accept(self)) + for key, value in o.items + ] + if all(key is not UNKNOWN and value is not None for key, value in items): + return dict(items) + return UNKNOWN + + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> object: + items = [item.accept(self) for item in o.items] + if all(item is not UNKNOWN for item in items): + return tuple(items) + return UNKNOWN + + def visit_set_expr(self, o: mypy.nodes.SetExpr) -> object: + items = [item.accept(self) for item in o.items] + if all(item is not UNKNOWN for item in items): + return set(items) + return UNKNOWN + + def visit_index_expr(self, o: mypy.nodes.IndexExpr) -> object: + return UNKNOWN + + def visit_type_application(self, o: mypy.nodes.TypeApplication) -> object: + return UNKNOWN + + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr) -> object: + return UNKNOWN + + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension) -> object: + return UNKNOWN + + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension) -> object: + return UNKNOWN + + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension) -> object: + return UNKNOWN + + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr) -> object: + return UNKNOWN + + def visit_slice_expr(self, o: mypy.nodes.SliceExpr) -> object: + return UNKNOWN + + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr) -> object: + return UNKNOWN + + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr) -> object: + return UNKNOWN + + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr) -> object: + return UNKNOWN + + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr) -> object: + return UNKNOWN + + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr) -> object: + return UNKNOWN + + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr) -> object: + return UNKNOWN + + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr) -> object: + return UNKNOWN + + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr) -> object: + return UNKNOWN + + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr) -> object: + return UNKNOWN + + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr) -> object: + return UNKNOWN + + def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> object: + return UNKNOWN + + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr) -> object: + return UNKNOWN + + def visit_temp_node(self, o: mypy.nodes.TempNode) -> object: + return UNKNOWN + + +_evaluator: Final = _NodeEvaluator() + + +def evaluate_expression(expr: mypy.nodes.Expression) -> object: + """Evaluate an expression at runtime. + + Return the result of the expression, or UNKNOWN if the expression cannot be + evaluated. + """ + return expr.accept(_evaluator) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..8602768428c753e96af5b8ae951baeb3f95797e5 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/expandtype.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/expandtype.py new file mode 100644 index 0000000000000000000000000000000000000000..5790b717172acafe218f45882aaa010ef62be236 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/expandtype.py @@ -0,0 +1,662 @@ +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import Final, TypeVar, cast, overload + +from mypy.nodes import ARG_STAR, ArgKind, FakeInfo, Var +from mypy.state import state +from mypy.types import ( + ANY_STRATEGY, + AnyType, + BoolTypeQuery, + CallableType, + DeletedType, + ErasedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PartialType, + ProperType, + TrivialSyntheticTypeTranslator, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + split_with_prefix_and_suffix, +) +from mypy.typevartuples import split_with_instance + +# Solving the import cycle: +import mypy.type_visitor # ruff: isort: skip + +# WARNING: these functions should never (directly or indirectly) depend on +# is_subtype(), meet_types(), join_types() etc. +# TODO: add a static dependency test for this. + + +@overload +def expand_type(typ: CallableType, env: Mapping[TypeVarId, Type]) -> CallableType: ... + + +@overload +def expand_type(typ: ProperType, env: Mapping[TypeVarId, Type]) -> ProperType: ... + + +@overload +def expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: ... + + +def expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: + """Substitute any type variable references in a type given by a type + environment. + """ + return typ.accept(ExpandTypeVisitor(env)) + + +@overload +def expand_type_by_instance(typ: CallableType, instance: Instance) -> CallableType: ... + + +@overload +def expand_type_by_instance(typ: ProperType, instance: Instance) -> ProperType: ... + + +@overload +def expand_type_by_instance(typ: Type, instance: Instance) -> Type: ... + + +def expand_type_by_instance(typ: Type, instance: Instance) -> Type: + """Substitute type variables in type using values from an Instance. + Type variables are considered to be bound by the class declaration.""" + if not instance.args and not instance.type.has_type_var_tuple_type: + return typ + else: + variables: dict[TypeVarId, Type] = {} + if instance.type.has_type_var_tuple_type: + assert instance.type.type_var_tuple_prefix is not None + assert instance.type.type_var_tuple_suffix is not None + + args_prefix, args_middle, args_suffix = split_with_instance(instance) + tvars_prefix, tvars_middle, tvars_suffix = split_with_prefix_and_suffix( + tuple(instance.type.defn.type_vars), + instance.type.type_var_tuple_prefix, + instance.type.type_var_tuple_suffix, + ) + tvar = tvars_middle[0] + assert isinstance(tvar, TypeVarTupleType) + variables = {tvar.id: TupleType(list(args_middle), tvar.tuple_fallback)} + instance_args = args_prefix + args_suffix + tvars = tvars_prefix + tvars_suffix + else: + tvars = tuple(instance.type.defn.type_vars) + instance_args = instance.args + + for binder, arg in zip(tvars, instance_args): + assert isinstance(binder, TypeVarLikeType) + variables[binder.id] = arg + + return expand_type(typ, variables) + + +F = TypeVar("F", bound=FunctionLike) + + +def freshen_function_type_vars(callee: F) -> F: + """Substitute fresh type variables for generic function type variables.""" + if isinstance(callee, CallableType): + if not callee.is_generic(): + return callee + tvs = [] + tvmap: dict[TypeVarId, Type] = {} + for v in callee.variables: + tv = v.new_unification_variable(v) + tvs.append(tv) + tvmap[v.id] = tv + fresh = expand_type(callee, tvmap).copy_modified(variables=tvs) + return cast(F, fresh) + else: + assert isinstance(callee, Overloaded) + fresh_overload = Overloaded([freshen_function_type_vars(item) for item in callee.items]) + return cast(F, fresh_overload) + + +class HasGenericCallable(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_callable_type(self, t: CallableType) -> bool: + return t.is_generic() or super().visit_callable_type(t) + + +# Share a singleton since this is performance sensitive +has_generic_callable: Final = HasGenericCallable() + + +T = TypeVar("T", bound=Type) + + +def freshen_all_functions_type_vars(t: T) -> T: + result: Type + has_generic_callable.reset() + if not t.accept(has_generic_callable): + return t # Fast path to avoid expensive freshening + else: + result = t.accept(FreshenCallableVisitor()) + assert isinstance(result, type(t)) + return result + + +class FreshenCallableVisitor(mypy.type_visitor.TypeTranslator): + def visit_callable_type(self, t: CallableType) -> Type: + result = super().visit_callable_type(t) + assert isinstance(result, ProperType) and isinstance(result, CallableType) + return freshen_function_type_vars(result) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # Same as for ExpandTypeVisitor + return t.copy_modified(args=[arg.accept(self) for arg in t.args]) + + +class ExpandTypeVisitor(TrivialSyntheticTypeTranslator): + """Visitor that substitutes type variables with values.""" + + variables: Mapping[TypeVarId, Type] # TypeVar id -> TypeVar value + + def __init__(self, variables: Mapping[TypeVarId, Type]) -> None: + super().__init__() + self.variables = variables + self.recursive_tvar_guard: dict[TypeVarId, Type | None] | None = None + + def visit_unbound_type(self, t: UnboundType) -> Type: + return t + + def visit_any(self, t: AnyType) -> Type: + return t + + def visit_none_type(self, t: NoneType) -> Type: + return t + + def visit_uninhabited_type(self, t: UninhabitedType) -> Type: + return t + + def visit_deleted_type(self, t: DeletedType) -> Type: + return t + + def visit_erased_type(self, t: ErasedType) -> Type: + # This may happen during type inference if some function argument + # type is a generic callable, and its erased form will appear in inferred + # constraints, then solver may check subtyping between them, which will trigger + # unify_generic_callables(), this is why we can get here. Another example is + # when inferring type of lambda in generic context, the lambda body contains + # a generic method in generic class. + return t + + def visit_instance(self, t: Instance) -> Type: + if len(t.args) == 0: + return t + + args = self.expand_type_tuple_with_unpack(t.args) + + if isinstance(t.type, FakeInfo): + # The type checker expands function definitions and bodies + # if they depend on constrained type variables but the body + # might contain a tuple type comment (e.g., # type: (int, float)), + # in which case 't.type' is not yet available. + # + # See: https://github.com/python/mypy/issues/16649 + return t.copy_modified(args=args) + + if t.type.fullname == "builtins.tuple": + # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...] + arg = args[0] + if isinstance(arg, UnpackType): + unpacked = get_proper_type(arg.type) + if isinstance(unpacked, Instance): + # TODO: this and similar asserts below may be unsafe because get_proper_type() + # may be called during semantic analysis before all invalid types are removed. + assert unpacked.type.fullname == "builtins.tuple" + args = list(unpacked.args) + return t.copy_modified(args=args) + + def visit_type_var(self, t: TypeVarType) -> Type: + # Normally upper bounds can't contain other type variables, the only exception is + # special type variable Self`0 <: C[T, S], where C is the class where Self is used. + if t.id.is_self(): + t = t.copy_modified(upper_bound=t.upper_bound.accept(self)) + repl = self.variables.get(t.id, t) + if isinstance(repl, ProperType) and isinstance(repl, Instance): + # TODO: do we really need to do this? + # If I try to remove this special-casing ~40 tests fail on reveal_type(). + return repl.copy_modified(last_known_value=None) + if isinstance(repl, TypeVarType) and repl.has_default(): + if self.recursive_tvar_guard is None: + self.recursive_tvar_guard = {} + if (tvar_id := repl.id) in self.recursive_tvar_guard: + return self.recursive_tvar_guard[tvar_id] or repl + self.recursive_tvar_guard[tvar_id] = None + repl.default = repl.default.accept(self) + expanded = repl.accept(self) # Note: `expanded is repl` may be true. + repl = repl if isinstance(expanded, TypeVarType) else expanded + self.recursive_tvar_guard[tvar_id] = repl + return repl + + def visit_param_spec(self, t: ParamSpecType) -> Type: + # Set prefix to something empty, so we don't duplicate it below. + repl = self.variables.get(t.id, t.copy_modified(prefix=Parameters([], [], []))) + if isinstance(repl, ParamSpecType): + return repl.copy_modified( + flavor=t.flavor, + prefix=t.prefix.copy_modified( + arg_types=self.expand_types(t.prefix.arg_types) + repl.prefix.arg_types, + arg_kinds=t.prefix.arg_kinds + repl.prefix.arg_kinds, + arg_names=t.prefix.arg_names + repl.prefix.arg_names, + ), + ) + elif isinstance(repl, Parameters): + assert isinstance(t.upper_bound, ProperType) and isinstance(t.upper_bound, Instance) + if t.flavor == ParamSpecFlavor.BARE: + return Parameters( + self.expand_types(t.prefix.arg_types) + repl.arg_types, + t.prefix.arg_kinds + repl.arg_kinds, + t.prefix.arg_names + repl.arg_names, + variables=[*t.prefix.variables, *repl.variables], + imprecise_arg_kinds=repl.imprecise_arg_kinds, + ) + elif t.flavor == ParamSpecFlavor.ARGS: + assert all(k.is_positional() for k in t.prefix.arg_kinds) + return self._possible_callable_varargs( + repl, list(t.prefix.arg_types), t.upper_bound + ) + else: + assert t.flavor == ParamSpecFlavor.KWARGS + return self._possible_callable_kwargs(repl, t.upper_bound) + else: + # We could encode Any as trivial parameters etc., but it would be too verbose. + # TODO: assert this is a trivial type, like Any, Never, or object. + return repl + + @classmethod + def _possible_callable_varargs( + cls, repl: Parameters, required_prefix: list[Type], tuple_type: Instance + ) -> ProperType: + """Given a callable, extract all parameters that can be passed as `*args`. + + This builds a union of all (possibly variadic) tuples representing all possible + argument sequences that can be passed positionally. Each such tuple starts with + all required (pos-only without a default) arguments, followed by some prefix + of other arguments that can be passed positionally. + """ + required_posargs = required_prefix + if repl.variables: + # We will tear the callable apart, do not leak type variables + return tuple_type + optional_posargs: list[Type] = [] + for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types): + if kind == ArgKind.ARG_POS and name is None: + if optional_posargs: + # May happen following Unpack expansion without kinds correction + required_posargs += optional_posargs + optional_posargs = [] + required_posargs.append(type) + elif kind.is_positional(): + optional_posargs.append(type) + elif kind == ArgKind.ARG_STAR: + if isinstance(type, UnpackType): + optional_posargs.append(type) + else: + optional_posargs.append(UnpackType(Instance(tuple_type.type, [type]))) + break + return UnionType.make_union( + [ + TupleType(required_posargs + optional_posargs[:i], fallback=tuple_type) + for i in range(len(optional_posargs) + 1) + ] + ) + + @classmethod + def _possible_callable_kwargs(cls, repl: Parameters, dict_type: Instance) -> ProperType: + """Given a callable, extract all parameters that can be passed as `**kwargs`. + + If the function only accepts **kwargs, this will be a `dict[str, KwargsValueType]`. + Otherwise, this will be a `TypedDict` containing all explicit args and ignoring + `**kwargs` (until PEP 728 `extra_items` is supported). TypedDict entries will + be required iff the corresponding argument is kw-only and has no default. + """ + if repl.variables: + # We will tear the callable apart, do not leak type variables + return dict_type + kwargs = {} + required_names = set() + extra_items: Type = UninhabitedType() + for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types): + if kind == ArgKind.ARG_NAMED and name is not None: + kwargs[name] = type + required_names.add(name) + elif kind == ArgKind.ARG_STAR2: + # Unpack[TypedDict] is normalized early, it isn't stored as Unpack + extra_items = type + elif not kind.is_star() and name is not None: + kwargs[name] = type + if not kwargs: + return Instance(dict_type.type, [dict_type.args[0], extra_items]) + # TODO: when PEP 728 is implemented, pass extra_items below. + return TypedDictType(kwargs, required_names, set(), fallback=dict_type) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + # Sometimes solver may need to expand a type variable with (a copy of) itself + # (usually together with other TypeVars, but it is hard to filter out TypeVarTuples). + repl = self.variables.get(t.id, t) + if isinstance(repl, TypeVarTupleType): + return repl + elif isinstance(repl, ProperType) and isinstance(repl, (AnyType, UninhabitedType)): + # Some failed inference scenarios will try to set all type variables to Never. + # Instead of being picky and require all the callers to wrap them, + # do this here instead. + # Note: most cases when this happens are handled in expand unpack below, but + # in rare cases (e.g. ParamSpec containing Unpack star args) it may be skipped. + return t.tuple_fallback.copy_modified(args=[repl]) + raise NotImplementedError + + def visit_unpack_type(self, t: UnpackType) -> Type: + # It is impossible to reasonably implement visit_unpack_type, because + # unpacking inherently expands to something more like a list of types. + # + # Relevant sections that can call unpack should call expand_unpack() + # instead. + # However, if the item is a variadic tuple, we can simply carry it over. + # In particular, if we expand A[*tuple[T, ...]] with substitutions {T: str}, + # it is hard to assert this without getting proper type. Another important + # example is non-normalized types when called from semanal.py. + return UnpackType(t.type.accept(self)) + + def expand_unpack(self, t: UnpackType) -> list[Type]: + assert isinstance(t.type, TypeVarTupleType) + repl = get_proper_type(self.variables.get(t.type.id, t.type)) + if isinstance(repl, UnpackType): + repl = get_proper_type(repl.type) + if isinstance(repl, TupleType): + return repl.items + elif ( + isinstance(repl, Instance) + and repl.type.fullname == "builtins.tuple" + or isinstance(repl, TypeVarTupleType) + ): + return [UnpackType(typ=repl)] + elif isinstance(repl, (AnyType, UninhabitedType)): + # Replace *Ts = Any with *Ts = *tuple[Any, ...] and same for Never. + # These types may appear here as a result of user error or failed inference. + return [UnpackType(t.type.tuple_fallback.copy_modified(args=[repl]))] + else: + raise RuntimeError(f"Invalid type replacement to expand: {repl}") + + def visit_parameters(self, t: Parameters) -> Type: + return t.copy_modified(arg_types=self.expand_types(t.arg_types)) + + def interpolate_args_for_unpack(self, t: CallableType, var_arg: UnpackType) -> list[Type]: + star_index = t.arg_kinds.index(ARG_STAR) + prefix = self.expand_types(t.arg_types[:star_index]) + suffix = self.expand_types(t.arg_types[star_index + 1 :]) + + var_arg_type = get_proper_type(var_arg.type) + new_unpack: Type + if isinstance(var_arg_type, TupleType): + # We have something like Unpack[Tuple[Unpack[Ts], X1, X2]] + expanded_tuple = var_arg_type.accept(self) + assert isinstance(expanded_tuple, ProperType) and isinstance(expanded_tuple, TupleType) + expanded_items = expanded_tuple.items + fallback = var_arg_type.partial_fallback + new_unpack = UnpackType(TupleType(expanded_items, fallback)) + elif isinstance(var_arg_type, TypeVarTupleType): + # We have plain Unpack[Ts] + fallback = var_arg_type.tuple_fallback + expanded_items = self.expand_unpack(var_arg) + new_unpack = UnpackType(TupleType(expanded_items, fallback)) + # Since get_proper_type() may be called in semanal.py before callable + # normalization happens, we need to also handle non-normal cases here. + elif isinstance(var_arg_type, Instance): + # we have something like Unpack[Tuple[Any, ...]] + new_unpack = UnpackType(var_arg.type.accept(self)) + else: + # We have invalid type in Unpack. This can happen when expanding aliases + # to Callable[[*Invalid], Ret] + new_unpack = AnyType(TypeOfAny.from_error, line=var_arg.line, column=var_arg.column) + return prefix + [new_unpack] + suffix + + def visit_callable_type(self, t: CallableType) -> CallableType: + param_spec = t.param_spec() + if param_spec is not None: + repl = self.variables.get(param_spec.id) + # If a ParamSpec in a callable type is substituted with a + # callable type, we can't use normal substitution logic, + # since ParamSpec is actually split into two components + # *P.args and **P.kwargs in the original type. Instead, we + # must expand both of them with all the argument types, + # kinds and names in the replacement. The return type in + # the replacement is ignored. + if isinstance(repl, Parameters): + # We need to expand both the types in the prefix and the ParamSpec itself + expanded = t.copy_modified( + arg_types=self.expand_types(t.arg_types[:-2]) + repl.arg_types, + arg_kinds=t.arg_kinds[:-2] + repl.arg_kinds, + arg_names=t.arg_names[:-2] + repl.arg_names, + ret_type=t.ret_type.accept(self), + type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), + imprecise_arg_kinds=(t.imprecise_arg_kinds or repl.imprecise_arg_kinds), + variables=[*repl.variables, *t.variables], + ) + var_arg = expanded.var_arg() + if var_arg is not None and isinstance(var_arg.typ, UnpackType): + # Sometimes we get new unpacks after expanding ParamSpec. + expanded.normalize_trivial_unpack() + return expanded + elif isinstance(repl, ParamSpecType): + # We're substituting one ParamSpec for another; this can mean that the prefix + # changes, e.g. substitute Concatenate[int, P] in place of Q. + prefix = repl.prefix + clean_repl = repl.copy_modified(prefix=Parameters([], [], [])) + return t.copy_modified( + arg_types=self.expand_types(t.arg_types[:-2]) + + prefix.arg_types + + [ + clean_repl.with_flavor(ParamSpecFlavor.ARGS), + clean_repl.with_flavor(ParamSpecFlavor.KWARGS), + ], + arg_kinds=t.arg_kinds[:-2] + prefix.arg_kinds + t.arg_kinds[-2:], + arg_names=t.arg_names[:-2] + prefix.arg_names + t.arg_names[-2:], + ret_type=t.ret_type.accept(self), + from_concatenate=t.from_concatenate or bool(repl.prefix.arg_types), + imprecise_arg_kinds=(t.imprecise_arg_kinds or prefix.imprecise_arg_kinds), + ) + + var_arg = t.var_arg() + needs_normalization = False + if var_arg is not None and isinstance(var_arg.typ, UnpackType): + needs_normalization = True + arg_types = self.interpolate_args_for_unpack(t, var_arg.typ) + else: + arg_types = self.expand_types(t.arg_types) + expanded = t.copy_modified( + arg_types=arg_types, + ret_type=t.ret_type.accept(self), + type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), + ) + if needs_normalization: + return expanded.with_normalized_var_args() + return expanded + + def visit_overloaded(self, t: Overloaded) -> Type: + items: list[CallableType] = [] + for item in t.items: + new_item = item.accept(self) + assert isinstance(new_item, ProperType) + assert isinstance(new_item, CallableType) + items.append(new_item) + return Overloaded(items) + + def expand_type_list_with_unpack(self, typs: list[Type]) -> list[Type]: + """Expands a list of types that has an unpack.""" + items: list[Type] = [] + for item in typs: + if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType): + items.extend(self.expand_unpack(item)) + else: + items.append(item.accept(self)) + return items + + def expand_type_tuple_with_unpack(self, typs: tuple[Type, ...]) -> list[Type]: + """Expands a tuple of types that has an unpack.""" + # Micro-optimization: Specialized variant of expand_type_list_with_unpack + items: list[Type] = [] + for item in typs: + if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType): + items.extend(self.expand_unpack(item)) + else: + items.append(item.accept(self)) + return items + + def visit_tuple_type(self, t: TupleType) -> Type: + items = self.expand_type_list_with_unpack(t.items) + if len(items) == 1: + # Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...] + item = items[0] + if isinstance(item, UnpackType): + unpacked = get_proper_type(item.type) + if isinstance(unpacked, Instance): + # expand_type() may be called during semantic analysis, before invalid unpacks are fixed. + if unpacked.type.fullname != "builtins.tuple": + return t.partial_fallback.accept(self) + if t.partial_fallback.type.fullname != "builtins.tuple": + # If it is a subtype (like named tuple) we need to preserve it, + # this essentially mimics the logic in tuple_fallback(). + return t.partial_fallback.accept(self) + return unpacked + fallback = t.partial_fallback.accept(self) + assert isinstance(fallback, ProperType) and isinstance(fallback, Instance) + return t.copy_modified(items=items, fallback=fallback) + + def visit_typeddict_type(self, t: TypedDictType) -> Type: + if cached := self.get_cached(t): + return cached + fallback = t.fallback.accept(self) + assert isinstance(fallback, ProperType) and isinstance(fallback, Instance) + result = t.copy_modified(item_types=self.expand_types(t.items.values()), fallback=fallback) + self.set_cached(t, result) + return result + + def visit_literal_type(self, t: LiteralType) -> Type: + # TODO: Verify this implementation is correct + return t + + def visit_union_type(self, t: UnionType) -> Type: + # Use cache to avoid O(n**2) or worse expansion of types during translation + # (only for large unions, since caching adds overhead) + use_cache = len(t.items) > 3 + if use_cache and (cached := self.get_cached(t)): + return cached + + expanded = self.expand_types(t.items) + # After substituting for type variables in t.items, some resulting types + # might be subtypes of others, however calling make_simplified_union() + # can cause recursion, so we just remove strict duplicates. + simplified = UnionType.make_union( + remove_trivial(flatten_nested_unions(expanded)), t.line, t.column + ) + # This call to get_proper_type() is unfortunate but is required to preserve + # the invariant that ProperType will stay ProperType after applying expand_type(), + # otherwise a single item union of a type alias will break it. Note this should not + # cause infinite recursion since pathological aliases like A = Union[A, B] are + # banned at the semantic analysis level. + result = get_proper_type(simplified) + + if use_cache: + self.set_cached(t, result) + return result + + def visit_partial_type(self, t: PartialType) -> Type: + return t + + def visit_type_type(self, t: TypeType) -> Type: + # TODO: Verify that the new item type is valid (instance or + # union of instances or Any). Sadly we can't report errors + # here yet. + item = t.item.accept(self) + return TypeType.make_normalized(item, is_type_form=t.is_type_form) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # Target of the type alias cannot contain type variables (not bound by the type + # alias itself), so we just expand the arguments. + if len(t.args) == 0: + return t + args = self.expand_type_list_with_unpack(t.args) + # TODO: normalize if target is Tuple, and args are [*tuple[X, ...]]? + return t.copy_modified(args=args) + + def expand_types(self, types: Iterable[Type]) -> list[Type]: + a: list[Type] = [] + for t in types: + a.append(t.accept(self)) + return a + + +@overload +def expand_self_type(var: Var, typ: ProperType, replacement: ProperType) -> ProperType: ... + + +@overload +def expand_self_type(var: Var, typ: Type, replacement: Type) -> Type: ... + + +def expand_self_type(var: Var, typ: Type, replacement: Type) -> Type: + """Expand appearances of Self type in a variable type.""" + if var.info.self_type is not None and not var.is_property: + return expand_type(typ, {var.info.self_type.id: replacement}) + return typ + + +def remove_trivial(types: Iterable[Type]) -> list[Type]: + """Make trivial simplifications on a list of types without calling is_subtype(). + + This makes following simplifications: + * Remove bottom types (taking into account strict optional setting) + * Remove everything else if there is an `object` + * Remove strict duplicate types + """ + removed_none = False + new_types = [] + all_types = set() + for t in types: + p_t = get_proper_type(t) + if isinstance(p_t, UninhabitedType): + continue + if isinstance(p_t, NoneType) and not state.strict_optional: + removed_none = True + continue + if isinstance(p_t, Instance) and p_t.type.fullname == "builtins.object": + return [p_t] + if p_t not in all_types: + new_types.append(t) + all_types.add(p_t) + if new_types: + return new_types + if removed_none: + return [NoneType()] + return [UninhabitedType()] diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exportjson.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exportjson.py new file mode 100644 index 0000000000000000000000000000000000000000..c08f0f9f2911824ffa0a7fca65b73a4a296b8abb --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exportjson.py @@ -0,0 +1,612 @@ +"""Tool to convert binary mypy cache files (.ff) to JSON (.ff.json). + +Usage: + python -m mypy.exportjson .mypy_cache/.../my_module.data.ff + +The idea is to make caches introspectable once we've switched to a binary +cache format and removed support for the older JSON cache format. + +This is primarily to support existing use cases that need to inspect +cache files, and to support debugging mypy caching issues. This means that +this doesn't necessarily need to be kept 1:1 up to date with changes in the +binary cache format (to simplify maintenance -- we don't want this to slow +down mypy development). +""" + +import argparse +import json +import sys +from typing import Any, TypeAlias as _TypeAlias + +from librt.internal import ReadBuffer, cache_version + +from mypy.cache import CACHE_VERSION, CacheMeta +from mypy.nodes import ( + FUNCBASE_FLAGS, + FUNCDEF_FLAGS, + VAR_FLAGS, + ClassDef, + DataclassTransformSpec, + Decorator, + FuncDef, + MypyFile, + OverloadedFuncDef, + OverloadPart, + ParamSpecExpr, + SymbolNode, + SymbolTable, + SymbolTableNode, + TypeAlias, + TypeInfo, + TypeVarExpr, + TypeVarTupleExpr, + Var, + get_flags, + node_kinds, +) +from mypy.types import ( + NOT_READY, + AnyType, + CallableType, + ExtraAttrs, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + get_proper_type, +) + +Json: _TypeAlias = dict[str, Any] | str + + +class Config: + def __init__(self, *, implicit_names: bool = True) -> None: + self.implicit_names = implicit_names + + +def convert_binary_cache_to_json(data: bytes, *, implicit_names: bool = True) -> Json: + tree = MypyFile.read(ReadBuffer(data)) + return convert_mypy_file_to_json(tree, Config(implicit_names=implicit_names)) + + +def convert_mypy_file_to_json(self: MypyFile, cfg: Config) -> Json: + return { + ".class": "MypyFile", + "_fullname": self._fullname, + "names": convert_symbol_table(self.names, cfg), + "is_stub": self.is_stub, + "path": self.path, + "is_partial_stub_package": self.is_partial_stub_package, + "future_import_flags": sorted(self.future_import_flags), + } + + +def convert_symbol_table(self: SymbolTable, cfg: Config) -> Json: + data: dict[str, Any] = {".class": "SymbolTable"} + for key, value in self.items(): + # Skip __builtins__: it's a reference to the builtins + # module that gets added to every module by + # SemanticAnalyzerPass2.visit_file(), but it shouldn't be + # accessed by users of the module. + if key == "__builtins__" or value.no_serialize: + continue + if not cfg.implicit_names and key in { + "__spec__", + "__package__", + "__file__", + "__doc__", + "__annotations__", + "__name__", + }: + continue + data[key] = convert_symbol_table_node(value, cfg) + return data + + +def convert_symbol_table_node(self: SymbolTableNode, cfg: Config) -> Json: + data: dict[str, Any] = {".class": "SymbolTableNode", "kind": node_kinds[self.kind]} + if self.module_hidden: + data["module_hidden"] = True + if not self.module_public: + data["module_public"] = False + if self.implicit: + data["implicit"] = True + if self.plugin_generated: + data["plugin_generated"] = True + if self.cross_ref: + data["cross_ref"] = self.cross_ref + elif self.node is not None: + data["node"] = convert_symbol_node(self.node, cfg) + return data + + +def convert_symbol_node(self: SymbolNode, cfg: Config) -> Json: + if isinstance(self, FuncDef): + return convert_func_def(self) + elif isinstance(self, OverloadedFuncDef): + return convert_overloaded_func_def(self) + elif isinstance(self, Decorator): + return convert_decorator(self) + elif isinstance(self, Var): + return convert_var(self) + elif isinstance(self, TypeInfo): + return convert_type_info(self, cfg) + elif isinstance(self, TypeAlias): + return convert_type_alias(self) + elif isinstance(self, TypeVarExpr): + return convert_type_var_expr(self) + elif isinstance(self, ParamSpecExpr): + return convert_param_spec_expr(self) + elif isinstance(self, TypeVarTupleExpr): + return convert_type_var_tuple_expr(self) + return {"ERROR": f"{type(self)!r} unrecognized"} + + +def convert_func_def(self: FuncDef) -> Json: + return { + ".class": "FuncDef", + "name": self._name, + "fullname": self._fullname, + "arg_names": self.arg_names, + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "type": None if self.type is None else convert_type(self.type), + "flags": get_flags(self, FUNCDEF_FLAGS), + "abstract_status": self.abstract_status, + # TODO: Do we need expanded, original_def? + "dataclass_transform_spec": ( + None + if self.dataclass_transform_spec is None + else convert_dataclass_transform_spec(self.dataclass_transform_spec) + ), + "deprecated": self.deprecated, + "original_first_arg": self.original_first_arg, + } + + +def convert_dataclass_transform_spec(self: DataclassTransformSpec) -> Json: + return { + "eq_default": self.eq_default, + "order_default": self.order_default, + "kw_only_default": self.kw_only_default, + "frozen_default": self.frozen_default, + "field_specifiers": list(self.field_specifiers), + } + + +def convert_overloaded_func_def(self: OverloadedFuncDef) -> Json: + return { + ".class": "OverloadedFuncDef", + "items": [convert_overload_part(i) for i in self.items], + "type": None if self.type is None else convert_type(self.type), + "fullname": self._fullname, + "impl": None if self.impl is None else convert_overload_part(self.impl), + "flags": get_flags(self, FUNCBASE_FLAGS), + "deprecated": self.deprecated, + "setter_index": self.setter_index, + } + + +def convert_overload_part(self: OverloadPart) -> Json: + if isinstance(self, FuncDef): + return convert_func_def(self) + else: + return convert_decorator(self) + + +def convert_decorator(self: Decorator) -> Json: + return { + ".class": "Decorator", + "func": convert_func_def(self.func), + "var": convert_var(self.var), + "is_overload": self.is_overload, + } + + +def convert_var(self: Var) -> Json: + data: dict[str, Any] = { + ".class": "Var", + "name": self._name, + "fullname": self._fullname, + "type": None if self.type is None else convert_type(self.type), + "setter_type": None if self.setter_type is None else convert_type(self.setter_type), + "flags": get_flags(self, VAR_FLAGS), + } + if self.final_value is not None: + data["final_value"] = self.final_value + return data + + +def convert_type_info(self: TypeInfo, cfg: Config) -> Json: + data = { + ".class": "TypeInfo", + "module_name": self.module_name, + "fullname": self.fullname, + "names": convert_symbol_table(self.names, cfg), + "defn": convert_class_def(self.defn), + "abstract_attributes": self.abstract_attributes, + "type_vars": self.type_vars, + "has_param_spec_type": self.has_param_spec_type, + "bases": [convert_type(b) for b in self.bases], + "mro": self._mro_refs, + "_promote": [convert_type(p) for p in self._promote], + "alt_promote": None if self.alt_promote is None else convert_type(self.alt_promote), + "declared_metaclass": ( + None if self.declared_metaclass is None else convert_type(self.declared_metaclass) + ), + "metaclass_type": ( + None if self.metaclass_type is None else convert_type(self.metaclass_type) + ), + "tuple_type": None if self.tuple_type is None else convert_type(self.tuple_type), + "typeddict_type": ( + None if self.typeddict_type is None else convert_typeddict_type(self.typeddict_type) + ), + "flags": get_flags(self, TypeInfo.FLAGS), + "metadata": self.metadata, + "slots": sorted(self.slots) if self.slots is not None else None, + "deletable_attributes": self.deletable_attributes, + "self_type": convert_type(self.self_type) if self.self_type is not None else None, + "dataclass_transform_spec": ( + convert_dataclass_transform_spec(self.dataclass_transform_spec) + if self.dataclass_transform_spec is not None + else None + ), + "deprecated": self.deprecated, + } + return data + + +def convert_class_def(self: ClassDef) -> Json: + return { + ".class": "ClassDef", + "name": self.name, + "fullname": self.fullname, + "type_vars": [convert_type(v) for v in self.type_vars], + } + + +def convert_type_alias(self: TypeAlias) -> Json: + data: Json = { + ".class": "TypeAlias", + "fullname": self._fullname, + "module": self.module, + "target": convert_type(self.target), + "alias_tvars": [convert_type(v) for v in self.alias_tvars], + "no_args": self.no_args, + "normalized": self.normalized, + "python_3_12_type_alias": self.python_3_12_type_alias, + } + return data + + +def convert_type_var_expr(self: TypeVarExpr) -> Json: + return { + ".class": "TypeVarExpr", + "name": self._name, + "fullname": self._fullname, + "values": [convert_type(t) for t in self.values], + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_param_spec_expr(self: ParamSpecExpr) -> Json: + return { + ".class": "ParamSpecExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_type_var_tuple_expr(self: TypeVarTupleExpr) -> Json: + return { + ".class": "TypeVarTupleExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": convert_type(self.upper_bound), + "tuple_fallback": convert_type(self.tuple_fallback), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_type(typ: Type) -> Json: + if type(typ) is TypeAliasType: + return convert_type_alias_type(typ) + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return convert_instance(typ) + elif isinstance(typ, AnyType): + return convert_any_type(typ) + elif isinstance(typ, NoneType): + return convert_none_type(typ) + elif isinstance(typ, UnionType): + return convert_union_type(typ) + elif isinstance(typ, TupleType): + return convert_tuple_type(typ) + elif isinstance(typ, CallableType): + return convert_callable_type(typ) + elif isinstance(typ, Overloaded): + return convert_overloaded(typ) + elif isinstance(typ, LiteralType): + return convert_literal_type(typ) + elif isinstance(typ, TypeVarType): + return convert_type_var_type(typ) + elif isinstance(typ, TypeType): + return convert_type_type(typ) + elif isinstance(typ, UninhabitedType): + return convert_uninhabited_type(typ) + elif isinstance(typ, UnpackType): + return convert_unpack_type(typ) + elif isinstance(typ, ParamSpecType): + return convert_param_spec_type(typ) + elif isinstance(typ, TypeVarTupleType): + return convert_type_var_tuple_type(typ) + elif isinstance(typ, Parameters): + return convert_parameters(typ) + elif isinstance(typ, TypedDictType): + return convert_typeddict_type(typ) + elif isinstance(typ, UnboundType): + return convert_unbound_type(typ) + return {"ERROR": f"{type(typ)!r} unrecognized"} + + +def convert_instance(self: Instance) -> Json: + ready = self.type is not NOT_READY + if not self.args and not self.last_known_value and not self.extra_attrs: + if ready: + return self.type.fullname + elif self.type_ref: + return self.type_ref + + data: dict[str, Any] = { + ".class": "Instance", + "type_ref": self.type.fullname if ready else self.type_ref, + "args": [convert_type(arg) for arg in self.args], + } + if self.last_known_value is not None: + data["last_known_value"] = convert_type(self.last_known_value) + data["extra_attrs"] = convert_extra_attrs(self.extra_attrs) if self.extra_attrs else None + return data + + +def convert_extra_attrs(self: ExtraAttrs) -> Json: + return { + ".class": "ExtraAttrs", + "attrs": {k: convert_type(v) for k, v in self.attrs.items()}, + "immutable": sorted(self.immutable), + "mod_name": self.mod_name, + } + + +def convert_type_alias_type(self: TypeAliasType) -> Json: + data: Json = { + ".class": "TypeAliasType", + "type_ref": self.type_ref, + "args": [convert_type(arg) for arg in self.args], + } + return data + + +def convert_any_type(self: AnyType) -> Json: + return { + ".class": "AnyType", + "type_of_any": self.type_of_any, + "source_any": convert_type(self.source_any) if self.source_any is not None else None, + "missing_import_name": self.missing_import_name, + } + + +def convert_none_type(self: NoneType) -> Json: + return {".class": "NoneType"} + + +def convert_union_type(self: UnionType) -> Json: + return { + ".class": "UnionType", + "items": [convert_type(t) for t in self.items], + "uses_pep604_syntax": self.uses_pep604_syntax, + } + + +def convert_tuple_type(self: TupleType) -> Json: + return { + ".class": "TupleType", + "items": [convert_type(t) for t in self.items], + "partial_fallback": convert_type(self.partial_fallback), + "implicit": self.implicit, + } + + +def convert_literal_type(self: LiteralType) -> Json: + return {".class": "LiteralType", "value": self.value, "fallback": convert_type(self.fallback)} + + +def convert_type_var_type(self: TypeVarType) -> Json: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "values": [convert_type(v) for v in self.values], + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_callable_type(self: CallableType) -> Json: + return { + ".class": "CallableType", + "arg_types": [convert_type(t) for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "ret_type": convert_type(self.ret_type), + "fallback": convert_type(self.fallback), + "name": self.name, + # We don't serialize the definition (only used for error messages). + "variables": [convert_type(v) for v in self.variables], + "is_ellipsis_args": self.is_ellipsis_args, + "implicit": self.implicit, + "is_bound": self.is_bound, + "type_guard": convert_type(self.type_guard) if self.type_guard is not None else None, + "type_is": convert_type(self.type_is) if self.type_is is not None else None, + "from_concatenate": self.from_concatenate, + "imprecise_arg_kinds": self.imprecise_arg_kinds, + "unpack_kwargs": self.unpack_kwargs, + } + + +def convert_overloaded(self: Overloaded) -> Json: + return {".class": "Overloaded", "items": [convert_type(t) for t in self.items]} + + +def convert_type_type(self: TypeType) -> Json: + return {".class": "TypeType", "item": convert_type(self.item)} + + +def convert_uninhabited_type(self: UninhabitedType) -> Json: + return {".class": "UninhabitedType"} + + +def convert_unpack_type(self: UnpackType) -> Json: + return {".class": "UnpackType", "type": convert_type(self.type)} + + +def convert_param_spec_type(self: ParamSpecType) -> Json: + assert not self.id.is_meta_var() + return { + ".class": "ParamSpecType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "flavor": self.flavor, + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "prefix": convert_type(self.prefix), + } + + +def convert_type_var_tuple_type(self: TypeVarTupleType) -> Json: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarTupleType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "upper_bound": convert_type(self.upper_bound), + "tuple_fallback": convert_type(self.tuple_fallback), + "default": convert_type(self.default), + "min_len": self.min_len, + } + + +def convert_parameters(self: Parameters) -> Json: + return { + ".class": "Parameters", + "arg_types": [convert_type(t) for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "variables": [convert_type(tv) for tv in self.variables], + "imprecise_arg_kinds": self.imprecise_arg_kinds, + } + + +def convert_typeddict_type(self: TypedDictType) -> Json: + return { + ".class": "TypedDictType", + "items": [[n, convert_type(t)] for (n, t) in self.items.items()], + "required_keys": sorted(self.required_keys), + "readonly_keys": sorted(self.readonly_keys), + "fallback": convert_type(self.fallback), + } + + +def convert_unbound_type(self: UnboundType) -> Json: + return { + ".class": "UnboundType", + "name": self.name, + "args": [convert_type(a) for a in self.args], + "expr": self.original_str_expr, + "expr_fallback": self.original_str_fallback, + } + + +def convert_binary_cache_meta_to_json(data: bytes, data_file: str) -> Json: + assert ( + data[0] == cache_version() and data[1] == CACHE_VERSION + ), "Cache file created by an incompatible mypy version" + meta = CacheMeta.read(ReadBuffer(data[2:]), data_file) + assert meta is not None, f"Error reading meta cache file associated with {data_file}" + return { + "id": meta.id, + "path": meta.path, + "mtime": meta.mtime, + "size": meta.size, + "hash": meta.hash, + "data_mtime": meta.data_mtime, + "dependencies": meta.dependencies, + "suppressed": meta.suppressed, + "options": meta.options, + "dep_prios": meta.dep_prios, + "dep_lines": meta.dep_lines, + "dep_hashes": [dep.hex() for dep in meta.dep_hashes], + "interface_hash": meta.interface_hash.hex(), + "version_id": meta.version_id, + "ignore_all": meta.ignore_all, + "plugin_data": meta.plugin_data, + } + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Convert binary cache files to JSON. " + "Create files in the same directory with extra .json extension." + ) + parser.add_argument( + "path", nargs="+", help="mypy cache data file to convert (.data.ff extension)" + ) + args = parser.parse_args() + fnams: list[str] = args.path + for fnam in fnams: + if fnam.endswith(".data.ff"): + is_data = True + elif fnam.endswith(".meta.ff"): + is_data = False + else: + sys.exit(f"error: Expected .data.ff or .meta.ff extension, but got {fnam}") + with open(fnam, "rb") as f: + data = f.read() + if is_data: + json_data = convert_binary_cache_to_json(data) + else: + data_file = fnam.removesuffix(".meta.ff") + ".data.ff" + json_data = convert_binary_cache_meta_to_json(data, data_file) + new_fnam = fnam + ".json" + with open(new_fnam, "w") as f: + json.dump(json_data, f) + print(f"{fnam} -> {new_fnam}") + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..21911c9f92452926eebccd2daf3982a4a06307f4 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exprtotype.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exprtotype.py new file mode 100644 index 0000000000000000000000000000000000000000..ae36fc8adde09560e04d2e516a277d804906a77c --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/exprtotype.py @@ -0,0 +1,289 @@ +"""Translate an Expression to a Type value.""" + +from __future__ import annotations + +from collections.abc import Callable + +from mypy.fastparse import parse_type_string +from mypy.nodes import ( + MISSING_FALLBACK, + BytesExpr, + CallExpr, + ComplexExpr, + Context, + DictExpr, + EllipsisExpr, + Expression, + FloatExpr, + IndexExpr, + IntExpr, + ListExpr, + MemberExpr, + NameExpr, + OpExpr, + RefExpr, + StarExpr, + StrExpr, + SymbolTableNode, + TupleExpr, + UnaryExpr, + get_member_expr_fullname, +) +from mypy.options import Options +from mypy.types import ( + ANNOTATED_TYPE_NAMES, + AnyType, + CallableArgument, + EllipsisType, + Instance, + ProperType, + RawExpressionType, + Type, + TypedDictType, + TypeList, + TypeOfAny, + UnboundType, + UnionType, + UnpackType, +) + + +class TypeTranslationError(Exception): + """Exception raised when an expression is not valid as a type.""" + + +def _extract_argument_name(expr: Expression) -> str | None: + if isinstance(expr, NameExpr) and expr.name == "None": + return None + elif isinstance(expr, StrExpr): + return expr.value + else: + raise TypeTranslationError() + + +def expr_to_unanalyzed_type( + expr: Expression, + options: Options, + allow_new_syntax: bool = False, + _parent: Expression | None = None, + allow_unpack: bool = False, + lookup_qualified: Callable[[str, Context], SymbolTableNode | None] | None = None, +) -> ProperType: + """Translate an expression to the corresponding type. + + The result is not semantically analyzed. It can be UnboundType or TypeList. + Raise TypeTranslationError if the expression cannot represent a type. + + If lookup_qualified is not provided, the expression is expected to be semantically + analyzed. + + If allow_new_syntax is True, allow all type syntax independent of the target + Python version (used in stubs). + + # TODO: a lot of code here is duplicated in fastparse.py, refactor this. + """ + # The `parent` parameter is used in recursive calls to provide context for + # understanding whether an CallableArgument is ok. + name: str | None = None + if isinstance(expr, NameExpr): + name = expr.name + if name == "True": + return RawExpressionType(True, "builtins.bool", line=expr.line, column=expr.column) + elif name == "False": + return RawExpressionType(False, "builtins.bool", line=expr.line, column=expr.column) + else: + return UnboundType(name, line=expr.line, column=expr.column) + elif isinstance(expr, MemberExpr): + fullname = get_member_expr_fullname(expr) + if fullname: + return UnboundType(fullname, line=expr.line, column=expr.column) + else: + raise TypeTranslationError() + elif isinstance(expr, IndexExpr): + base = expr_to_unanalyzed_type( + expr.base, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + if isinstance(base, UnboundType): + if base.args: + raise TypeTranslationError() + if isinstance(expr.index, TupleExpr): + args = expr.index.items + else: + args = [expr.index] + + if isinstance(expr.base, RefExpr): + # Check if the type is Annotated[...]. For this we need the fullname, + # which must be looked up if the expression hasn't been semantically analyzed. + base_fullname = None + if lookup_qualified is not None: + sym = lookup_qualified(base.name, expr) + if sym and sym.node: + base_fullname = sym.node.fullname + else: + base_fullname = expr.base.fullname + + if base_fullname is not None and base_fullname in ANNOTATED_TYPE_NAMES: + # TODO: this is not the optimal solution as we are basically getting rid + # of the Annotation definition and only returning the type information, + # losing all the annotations. + return expr_to_unanalyzed_type( + args[0], options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + base.args = tuple( + expr_to_unanalyzed_type( + arg, + options, + allow_new_syntax, + expr, + allow_unpack=True, + lookup_qualified=lookup_qualified, + ) + for arg in args + ) + if not base.args: + base.empty_tuple_index = True + return base + else: + raise TypeTranslationError() + elif ( + isinstance(expr, OpExpr) + and expr.op == "|" + and ((options.python_version >= (3, 10)) or allow_new_syntax) + ): + return UnionType( + [ + expr_to_unanalyzed_type( + expr.left, options, allow_new_syntax, lookup_qualified=lookup_qualified + ), + expr_to_unanalyzed_type( + expr.right, options, allow_new_syntax, lookup_qualified=lookup_qualified + ), + ], + uses_pep604_syntax=True, + ) + elif isinstance(expr, CallExpr) and isinstance(_parent, ListExpr): + c = expr.callee + names = [] + # Go through the dotted member expr chain to get the full arg + # constructor name to look up + while True: + if isinstance(c, NameExpr): + names.append(c.name) + break + elif isinstance(c, MemberExpr): + names.append(c.name) + c = c.expr + else: + raise TypeTranslationError() + arg_const = ".".join(reversed(names)) + + # Go through the constructor args to get its name and type. + name = None + default_type = AnyType(TypeOfAny.unannotated) + typ: Type = default_type + for i, arg in enumerate(expr.args): + if expr.arg_names[i] is not None: + if expr.arg_names[i] == "name": + if name is not None: + # Two names + raise TypeTranslationError() + name = _extract_argument_name(arg) + continue + elif expr.arg_names[i] == "type": + if typ is not default_type: + # Two types + raise TypeTranslationError() + typ = expr_to_unanalyzed_type( + arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + continue + else: + raise TypeTranslationError() + elif i == 0: + typ = expr_to_unanalyzed_type( + arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + elif i == 1: + name = _extract_argument_name(arg) + else: + raise TypeTranslationError() + return CallableArgument(typ, name, arg_const, expr.line, expr.column) + elif isinstance(expr, ListExpr): + return TypeList( + [ + expr_to_unanalyzed_type( + t, + options, + allow_new_syntax, + expr, + allow_unpack=True, + lookup_qualified=lookup_qualified, + ) + for t in expr.items + ], + line=expr.line, + column=expr.column, + ) + elif isinstance(expr, StrExpr): + return parse_type_string(expr.value, "builtins.str", expr.line, expr.column) + elif isinstance(expr, BytesExpr): + return parse_type_string(expr.value, "builtins.bytes", expr.line, expr.column) + elif isinstance(expr, UnaryExpr): + typ = expr_to_unanalyzed_type( + expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified + ) + if isinstance(typ, RawExpressionType): + if isinstance(typ.literal_value, int): + if expr.op == "-": + typ.literal_value *= -1 + return typ + elif expr.op == "+": + return typ + raise TypeTranslationError() + elif isinstance(expr, IntExpr): + return RawExpressionType(expr.value, "builtins.int", line=expr.line, column=expr.column) + elif isinstance(expr, FloatExpr): + # Floats are not valid parameters for RawExpressionType , so we just + # pass in 'None' for now. We'll report the appropriate error at a later stage. + return RawExpressionType(None, "builtins.float", line=expr.line, column=expr.column) + elif isinstance(expr, ComplexExpr): + # Same thing as above with complex numbers. + return RawExpressionType(None, "builtins.complex", line=expr.line, column=expr.column) + elif isinstance(expr, EllipsisExpr): + return EllipsisType(expr.line) + elif allow_unpack and isinstance(expr, StarExpr): + return UnpackType( + expr_to_unanalyzed_type( + expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified + ), + from_star_syntax=True, + ) + elif isinstance(expr, DictExpr): + if not expr.items: + raise TypeTranslationError() + items: dict[str, Type] = {} + extra_items_from = [] + for item_name, value in expr.items: + if not isinstance(item_name, StrExpr): + if item_name is None: + extra_items_from.append( + expr_to_unanalyzed_type( + value, + options, + allow_new_syntax, + expr, + lookup_qualified=lookup_qualified, + ) + ) + continue + raise TypeTranslationError() + items[item_name.value] = expr_to_unanalyzed_type( + value, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + result = TypedDictType( + items, set(), set(), Instance(MISSING_FALLBACK, ()), expr.line, expr.column + ) + result.extra_items_from = extra_items_from + return result + else: + raise TypeTranslationError() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3438cdc5d3e1f74e5031889bce995e7dc650a76e Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fastparse.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fastparse.py new file mode 100644 index 0000000000000000000000000000000000000000..e85b8fffaf9e970710589890cc59a2d17b042640 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fastparse.py @@ -0,0 +1,2256 @@ +from __future__ import annotations + +import re +import sys +import warnings +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, TypeVar, cast, overload + +from mypy import defaults, errorcodes as codes, message_registry +from mypy.errors import Errors +from mypy.message_registry import ErrorMessage +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR, + ARG_STAR2, + MISSING_FALLBACK, + PARAM_SPEC_KIND, + TYPE_VAR_KIND, + TYPE_VAR_TUPLE_KIND, + ArgKind, + Argument, + AssertStmt, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + Expression, + ExpressionStmt, + FloatExpr, + ForStmt, + FuncDef, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportBase, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NameExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + PassStmt, + RaiseStmt, + RefExpr, + ReturnStmt, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAliasStmt, + TypeParam, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, + check_param_names, +) +from mypy.options import Options +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.reachability import infer_reachability_of_if_statement, mark_block_unreachable +from mypy.sharedparse import argument_elide_name, special_function_elide_names +from mypy.traverser import TraverserVisitor +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + EllipsisType, + Instance, + ProperType, + RawExpressionType, + TupleType, + Type, + TypedDictType, + TypeList, + TypeOfAny, + UnboundType, + UnionType, + UnpackType, +) +from mypy.util import bytes_to_human_readable_repr, unnamed_function + +# pull this into a final variable to make mypyc be quiet about the +# the default argument warning +PY_MINOR_VERSION: Final = sys.version_info[1] + +import ast as ast3 +from ast import AST, Attribute, Call, FunctionType, Name, Starred, UAdd, UnaryOp, USub + + +def ast3_parse( + source: str | bytes, filename: str, mode: str, feature_version: int = PY_MINOR_VERSION +) -> AST: + # Ignore warnings that look like: + # :1: SyntaxWarning: invalid escape sequence '\.' + # because `source` could be anything, including literals like r'(re\.match)' + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + return ast3.parse( + source, + filename, + mode, + type_comments=True, # This works the magic + feature_version=feature_version, + ) + + +AstNode = ast3.expr | ast3.stmt | ast3.pattern | ast3.ExceptHandler + +if sys.version_info >= (3, 11): + TryStar = ast3.TryStar +else: + TryStar = Any + +if sys.version_info >= (3, 12): + ast_TypeAlias = ast3.TypeAlias + ast_ParamSpec = ast3.ParamSpec + ast_TypeVar = ast3.TypeVar + ast_TypeVarTuple = ast3.TypeVarTuple +else: + ast_TypeAlias = Any + ast_ParamSpec = Any + ast_TypeVar = Any + ast_TypeVarTuple = Any + +if sys.version_info >= (3, 14): + ast_TemplateStr = ast3.TemplateStr + ast_Interpolation = ast3.Interpolation +else: + ast_TemplateStr = Any + ast_Interpolation = Any + +N = TypeVar("N", bound=Node) + +# There is no way to create reasonable fallbacks at this stage, +# they must be patched later. +_dummy_fallback: Final = Instance(MISSING_FALLBACK, [], -1) + +TYPE_IGNORE_PATTERN: Final = re.compile(r"[^#]*#\s*type:\s*ignore\s*(.*)") + + +def parse( + source: str | bytes, + fnam: str, + module: str | None, + errors: Errors, + options: Options | None = None, +) -> MypyFile: + """Parse a source file, without doing any semantic analysis. + + Return the parse tree. If errors is not provided, raise ParseError + on failure. Otherwise, use the errors object to report parse errors. + """ + ignore_errors = (options is not None and options.ignore_errors) or ( + fnam in errors.ignored_files + ) + # If errors are ignored, we can drop many function bodies to speed up type checking. + strip_function_bodies = ignore_errors and (options is None or not options.preserve_asts) + + if options is None: + options = Options() + errors.set_file(fnam, module, options=options) + is_stub_file = fnam.endswith(".pyi") + if is_stub_file: + feature_version = defaults.PYTHON3_VERSION[1] + if options.python_version[0] == 3 and options.python_version[1] > feature_version: + feature_version = options.python_version[1] + else: + assert options.python_version[0] >= 3 + feature_version = options.python_version[1] + try: + # Disable + # - deprecation warnings for 'invalid escape sequence' (Python 3.11 and below) + # - syntax warnings for 'invalid escape sequence' (3.12+) and 'return in finally' (3.14+) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=SyntaxWarning) + ast = ast3_parse(source, fnam, "exec", feature_version=feature_version) + + tree = ASTConverter( + options=options, + is_stub=is_stub_file, + errors=errors, + strip_function_bodies=strip_function_bodies, + path=fnam, + ).visit(ast) + + except RecursionError as e: + # For very complex expressions it is possible to hit recursion limit + # before reaching a leaf node. + # Should reject at top level instead at bottom, since bottom would already + # be at the threshold of the recursion limit, and may fail again later. + # E.G. x1+x2+x3+...+xn -> BinOp(left=BinOp(left=BinOp(left=... + try: + # But to prove that is the cause of this particular recursion error, + # try to walk the tree using builtin visitor + ast3.NodeVisitor().visit(ast) + except RecursionError: + errors.report( + -1, -1, "Source expression too complex to parse", blocker=False, code=codes.MISC + ) + + tree = MypyFile([], [], False, {}) + + else: + # re-raise original recursion error if it *can* be unparsed, + # maybe this is some other issue that shouldn't be silenced/misdirected + raise e + + except SyntaxError as e: + message = e.msg + if feature_version > sys.version_info.minor and message.startswith("invalid syntax"): + python_version_str = f"{options.python_version[0]}.{options.python_version[1]}" + message += f"; you likely need to run mypy using Python {python_version_str} or newer" + errors.report( + e.lineno if e.lineno is not None else -1, + e.offset, + re.sub( + r"^(\s*\w)", lambda m: m.group(1).upper(), message + ), # Standardizing error message + blocker=True, + code=codes.SYNTAX, + ) + tree = MypyFile([], [], False, {}) + + assert isinstance(tree, MypyFile) + return tree + + +def parse_type_ignore_tag(tag: str | None) -> list[str] | None: + """Parse optional "[code, ...]" tag after "# type: ignore". + + Return: + * [] if no tag was found (ignore all errors) + * list of ignored error codes if a tag was found + * None if the tag was invalid. + """ + if not tag or tag.strip() == "" or tag.strip().startswith("#"): + # No tag -- ignore all errors. + return [] + m = re.match(r"\s*\[([^]#]*)\]\s*(#.*)?$", tag) + if m is None: + # Invalid "# type: ignore" comment. + return None + return [stripped_code for code in m.group(1).split(",") if (stripped_code := code.strip())] + + +def parse_type_comment( + type_comment: str, line: int, column: int, errors: Errors | None +) -> tuple[list[str] | None, ProperType | None]: + """Parse type portion of a type comment (+ optional type ignore). + + Return (ignore info, parsed type). + """ + try: + typ = ast3_parse(type_comment, "", "eval") + except SyntaxError: + if errors is not None: + stripped_type = type_comment.split("#", 2)[0].strip() + err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type) + errors.report(line, column, err_msg.value, blocker=True, code=err_msg.code) + return None, None + else: + raise + else: + extra_ignore = TYPE_IGNORE_PATTERN.match(type_comment) + if extra_ignore: + tag: str | None = extra_ignore.group(1) + ignored: list[str] | None = parse_type_ignore_tag(tag) + if ignored is None: + if errors is not None: + errors.report( + line, column, message_registry.INVALID_TYPE_IGNORE.value, code=codes.SYNTAX + ) + else: + raise SyntaxError + else: + ignored = None + assert isinstance(typ, ast3.Expression) + converted = TypeConverter( + errors, line=line, override_column=column, is_evaluated=False + ).visit(typ.body) + return ignored, converted + + +def parse_type_string( + expr_string: str, expr_fallback_name: str, line: int, column: int +) -> ProperType: + """Parses a type that was originally present inside of an explicit string. + + For example, suppose we have the type `Foo["blah"]`. We should parse the + string expression "blah" using this function. + """ + try: + _, node = parse_type_comment(f"({expr_string})", line=line, column=column, errors=None) + if isinstance(node, (UnboundType, UnionType)) and node.original_str_expr is None: + node.original_str_expr = expr_string + node.original_str_fallback = expr_fallback_name + return node + else: + return RawExpressionType(expr_string, expr_fallback_name, line, column) + except (SyntaxError, ValueError): + # Note: the parser will raise a `ValueError` instead of a SyntaxError if + # the string happens to contain things like \x00. + return RawExpressionType(expr_string, expr_fallback_name, line, column) + + +def is_no_type_check_decorator(expr: ast3.expr) -> bool: + if isinstance(expr, Name): + return expr.id == "no_type_check" + elif isinstance(expr, Attribute): + if isinstance(expr.value, Name): + return expr.value.id == "typing" and expr.attr == "no_type_check" + return False + + +def find_disallowed_expression_in_annotation_scope(expr: ast3.expr | None) -> ast3.expr | None: + if expr is None: + return None + for node in ast3.walk(expr): + if isinstance(node, (ast3.Yield, ast3.YieldFrom, ast3.NamedExpr, ast3.Await)): + return node + return None + + +class ASTConverter: + def __init__( + self, + options: Options, + is_stub: bool, + errors: Errors, + *, + strip_function_bodies: bool, + path: str, + ) -> None: + # 'C' for class, 'D' for function signature, 'F' for function, 'L' for lambda + self.class_and_function_stack: list[Literal["C", "D", "F", "L"]] = [] + self.imports: list[ImportBase] = [] + + self.options = options + self.is_stub = is_stub + self.errors = errors + self.strip_function_bodies = strip_function_bodies + self.path = path + + self.type_ignores: dict[int, list[str]] = {} + self.uses_template_strings = False + + # Cache of visit_X methods keyed by type of visited object + self.visitor_cache: dict[type, Callable[[AST | None], Any]] = {} + + def note(self, msg: str, line: int, column: int) -> None: + self.errors.report(line, column, msg, severity="note", code=codes.SYNTAX) + + def fail(self, msg: ErrorMessage, line: int, column: int, blocker: bool) -> None: + if blocker or not self.options.ignore_errors: + # Make sure self.errors reflects any type ignores that we have parsed + self.errors.set_file_ignored_lines( + self.path, self.type_ignores, self.options.ignore_errors + ) + self.errors.report(line, column, msg.value, blocker=blocker, code=msg.code) + + def fail_merge_overload(self, node: IfStmt) -> None: + self.fail( + message_registry.FAILED_TO_MERGE_OVERLOADS, + line=node.line, + column=node.column, + blocker=False, + ) + + def visit(self, node: AST | None) -> Any: + if node is None: + return None + typeobj = type(node) + visitor = self.visitor_cache.get(typeobj) + if visitor is None: + method = "visit_" + node.__class__.__name__ + visitor = getattr(self, method) + self.visitor_cache[typeobj] = visitor + + return visitor(node) + + def set_line(self, node: N, n: AstNode) -> N: + node.line = n.lineno + node.column = n.col_offset + node.end_line = n.end_lineno + node.end_column = n.end_col_offset + + return node + + def translate_opt_expr_list(self, l: Sequence[AST | None]) -> list[Expression | None]: + res: list[Expression | None] = [] + for e in l: + exp = self.visit(e) + res.append(exp) + return res + + def translate_expr_list(self, l: Sequence[AST]) -> list[Expression]: + return cast(list[Expression], self.translate_opt_expr_list(l)) + + def get_lineno(self, node: ast3.expr | ast3.stmt) -> int: + if ( + isinstance(node, (ast3.AsyncFunctionDef, ast3.ClassDef, ast3.FunctionDef)) + and node.decorator_list + ): + return node.decorator_list[0].lineno + return node.lineno + + def translate_stmt_list( + self, + stmts: Sequence[ast3.stmt], + *, + ismodule: bool = False, + can_strip: bool = False, + is_coroutine: bool = False, + ) -> list[Statement]: + # A "# type: ignore" comment before the first statement of a module + # ignores the whole module: + if ( + ismodule + and stmts + and self.type_ignores + and (first := min(self.type_ignores)) < self.get_lineno(stmts[0]) + ): + ignores = self.type_ignores.pop(first) + if ignores: + joined_ignores = ", ".join(ignores) + self.fail( + message_registry.TYPE_IGNORE_WITH_ERRCODE_ON_MODULE.format(joined_ignores), + line=first, + column=0, + blocker=False, + ) + block = Block(self.fix_function_overloads(self.translate_stmt_list(stmts))) + self.set_block_lines(block, stmts) + mark_block_unreachable(block) + return [block] + + stack = self.class_and_function_stack + # Fast case for stripping function bodies + if ( + can_strip + and self.strip_function_bodies + and len(stack) == 1 + and stack[0] == "F" + and not is_coroutine + ): + return [] + + res: list[Statement] = [] + for stmt in stmts: + node = self.visit(stmt) + res.append(node) + + # Slow case for stripping function bodies + if can_strip and self.strip_function_bodies: + if stack[-2:] == ["C", "F"]: + if is_possible_trivial_body(res): + can_strip = False + else: + # We only strip method bodies if they don't assign to an attribute, as + # this may define an attribute which has an externally visible effect. + visitor = FindAttributeAssign() + for s in res: + s.accept(visitor) + if visitor.found: + can_strip = False + break + + if can_strip and stack[-1] == "F" and is_coroutine: + # Yields inside an async function affect the return type and should not + # be stripped. + yield_visitor = FindYield() + for s in res: + s.accept(yield_visitor) + if yield_visitor.found: + can_strip = False + break + + if can_strip: + return [] + return res + + def translate_type_comment( + self, n: ast3.stmt | ast3.arg, type_comment: str | None + ) -> ProperType | None: + if type_comment is None: + return None + else: + lineno = n.lineno + extra_ignore, typ = parse_type_comment(type_comment, lineno, n.col_offset, self.errors) + if extra_ignore is not None: + self.type_ignores[lineno] = extra_ignore + return typ + + op_map: Final[dict[type[AST], str]] = { + ast3.Add: "+", + ast3.Sub: "-", + ast3.Mult: "*", + ast3.MatMult: "@", + ast3.Div: "/", + ast3.Mod: "%", + ast3.Pow: "**", + ast3.LShift: "<<", + ast3.RShift: ">>", + ast3.BitOr: "|", + ast3.BitXor: "^", + ast3.BitAnd: "&", + ast3.FloorDiv: "//", + } + + def from_operator(self, op: ast3.operator) -> str: + op_name = ASTConverter.op_map.get(type(op)) + if op_name is None: + raise RuntimeError("Unknown operator " + str(type(op))) + else: + return op_name + + comp_op_map: Final[dict[type[AST], str]] = { + ast3.Gt: ">", + ast3.Lt: "<", + ast3.Eq: "==", + ast3.GtE: ">=", + ast3.LtE: "<=", + ast3.NotEq: "!=", + ast3.Is: "is", + ast3.IsNot: "is not", + ast3.In: "in", + ast3.NotIn: "not in", # codespell:ignore notin + } + + def from_comp_operator(self, op: ast3.cmpop) -> str: + op_name = ASTConverter.comp_op_map.get(type(op)) + if op_name is None: + raise RuntimeError("Unknown comparison operator " + str(type(op))) + else: + return op_name + + def set_block_lines(self, b: Block, stmts: Sequence[ast3.stmt]) -> None: + first, last = stmts[0], stmts[-1] + b.line = first.lineno + b.column = first.col_offset + b.end_line = last.end_lineno + b.end_column = last.end_col_offset + if not b.body: + return + new_first = b.body[0] + if isinstance(new_first, (Decorator, OverloadedFuncDef)): + # Decorated function lines are different between Python versions. + # copy the normalization we do for them to block first lines. + b.line = new_first.line + b.column = new_first.column + + def as_block(self, stmts: list[ast3.stmt]) -> Block | None: + b = None + if stmts: + b = Block(self.fix_function_overloads(self.translate_stmt_list(stmts))) + self.set_block_lines(b, stmts) + return b + + def as_required_block( + self, stmts: list[ast3.stmt], *, can_strip: bool = False, is_coroutine: bool = False + ) -> Block: + assert stmts # must be non-empty + b = Block( + self.fix_function_overloads( + self.translate_stmt_list(stmts, can_strip=can_strip, is_coroutine=is_coroutine) + ) + ) + self.set_block_lines(b, stmts) + return b + + def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]: + ret: list[Statement] = [] + current_overload: list[OverloadPart] = [] + current_overload_name: str | None = None + last_unconditional_func_def: str | None = None + last_if_stmt: IfStmt | None = None + last_if_overload: Decorator | FuncDef | OverloadedFuncDef | None = None + last_if_stmt_overload_name: str | None = None + last_if_unknown_truth_value: IfStmt | None = None + skipped_if_stmts: list[IfStmt] = [] + for stmt in stmts: + if_overload_name: str | None = None + if_block_with_overload: Block | None = None + if_unknown_truth_value: IfStmt | None = None + if isinstance(stmt, IfStmt): + # Check IfStmt block to determine if function overloads can be merged + if_overload_name = self._check_ifstmt_for_overloads(stmt, current_overload_name) + if if_overload_name is not None: + if_block_with_overload, if_unknown_truth_value = ( + self._get_executable_if_block_with_overloads(stmt) + ) + + if ( + current_overload_name is not None + and isinstance(stmt, (Decorator, FuncDef)) + and stmt.name == current_overload_name + ): + if last_if_stmt is not None: + skipped_if_stmts.append(last_if_stmt) + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if last_if_unknown_truth_value: + self.fail_merge_overload(last_if_unknown_truth_value) + last_if_unknown_truth_value = None + current_overload.append(stmt) + if isinstance(stmt, FuncDef): + # This is, strictly speaking, wrong: there might be a decorated + # implementation. However, it only affects the error message we show: + # ideally it's "already defined", but "implementation must come last" + # is also reasonable. + # TODO: can we get rid of this completely and just always emit + # "implementation must come last" instead? + last_unconditional_func_def = stmt.name + elif ( + current_overload_name is not None + and isinstance(stmt, IfStmt) + and if_overload_name == current_overload_name + and last_unconditional_func_def != current_overload_name + ): + # IfStmt only contains stmts relevant to current_overload. + # Check if stmts are reachable and add them to current_overload, + # otherwise skip IfStmt to allow subsequent overload + # or function definitions. + skipped_if_stmts.append(stmt) + if if_block_with_overload is None: + if if_unknown_truth_value is not None: + self.fail_merge_overload(if_unknown_truth_value) + continue + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef): + skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1])) + current_overload.extend(if_block_with_overload.body[-1].items) + else: + current_overload.append( + cast(Decorator | FuncDef, if_block_with_overload.body[0]) + ) + else: + if last_if_stmt is not None: + ret.append(last_if_stmt) + last_if_stmt_overload_name = current_overload_name + last_if_stmt, last_if_overload = None, None + last_if_unknown_truth_value = None + + if current_overload and current_overload_name == last_if_stmt_overload_name: + # Remove last stmt (IfStmt) from ret if the overload names matched + # Only happens if no executable block had been found in IfStmt + popped = ret.pop() + assert isinstance(popped, IfStmt) + skipped_if_stmts.append(popped) + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + self._strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + skipped_if_stmts = [] + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + + # If we have multiple decorated functions named "_" next to each, we want to treat + # them as a series of regular FuncDefs instead of one OverloadedFuncDef because + # most of mypy/mypyc assumes that all the functions in an OverloadedFuncDef are + # related, but multiple underscore functions next to each other aren't necessarily + # related + last_unconditional_func_def = None + if isinstance(stmt, Decorator) and not unnamed_function(stmt.name): + current_overload = [stmt] + current_overload_name = stmt.name + elif isinstance(stmt, IfStmt) and if_overload_name is not None: + current_overload = [] + current_overload_name = if_overload_name + last_if_stmt = stmt + last_if_stmt_overload_name = None + if if_block_with_overload is not None: + skipped_if_stmts.extend( + cast(list[IfStmt], if_block_with_overload.body[:-1]) + ) + last_if_overload = cast( + Decorator | FuncDef | OverloadedFuncDef, + if_block_with_overload.body[-1], + ) + last_if_unknown_truth_value = if_unknown_truth_value + else: + current_overload = [] + current_overload_name = None + ret.append(stmt) + + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + self._strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + elif last_if_overload is not None: + ret.append(last_if_overload) + elif last_if_stmt is not None: + ret.append(last_if_stmt) + return ret + + def _check_ifstmt_for_overloads( + self, stmt: IfStmt, current_overload_name: str | None = None + ) -> str | None: + """Check if IfStmt contains only overloads with the same name. + Return overload_name if found, None otherwise. + """ + # Check that block only contains a single Decorator, FuncDef, or OverloadedFuncDef. + # Multiple overloads have already been merged as OverloadedFuncDef. + if not ( + len(stmt.body[0].body) == 1 + and ( + isinstance(stmt.body[0].body[0], (Decorator, OverloadedFuncDef)) + or current_overload_name is not None + and isinstance(stmt.body[0].body[0], FuncDef) + ) + or len(stmt.body[0].body) > 1 + and isinstance(stmt.body[0].body[-1], OverloadedFuncDef) + and all(self._is_stripped_if_stmt(if_stmt) for if_stmt in stmt.body[0].body[:-1]) + ): + return None + + overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name + if stmt.else_body is None: + return overload_name + + if len(stmt.else_body.body) == 1: + # For elif: else_body contains an IfStmt itself -> do a recursive check. + if ( + isinstance(stmt.else_body.body[0], (Decorator, FuncDef, OverloadedFuncDef)) + and stmt.else_body.body[0].name == overload_name + ): + return overload_name + if ( + isinstance(stmt.else_body.body[0], IfStmt) + and self._check_ifstmt_for_overloads(stmt.else_body.body[0], current_overload_name) + == overload_name + ): + return overload_name + + return None + + def _get_executable_if_block_with_overloads( + self, stmt: IfStmt + ) -> tuple[Block | None, IfStmt | None]: + """Return block from IfStmt that will get executed. + + Return + 0 -> A block if sure that alternative blocks are unreachable. + 1 -> An IfStmt if the reachability of it can't be inferred, + i.e. the truth value is unknown. + """ + infer_reachability_of_if_statement(stmt, self.options) + if stmt.else_body is None and stmt.body[0].is_unreachable is True: + # always False condition with no else + return None, None + if ( + stmt.else_body is None + or stmt.body[0].is_unreachable is False + and stmt.else_body.is_unreachable is False + ): + # The truth value is unknown, thus not conclusive + return None, stmt + if stmt.else_body.is_unreachable is True: + # else_body will be set unreachable if condition is always True + return stmt.body[0], None + if stmt.body[0].is_unreachable is True: + # body will be set unreachable if condition is always False + # else_body can contain an IfStmt itself (for elif) -> do a recursive check + if isinstance(stmt.else_body.body[0], IfStmt): + return self._get_executable_if_block_with_overloads(stmt.else_body.body[0]) + return stmt.else_body, None + return None, stmt + + def _strip_contents_from_if_stmt(self, stmt: IfStmt) -> None: + """Remove contents from IfStmt. + + Needed to still be able to check the conditions after the contents + have been merged with the surrounding function overloads. + """ + if len(stmt.body) == 1: + stmt.body[0].body = [] + if stmt.else_body and len(stmt.else_body.body) == 1: + if isinstance(stmt.else_body.body[0], IfStmt): + self._strip_contents_from_if_stmt(stmt.else_body.body[0]) + else: + stmt.else_body.body = [] + + def _is_stripped_if_stmt(self, stmt: Statement) -> bool: + """Check stmt to make sure it is a stripped IfStmt. + + See also: _strip_contents_from_if_stmt + """ + if not isinstance(stmt, IfStmt): + return False + + if not (len(stmt.body) == 1 and len(stmt.body[0].body) == 0): + # Body not empty + return False + + if not stmt.else_body or len(stmt.else_body.body) == 0: + # No or empty else_body + return True + + # For elif, IfStmt are stored recursively in else_body + return self._is_stripped_if_stmt(stmt.else_body.body[0]) + + def translate_module_id(self, id: str) -> str: + """Return the actual, internal module id for a source text id.""" + if id == self.options.custom_typing_module: + return "typing" + return id + + def visit_Module(self, mod: ast3.Module) -> MypyFile: + self.type_ignores = {} + self.uses_template_strings = False + for ti in mod.type_ignores: + parsed = parse_type_ignore_tag(ti.tag) + if parsed is not None: + self.type_ignores[ti.lineno] = parsed + else: + self.fail(message_registry.INVALID_TYPE_IGNORE, ti.lineno, -1, blocker=False) + + body = self.fix_function_overloads(self.translate_stmt_list(mod.body, ismodule=True)) + + ret = MypyFile(body, self.imports, False, ignored_lines=self.type_ignores) + ret.is_stub = self.is_stub + ret.path = self.path + ret.uses_template_strings = self.uses_template_strings + return ret + + # --- stmt --- + # FunctionDef(identifier name, arguments args, + # stmt* body, expr* decorator_list, expr? returns, string? type_comment) + # arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, + # arg? kwarg, expr* defaults) + def visit_FunctionDef(self, n: ast3.FunctionDef) -> FuncDef | Decorator: + return self.do_func_def(n) + + # AsyncFunctionDef(identifier name, arguments args, + # stmt* body, expr* decorator_list, expr? returns, string? type_comment) + def visit_AsyncFunctionDef(self, n: ast3.AsyncFunctionDef) -> FuncDef | Decorator: + return self.do_func_def(n, is_coroutine=True) + + def do_func_def( + self, n: ast3.FunctionDef | ast3.AsyncFunctionDef, is_coroutine: bool = False + ) -> FuncDef | Decorator: + """Helper shared between visit_FunctionDef and visit_AsyncFunctionDef.""" + self.class_and_function_stack.append("D") + no_type_check = bool( + n.decorator_list and any(is_no_type_check_decorator(d) for d in n.decorator_list) + ) + + lineno = n.lineno + args = self.transform_args(n.args, lineno, no_type_check=no_type_check) + if self.options.pos_only_special_methods and special_function_elide_names(n.name): + for arg in args: + arg.pos_only = True + + arg_kinds = [arg.kind for arg in args] + arg_names = [None if arg.pos_only else arg.variable.name for arg in args] + # Type parameters, if using new syntax for generics (PEP 695) + explicit_type_params: list[TypeParam] | None = None + + arg_types: list[Type | None] = [] + if no_type_check: + arg_types = [None] * len(args) + return_type = None + elif n.type_comment is not None: + try: + func_type_ast = ast3_parse(n.type_comment, "", "func_type") + assert isinstance(func_type_ast, FunctionType) + # for ellipsis arg + if ( + len(func_type_ast.argtypes) == 1 + and isinstance(func_type_ast.argtypes[0], ast3.Constant) + and func_type_ast.argtypes[0].value is Ellipsis + ): + if n.returns: + # PEP 484 disallows both type annotations and type comments + self.fail( + message_registry.DUPLICATE_TYPE_SIGNATURES, + lineno, + n.col_offset, + blocker=False, + ) + arg_types = [ + ( + a.type_annotation + if a.type_annotation is not None + else AnyType(TypeOfAny.unannotated) + ) + for a in args + ] + else: + # PEP 484 disallows both type annotations and type comments + if n.returns or any(a.type_annotation is not None for a in args): + self.fail( + message_registry.DUPLICATE_TYPE_SIGNATURES, + lineno, + n.col_offset, + blocker=False, + ) + translated_args: list[Type] = TypeConverter( + self.errors, line=lineno, override_column=n.col_offset + ).translate_expr_list(func_type_ast.argtypes) + # Use a cast to work around `list` invariance + arg_types = cast(list[Type | None], translated_args) + return_type = TypeConverter(self.errors, line=lineno).visit(func_type_ast.returns) + + # add implicit self type + in_method_scope = self.class_and_function_stack[-2:] == ["C", "D"] + if in_method_scope and len(arg_types) < len(args): + arg_types.insert(0, AnyType(TypeOfAny.special_form)) + except SyntaxError: + stripped_type = n.type_comment.split("#", 2)[0].strip() + err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type) + self.fail(err_msg, lineno, n.col_offset, blocker=False) + if n.type_comment and n.type_comment[0] not in ["(", "#"]: + self.note( + "Suggestion: wrap argument types in parentheses", lineno, n.col_offset + ) + arg_types = [AnyType(TypeOfAny.from_error)] * len(args) + return_type = AnyType(TypeOfAny.from_error) + else: + if sys.version_info >= (3, 12) and n.type_params: + explicit_type_params = self.translate_type_params(n.type_params) + + arg_types = [a.type_annotation for a in args] + return_type = TypeConverter( + self.errors, line=n.returns.lineno if n.returns else lineno + ).visit(n.returns) + + for arg, arg_type in zip(args, arg_types): + self.set_type_optional(arg_type, arg.initializer) + + func_type = None + if any(arg_types) or return_type: + if len(arg_types) != 1 and any(isinstance(t, EllipsisType) for t in arg_types): + self.fail( + message_registry.ELLIPSIS_WITH_OTHER_TYPEPARAMS, + lineno, + n.col_offset, + blocker=False, + ) + elif len(arg_types) > len(arg_kinds): + self.fail( + message_registry.TYPE_SIGNATURE_TOO_MANY_PARAMS, + lineno, + n.col_offset, + blocker=False, + ) + elif len(arg_types) < len(arg_kinds): + self.fail( + message_registry.TYPE_SIGNATURE_TOO_FEW_PARAMS, + lineno, + n.col_offset, + blocker=False, + ) + else: + func_type = CallableType( + [a if a is not None else AnyType(TypeOfAny.unannotated) for a in arg_types], + arg_kinds, + arg_names, + return_type if return_type is not None else AnyType(TypeOfAny.unannotated), + _dummy_fallback, + ) + + # End position is always the same. + end_line = n.end_lineno + end_column = n.end_col_offset + + self.class_and_function_stack.pop() + self.class_and_function_stack.append("F") + body = self.as_required_block(n.body, can_strip=True, is_coroutine=is_coroutine) + func_def = FuncDef(n.name, args, body, func_type, explicit_type_params) + if isinstance(func_def.type, CallableType): + # semanal.py does some in-place modifications we want to avoid + func_def.unanalyzed_type = func_def.type.copy_modified() + if is_coroutine: + func_def.is_coroutine = True + if func_type is not None: + func_type.definition = func_def + func_type.set_line(lineno) + + if n.decorator_list: + var = Var(func_def.name) + var.is_ready = False + var.set_line(lineno) + + func_def.is_decorated = True + self.set_line(func_def, n) + + deco = Decorator(func_def, self.translate_expr_list(n.decorator_list), var) + first = n.decorator_list[0] + deco.set_line(first.lineno, first.col_offset, end_line, end_column) + retval: FuncDef | Decorator = deco + else: + self.set_line(func_def, n) + retval = func_def + if self.options.include_docstrings: + func_def.docstring = ast3.get_docstring(n, clean=False) + self.class_and_function_stack.pop() + return retval + + def set_type_optional(self, type: Type | None, initializer: Expression | None) -> None: + if not self.options.implicit_optional: + return + # Indicate that type should be wrapped in an Optional if arg is initialized to None. + optional = isinstance(initializer, NameExpr) and initializer.name == "None" + if isinstance(type, UnboundType): + type.optional = optional + + def transform_args( + self, args: ast3.arguments, line: int, no_type_check: bool = False + ) -> list[Argument]: + new_args = [] + names: list[ast3.arg] = [] + posonlyargs = args.posonlyargs + args_args = posonlyargs + args.args + args_defaults = args.defaults + num_no_defaults = len(args_args) - len(args_defaults) + # positional arguments without defaults + for i, a in enumerate(args_args[:num_no_defaults]): + pos_only = i < len(posonlyargs) + new_args.append(self.make_argument(a, None, ARG_POS, no_type_check, pos_only)) + names.append(a) + + # positional arguments with defaults + for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)): + pos_only = num_no_defaults + i < len(posonlyargs) + new_args.append(self.make_argument(a, d, ARG_OPT, no_type_check, pos_only)) + names.append(a) + + # *arg + if args.vararg is not None: + new_args.append(self.make_argument(args.vararg, None, ARG_STAR, no_type_check)) + names.append(args.vararg) + + # keyword-only arguments with defaults + for a, kd in zip(args.kwonlyargs, args.kw_defaults): + new_args.append( + self.make_argument( + a, kd, ARG_NAMED if kd is None else ARG_NAMED_OPT, no_type_check + ) + ) + names.append(a) + + # **kwarg + if args.kwarg is not None: + new_args.append(self.make_argument(args.kwarg, None, ARG_STAR2, no_type_check)) + names.append(args.kwarg) + + check_param_names([arg.variable.name for arg in new_args], names, self.fail_arg) + + return new_args + + def make_argument( + self, + arg: ast3.arg, + default: ast3.expr | None, + kind: ArgKind, + no_type_check: bool, + pos_only: bool = False, + ) -> Argument: + if no_type_check: + arg_type = None + else: + annotation = arg.annotation + type_comment = arg.type_comment + if annotation is not None and type_comment is not None: + self.fail( + message_registry.DUPLICATE_TYPE_SIGNATURES, + arg.lineno, + arg.col_offset, + blocker=False, + ) + arg_type = None + if annotation is not None: + arg_type = TypeConverter(self.errors, line=arg.lineno).visit(annotation) + else: + arg_type = self.translate_type_comment(arg, type_comment) + if argument_elide_name(arg.arg): + pos_only = True + + var = Var(arg.arg, arg_type) + var.is_inferred = False + var.is_argument = True + argument = Argument(var, arg_type, self.visit(default), kind, pos_only) + argument.set_line(arg.lineno, arg.col_offset, arg.end_lineno, arg.end_col_offset) + return argument + + def fail_arg(self, msg: str, arg: ast3.arg) -> None: + self.fail(ErrorMessage(msg), arg.lineno, arg.col_offset, blocker=True) + + # ClassDef(identifier name, + # expr* bases, + # keyword* keywords, + # stmt* body, + # expr* decorator_list) + def visit_ClassDef(self, n: ast3.ClassDef) -> ClassDef: + self.class_and_function_stack.append("C") + keywords = [(kw.arg, self.visit(kw.value)) for kw in n.keywords if kw.arg] + + # Type parameters, if using new syntax for generics (PEP 695) + explicit_type_params: list[TypeParam] | None = None + + if sys.version_info >= (3, 12) and n.type_params: + explicit_type_params = self.translate_type_params(n.type_params) + + cdef = ClassDef( + n.name, + self.as_required_block(n.body), + None, + self.translate_expr_list(n.bases), + metaclass=dict(keywords).get("metaclass"), + keywords=keywords, + type_args=explicit_type_params, + ) + cdef.decorators = self.translate_expr_list(n.decorator_list) + self.set_line(cdef, n) + + if self.options.include_docstrings: + cdef.docstring = ast3.get_docstring(n, clean=False) + cdef.column = n.col_offset + cdef.end_line = n.end_lineno + cdef.end_column = n.end_col_offset + self.class_and_function_stack.pop() + return cdef + + def validate_type_param(self, type_param: ast_TypeVar) -> None: + incorrect_expr = find_disallowed_expression_in_annotation_scope(type_param.bound) + if incorrect_expr is None: + return + if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)): + self.fail( + message_registry.TYPE_VAR_YIELD_EXPRESSION_IN_BOUND, + type_param.lineno, + type_param.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.NamedExpr): + self.fail( + message_registry.TYPE_VAR_NAMED_EXPRESSION_IN_BOUND, + type_param.lineno, + type_param.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.Await): + self.fail( + message_registry.TYPE_VAR_AWAIT_EXPRESSION_IN_BOUND, + type_param.lineno, + type_param.col_offset, + blocker=True, + ) + + def translate_type_params(self, type_params: list[Any]) -> list[TypeParam]: + explicit_type_params = [] + for p in type_params: + bound: Type | None = None + values: list[Type] = [] + default: Type | None = None + if sys.version_info >= (3, 13): + default = TypeConverter(self.errors, line=p.lineno).visit(p.default_value) + if isinstance(p, ast_ParamSpec): # type: ignore[misc] + explicit_type_params.append(TypeParam(p.name, PARAM_SPEC_KIND, None, [], default)) + elif isinstance(p, ast_TypeVarTuple): # type: ignore[misc] + explicit_type_params.append( + TypeParam(p.name, TYPE_VAR_TUPLE_KIND, None, [], default) + ) + else: + if isinstance(p.bound, ast3.Tuple): + if len(p.bound.elts) < 2: + self.fail( + message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES, + p.lineno, + p.col_offset, + blocker=False, + ) + else: + conv = TypeConverter(self.errors, line=p.lineno) + values = [conv.visit(t) for t in p.bound.elts] + elif p.bound is not None: + self.validate_type_param(p) + bound = TypeConverter(self.errors, line=p.lineno).visit(p.bound) + explicit_type_params.append( + TypeParam(p.name, TYPE_VAR_KIND, bound, values, default) + ) + return explicit_type_params + + # Return(expr? value) + def visit_Return(self, n: ast3.Return) -> ReturnStmt: + node = ReturnStmt(self.visit(n.value)) + return self.set_line(node, n) + + # Delete(expr* targets) + def visit_Delete(self, n: ast3.Delete) -> DelStmt: + if len(n.targets) > 1: + tup = TupleExpr(self.translate_expr_list(n.targets)) + tup.set_line(n.lineno) + node = DelStmt(tup) + else: + node = DelStmt(self.visit(n.targets[0])) + return self.set_line(node, n) + + # Assign(expr* targets, expr? value, string? type_comment, expr? annotation) + def visit_Assign(self, n: ast3.Assign) -> AssignmentStmt: + lvalues = self.translate_expr_list(n.targets) + rvalue = self.visit(n.value) + typ = self.translate_type_comment(n, n.type_comment) + s = AssignmentStmt(lvalues, rvalue, type=typ, new_syntax=False) + return self.set_line(s, n) + + # AnnAssign(expr target, expr annotation, expr? value, int simple) + def visit_AnnAssign(self, n: ast3.AnnAssign) -> AssignmentStmt: + line = n.lineno + if n.value is None: # always allow 'x: int' + rvalue: Expression = TempNode(AnyType(TypeOfAny.special_form), no_rhs=True) + self.set_line(rvalue, n) + else: + rvalue = self.visit(n.value) + typ = TypeConverter(self.errors, line=line).visit(n.annotation) + assert typ is not None + typ.column = n.annotation.col_offset + s = AssignmentStmt([self.visit(n.target)], rvalue, type=typ, new_syntax=True) + return self.set_line(s, n) + + # AugAssign(expr target, operator op, expr value) + def visit_AugAssign(self, n: ast3.AugAssign) -> OperatorAssignmentStmt: + s = OperatorAssignmentStmt( + self.from_operator(n.op), self.visit(n.target), self.visit(n.value) + ) + return self.set_line(s, n) + + # For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) + def visit_For(self, n: ast3.For) -> ForStmt: + target_type = self.translate_type_comment(n, n.type_comment) + node = ForStmt( + self.visit(n.target), + self.visit(n.iter), + self.as_required_block(n.body), + self.as_block(n.orelse), + target_type, + ) + return self.set_line(node, n) + + # AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) + def visit_AsyncFor(self, n: ast3.AsyncFor) -> ForStmt: + target_type = self.translate_type_comment(n, n.type_comment) + node = ForStmt( + self.visit(n.target), + self.visit(n.iter), + self.as_required_block(n.body), + self.as_block(n.orelse), + target_type, + ) + node.is_async = True + return self.set_line(node, n) + + # While(expr test, stmt* body, stmt* orelse) + def visit_While(self, n: ast3.While) -> WhileStmt: + node = WhileStmt( + self.visit(n.test), self.as_required_block(n.body), self.as_block(n.orelse) + ) + return self.set_line(node, n) + + # If(expr test, stmt* body, stmt* orelse) + def visit_If(self, n: ast3.If) -> IfStmt: + node = IfStmt( + [self.visit(n.test)], [self.as_required_block(n.body)], self.as_block(n.orelse) + ) + return self.set_line(node, n) + + # With(withitem* items, stmt* body, string? type_comment) + def visit_With(self, n: ast3.With) -> WithStmt: + target_type = self.translate_type_comment(n, n.type_comment) + node = WithStmt( + [self.visit(i.context_expr) for i in n.items], + [self.visit(i.optional_vars) for i in n.items], + self.as_required_block(n.body), + target_type, + ) + return self.set_line(node, n) + + # AsyncWith(withitem* items, stmt* body, string? type_comment) + def visit_AsyncWith(self, n: ast3.AsyncWith) -> WithStmt: + target_type = self.translate_type_comment(n, n.type_comment) + s = WithStmt( + [self.visit(i.context_expr) for i in n.items], + [self.visit(i.optional_vars) for i in n.items], + self.as_required_block(n.body), + target_type, + ) + s.is_async = True + return self.set_line(s, n) + + # Raise(expr? exc, expr? cause) + def visit_Raise(self, n: ast3.Raise) -> RaiseStmt: + node = RaiseStmt(self.visit(n.exc), self.visit(n.cause)) + return self.set_line(node, n) + + # Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) + def visit_Try(self, n: ast3.Try) -> TryStmt: + vs = [ + self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers + ] + types = [self.visit(h.type) for h in n.handlers] + handlers = [self.as_required_block(h.body) for h in n.handlers] + + node = TryStmt( + self.as_required_block(n.body), + vs, + types, + handlers, + self.as_block(n.orelse), + self.as_block(n.finalbody), + ) + return self.set_line(node, n) + + def visit_TryStar(self, n: TryStar) -> TryStmt: + vs = [ + self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers + ] + types = [self.visit(h.type) for h in n.handlers] + handlers = [self.as_required_block(h.body) for h in n.handlers] + + node = TryStmt( + self.as_required_block(n.body), + vs, + types, + handlers, + self.as_block(n.orelse), + self.as_block(n.finalbody), + ) + node.is_star = True + return self.set_line(node, n) + + # Assert(expr test, expr? msg) + def visit_Assert(self, n: ast3.Assert) -> AssertStmt: + node = AssertStmt(self.visit(n.test), self.visit(n.msg)) + return self.set_line(node, n) + + # Import(alias* names) + def visit_Import(self, n: ast3.Import) -> Import: + names: list[tuple[str, str | None]] = [] + for alias in n.names: + name = self.translate_module_id(alias.name) + asname = alias.asname + if asname is None and name != alias.name: + # if the module name has been translated (and it's not already + # an explicit import-as), make it an implicit import-as the + # original name + asname = alias.name + names.append((name, asname)) + i = Import(names) + self.imports.append(i) + return self.set_line(i, n) + + # ImportFrom(identifier? module, alias* names, int? level) + def visit_ImportFrom(self, n: ast3.ImportFrom) -> ImportBase: + assert n.level is not None + if len(n.names) == 1 and n.names[0].name == "*": + mod = n.module if n.module is not None else "" + i: ImportBase = ImportAll(mod, n.level) + else: + i = ImportFrom( + self.translate_module_id(n.module) if n.module is not None else "", + n.level, + [(a.name, a.asname) for a in n.names], + ) + self.imports.append(i) + return self.set_line(i, n) + + # Global(identifier* names) + def visit_Global(self, n: ast3.Global) -> GlobalDecl: + g = GlobalDecl(n.names) + return self.set_line(g, n) + + # Nonlocal(identifier* names) + def visit_Nonlocal(self, n: ast3.Nonlocal) -> NonlocalDecl: + d = NonlocalDecl(n.names) + return self.set_line(d, n) + + # Expr(expr value) + def visit_Expr(self, n: ast3.Expr) -> ExpressionStmt: + value = self.visit(n.value) + node = ExpressionStmt(value) + return self.set_line(node, n) + + # Pass + def visit_Pass(self, n: ast3.Pass) -> PassStmt: + s = PassStmt() + return self.set_line(s, n) + + # Break + def visit_Break(self, n: ast3.Break) -> BreakStmt: + s = BreakStmt() + return self.set_line(s, n) + + # Continue + def visit_Continue(self, n: ast3.Continue) -> ContinueStmt: + s = ContinueStmt() + return self.set_line(s, n) + + # --- expr --- + + def visit_NamedExpr(self, n: ast3.NamedExpr) -> AssignmentExpr: + s = AssignmentExpr(self.visit(n.target), self.visit(n.value)) + return self.set_line(s, n) + + # BoolOp(boolop op, expr* values) + def visit_BoolOp(self, n: ast3.BoolOp) -> OpExpr: + # mypy translates (1 and 2 and 3) as (1 and (2 and 3)) + assert len(n.values) >= 2 + op_node = n.op + if isinstance(op_node, ast3.And): + op = "and" + elif isinstance(op_node, ast3.Or): + op = "or" + else: + raise RuntimeError("unknown BoolOp " + str(type(n))) + + # potentially inefficient! + return self.group(op, self.translate_expr_list(n.values), n) + + def group(self, op: str, vals: list[Expression], n: ast3.expr) -> OpExpr: + if len(vals) == 2: + e = OpExpr(op, vals[0], vals[1]) + else: + e = OpExpr(op, vals[0], self.group(op, vals[1:], n)) + return self.set_line(e, n) + + # BinOp(expr left, operator op, expr right) + def visit_BinOp(self, n: ast3.BinOp) -> OpExpr: + op = self.from_operator(n.op) + + if op is None: + raise RuntimeError("cannot translate BinOp " + str(type(n.op))) + + e = OpExpr(op, self.visit(n.left), self.visit(n.right)) + return self.set_line(e, n) + + # UnaryOp(unaryop op, expr operand) + def visit_UnaryOp(self, n: ast3.UnaryOp) -> UnaryExpr: + op = None + if isinstance(n.op, ast3.Invert): + op = "~" + elif isinstance(n.op, ast3.Not): + op = "not" + elif isinstance(n.op, ast3.UAdd): + op = "+" + elif isinstance(n.op, ast3.USub): + op = "-" + + if op is None: + raise RuntimeError("cannot translate UnaryOp " + str(type(n.op))) + + e = UnaryExpr(op, self.visit(n.operand)) + return self.set_line(e, n) + + # Lambda(arguments args, expr body) + def visit_Lambda(self, n: ast3.Lambda) -> LambdaExpr: + body = ast3.Return(n.body) + body.lineno = n.body.lineno + body.col_offset = n.body.col_offset + + self.class_and_function_stack.append("L") + e = LambdaExpr(self.transform_args(n.args, n.lineno), self.as_required_block([body])) + self.class_and_function_stack.pop() + e.set_line(n.lineno, n.col_offset) # Overrides set_line -- can't use self.set_line + return e + + # IfExp(expr test, expr body, expr orelse) + def visit_IfExp(self, n: ast3.IfExp) -> ConditionalExpr: + e = ConditionalExpr(self.visit(n.test), self.visit(n.body), self.visit(n.orelse)) + return self.set_line(e, n) + + # Dict(expr* keys, expr* values) + def visit_Dict(self, n: ast3.Dict) -> DictExpr: + e = DictExpr( + list(zip(self.translate_opt_expr_list(n.keys), self.translate_expr_list(n.values))) + ) + return self.set_line(e, n) + + # Set(expr* elts) + def visit_Set(self, n: ast3.Set) -> SetExpr: + e = SetExpr(self.translate_expr_list(n.elts)) + return self.set_line(e, n) + + # ListComp(expr elt, comprehension* generators) + def visit_ListComp(self, n: ast3.ListComp) -> ListComprehension: + e = ListComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n))) + return self.set_line(e, n) + + # SetComp(expr elt, comprehension* generators) + def visit_SetComp(self, n: ast3.SetComp) -> SetComprehension: + e = SetComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n))) + return self.set_line(e, n) + + # DictComp(expr key, expr value, comprehension* generators) + def visit_DictComp(self, n: ast3.DictComp) -> DictionaryComprehension: + targets = [self.visit(c.target) for c in n.generators] + iters = [self.visit(c.iter) for c in n.generators] + ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators] + is_async = [bool(c.is_async) for c in n.generators] + e = DictionaryComprehension( + self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async + ) + return self.set_line(e, n) + + # GeneratorExp(expr elt, comprehension* generators) + def visit_GeneratorExp(self, n: ast3.GeneratorExp) -> GeneratorExpr: + targets = [self.visit(c.target) for c in n.generators] + iters = [self.visit(c.iter) for c in n.generators] + ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators] + is_async = [bool(c.is_async) for c in n.generators] + e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async) + return self.set_line(e, n) + + # Await(expr value) + def visit_Await(self, n: ast3.Await) -> AwaitExpr: + v = self.visit(n.value) + e = AwaitExpr(v) + return self.set_line(e, n) + + # Yield(expr? value) + def visit_Yield(self, n: ast3.Yield) -> YieldExpr: + e = YieldExpr(self.visit(n.value)) + return self.set_line(e, n) + + # YieldFrom(expr value) + def visit_YieldFrom(self, n: ast3.YieldFrom) -> YieldFromExpr: + e = YieldFromExpr(self.visit(n.value)) + return self.set_line(e, n) + + # Compare(expr left, cmpop* ops, expr* comparators) + def visit_Compare(self, n: ast3.Compare) -> ComparisonExpr: + operators = [self.from_comp_operator(o) for o in n.ops] + operands = self.translate_expr_list([n.left] + n.comparators) + e = ComparisonExpr(operators, operands) + return self.set_line(e, n) + + # Call(expr func, expr* args, keyword* keywords) + # keyword = (identifier? arg, expr value) + def visit_Call(self, n: Call) -> CallExpr: + args = n.args + keywords = n.keywords + keyword_names = [k.arg for k in keywords] + arg_types = self.translate_expr_list( + [a.value if isinstance(a, Starred) else a for a in args] + [k.value for k in keywords] + ) + arg_kinds = [ARG_STAR if type(a) is Starred else ARG_POS for a in args] + [ + ARG_STAR2 if arg is None else ARG_NAMED for arg in keyword_names + ] + e = CallExpr( + self.visit(n.func), + arg_types, + arg_kinds, + cast("list[str | None]", [None] * len(args)) + keyword_names, + ) + return self.set_line(e, n) + + # Constant(object value) + def visit_Constant(self, n: ast3.Constant) -> Any: + val = n.value + e: Any = None + if val is None: + e = NameExpr("None") + elif isinstance(val, str): + e = StrExpr(val) + elif isinstance(val, bytes): + e = BytesExpr(bytes_to_human_readable_repr(val)) + elif isinstance(val, bool): # Must check before int! + e = NameExpr(str(val)) + elif isinstance(val, int): + e = IntExpr(val) + elif isinstance(val, float): + e = FloatExpr(val) + elif isinstance(val, complex): + e = ComplexExpr(val) + elif val is Ellipsis: + e = EllipsisExpr() + else: + raise RuntimeError("Constant not implemented for " + str(type(val))) + return self.set_line(e, n) + + # JoinedStr(expr* values) + def visit_JoinedStr(self, n: ast3.JoinedStr) -> Expression: + # Each of n.values is a str or FormattedValue; we just concatenate + # them all using ''.join. + empty_string = StrExpr("") + empty_string.set_line(n.lineno, n.col_offset) + strs_to_join = ListExpr(self.translate_expr_list(n.values)) + strs_to_join.set_line(empty_string) + # Don't make unnecessary join call if there is only one str to join + if len(strs_to_join.items) == 1: + return self.set_line(strs_to_join.items[0], n) + elif len(strs_to_join.items) > 1: + last = strs_to_join.items[-1] + if isinstance(last, StrExpr) and last.value == "": + # 3.12 can add an empty literal at the end. Delete it for consistency + # between Python versions. + del strs_to_join.items[-1:] + join_method = MemberExpr(empty_string, "join") + join_method.set_line(empty_string) + result_expression = CallExpr(join_method, [strs_to_join], [ARG_POS], [None]) + return self.set_line(result_expression, n) + + # FormattedValue(expr value) + def visit_FormattedValue(self, n: ast3.FormattedValue) -> Expression: + # A FormattedValue is a component of a JoinedStr, or it can exist + # on its own. We translate them to individual '{}'.format(value) + # calls. Format specifier and conversion information is passed along + # to allow mypyc to support f-strings with format specifiers and conversions. + val_exp = self.visit(n.value) + val_exp.set_line(n.lineno, n.col_offset) + conv_str = "" if n.conversion < 0 else "!" + chr(n.conversion) + format_string = StrExpr("{" + conv_str + ":{}}") + format_spec_exp = self.visit(n.format_spec) if n.format_spec is not None else StrExpr("") + format_string.set_line(n.lineno, n.col_offset) + format_method = MemberExpr(format_string, "format") + format_method.set_line(format_string) + result_expression = CallExpr( + format_method, [val_exp, format_spec_exp], [ARG_POS, ARG_POS], [None, None] + ) + return self.set_line(result_expression, n) + + # TemplateStr(expr* values) + def visit_TemplateStr(self, n: ast_TemplateStr) -> TemplateStrExpr: + self.uses_template_strings = True + items: list[Expression | tuple[Expression, str, str | None, Expression | None]] = [] + for value in n.values: + if isinstance(value, ast_Interpolation): # type: ignore[misc] + val_expr = self.visit(value.value) + val_expr.set_line(value.lineno, value.col_offset) + conversion = None if value.conversion < 0 else chr(value.conversion) + format_spec = ( + self.visit(value.format_spec) if value.format_spec is not None else None + ) + items.append((val_expr, value.str, conversion, format_spec)) + else: + items.append(self.visit(value)) + e = TemplateStrExpr(items) + return self.set_line(e, n) + + # Attribute(expr value, identifier attr, expr_context ctx) + def visit_Attribute(self, n: Attribute) -> MemberExpr | SuperExpr: + value = n.value + member_expr = MemberExpr(self.visit(value), n.attr) + obj = member_expr.expr + if ( + isinstance(obj, CallExpr) + and isinstance(obj.callee, NameExpr) + and obj.callee.name == "super" + ): + e: MemberExpr | SuperExpr = SuperExpr(member_expr.name, obj) + else: + e = member_expr + return self.set_line(e, n) + + # Subscript(expr value, slice slice, expr_context ctx) + def visit_Subscript(self, n: ast3.Subscript) -> IndexExpr: + e = IndexExpr(self.visit(n.value), self.visit(n.slice)) + return self.set_line(e, n) + + # Starred(expr value, expr_context ctx) + def visit_Starred(self, n: Starred) -> StarExpr: + e = StarExpr(self.visit(n.value)) + return self.set_line(e, n) + + # Name(identifier id, expr_context ctx) + def visit_Name(self, n: Name) -> NameExpr: + e = NameExpr(n.id) + return self.set_line(e, n) + + # List(expr* elts, expr_context ctx) + def visit_List(self, n: ast3.List) -> ListExpr | TupleExpr: + expr_list: list[Expression] = [self.visit(e) for e in n.elts] + if isinstance(n.ctx, ast3.Store): + # [x, y] = z and (x, y) = z means exactly the same thing + e: ListExpr | TupleExpr = TupleExpr(expr_list) + else: + e = ListExpr(expr_list) + return self.set_line(e, n) + + # Tuple(expr* elts, expr_context ctx) + def visit_Tuple(self, n: ast3.Tuple) -> TupleExpr: + e = TupleExpr(self.translate_expr_list(n.elts)) + return self.set_line(e, n) + + # Slice(expr? lower, expr? upper, expr? step) + def visit_Slice(self, n: ast3.Slice) -> SliceExpr: + e = SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step)) + return self.set_line(e, n) + + # Match(expr subject, match_case* cases) # python 3.10 and later + def visit_Match(self, n: ast3.Match) -> MatchStmt: + node = MatchStmt( + self.visit(n.subject), + [self.visit(c.pattern) for c in n.cases], + [self.visit(c.guard) for c in n.cases], + [self.as_required_block(c.body) for c in n.cases], + ) + return self.set_line(node, n) + + def visit_MatchValue(self, n: ast3.MatchValue) -> ValuePattern: + node = ValuePattern(self.visit(n.value)) + return self.set_line(node, n) + + def visit_MatchSingleton(self, n: ast3.MatchSingleton) -> SingletonPattern: + node = SingletonPattern(n.value) + return self.set_line(node, n) + + def visit_MatchSequence(self, n: ast3.MatchSequence) -> SequencePattern: + patterns = [self.visit(p) for p in n.patterns] + stars = [p for p in patterns if isinstance(p, StarredPattern)] + assert len(stars) < 2 + + node = SequencePattern(patterns) + return self.set_line(node, n) + + def visit_MatchStar(self, n: ast3.MatchStar) -> StarredPattern: + if n.name is None: + node = StarredPattern(None) + else: + name = self.set_line(NameExpr(n.name), n) + node = StarredPattern(name) + + return self.set_line(node, n) + + def visit_MatchMapping(self, n: ast3.MatchMapping) -> MappingPattern: + keys = [self.visit(k) for k in n.keys] + values = [self.visit(v) for v in n.patterns] + + if n.rest is None: + rest = None + else: + rest = self.set_line(NameExpr(n.rest), n) + + node = MappingPattern(keys, values, rest) + return self.set_line(node, n) + + def visit_MatchClass(self, n: ast3.MatchClass) -> ClassPattern: + class_ref = self.visit(n.cls) + assert isinstance(class_ref, RefExpr) + positionals = [self.visit(p) for p in n.patterns] + keyword_keys = n.kwd_attrs + keyword_values = [self.visit(p) for p in n.kwd_patterns] + + node = ClassPattern(class_ref, positionals, keyword_keys, keyword_values) + return self.set_line(node, n) + + # MatchAs(expr pattern, identifier name) + def visit_MatchAs(self, n: ast3.MatchAs) -> AsPattern: + if n.name is None: + name = None + else: + name = NameExpr(n.name) + name = self.set_line(name, n) + node = AsPattern(self.visit(n.pattern), name) + return self.set_line(node, n) + + # MatchOr(expr* pattern) + def visit_MatchOr(self, n: ast3.MatchOr) -> OrPattern: + node = OrPattern([self.visit(pattern) for pattern in n.patterns]) + return self.set_line(node, n) + + def validate_type_alias(self, n: ast_TypeAlias) -> None: + incorrect_expr = find_disallowed_expression_in_annotation_scope(n.value) + if incorrect_expr is None: + return + if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)): + self.fail( + message_registry.TYPE_ALIAS_WITH_YIELD_EXPRESSION, + n.lineno, + n.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.NamedExpr): + self.fail( + message_registry.TYPE_ALIAS_WITH_NAMED_EXPRESSION, + n.lineno, + n.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.Await): + self.fail( + message_registry.TYPE_ALIAS_WITH_AWAIT_EXPRESSION, + n.lineno, + n.col_offset, + blocker=True, + ) + + # TypeAlias(identifier name, type_param* type_params, expr value) + def visit_TypeAlias(self, n: ast_TypeAlias) -> TypeAliasStmt | AssignmentStmt: + node: TypeAliasStmt | AssignmentStmt + type_params = self.translate_type_params(n.type_params) + self.validate_type_alias(n) + value = self.visit(n.value) + # Since the value is evaluated lazily, wrap the value inside a lambda. + # This helps mypyc. + ret = ReturnStmt(value) + self.set_line(ret, n.value) + value_func = LambdaExpr(body=Block([ret])) + self.set_line(value_func, n.value) + node = TypeAliasStmt(self.visit_Name(n.name), type_params, value_func) + return self.set_line(node, n) + + +class TypeConverter: + def __init__( + self, + errors: Errors | None, + line: int = -1, + override_column: int = -1, + is_evaluated: bool = True, + ) -> None: + self.errors = errors + self.line = line + self.override_column = override_column + self.node_stack: list[AST] = [] + self.is_evaluated = is_evaluated + + def convert_column(self, column: int) -> int: + """Apply column override if defined; otherwise return column. + + Column numbers are sometimes incorrect in the AST and the column + override can be used to work around that. + """ + if self.override_column < 0: + return column + else: + return self.override_column + + def invalid_type(self, node: AST, note: str | None = None) -> RawExpressionType: + """Constructs a type representing some expression that normally forms an invalid type. + For example, if we see a type hint that says "3 + 4", we would transform that + expression into a RawExpressionType. + + The semantic analysis layer will report an "Invalid type" error when it + encounters this type, along with the given note if one is provided. + + See RawExpressionType's docstring for more details on how it's used. + """ + return RawExpressionType( + None, "typing.Any", line=self.line, column=getattr(node, "col_offset", -1), note=note + ) + + @overload + def visit(self, node: ast3.expr) -> ProperType: ... + + @overload + def visit(self, node: AST | None) -> ProperType | None: ... + + def visit(self, node: AST | None) -> ProperType | None: + """Modified visit -- keep track of the stack of nodes""" + if node is None: + return None + self.node_stack.append(node) + try: + method = "visit_" + node.__class__.__name__ + visitor = getattr(self, method, None) + if visitor is not None: + typ = visitor(node) + assert isinstance(typ, ProperType) + return typ + else: + return self.invalid_type(node) + finally: + self.node_stack.pop() + + def parent(self) -> AST | None: + """Return the AST node above the one we are processing""" + if len(self.node_stack) < 2: + return None + return self.node_stack[-2] + + def fail(self, msg: ErrorMessage, line: int, column: int) -> None: + if self.errors: + self.errors.report(line, column, msg.value, blocker=True, code=msg.code) + + def note(self, msg: str, line: int, column: int) -> None: + if self.errors: + self.errors.report(line, column, msg, severity="note", code=codes.SYNTAX) + + def translate_expr_list(self, l: Sequence[ast3.expr]) -> list[Type]: + return [self.visit(e) for e in l] + + def visit_Call(self, e: Call) -> Type: + # Parse the arg constructor + f = e.func + constructor = stringify_name(f) + + if not isinstance(self.parent(), ast3.List): + note = None + if constructor: + note = "Suggestion: use {0}[...] instead of {0}(...)".format(constructor) + return self.invalid_type(e, note=note) + if not constructor: + self.fail(message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED, e.lineno, e.col_offset) + + name: str | None = None + default_type = AnyType(TypeOfAny.special_form) + typ: Type = default_type + for i, arg in enumerate(e.args): + if i == 0: + converted = self.visit(arg) + assert converted is not None + typ = converted + elif i == 1: + name = self._extract_argument_name(arg) + else: + self.fail(message_registry.ARG_CONSTRUCTOR_TOO_MANY_ARGS, f.lineno, f.col_offset) + for k in e.keywords: + value = k.value + if k.arg == "name": + if name is not None: + self.fail( + message_registry.MULTIPLE_VALUES_FOR_NAME_KWARG.format(constructor), + f.lineno, + f.col_offset, + ) + name = self._extract_argument_name(value) + elif k.arg == "type": + if typ is not default_type: + self.fail( + message_registry.MULTIPLE_VALUES_FOR_TYPE_KWARG.format(constructor), + f.lineno, + f.col_offset, + ) + converted = self.visit(value) + assert converted is not None + typ = converted + else: + self.fail( + message_registry.ARG_CONSTRUCTOR_UNEXPECTED_ARG.format(k.arg), + value.lineno, + value.col_offset, + ) + return CallableArgument(typ, name, constructor, e.lineno, e.col_offset) + + def translate_argument_list(self, l: Sequence[ast3.expr]) -> TypeList: + return TypeList([self.visit(e) for e in l], line=self.line) + + def _extract_argument_name(self, n: ast3.expr) -> str | None: + if isinstance(n, ast3.Constant) and isinstance(n.value, str): + return n.value.strip() + elif isinstance(n, ast3.Constant) and n.value is None: + return None + self.fail( + message_registry.ARG_NAME_EXPECTED_STRING_LITERAL.format(type(n).__name__), + self.line, + 0, + ) + return None + + def visit_Name(self, n: Name) -> Type: + return UnboundType(n.id, line=self.line, column=self.convert_column(n.col_offset)) + + def visit_BinOp(self, n: ast3.BinOp) -> Type: + if not isinstance(n.op, ast3.BitOr): + return self.invalid_type(n) + + left = self.visit(n.left) + right = self.visit(n.right) + return UnionType( + [left, right], + line=self.line, + column=self.convert_column(n.col_offset), + is_evaluated=self.is_evaluated, + uses_pep604_syntax=True, + ) + + def visit_Constant(self, n: ast3.Constant) -> Type: + val = n.value + if val is None: + # None is a type. + return UnboundType("None", line=self.line) + if isinstance(val, str): + # Parse forward reference. + return parse_type_string(val, "builtins.str", self.line, n.col_offset) + if val is Ellipsis: + # '...' is valid in some types. + return EllipsisType(line=self.line) + if isinstance(val, bool): + # Special case for True/False. + return RawExpressionType(val, "builtins.bool", line=self.line) + if isinstance(val, (int, float, complex)): + return self.numeric_type(val, n) + if isinstance(val, bytes): + contents = bytes_to_human_readable_repr(val) + return RawExpressionType(contents, "builtins.bytes", self.line, column=n.col_offset) + # Everything else is invalid. + + # UnaryOp(op, operand) + def visit_UnaryOp(self, n: UnaryOp) -> Type: + # We support specifically Literal[-4], Literal[+4], and nothing else. + # For example, Literal[~6] or Literal[not False] is not supported. + typ = self.visit(n.operand) + if ( + isinstance(typ, RawExpressionType) + # Use type() because we do not want to allow bools. + and type(typ.literal_value) is int + ): + if isinstance(n.op, USub): + typ.literal_value *= -1 + return typ + if isinstance(n.op, UAdd): + return typ + return self.invalid_type(n) + + def numeric_type(self, value: object, n: AST) -> Type: + # The node's field has the type complex, but complex isn't *really* + # a parent of int and float, and this causes isinstance below + # to think that the complex branch is always picked. Avoid + # this by throwing away the type. + if isinstance(value, int): + numeric_value: int | None = value + type_name = "builtins.int" + else: + # Other kinds of numbers (floats, complex) are not valid parameters for + # RawExpressionType so we just pass in 'None' for now. We'll report the + # appropriate error at a later stage. + numeric_value = None + type_name = f"builtins.{type(value).__name__}" + return RawExpressionType( + numeric_value, type_name, line=self.line, column=getattr(n, "col_offset", -1) + ) + + def visit_Slice(self, n: ast3.Slice) -> Type: + return self.invalid_type(n, note="did you mean to use ',' instead of ':' ?") + + # Subscript(expr value, expr slice, expr_context ctx) + def visit_Subscript(self, n: ast3.Subscript) -> Type: + empty_tuple_index = False + if isinstance(n.slice, ast3.Tuple): + params = self.translate_expr_list(n.slice.elts) + if len(n.slice.elts) == 0: + empty_tuple_index = True + else: + params = [self.visit(n.slice)] + + value = self.visit(n.value) + if isinstance(value, UnboundType) and not value.args: + result = UnboundType( + value.name, + params, + line=self.line, + column=value.column, + empty_tuple_index=empty_tuple_index, + ) + result.end_column = n.end_col_offset + result.end_line = n.end_lineno + return result + else: + return self.invalid_type(n) + + def visit_Tuple(self, n: ast3.Tuple) -> Type: + return TupleType( + self.translate_expr_list(n.elts), + _dummy_fallback, + implicit=True, + line=self.line, + column=self.convert_column(n.col_offset), + ) + + def visit_Dict(self, n: ast3.Dict) -> Type: + if not n.keys: + return self.invalid_type(n) + items: dict[str, Type] = {} + extra_items_from = [] + for item_name, value in zip(n.keys, n.values): + if not isinstance(item_name, ast3.Constant) or not isinstance(item_name.value, str): + if item_name is None: + extra_items_from.append(self.visit(value)) + continue + return self.invalid_type(n) + items[item_name.value] = self.visit(value) + result = TypedDictType(items, set(), set(), _dummy_fallback, n.lineno, n.col_offset) + result.extra_items_from = extra_items_from + return result + + # Attribute(expr value, identifier attr, expr_context ctx) + def visit_Attribute(self, n: Attribute) -> Type: + before_dot = self.visit(n.value) + + if isinstance(before_dot, UnboundType) and not before_dot.args: + return UnboundType(f"{before_dot.name}.{n.attr}", line=self.line, column=n.col_offset) + else: + return self.invalid_type(n) + + # Used for Callable[[X *Ys, Z], R] etc. + def visit_Starred(self, n: ast3.Starred) -> Type: + return UnpackType(self.visit(n.value), from_star_syntax=True) + + # List(expr* elts, expr_context ctx) + def visit_List(self, n: ast3.List) -> Type: + assert isinstance(n.ctx, ast3.Load) + result = self.translate_argument_list(n.elts) + return result + + +def stringify_name(n: AST) -> str | None: + if isinstance(n, Name): + return n.id + elif isinstance(n, Attribute): + sv = stringify_name(n.value) + if sv is not None: + return f"{sv}.{n.attr}" + return None # Can't do it. + + +class FindAttributeAssign(TraverserVisitor): + """Check if an AST contains attribute assignments (e.g. self.x = 0).""" + + def __init__(self) -> None: + self.lvalue = False + self.found = False + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + self.lvalue = True + for lv in s.lvalues: + lv.accept(self) + self.lvalue = False + + def visit_with_stmt(self, s: WithStmt) -> None: + self.lvalue = True + for lv in s.target: + if lv is not None: + lv.accept(self) + self.lvalue = False + s.body.accept(self) + + def visit_for_stmt(self, s: ForStmt) -> None: + self.lvalue = True + s.index.accept(self) + self.lvalue = False + s.body.accept(self) + if s.else_body: + s.else_body.accept(self) + + def visit_expression_stmt(self, s: ExpressionStmt) -> None: + # No need to look inside these + pass + + def visit_call_expr(self, e: CallExpr) -> None: + # No need to look inside these + pass + + def visit_index_expr(self, e: IndexExpr) -> None: + # No need to look inside these + pass + + def visit_member_expr(self, e: MemberExpr) -> None: + if self.lvalue and isinstance(e.expr, NameExpr): + self.found = True + + +class FindYield(TraverserVisitor): + """Check if an AST contains yields or yield froms.""" # codespell:ignore froms + + def __init__(self) -> None: + self.found = False + + def visit_yield_expr(self, e: YieldExpr) -> None: + self.found = True + + def visit_yield_from_expr(self, e: YieldFromExpr) -> None: + self.found = True + + +def is_possible_trivial_body(s: list[Statement]) -> bool: + """Could the statements form a "trivial" function body, such as 'pass'? + + This mimics mypy.semanal.is_trivial_body, but this runs before + semantic analysis so some checks must be conservative. + """ + l = len(s) + if l == 0: + return False + i = 0 + if isinstance(s[0], ExpressionStmt) and isinstance(s[0].expr, StrExpr): + # Skip docstring + i += 1 + if i == l: + return True + if l > i + 1: + return False + stmt = s[i] + return isinstance(stmt, (PassStmt, RaiseStmt)) or ( + isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr) + ) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3d28dc16a4b1058abb0859948d7b01604d0c0a26 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/find_sources.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/find_sources.py new file mode 100644 index 0000000000000000000000000000000000000000..e1edebe90985b091021580fc88d9a66ead9de40a --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/find_sources.py @@ -0,0 +1,257 @@ +"""Routines for finding the sources that mypy will check""" + +from __future__ import annotations + +import functools +import os +from collections.abc import Sequence +from typing import Final + +from mypy.fscache import FileSystemCache +from mypy.modulefinder import ( + PYTHON_EXTENSIONS, + BuildSource, + matches_exclude, + matches_gitignore, + mypy_path, +) +from mypy.options import Options + +PY_EXTENSIONS: Final = tuple(PYTHON_EXTENSIONS) + + +class InvalidSourceList(Exception): + """Exception indicating a problem in the list of sources given to mypy.""" + + +def create_source_list( + paths: Sequence[str], + options: Options, + fscache: FileSystemCache | None = None, + allow_empty_dir: bool = False, +) -> list[BuildSource]: + """From a list of source files/directories, makes a list of BuildSources. + + Raises InvalidSourceList on errors. + """ + fscache = fscache or FileSystemCache() + finder = SourceFinder(fscache, options) + + sources = [] + for path in paths: + path = os.path.normpath(path) + if path.endswith(PY_EXTENSIONS): + # Can raise InvalidSourceList if a directory doesn't have a valid module name. + name, base_dir = finder.crawl_up(path) + sources.append(BuildSource(path, name, None, base_dir)) + elif fscache.isdir(path): + sub_sources = finder.find_sources_in_dir(path) + if not sub_sources and not allow_empty_dir: + raise InvalidSourceList(f"There are no .py[i] files in directory '{path}'") + sources.extend(sub_sources) + else: + mod = os.path.basename(path) if options.scripts_are_modules else None + sources.append(BuildSource(path, mod, None)) + return sources + + +def keyfunc(name: str) -> tuple[bool, int, str]: + """Determines sort order for directory listing. + + The desirable properties are: + 1) foo < foo.pyi < foo.py + 2) __init__.py[i] < foo + """ + base, suffix = os.path.splitext(name) + for i, ext in enumerate(PY_EXTENSIONS): + if suffix == ext: + return (base != "__init__", i, base) + return (base != "__init__", -1, name) + + +def normalise_package_base(root: str) -> str: + if not root: + root = os.curdir + root = os.path.abspath(root) + if root.endswith(os.sep): + root = root[:-1] + return root + + +def get_explicit_package_bases(options: Options) -> list[str] | None: + """Returns explicit package bases to use if the option is enabled, or None if disabled. + + We currently use MYPYPATH and the current directory as the package bases. In the future, + when --namespace-packages is the default could also use the values passed with the + --package-root flag, see #9632. + + Values returned are normalised so we can use simple string comparisons in + SourceFinder.is_explicit_package_base + """ + if not options.explicit_package_bases: + return None + roots = mypy_path() + options.mypy_path + [os.getcwd()] + return [normalise_package_base(root) for root in roots] + + +class SourceFinder: + def __init__(self, fscache: FileSystemCache, options: Options) -> None: + self.fscache = fscache + self.explicit_package_bases = get_explicit_package_bases(options) + self.namespace_packages = options.namespace_packages + self.exclude = options.exclude + self.exclude_gitignore = options.exclude_gitignore + self.verbosity = options.verbosity + + def is_explicit_package_base(self, path: str) -> bool: + assert self.explicit_package_bases + return normalise_package_base(path) in self.explicit_package_bases + + def find_sources_in_dir(self, path: str) -> list[BuildSource]: + sources = [] + + seen: set[str] = set() + names = sorted(self.fscache.listdir(path), key=keyfunc) + for name in names: + # Skip certain names altogether + if name in ("__pycache__", "site-packages", "node_modules") or name.startswith("."): + continue + subpath = os.path.join(path, name) + + if matches_exclude(subpath, self.exclude, self.fscache, self.verbosity >= 2): + continue + if self.exclude_gitignore and matches_gitignore( + subpath, self.fscache, self.verbosity >= 2 + ): + continue + + if self.fscache.isdir(subpath): + sub_sources = self.find_sources_in_dir(subpath) + if sub_sources: + seen.add(name) + sources.extend(sub_sources) + else: + stem, suffix = os.path.splitext(name) + if stem not in seen and suffix in PY_EXTENSIONS: + seen.add(stem) + module, base_dir = self.crawl_up(subpath) + sources.append(BuildSource(subpath, module, None, base_dir)) + + return sources + + def crawl_up(self, path: str) -> tuple[str, str]: + """Given a .py[i] filename, return module and base directory. + + For example, given "xxx/yyy/foo/bar.py", we might return something like: + ("foo.bar", "xxx/yyy") + + If namespace packages is off, we crawl upwards until we find a directory without + an __init__.py + + If namespace packages is on, we crawl upwards until the nearest explicit base directory. + Failing that, we return one past the highest directory containing an __init__.py + + We won't crawl past directories with invalid package names. + The base directory returned is an absolute path. + """ + path = os.path.abspath(path) + parent, filename = os.path.split(path) + + module_name = strip_py(filename) or filename + + parent_module, base_dir = self.crawl_up_dir(parent) + if module_name == "__init__": + return parent_module, base_dir + + # Note that module_name might not actually be a valid identifier, but that's okay + # Ignoring this possibility sidesteps some search path confusion + module = module_join(parent_module, module_name) + return module, base_dir + + def crawl_up_dir(self, dir: str) -> tuple[str, str]: + return self._crawl_up_helper(dir) or ("", dir) + + @functools.lru_cache # noqa: B019 + def _crawl_up_helper(self, dir: str) -> tuple[str, str] | None: + """Given a directory, maybe returns module and base directory. + + We return a non-None value if we were able to find something clearly intended as a base + directory (as adjudicated by being an explicit base directory or by containing a package + with __init__.py). + + This distinction is necessary for namespace packages, so that we know when to treat + ourselves as a subpackage. + """ + # stop crawling if we're an explicit base directory + if self.explicit_package_bases is not None and self.is_explicit_package_base(dir): + return "", dir + + parent, name = os.path.split(dir) + name = name.removesuffix("-stubs") # PEP-561 stub-only directory + + # recurse if there's an __init__.py + init_file = self.get_init_file(dir) + if init_file is not None: + if not name.isidentifier(): + # in most cases the directory name is invalid, we'll just stop crawling upwards + # but if there's an __init__.py in the directory, something is messed up + raise InvalidSourceList( + f"{name} contains {os.path.basename(init_file)} " + "but is not a valid Python package name" + ) + # we're definitely a package, so we always return a non-None value + mod_prefix, base_dir = self.crawl_up_dir(parent) + return module_join(mod_prefix, name), base_dir + + # stop crawling if we're out of path components or our name is an invalid identifier + if not name or not parent or not name.isidentifier(): + return None + + # stop crawling if namespace packages is off (since we don't have an __init__.py) + if not self.namespace_packages: + return None + + # at this point: namespace packages is on, we don't have an __init__.py and we're not an + # explicit base directory + result = self._crawl_up_helper(parent) + if result is None: + # we're not an explicit base directory and we don't have an __init__.py + # and none of our parents are either, so return + return None + # one of our parents was an explicit base directory or had an __init__.py, so we're + # definitely a subpackage! chain our name to the module. + mod_prefix, base_dir = result + return module_join(mod_prefix, name), base_dir + + def get_init_file(self, dir: str) -> str | None: + """Check whether a directory contains a file named __init__.py[i]. + + If so, return the file's name (with dir prefixed). If not, return None. + + This prefers .pyi over .py (because of the ordering of PY_EXTENSIONS). + """ + for ext in PY_EXTENSIONS: + f = os.path.join(dir, "__init__" + ext) + if self.fscache.isfile(f): + return f + if ext == ".py" and self.fscache.init_under_package_root(f): + return f + return None + + +def module_join(parent: str, child: str) -> str: + """Join module ids, accounting for a possibly empty parent.""" + if parent: + return parent + "." + child + return child + + +def strip_py(arg: str) -> str | None: + """Strip a trailing .py or .pyi suffix. + + Return None if no such suffix is found. + """ + for ext in PY_EXTENSIONS: + if arg.endswith(ext): + return arg[: -len(ext)] + return None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..549621bcecf43d784900ecb89ac7fb8f7954ddab Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fixup.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fixup.py new file mode 100644 index 0000000000000000000000000000000000000000..d0205f64b7207e1e092ab1f1f476923f9aed4c41 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fixup.py @@ -0,0 +1,444 @@ +"""Fix up various things after deserialization.""" + +from __future__ import annotations + +from typing import Any, Final + +from mypy.lookup import lookup_fully_qualified +from mypy.nodes import ( + Block, + ClassDef, + Decorator, + FuncDef, + MypyFile, + OverloadedFuncDef, + ParamSpecExpr, + SymbolTable, + TypeAlias, + TypeInfo, + TypeVarExpr, + TypeVarTupleExpr, + Var, +) +from mypy.types import ( + NOT_READY, + AnyType, + CallableType, + Instance, + LiteralType, + Overloaded, + Parameters, + ParamSpecType, + ProperType, + TupleType, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UnionType, + UnpackType, +) +from mypy.visitor import NodeVisitor + + +# N.B: we do a allow_missing fixup when fixing up a fine-grained +# incremental cache load (since there may be cross-refs into deleted +# modules) +def fixup_module(tree: MypyFile, modules: dict[str, MypyFile], allow_missing: bool) -> None: + node_fixer = NodeFixer(modules, allow_missing) + node_fixer.visit_symbol_table(tree.names, tree.fullname) + + +# TODO: Fix up .info when deserializing, i.e. much earlier. +class NodeFixer(NodeVisitor[None]): + current_info: TypeInfo | None = None + + def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None: + self.modules = modules + self.allow_missing = allow_missing + self.type_fixer = TypeFixer(self.modules, allow_missing) + + # NOTE: This method isn't (yet) part of the NodeVisitor API. + def visit_type_info(self, info: TypeInfo) -> None: + save_info = self.current_info + try: + self.current_info = info + if info.defn: + info.defn.accept(self) + if info.names: + self.visit_symbol_table(info.names, info.fullname) + if info.bases: + for base in info.bases: + base.accept(self.type_fixer) + if info._promote: + for p in info._promote: + p.accept(self.type_fixer) + if info.tuple_type: + info.tuple_type.accept(self.type_fixer) + info.update_tuple_type(info.tuple_type) + if info.special_alias: + info.special_alias.alias_tvars = list(info.defn.type_vars) + for i, t in enumerate(info.defn.type_vars): + if isinstance(t, TypeVarTupleType): + info.special_alias.tvar_tuple_index = i + if info.typeddict_type: + info.typeddict_type.accept(self.type_fixer) + info.update_typeddict_type(info.typeddict_type) + if info.special_alias: + info.special_alias.alias_tvars = list(info.defn.type_vars) + for i, t in enumerate(info.defn.type_vars): + if isinstance(t, TypeVarTupleType): + info.special_alias.tvar_tuple_index = i + if info.declared_metaclass: + info.declared_metaclass.accept(self.type_fixer) + if info.metaclass_type: + info.metaclass_type.accept(self.type_fixer) + if info.self_type: + info.self_type.accept(self.type_fixer) + if info.alt_promote: + info.alt_promote.accept(self.type_fixer) + instance = Instance(info, []) + # Hack: We may also need to add a backwards promotion (from int to native int), + # since it might not be serialized. + if instance not in info.alt_promote.type._promote: + info.alt_promote.type._promote.append(instance) + if info._mro_refs: + info.mro = [ + lookup_fully_qualified_typeinfo( + self.modules, name, allow_missing=self.allow_missing + ) + for name in info._mro_refs + ] + info._mro_refs = None + finally: + self.current_info = save_info + + # NOTE: This method *definitely* isn't part of the NodeVisitor API. + def visit_symbol_table(self, symtab: SymbolTable, table_fullname: str) -> None: + # Copy the items because we may mutate symtab. + for key in list(symtab): + value = symtab[key] + cross_ref = value.cross_ref + if cross_ref is not None: # Fix up cross-reference. + value.cross_ref = None + if cross_ref in self.modules: + value.node = self.modules[cross_ref] + else: + stnode = lookup_fully_qualified( + cross_ref, self.modules, raise_on_missing=not self.allow_missing + ) + if stnode is not None: + if stnode is value: + # The node seems to refer to itself, which can mean that + # the target is a deleted submodule of the current module, + # and thus lookup falls back to the symbol table of the parent + # package. Here's how this may happen: + # + # pkg/__init__.py: + # from pkg import sub + # + # Now if pkg.sub is deleted, the pkg.sub symbol table entry + # appears to refer to itself. Replace the entry with a + # placeholder to avoid a crash. We can't delete the entry, + # as it would stop dependency propagation. + value.node = Var(key + "@deleted") + else: + assert stnode.node is not None, (table_fullname + "." + key, cross_ref) + value.node = stnode.node + elif not self.allow_missing: + assert False, f"Could not find cross-ref {cross_ref}" + else: + # We have a missing crossref in allow missing mode, need to put something + value.node = missing_info(self.modules) + else: + if isinstance(value.node, TypeInfo): + # TypeInfo has no accept(). TODO: Add it? + self.visit_type_info(value.node) + elif value.node is not None: + value.node.accept(self) + else: + assert False, f"Unexpected empty node {key!r}: {value}" + + def visit_func_def(self, func: FuncDef) -> None: + if self.current_info is not None: + func.info = self.current_info + if func.type is not None: + func.type.accept(self.type_fixer) + if isinstance(func.type, CallableType): + func.type.definition = func + + def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None: + if self.current_info is not None: + o.info = self.current_info + if o.type: + o.type.accept(self.type_fixer) + for item in o.items: + item.accept(self) + if o.impl: + o.impl.accept(self) + if isinstance(o.type, Overloaded): + # For error messages we link the original definition for each item. + for typ, item in zip(o.type.items, o.items): + typ.definition = item + + def visit_decorator(self, d: Decorator) -> None: + if self.current_info is not None: + d.var.info = self.current_info + if d.func: + d.func.accept(self) + if d.var: + d.var.accept(self) + for node in d.decorators: + node.accept(self) + typ = d.var.type + if isinstance(typ, ProperType) and isinstance(typ, CallableType): + typ.definition = d.func + + def visit_class_def(self, c: ClassDef) -> None: + for v in c.type_vars: + v.accept(self.type_fixer) + + def visit_type_var_expr(self, tv: TypeVarExpr) -> None: + for value in tv.values: + value.accept(self.type_fixer) + tv.upper_bound.accept(self.type_fixer) + tv.default.accept(self.type_fixer) + + def visit_paramspec_expr(self, p: ParamSpecExpr) -> None: + p.upper_bound.accept(self.type_fixer) + p.default.accept(self.type_fixer) + + def visit_type_var_tuple_expr(self, tv: TypeVarTupleExpr) -> None: + tv.upper_bound.accept(self.type_fixer) + tv.tuple_fallback.accept(self.type_fixer) + tv.default.accept(self.type_fixer) + + def visit_var(self, v: Var) -> None: + if self.current_info is not None: + v.info = self.current_info + if v.type is not None: + v.type.accept(self.type_fixer) + if v.setter_type is not None: + v.setter_type.accept(self.type_fixer) + + def visit_type_alias(self, a: TypeAlias) -> None: + a.target.accept(self.type_fixer) + for v in a.alias_tvars: + v.accept(self.type_fixer) + + +class TypeFixer(TypeVisitor[None]): + def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None: + self.modules = modules + self.allow_missing = allow_missing + + def visit_instance(self, inst: Instance) -> None: + # TODO: Combine Instances that are exactly the same? + type_ref = inst.type_ref + if type_ref is None: + return # We've already been here. + inst.type_ref = None + inst.type = lookup_fully_qualified_typeinfo( + self.modules, type_ref, allow_missing=self.allow_missing + ) + # TODO: Is this needed or redundant? + # Also fix up the bases, just in case. + for base in inst.type.bases: + if base.type is NOT_READY: + base.accept(self) + for a in inst.args: + a.accept(self) + if inst.last_known_value is not None: + inst.last_known_value.accept(self) + if inst.extra_attrs: + for v in inst.extra_attrs.attrs.values(): + v.accept(self) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + type_ref = t.type_ref + if type_ref is None: + return # We've already been here. + t.type_ref = None + t.alias = lookup_fully_qualified_alias( + self.modules, type_ref, allow_missing=self.allow_missing + ) + for a in t.args: + a.accept(self) + + def visit_any(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_callable_type(self, ct: CallableType) -> None: + if ct.fallback: + ct.fallback.accept(self) + for argt in ct.arg_types: + # argt may be None, e.g. for __self in NamedTuple constructors. + if argt is not None: + argt.accept(self) + if ct.ret_type is not None: + ct.ret_type.accept(self) + for v in ct.variables: + v.accept(self) + if ct.type_guard is not None: + ct.type_guard.accept(self) + if ct.type_is is not None: + ct.type_is.accept(self) + + def visit_overloaded(self, t: Overloaded) -> None: + for ct in t.items: + ct.accept(self) + + def visit_erased_type(self, o: Any) -> None: + # This type should exist only temporarily during type inference + raise RuntimeError("Shouldn't get here", o) + + def visit_deleted_type(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_none_type(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_uninhabited_type(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_partial_type(self, o: Any) -> None: + raise RuntimeError("Shouldn't get here", o) + + def visit_tuple_type(self, tt: TupleType) -> None: + if tt.items: + for it in tt.items: + it.accept(self) + if tt.partial_fallback is not None: + tt.partial_fallback.accept(self) + + def visit_typeddict_type(self, tdt: TypedDictType) -> None: + if tdt.items: + for it in tdt.items.values(): + it.accept(self) + if tdt.fallback is not None: + if tdt.fallback.type_ref is not None: + if ( + lookup_fully_qualified( + tdt.fallback.type_ref, + self.modules, + raise_on_missing=not self.allow_missing, + ) + is None + ): + # We reject fake TypeInfos for TypedDict fallbacks because + # the latter are used in type checking and must be valid. + tdt.fallback.type_ref = "typing._TypedDict" + tdt.fallback.accept(self) + + def visit_literal_type(self, lt: LiteralType) -> None: + lt.fallback.accept(self) + + def visit_type_var(self, tvt: TypeVarType) -> None: + if tvt.values: + for vt in tvt.values: + vt.accept(self) + tvt.upper_bound.accept(self) + tvt.default.accept(self) + + def visit_param_spec(self, p: ParamSpecType) -> None: + p.upper_bound.accept(self) + p.default.accept(self) + p.prefix.accept(self) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: + t.tuple_fallback.accept(self) + t.upper_bound.accept(self) + t.default.accept(self) + + def visit_unpack_type(self, u: UnpackType) -> None: + u.type.accept(self) + + def visit_parameters(self, p: Parameters) -> None: + for argt in p.arg_types: + if argt is not None: + argt.accept(self) + for var in p.variables: + var.accept(self) + + def visit_unbound_type(self, o: UnboundType) -> None: + for a in o.args: + a.accept(self) + + def visit_union_type(self, ut: UnionType) -> None: + if ut.items: + for it in ut.items: + it.accept(self) + + def visit_type_type(self, t: TypeType) -> None: + t.item.accept(self) + + +def lookup_fully_qualified_typeinfo( + modules: dict[str, MypyFile], name: str, *, allow_missing: bool +) -> TypeInfo: + stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing) + node = stnode.node if stnode else None + if isinstance(node, TypeInfo): + return node + else: + # Looks like a missing TypeInfo during an initial daemon load, put something there + assert ( + allow_missing + ), "Should never get here in normal mode, got {}:{} instead of TypeInfo".format( + type(node).__name__, node.fullname if node else "" + ) + return missing_info(modules) + + +def lookup_fully_qualified_alias( + modules: dict[str, MypyFile], name: str, *, allow_missing: bool +) -> TypeAlias: + stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing) + node = stnode.node if stnode else None + if isinstance(node, TypeAlias): + return node + elif isinstance(node, TypeInfo): + if node.special_alias: + # Already fixed up. + return node.special_alias + if node.tuple_type: + alias = TypeAlias.from_tuple_type(node) + elif node.typeddict_type: + alias = TypeAlias.from_typeddict_type(node) + else: + assert allow_missing + return missing_alias() + node.special_alias = alias + return alias + else: + # Looks like a missing TypeAlias during an initial daemon load, put something there + assert ( + allow_missing + ), "Should never get here in normal mode, got {}:{} instead of TypeAlias".format( + type(node).__name__, node.fullname if node else "" + ) + return missing_alias() + + +_SUGGESTION: Final = "" + + +def missing_info(modules: dict[str, MypyFile]) -> TypeInfo: + suggestion = _SUGGESTION.format("info") + dummy_def = ClassDef(suggestion, Block([])) + dummy_def.fullname = suggestion + + info = TypeInfo(SymbolTable(), dummy_def, "") + obj_type = lookup_fully_qualified_typeinfo(modules, "builtins.object", allow_missing=False) + info.bases = [Instance(obj_type, [])] + info.mro = [info, obj_type] + return info + + +def missing_alias() -> TypeAlias: + suggestion = _SUGGESTION.format("alias") + return TypeAlias(AnyType(TypeOfAny.special_form), suggestion, "", line=-1, column=-1) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..762a07c7d2915372384b2c1c81ef57d890bd8343 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/freetree.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/freetree.py new file mode 100644 index 0000000000000000000000000000000000000000..75b89e2623aefcf5bccc255b7d606da91cb5f9b7 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/freetree.py @@ -0,0 +1,23 @@ +"""Generic node traverser visitor""" + +from __future__ import annotations + +from mypy.nodes import Block, MypyFile +from mypy.traverser import TraverserVisitor + + +class TreeFreer(TraverserVisitor): + def visit_block(self, block: Block) -> None: + super().visit_block(block) + block.body.clear() + + +def free_tree(tree: MypyFile) -> None: + """Free all the ASTs associated with a module. + + This needs to be done recursively, since symbol tables contain + references to definitions, so those won't be freed but we want their + contents to be. + """ + tree.accept(TreeFreer()) + tree.defs.clear() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..99c3245771aaf7d51bc65d35a497ab65a484d69d Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fscache.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fscache.py new file mode 100644 index 0000000000000000000000000000000000000000..240370159fff6c939b9247adfc50ca2c65ffa6f6 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fscache.py @@ -0,0 +1,307 @@ +"""Interface for accessing the file system with automatic caching. + +The idea is to cache the results of any file system state reads during +a single transaction. This has two main benefits: + +* This avoids redundant syscalls, as we won't perform the same OS + operations multiple times. + +* This makes it easier to reason about concurrent FS updates, as different + operations targeting the same paths can't report different state during + a transaction. + +Note that this only deals with reading state, not writing. + +Properties maintained by the API: + +* The contents of the file are always from the same or later time compared + to the reported mtime of the file, even if mtime is queried after reading + a file. + +* Repeating an operation produces the same result as the first one during + a transaction. + +* Call flush() to start a new transaction (flush the caches). + +The API is a bit limited. It's easy to add new cached operations, however. +You should perform all file system reads through the API to actually take +advantage of the benefits. +""" + +from __future__ import annotations + +import os +import stat + +from mypy_extensions import mypyc_attr + +from mypy.util import hash_digest + + +@mypyc_attr(allow_interpreted_subclasses=True) # for tests +class FileSystemCache: + def __init__(self) -> None: + # The package root is not flushed with the caches. + # It is set by set_package_root() below. + self.package_root: list[str] = [] + self.flush() + + def set_package_root(self, package_root: list[str]) -> None: + self.package_root = package_root + + def flush(self) -> None: + """Start another transaction and empty all caches.""" + self.stat_or_none_cache: dict[str, os.stat_result | None] = {} + + self.listdir_cache: dict[str, list[str]] = {} + self.listdir_error_cache: dict[str, OSError] = {} + self.isfile_case_cache: dict[str, bool] = {} + self.exists_case_cache: dict[str, bool] = {} + self.read_cache: dict[str, bytes] = {} + self.read_error_cache: dict[str, Exception] = {} + self.hash_cache: dict[str, str] = {} + self.fake_package_cache: set[str] = set() + + def stat_or_none(self, path: str) -> os.stat_result | None: + if path in self.stat_or_none_cache: + return self.stat_or_none_cache[path] + + st = None + try: + st = os.stat(path) + except OSError: + if self.init_under_package_root(path): + try: + st = self._fake_init(path) + except OSError: + pass + + self.stat_or_none_cache[path] = st + return st + + def init_under_package_root(self, path: str) -> bool: + """Is this path an __init__.py under a package root? + + This is used to detect packages that don't contain __init__.py + files, which is needed to support Bazel. The function should + only be called for non-existing files. + + It will return True if it refers to a __init__.py file that + Bazel would create, so that at runtime Python would think the + directory containing it is a package. For this to work you + must pass one or more package roots using the --package-root + flag. + + As an exceptional case, any directory that is a package root + itself will not be considered to contain a __init__.py file. + This is different from the rules Bazel itself applies, but is + necessary for mypy to properly distinguish packages from other + directories. + + See https://docs.bazel.build/versions/master/be/python.html, + where this behavior is described under legacy_create_init. + """ + if not self.package_root: + return False + dirname, basename = os.path.split(path) + if basename != "__init__.py": + return False + if not os.path.basename(dirname).isidentifier(): + # Can't put an __init__.py in a place that's not an identifier + return False + + st = self.stat_or_none(dirname) + if st is None: + return False + else: + if not stat.S_ISDIR(st.st_mode): + return False + ok = False + + # skip if on a different drive + current_drive, _ = os.path.splitdrive(os.getcwd()) + drive, _ = os.path.splitdrive(path) + if drive != current_drive: + return False + if os.path.isabs(path): + path = os.path.relpath(path) + path = os.path.normpath(path) + for root in self.package_root: + if path.startswith(root): + if path == root + basename: + # A package root itself is never a package. + ok = False + break + else: + ok = True + return ok + + def _fake_init(self, path: str) -> os.stat_result: + """Prime the cache with a fake __init__.py file. + + This makes code that looks for path believe an empty file by + that name exists. Should only be called after + init_under_package_root() returns True. + """ + dirname, basename = os.path.split(path) + assert basename == "__init__.py", path + assert not os.path.exists(path), path # Not cached! + dirname = os.path.normpath(dirname) + st = os.stat(dirname) # May raise OSError + # Get stat result as a list so we can modify it. + seq: list[float] = list(st) + seq[stat.ST_MODE] = stat.S_IFREG | 0o444 + seq[stat.ST_INO] = 1 + seq[stat.ST_NLINK] = 1 + seq[stat.ST_SIZE] = 0 + st = os.stat_result(seq) + # Make listdir() and read() also pretend this file exists. + self.fake_package_cache.add(dirname) + return st + + def listdir(self, path: str) -> list[str]: + path = os.path.normpath(path) + if path in self.listdir_cache: + res = self.listdir_cache[path] + # Check the fake cache. + if path in self.fake_package_cache and "__init__.py" not in res: + res.append("__init__.py") # Updates the result as well as the cache + return res + if path in self.listdir_error_cache: + raise copy_os_error(self.listdir_error_cache[path]) + try: + results = os.listdir(path) + except OSError as err: + # Like above, take a copy to reduce memory use. + self.listdir_error_cache[path] = copy_os_error(err) + raise err + self.listdir_cache[path] = results + # Check the fake cache. + if path in self.fake_package_cache and "__init__.py" not in results: + results.append("__init__.py") + return results + + def isfile(self, path: str) -> bool: + st = self.stat_or_none(path) + if st is None: + return False + return stat.S_ISREG(st.st_mode) + + def isfile_case(self, path: str, prefix: str) -> bool: + """Return whether path exists and is a file. + + On case-insensitive filesystems (like Mac or Windows) this returns + False if the case of path's last component does not exactly match + the case found in the filesystem. + + We check also the case of other path components up to prefix. + For example, if path is 'user-stubs/pack/mod.pyi' and prefix is 'user-stubs', + we check that the case of 'pack' and 'mod.py' matches exactly, 'user-stubs' will be + case insensitive on case insensitive filesystems. + + The caller must ensure that prefix is a valid file system prefix of path. + """ + if not self.isfile(path): + # Fast path + return False + if path in self.isfile_case_cache: + return self.isfile_case_cache[path] + head, tail = os.path.split(path) + if not tail: + self.isfile_case_cache[path] = False + return False + try: + names = self.listdir(head) + # This allows one to check file name case sensitively in + # case-insensitive filesystems. + res = tail in names + except OSError: + res = False + if res: + # Also recursively check the other path components in case sensitive way. + res = self.exists_case(head, prefix) + self.isfile_case_cache[path] = res + return res + + def exists_case(self, path: str, prefix: str) -> bool: + """Return whether path exists - checking path components in case sensitive + fashion, up to prefix. + """ + if path in self.exists_case_cache: + return self.exists_case_cache[path] + head, tail = os.path.split(path) + if not head.startswith(prefix) or not tail: + # Only perform the check for paths under prefix. + self.exists_case_cache[path] = True + return True + try: + names = self.listdir(head) + # This allows one to check file name case sensitively in + # case-insensitive filesystems. + res = tail in names + except OSError: + res = False + if res: + # Also recursively check other path components. + res = self.exists_case(head, prefix) + self.exists_case_cache[path] = res + return res + + def isdir(self, path: str) -> bool: + st = self.stat_or_none(path) + if st is None: + return False + return stat.S_ISDIR(st.st_mode) + + def exists(self, path: str) -> bool: + st = self.stat_or_none(path) + return st is not None + + def read(self, path: str) -> bytes: + if path in self.read_cache: + return self.read_cache[path] + if path in self.read_error_cache: + raise self.read_error_cache[path] + + # Need to stat first so that the contents of file are from no + # earlier instant than the mtime reported by self.stat(). + self.stat_or_none(path) + + dirname, basename = os.path.split(path) + dirname = os.path.normpath(dirname) + # Check the fake cache. + if basename == "__init__.py" and dirname in self.fake_package_cache: + data = b"" + else: + try: + with open(path, "rb") as f: + data = f.read() + except OSError as err: + self.read_error_cache[path] = err + raise + + self.read_cache[path] = data + self.hash_cache[path] = hash_digest(data) + return data + + def hash_digest(self, path: str) -> str: + if path not in self.hash_cache: + self.read(path) + return self.hash_cache[path] + + def samefile(self, f1: str, f2: str) -> bool: + s1 = self.stat_or_none(f1) + s2 = self.stat_or_none(f2) + if s1 is None or s2 is None: + return False + return os.path.samestat(s1, s2) + + +def copy_os_error(e: OSError) -> OSError: + new = OSError(*e.args) + new.errno = e.errno + new.strerror = e.strerror + new.filename = e.filename + if e.filename2: + new.filename2 = e.filename2 + return new diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..779f1eb756a38d2f55b28e7e20d74229652cdb20 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fswatcher.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fswatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d5873f3a0a99655189c797064e910b479d0c7c3e --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/fswatcher.py @@ -0,0 +1,106 @@ +"""Watch parts of the file system for changes.""" + +from __future__ import annotations + +import os +from collections.abc import Iterable, Set as AbstractSet +from typing import NamedTuple + +from mypy.fscache import FileSystemCache + + +class FileData(NamedTuple): + st_mtime: float + st_size: int + hash: str + + +class FileSystemWatcher: + """Watcher for file system changes among specific paths. + + All file system access is performed using FileSystemCache. We + detect changed files by stat()ing them all and comparing hashes + of potentially changed files. If a file has both size and mtime + unmodified, the file is assumed to be unchanged. + + An important goal of this class is to make it easier to eventually + use file system events to detect file changes. + + Note: This class doesn't flush the file system cache. If you don't + manually flush it, changes won't be seen. + """ + + # TODO: Watching directories? + # TODO: Handle non-files + + def __init__(self, fs: FileSystemCache) -> None: + self.fs = fs + self._paths: set[str] = set() + self._file_data: dict[str, FileData | None] = {} + + def dump_file_data(self) -> dict[str, tuple[float, int, str]]: + return {k: v for k, v in self._file_data.items() if v is not None} + + def set_file_data(self, path: str, data: FileData) -> None: + self._file_data[path] = data + + def add_watched_paths(self, paths: Iterable[str]) -> None: + for path in paths: + if path not in self._paths: + # By storing None this path will get reported as changed by + # find_changed if it exists. + self._file_data[path] = None + self._paths |= set(paths) + + def remove_watched_paths(self, paths: Iterable[str]) -> None: + for path in paths: + if path in self._file_data: + del self._file_data[path] + self._paths -= set(paths) + + def _update(self, path: str, st: os.stat_result) -> None: + hash_digest = self.fs.hash_digest(path) + self._file_data[path] = FileData(st.st_mtime, st.st_size, hash_digest) + + def _find_changed(self, paths: Iterable[str]) -> AbstractSet[str]: + changed = set() + for path in paths: + old = self._file_data[path] + st = self.fs.stat_or_none(path) + if st is None: + if old is not None: + # File was deleted. + changed.add(path) + self._file_data[path] = None + else: + if old is None: + # File is new. + changed.add(path) + self._update(path, st) + # Round mtimes down, to match the mtimes we write to meta files + elif st.st_size != old.st_size or int(st.st_mtime) != int(old.st_mtime): + # Only look for changes if size or mtime has changed as an + # optimization, since calculating hash is expensive. + new_hash = self.fs.hash_digest(path) + self._update(path, st) + if st.st_size != old.st_size or new_hash != old.hash: + # Changed file. + changed.add(path) + return changed + + def find_changed(self) -> AbstractSet[str]: + """Return paths that have changes since the last call, in the watched set.""" + return self._find_changed(self._paths) + + def update_changed(self, remove: list[str], update: list[str]) -> AbstractSet[str]: + """Alternative to find_changed() given explicit changes. + + This only calls self.fs.stat() on added or updated files, not + on all files. It believes all other files are unchanged! + + Implies add_watched_paths() for add and update, and + remove_watched_paths() for remove. + """ + self.remove_watched_paths(remove) + self.add_watched_paths(update) + return self._find_changed(update) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..64f980de351dd22e1dc166b68e9a3fa623cde1a8 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/gclogger.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/gclogger.py new file mode 100644 index 0000000000000000000000000000000000000000..bc908bdb6107dab5187c0e4b79613987a49f2b56 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/gclogger.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import gc +import time +from collections.abc import Mapping + + +class GcLogger: + """Context manager to log GC stats and overall time.""" + + def __enter__(self) -> GcLogger: + self.gc_start_time: float | None = None + self.gc_time = 0.0 + self.gc_calls = 0 + self.gc_collected = 0 + self.gc_uncollectable = 0 + gc.callbacks.append(self.gc_callback) + self.start_time = time.time() + return self + + def gc_callback(self, phase: str, info: Mapping[str, int]) -> None: + if phase == "start": + assert self.gc_start_time is None, "Start phase out of sequence" + self.gc_start_time = time.time() + elif phase == "stop": + assert self.gc_start_time is not None, "Stop phase out of sequence" + self.gc_calls += 1 + self.gc_time += time.time() - self.gc_start_time + self.gc_start_time = None + self.gc_collected += info["collected"] + self.gc_uncollectable += info["uncollectable"] + else: + assert False, f"Unrecognized gc phase ({phase!r})" + + def __exit__(self, *args: object) -> None: + while self.gc_callback in gc.callbacks: + gc.callbacks.remove(self.gc_callback) + + def get_stats(self) -> Mapping[str, float]: + end_time = time.time() + result = { + "gc_time": self.gc_time, + "gc_calls": self.gc_calls, + "gc_collected": self.gc_collected, + "gc_uncollectable": self.gc_uncollectable, + "build_time": end_time - self.start_time, + } + return result diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/git.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/git.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c894e39e0ef46d08edad00e933a70f85253546bf Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/git.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/git.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/git.py new file mode 100644 index 0000000000000000000000000000000000000000..1c63bf6471dccc1c7aec2686bd90245412738560 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/git.py @@ -0,0 +1,34 @@ +"""Git utilities.""" + +# Used also from setup.py, so don't pull in anything additional here (like mypy or typing): +from __future__ import annotations + +import os +import subprocess + + +def is_git_repo(dir: str) -> bool: + """Is the given directory version-controlled with git?""" + return os.path.exists(os.path.join(dir, ".git")) + + +def have_git() -> bool: + """Can we run the git executable?""" + try: + subprocess.check_output(["git", "--help"]) + return True + except subprocess.CalledProcessError: + return False + except OSError: + return False + + +def git_revision(dir: str) -> bytes: + """Get the SHA-1 of the HEAD of a git repository.""" + return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=dir).strip() + + +def is_dirty(dir: str) -> bool: + """Check whether a git repository has uncommitted changes.""" + output = subprocess.check_output(["git", "status", "-uno", "--porcelain"], cwd=dir) + return output.strip() != b"" diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..1f10682fc68f20f7f0af34265b2e80328420d9d8 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/graph_utils.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/graph_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5699bab3f7e2f9c93132c7f351281ac611eca428 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/graph_utils.py @@ -0,0 +1,161 @@ +"""Helpers for manipulations with graphs.""" + +from __future__ import annotations + +from collections.abc import Iterator, Set as AbstractSet +from typing import TypeVar + +T = TypeVar("T") + + +def strongly_connected_components( + vertices: AbstractSet[T], edges: dict[T, list[T]] +) -> Iterator[set[T]]: + """Compute Strongly Connected Components of a directed graph. + + Args: + vertices: the labels for the vertices + edges: for each vertex, gives the target vertices of its outgoing edges + + Returns: + An iterator yielding strongly connected components, each + represented as a set of vertices. Each input vertex will occur + exactly once; vertices not part of a SCC are returned as + singleton sets. + + From https://code.activestate.com/recipes/578507/. + """ + identified: set[T] = set() + stack: list[T] = [] + index: dict[T, int] = {} + boundaries: list[int] = [] + + def dfs(v: T) -> Iterator[set[T]]: + index[v] = len(stack) + stack.append(v) + boundaries.append(index[v]) + + for w in edges[v]: + if w not in index: + yield from dfs(w) + elif w not in identified: + while index[w] < boundaries[-1]: + boundaries.pop() + + if boundaries[-1] == index[v]: + boundaries.pop() + scc = set(stack[index[v] :]) + del stack[index[v] :] + identified.update(scc) + yield scc + + for v in vertices: + if v not in index: + yield from dfs(v) + + +def prepare_sccs( + sccs: list[set[T]], edges: dict[T, list[T]] +) -> dict[AbstractSet[T], set[AbstractSet[T]]]: + """Use original edges to organize SCCs in a graph by dependencies between them.""" + sccsmap = {} + for scc in sccs: + scc_frozen = frozenset(scc) + for v in scc: + sccsmap[v] = scc_frozen + data: dict[AbstractSet[T], set[AbstractSet[T]]] = {} + for scc in sccs: + deps: set[AbstractSet[T]] = set() + for v in scc: + deps.update(sccsmap[x] for x in edges[v]) + data[frozenset(scc)] = deps + return data + + +class topsort(Iterator[set[T]]): # noqa: N801 + """Topological sort using Kahn's algorithm. + + Uses in-degree counters and a reverse adjacency list, so the total work + is O(V + E). + + Implemented as a class rather than a generator for better mypyc + compilation. + + Args: + data: A map from vertices to all vertices that it has an edge + connecting it to. NOTE: dependency sets in this data + structure are modified in place to remove self-dependencies. + Orphans are handled internally and are not added to `data`. + + Returns: + An iterator yielding sets of vertices that have an equivalent + ordering. + + Example: + Suppose the input has the following structure: + + {A: {B, C}, B: {D}, C: {D}} + + The algorithm treats orphan dependencies as if normalized to: + + {A: {B, C}, B: {D}, C: {D}, D: {}} + + It will yield the following values: + + {D} + {B, C} + {A} + """ + + def __init__(self, data: dict[T, set[T]]) -> None: + # Single pass: remove self-deps, build reverse adjacency list, + # compute in-degree counts, detect orphans, and find initial ready set. + in_degree: dict[T, int] = {} + rev: dict[T, list[T]] = {} + ready: set[T] = set() + for item, deps in data.items(): + deps.discard(item) # Ignore self dependencies. + deg = len(deps) + in_degree[item] = deg + if deg == 0: + ready.add(item) + if item not in rev: + rev[item] = [] + for dep in deps: + if dep in rev: + rev[dep].append(item) + else: + rev[dep] = [item] + if dep not in data: + # Orphan: appears as dependency but has no entry in data. + in_degree[dep] = 0 + ready.add(dep) + + self.in_degree = in_degree + self.rev = rev + self.ready = ready + self.remaining = len(in_degree) - len(ready) + + def __iter__(self) -> Iterator[set[T]]: + return self + + def __next__(self) -> set[T]: + ready = self.ready + if not ready: + assert self.remaining == 0, ( + f"A cyclic dependency exists amongst " + f"{[k for k, deg in self.in_degree.items() if deg > 0]!r}" + ) + raise StopIteration + in_degree = self.in_degree + rev = self.rev + new_ready: set[T] = set() + for item in ready: + for dependent in rev[item]: + new_deg = in_degree[dependent] - 1 + in_degree[dependent] = new_deg + if new_deg == 0: + new_ready.add(dependent) + self.remaining -= len(new_ready) + self.ready = new_ready + return ready diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..171c6440eb2c11738a6a41235c6bdb2b45eb44eb Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/indirection.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/indirection.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f3fa89b8c4af53dc872f5c942b896d03d44c3b --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/indirection.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from collections.abc import Iterable + +import mypy.types as types +from mypy.types import TypeVisitor + + +class TypeIndirectionVisitor(TypeVisitor[None]): + """Returns all module references within a particular type.""" + + def __init__(self) -> None: + # Module references are collected here + self.modules: set[str] = set() + # User to avoid infinite recursion with recursive types + self.seen_types: set[types.TypeAliasType | types.Instance] = set() + + def find_modules(self, typs: Iterable[types.Type]) -> set[str]: + self.modules = set() + self.seen_types = set() + for typ in typs: + self._visit(typ) + return self.modules + + def _visit(self, typ: types.Type) -> None: + # Note: instances are needed for `class str(Sequence[str]): ...` + if ( + isinstance(typ, types.TypeAliasType) + or isinstance(typ, types.ProperType) + and isinstance(typ, types.Instance) + ): + # Avoid infinite recursion for recursive types. + if typ in self.seen_types: + return + self.seen_types.add(typ) + typ.accept(self) + + def _visit_type_tuple(self, typs: tuple[types.Type, ...]) -> None: + # Micro-optimization: Specialized version of _visit for lists + for typ in typs: + if ( + isinstance(typ, types.TypeAliasType) + or isinstance(typ, types.ProperType) + and isinstance(typ, types.Instance) + ): + # Avoid infinite recursion for recursive types. + if typ in self.seen_types: + continue + self.seen_types.add(typ) + typ.accept(self) + + def _visit_type_list(self, typs: list[types.Type]) -> None: + # Micro-optimization: Specialized version of _visit for tuples + for typ in typs: + if ( + isinstance(typ, types.TypeAliasType) + or isinstance(typ, types.ProperType) + and isinstance(typ, types.Instance) + ): + # Avoid infinite recursion for recursive types. + if typ in self.seen_types: + continue + self.seen_types.add(typ) + typ.accept(self) + + def visit_unbound_type(self, t: types.UnboundType) -> None: + self._visit_type_tuple(t.args) + + def visit_any(self, t: types.AnyType) -> None: + pass + + def visit_none_type(self, t: types.NoneType) -> None: + pass + + def visit_uninhabited_type(self, t: types.UninhabitedType) -> None: + pass + + def visit_erased_type(self, t: types.ErasedType) -> None: + pass + + def visit_deleted_type(self, t: types.DeletedType) -> None: + pass + + def visit_type_var(self, t: types.TypeVarType) -> None: + self._visit_type_list(t.values) + self._visit(t.upper_bound) + self._visit(t.default) + + def visit_param_spec(self, t: types.ParamSpecType) -> None: + self._visit(t.upper_bound) + self._visit(t.default) + self._visit(t.prefix) + + def visit_type_var_tuple(self, t: types.TypeVarTupleType) -> None: + self._visit(t.upper_bound) + self._visit(t.default) + + def visit_unpack_type(self, t: types.UnpackType) -> None: + t.type.accept(self) + + def visit_parameters(self, t: types.Parameters) -> None: + self._visit_type_list(t.arg_types) + + def visit_instance(self, t: types.Instance) -> None: + # Instance is named, record its definition and continue digging into + # components that constitute semantic meaning of this type: bases, metaclass, + # tuple type, and typeddict type. + # Note: we cannot simply record the MRO, in case an intermediate base contains + # a reference to type alias, this affects meaning of map_instance_to_supertype(), + # see e.g. testDoubleReexportGenericUpdated. + self._visit_type_tuple(t.args) + if t.type: + # Important optimization: instead of simply recording the definition and + # recursing into bases, record the MRO and only traverse generic bases. + for s in t.type.mro: + self.modules.add(s.module_name) + for base in s.bases: + if base.args: + self._visit_type_tuple(base.args) + if t.type.metaclass_type: + self._visit(t.type.metaclass_type) + if t.type.typeddict_type: + self._visit(t.type.typeddict_type) + if t.type.tuple_type: + self._visit(t.type.tuple_type) + if t.type.is_protocol: + # For protocols, member types constitute the semantic meaning of the type. + # TODO: this doesn't cover some edge cases, like setter types and exotic nodes. + for m in t.type.protocol_members: + node = t.type.names.get(m) + if node and node.type: + self._visit(node.type) + + def visit_callable_type(self, t: types.CallableType) -> None: + self._visit_type_list(t.arg_types) + self._visit(t.ret_type) + self._visit_type_tuple(t.variables) + + def visit_overloaded(self, t: types.Overloaded) -> None: + for item in t.items: + self._visit(item) + self._visit(t.fallback) + + def visit_tuple_type(self, t: types.TupleType) -> None: + self._visit_type_list(t.items) + self._visit(t.partial_fallback) + + def visit_typeddict_type(self, t: types.TypedDictType) -> None: + self._visit_type_list(list(t.items.values())) + self._visit(t.fallback) + + def visit_literal_type(self, t: types.LiteralType) -> None: + self._visit(t.fallback) + + def visit_union_type(self, t: types.UnionType) -> None: + self._visit_type_list(t.items) + + def visit_partial_type(self, t: types.PartialType) -> None: + pass + + def visit_type_type(self, t: types.TypeType) -> None: + self._visit(t.item) + + def visit_type_alias_type(self, t: types.TypeAliasType) -> None: + # Type alias is named, record its definition and continue digging into + # components that constitute semantic meaning of this type: target and args. + if t.alias: + self.modules.add(t.alias.module) + self._visit(t.alias.target) + self._visit_type_list(t.args) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b5028a808581e3875fa72076e73b3cb89d542d97 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/infer.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc43797d3b164ed9891a1439f3f14460b8ec451 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/infer.py @@ -0,0 +1,76 @@ +"""Utilities for type argument inference.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import NamedTuple + +from mypy.constraints import ( + SUBTYPE_OF, + SUPERTYPE_OF, + infer_constraints, + infer_constraints_for_callable, +) +from mypy.nodes import ArgKind +from mypy.solve import solve_constraints +from mypy.types import CallableType, Instance, Type, TypeVarLikeType + + +class ArgumentInferContext(NamedTuple): + """Type argument inference context. + + We need this because we pass around ``Mapping`` and ``Iterable`` types. + These types are only known by ``TypeChecker`` itself. + It is required for ``*`` and ``**`` argument inference. + + https://github.com/python/mypy/issues/11144 + """ + + mapping_type: Instance + iterable_type: Instance + + +def infer_function_type_arguments( + callee_type: CallableType, + arg_types: Sequence[Type | None], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + formal_to_actual: list[list[int]], + context: ArgumentInferContext, + strict: bool = True, + allow_polymorphic: bool = False, +) -> tuple[list[Type | None], list[TypeVarLikeType]]: + """Infer the type arguments of a generic function. + + Return an array of lower bound types for the type variables -1 (at + index 0), -2 (at index 1), etc. A lower bound is None if a value + could not be inferred. + + Arguments: + callee_type: the target generic function + arg_types: argument types at the call site (each optional; if None, + we are not considering this argument in the current pass) + arg_kinds: nodes.ARG_* values for arg_types + formal_to_actual: mapping from formal to actual variable indices + """ + # Infer constraints. + constraints = infer_constraints_for_callable( + callee_type, arg_types, arg_kinds, arg_names, formal_to_actual, context + ) + + # Solve constraints. + type_vars = callee_type.variables + return solve_constraints(type_vars, constraints, strict, allow_polymorphic) + + +def infer_type_arguments( + type_vars: Sequence[TypeVarLikeType], + template: Type, + actual: Type, + is_supertype: bool = False, + skip_unsatisfied: bool = False, +) -> list[Type | None]: + # Like infer_function_type_arguments, but only match a single type + # against a generic type. + constraints = infer_constraints(template, actual, SUPERTYPE_OF if is_supertype else SUBTYPE_OF) + return solve_constraints(type_vars, constraints, skip_unsatisfied=skip_unsatisfied)[0] diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e2d5ff12c77c0ce063ef2bbbc012c7f1769c323e Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/inspections.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/inspections.py new file mode 100644 index 0000000000000000000000000000000000000000..1a869438101fe19ba87876558f9a863547ed3004 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/inspections.py @@ -0,0 +1,626 @@ +from __future__ import annotations + +import os +from collections import defaultdict +from collections.abc import Callable +from functools import cmp_to_key + +from mypy.build import State +from mypy.messages import format_type +from mypy.modulefinder import PYTHON_EXTENSIONS +from mypy.nodes import ( + LDEF, + Decorator, + Expression, + FuncBase, + MemberExpr, + MypyFile, + Node, + OverloadedFuncDef, + RefExpr, + SymbolNode, + TypeInfo, + Var, +) +from mypy.server.update import FineGrainedBuildManager +from mypy.traverser import ExtendedTraverserVisitor +from mypy.typeops import tuple_fallback +from mypy.types import ( + FunctionLike, + Instance, + LiteralType, + ProperType, + TupleType, + TypedDictType, + TypeVarType, + UnionType, + get_proper_type, +) +from mypy.typevars import fill_typevars_with_any + + +def node_starts_after(o: Node, line: int, column: int) -> bool: + return o.line > line or o.line == line and o.column > column + + +def node_ends_before(o: Node, line: int, column: int) -> bool: + # Unfortunately, end positions for some statements are a mess, + # e.g. overloaded functions, so we return False when we don't know. + if o.end_line is not None and o.end_column is not None: + if o.end_line < line or o.end_line == line and o.end_column < column: + return True + return False + + +def expr_span(expr: Expression) -> str: + """Format expression span as in mypy error messages.""" + return f"{expr.line}:{expr.column + 1}:{expr.end_line}:{expr.end_column}" + + +def get_instance_fallback(typ: ProperType) -> list[Instance]: + """Returns the Instance fallback for this type if one exists or None.""" + if isinstance(typ, Instance): + return [typ] + elif isinstance(typ, TupleType): + return [tuple_fallback(typ)] + elif isinstance(typ, TypedDictType): + return [typ.fallback] + elif isinstance(typ, FunctionLike): + return [typ.fallback] + elif isinstance(typ, LiteralType): + return [typ.fallback] + elif isinstance(typ, TypeVarType): + if typ.values: + res = [] + for t in typ.values: + res.extend(get_instance_fallback(get_proper_type(t))) + return res + return get_instance_fallback(get_proper_type(typ.upper_bound)) + elif isinstance(typ, UnionType): + res = [] + for t in typ.items: + res.extend(get_instance_fallback(get_proper_type(t))) + return res + return [] + + +def find_node(name: str, info: TypeInfo) -> Var | FuncBase | None: + """Find the node defining member 'name' in given TypeInfo.""" + # TODO: this code shares some logic with checkmember.py + method = info.get_method(name) + if method: + if isinstance(method, Decorator): + return method.var + if method.is_property: + assert isinstance(method, OverloadedFuncDef) + dec = method.items[0] + assert isinstance(dec, Decorator) + return dec.var + return method + else: + # don't have such method, maybe variable? + node = info.get(name) + v = node.node if node else None + if isinstance(v, Var): + return v + return None + + +def find_module_by_fullname(fullname: str, modules: dict[str, State]) -> State | None: + """Find module by a node fullname. + + This logic mimics the one we use in fixup, so should be good enough. + """ + head = fullname + # Special case: a module symbol is considered to be defined in itself, not in enclosing + # package, since this is what users want when clicking go to definition on a module. + if head in modules: + return modules[head] + while True: + if "." not in head: + return None + head, tail = head.rsplit(".", maxsplit=1) + mod = modules.get(head) + if mod is not None: + return mod + + +class SearchVisitor(ExtendedTraverserVisitor): + """Visitor looking for an expression whose span matches given one exactly.""" + + def __init__(self, line: int, column: int, end_line: int, end_column: int) -> None: + self.line = line + self.column = column + self.end_line = end_line + self.end_column = end_column + self.result: Expression | None = None + + def visit(self, o: Node) -> bool: + if node_starts_after(o, self.line, self.column): + return False + if node_ends_before(o, self.end_line, self.end_column): + return False + if ( + o.line == self.line + and o.end_line == self.end_line + and o.column == self.column + and o.end_column == self.end_column + ): + if isinstance(o, Expression): + self.result = o + return self.result is None + + +def find_by_location( + tree: MypyFile, line: int, column: int, end_line: int, end_column: int +) -> Expression | None: + """Find an expression matching given span, or None if not found.""" + if end_line < line: + raise ValueError('"end_line" must not be before "line"') + if end_line == line and end_column <= column: + raise ValueError('"end_column" must be after "column"') + visitor = SearchVisitor(line, column, end_line, end_column) + tree.accept(visitor) + return visitor.result + + +class SearchAllVisitor(ExtendedTraverserVisitor): + """Visitor looking for all expressions whose spans enclose given position.""" + + def __init__(self, line: int, column: int) -> None: + self.line = line + self.column = column + self.result: list[Expression] = [] + + def visit(self, o: Node) -> bool: + if node_starts_after(o, self.line, self.column): + return False + if node_ends_before(o, self.line, self.column): + return False + if isinstance(o, Expression): + self.result.append(o) + return True + + +def find_all_by_location(tree: MypyFile, line: int, column: int) -> list[Expression]: + """Find all expressions enclosing given position starting from innermost.""" + visitor = SearchAllVisitor(line, column) + tree.accept(visitor) + return list(reversed(visitor.result)) + + +class InspectionEngine: + """Engine for locating and statically inspecting expressions.""" + + def __init__( + self, + fg_manager: FineGrainedBuildManager, + *, + verbosity: int = 0, + limit: int = 0, + include_span: bool = False, + include_kind: bool = False, + include_object_attrs: bool = False, + union_attrs: bool = False, + force_reload: bool = False, + ) -> None: + self.fg_manager = fg_manager + self.verbosity = verbosity + self.limit = limit + self.include_span = include_span + self.include_kind = include_kind + self.include_object_attrs = include_object_attrs + self.union_attrs = union_attrs + self.force_reload = force_reload + # Module for which inspection was requested. + self.module: State | None = None + + def reload_module(self, state: State) -> None: + """Reload given module while temporary exporting types.""" + old = self.fg_manager.manager.options.export_types + self.fg_manager.manager.options.export_types = True + try: + self.fg_manager.flush_cache() + assert state.path is not None + self.fg_manager.update([(state.id, state.path)], []) + finally: + self.fg_manager.manager.options.export_types = old + + def expr_type(self, expression: Expression) -> tuple[str, bool]: + """Format type for an expression using current options. + + If type is known, second item returned is True. If type is not known, an error + message is returned instead, and second item returned is False. + """ + expr_type = self.fg_manager.manager.all_types.get(expression) + if expr_type is None: + return self.missing_type(expression), False + + type_str = format_type( + expr_type, self.fg_manager.manager.options, verbosity=self.verbosity + ) + return self.add_prefixes(type_str, expression), True + + def object_type(self) -> Instance: + builtins = self.fg_manager.graph["builtins"].tree + assert builtins is not None + object_node = builtins.names["object"].node + assert isinstance(object_node, TypeInfo) + return Instance(object_node, []) + + def collect_attrs(self, instances: list[Instance]) -> dict[TypeInfo, list[str]]: + """Collect attributes from all union/typevar variants.""" + + def item_attrs(attr_dict: dict[TypeInfo, list[str]]) -> set[str]: + attrs = set() + for base in attr_dict: + attrs |= set(attr_dict[base]) + return attrs + + def cmp_types(x: TypeInfo, y: TypeInfo) -> int: + if x in y.mro: + return 1 + if y in x.mro: + return -1 + return 0 + + # First gather all attributes for every union variant. + assert instances + all_attrs = [] + for instance in instances: + attrs = {} + mro = instance.type.mro + if not self.include_object_attrs: + mro = mro[:-1] + for base in mro: + attrs[base] = sorted(base.names) + all_attrs.append(attrs) + + # Find attributes valid for all variants in a union or type variable. + intersection = item_attrs(all_attrs[0]) + for item in all_attrs[1:]: + intersection &= item_attrs(item) + + # Combine attributes from all variants into a single dict while + # also removing invalid attributes (unless using --union-attrs). + combined_attrs = defaultdict(list) + for item in all_attrs: + for base in item: + if base in combined_attrs: + continue + for name in item[base]: + if self.union_attrs or name in intersection: + combined_attrs[base].append(name) + + # Sort bases by MRO, unrelated will appear in the order they appeared as union variants. + sorted_bases = sorted(combined_attrs.keys(), key=cmp_to_key(cmp_types)) + result = {} + for base in sorted_bases: + if not combined_attrs[base]: + # Skip bases where everytihng was filtered out. + continue + result[base] = combined_attrs[base] + return result + + def _fill_from_dict( + self, attrs_strs: list[str], attrs_dict: dict[TypeInfo, list[str]] + ) -> None: + for base in attrs_dict: + cls_name = base.name if self.verbosity < 1 else base.fullname + attrs = [f'"{attr}"' for attr in attrs_dict[base]] + attrs_strs.append(f'"{cls_name}": [{", ".join(attrs)}]') + + def expr_attrs(self, expression: Expression) -> tuple[str, bool]: + """Format attributes that are valid for a given expression. + + If expression type is not an Instance, try using fallback. Attributes are + returned as a JSON (ordered by MRO) that maps base class name to list of + attributes. Attributes may appear in multiple bases if overridden (we simply + follow usual mypy logic for creating new Vars etc). + """ + expr_type = self.fg_manager.manager.all_types.get(expression) + if expr_type is None: + return self.missing_type(expression), False + + expr_type = get_proper_type(expr_type) + instances = get_instance_fallback(expr_type) + if not instances: + # Everything is an object in Python. + instances = [self.object_type()] + + attrs_dict = self.collect_attrs(instances) + + # Special case: modules have names apart from those from ModuleType. + if isinstance(expression, RefExpr) and isinstance(expression.node, MypyFile): + node = expression.node + names = sorted(node.names) + if "__builtins__" in names: + # This is just to make tests stable. No one will really need this name. + names.remove("__builtins__") + mod_dict = {f'"<{node.fullname}>"': [f'"{name}"' for name in names]} + else: + mod_dict = {} + + # Special case: for class callables, prepend with the class attributes. + # TODO: also handle cases when such callable appears in a union. + if isinstance(expr_type, FunctionLike) and expr_type.is_type_obj(): + template = fill_typevars_with_any(expr_type.type_object()) + class_dict = self.collect_attrs(get_instance_fallback(template)) + else: + class_dict = {} + + # We don't use JSON dump to be sure keys order is always preserved. + base_attrs = [] + if mod_dict: + for mod in mod_dict: + base_attrs.append(f'{mod}: [{", ".join(mod_dict[mod])}]') + self._fill_from_dict(base_attrs, class_dict) + self._fill_from_dict(base_attrs, attrs_dict) + return self.add_prefixes(f'{{{", ".join(base_attrs)}}}', expression), True + + def format_node(self, module: State, node: FuncBase | SymbolNode) -> str: + return f"{module.path}:{node.line}:{node.column + 1}:{node.name}" + + def collect_nodes(self, expression: RefExpr) -> list[FuncBase | SymbolNode]: + """Collect nodes that can be referred to by an expression. + + Note: it can be more than one for example in case of a union attribute. + """ + node: FuncBase | SymbolNode | None = expression.node + nodes: list[FuncBase | SymbolNode] + if node is None: + # Tricky case: instance attribute + if isinstance(expression, MemberExpr) and expression.kind is None: + base_type = self.fg_manager.manager.all_types.get(expression.expr) + if base_type is None: + return [] + + # Now we use the base type to figure out where the attribute is defined. + base_type = get_proper_type(base_type) + instances = get_instance_fallback(base_type) + nodes = [] + for instance in instances: + node = find_node(expression.name, instance.type) + if node: + nodes.append(node) + if not nodes: + # Try checking class namespace if attribute is on a class object. + if isinstance(base_type, FunctionLike) and base_type.is_type_obj(): + instances = get_instance_fallback( + fill_typevars_with_any(base_type.type_object()) + ) + for instance in instances: + node = find_node(expression.name, instance.type) + if node: + nodes.append(node) + else: + # Still no luck, give up. + return [] + else: + return [] + else: + # Easy case: a module-level definition + nodes = [node] + return nodes + + def modules_for_nodes( + self, nodes: list[FuncBase | SymbolNode], expression: RefExpr + ) -> tuple[dict[FuncBase | SymbolNode, State], bool]: + """Gather modules where given nodes where defined. + + Also check if they need to be refreshed (cached nodes may have + lines/columns missing). + """ + modules = {} + reload_needed = False + for node in nodes: + module = find_module_by_fullname(node.fullname, self.fg_manager.graph) + if not module: + if expression.kind == LDEF and self.module: + module = self.module + else: + continue + modules[node] = module + if not module.tree or module.tree.is_cache_skeleton or self.force_reload: + reload_needed |= not module.tree or module.tree.is_cache_skeleton + self.reload_module(module) + return modules, reload_needed + + def expression_def(self, expression: Expression) -> tuple[str, bool]: + """Find and format definition location for an expression. + + If it is not a RefExpr, it is effectively skipped by returning an + empty result. + """ + if not isinstance(expression, RefExpr): + # If there are no suitable matches at all, we return error later. + return "", True + + nodes = self.collect_nodes(expression) + + if not nodes: + return self.missing_node(expression), False + + modules, reload_needed = self.modules_for_nodes(nodes, expression) + if reload_needed: + # TODO: line/column are not stored in cache for vast majority of symbol nodes. + # Adding them will make thing faster, but will have visible memory impact. + nodes = self.collect_nodes(expression) + modules, reload_needed = self.modules_for_nodes(nodes, expression) + assert not reload_needed + + result = [] + for node in modules: + result.append(self.format_node(modules[node], node)) + + if not result: + return self.missing_node(expression), False + + return self.add_prefixes(", ".join(result), expression), True + + def missing_type(self, expression: Expression) -> str: + alt_suggestion = "" + if not self.force_reload: + alt_suggestion = " or try --force-reload" + return ( + f'No known type available for "{type(expression).__name__}"' + f" (maybe unreachable{alt_suggestion})" + ) + + def missing_node(self, expression: Expression) -> str: + return ( + f'Cannot find definition for "{type(expression).__name__}" at {expr_span(expression)}' + ) + + def add_prefixes(self, result: str, expression: Expression) -> str: + prefixes = [] + if self.include_kind: + prefixes.append(f"{type(expression).__name__}") + if self.include_span: + prefixes.append(expr_span(expression)) + if prefixes: + prefix = ":".join(prefixes) + " -> " + else: + prefix = "" + return prefix + result + + def run_inspection_by_exact_location( + self, + tree: MypyFile, + line: int, + column: int, + end_line: int, + end_column: int, + method: Callable[[Expression], tuple[str, bool]], + ) -> dict[str, object]: + """Get type of an expression matching a span. + + Type or error is returned as a standard daemon response dict. + """ + try: + expression = find_by_location(tree, line, column - 1, end_line, end_column) + except ValueError as err: + return {"error": str(err)} + + if expression is None: + span = f"{line}:{column}:{end_line}:{end_column}" + return {"out": f"Can't find expression at span {span}", "err": "", "status": 1} + + inspection_str, success = method(expression) + return {"out": inspection_str, "err": "", "status": 0 if success else 1} + + def run_inspection_by_position( + self, + tree: MypyFile, + line: int, + column: int, + method: Callable[[Expression], tuple[str, bool]], + ) -> dict[str, object]: + """Get types of all expressions enclosing a position. + + Types and/or errors are returned as a standard daemon response dict. + """ + expressions = find_all_by_location(tree, line, column - 1) + if not expressions: + position = f"{line}:{column}" + return { + "out": f"Can't find any expressions at position {position}", + "err": "", + "status": 1, + } + + inspection_strs = [] + status = 0 + for expression in expressions: + inspection_str, success = method(expression) + if not success: + status = 1 + if inspection_str: + inspection_strs.append(inspection_str) + if self.limit: + inspection_strs = inspection_strs[: self.limit] + return {"out": "\n".join(inspection_strs), "err": "", "status": status} + + def find_module(self, file: str) -> tuple[State | None, dict[str, object]]: + """Find module by path, or return a suitable error message. + + Note we don't use exceptions to simplify handling 1 vs 2 statuses. + """ + if not any(file.endswith(ext) for ext in PYTHON_EXTENSIONS): + return None, {"error": "Source file is not a Python file"} + + # We are using a bit slower but robust way to find a module by path, + # to be sure that namespace packages are handled properly. + abs_path = os.path.abspath(file) + state = next((s for s in self.fg_manager.graph.values() if s.abspath == abs_path), None) + self.module = state + return ( + state, + {"out": f"Unknown module: {file}", "err": "", "status": 1} if state is None else {}, + ) + + def run_inspection( + self, location: str, method: Callable[[Expression], tuple[str, bool]] + ) -> dict[str, object]: + """Top-level logic to inspect expression(s) at a location. + + This can be reused by various simple inspections. + """ + try: + file, pos = parse_location(location) + except ValueError as err: + return {"error": str(err)} + + state, err_dict = self.find_module(file) + if state is None: + assert err_dict + return err_dict + + # Force reloading to load from cache, account for any edits, etc. + if not state.tree or state.tree.is_cache_skeleton or self.force_reload: + self.reload_module(state) + assert state.tree is not None + + if len(pos) == 4: + # Full span, return an exact match only. + line, column, end_line, end_column = pos + return self.run_inspection_by_exact_location( + state.tree, line, column, end_line, end_column, method + ) + assert len(pos) == 2 + # Inexact location, return all expressions. + line, column = pos + return self.run_inspection_by_position(state.tree, line, column, method) + + def get_type(self, location: str) -> dict[str, object]: + """Get types of expression(s) at a location.""" + return self.run_inspection(location, self.expr_type) + + def get_attrs(self, location: str) -> dict[str, object]: + """Get attributes of expression(s) at a location.""" + return self.run_inspection(location, self.expr_attrs) + + def get_definition(self, location: str) -> dict[str, object]: + """Get symbol definitions of expression(s) at a location.""" + result = self.run_inspection(location, self.expression_def) + if "out" in result and not result["out"]: + # None of the expressions found turns out to be a RefExpr. + _, location = location.split(":", maxsplit=1) + result["out"] = f"No name or member expressions at {location}" + result["status"] = 1 + return result + + +def parse_location(location: str) -> tuple[str, list[int]]: + if location.count(":") < 2: + raise ValueError("Format should be file:line:column[:end_line:end_column]") + parts = location.rsplit(":", maxsplit=2) + start, *rest = parts + # Note: we must allow drive prefix like `C:` on Windows. + if start.count(":") < 2: + return start, [int(p) for p in rest] + parts = start.rsplit(":", maxsplit=2) + start, *start_rest = parts + if start.count(":") < 2: + return start, [int(p) for p in start_rest + rest] + raise ValueError("Format should be file:line:column[:end_line:end_column]") diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..01d2db7b8835fe4cadd755cd4cb61a16e2666da6 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/ipc.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/ipc.py new file mode 100644 index 0000000000000000000000000000000000000000..29710cd57a915f2ff5be2781837765dc58c76b09 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/ipc.py @@ -0,0 +1,457 @@ +"""Cross-platform abstractions for inter-process communication + +On Unix, this uses AF_UNIX sockets. +On Windows, this uses NamedPipes. +""" + +from __future__ import annotations + +import json +import os +import shutil +import struct +import sys +import tempfile +from abc import abstractmethod +from collections.abc import Callable +from select import select +from types import TracebackType +from typing import Final +from typing_extensions import Self + +from librt.base64 import urlsafe_b64encode +from librt.internal import ReadBuffer, WriteBuffer + +if sys.platform == "win32": + # This may be private, but it is needed for IPC on Windows, and is basically stable + import _winapi + import ctypes + + _IPCHandle = int + + kernel32 = ctypes.windll.kernel32 + DisconnectNamedPipe: Callable[[_IPCHandle], int] = kernel32.DisconnectNamedPipe + FlushFileBuffers: Callable[[_IPCHandle], int] = kernel32.FlushFileBuffers +else: + import socket + + _IPCHandle = socket.socket + +# Size of the message packed as !L, i.e. 4 bytes in network order (big-endian). +HEADER_SIZE = 4 + + +# TODO: we should make sure consistent exceptions are raised on different platforms. +# Currently we raise either IPCException or OSError for equivalent conditions. +class IPCException(Exception): + """Exception for IPC issues.""" + + +class IPCBase: + """Base class for communication between the dmypy client and server. + + This contains logic shared between the client and server, such as reading + and writing. + We want to be able to send multiple "messages" over a single connection and + to be able to separate the messages. We do this by prefixing each message + with its size in a fixed format. + """ + + connection: _IPCHandle + + def __init__(self, name: str, timeout: float | None) -> None: + self.name = name + self.timeout = timeout + self.message_size: int | None = None + self.buffer = bytearray() + + def frame_from_buffer(self) -> bytes | None: + """Return a full frame from the bytes we have in the buffer.""" + size = len(self.buffer) + if size < HEADER_SIZE: + return None + if self.message_size is None: + self.message_size = struct.unpack("!L", self.buffer[:HEADER_SIZE])[0] + if size < self.message_size + HEADER_SIZE: + return None + # We have a full frame, avoid extra copy in case we get a large frame. + bdata = memoryview(self.buffer)[HEADER_SIZE : HEADER_SIZE + self.message_size] + self.buffer = self.buffer[HEADER_SIZE + self.message_size :] + self.message_size = None + return bytes(bdata) + + def read(self, size: int = 100000) -> str: + return self.read_bytes(size).decode("utf-8") + + def read_bytes(self, size: int = 100000) -> bytes: + """Read bytes from an IPC connection until we have a full frame.""" + if sys.platform == "win32": + while True: + # Check if we already have a message in the buffer before + # receiving any more data from the socket. + bdata = self.frame_from_buffer() + if bdata is not None: + break + + # Receive more data into the buffer. + ov, err = _winapi.ReadFile(self.connection, size, overlapped=True) + try: + if err == _winapi.ERROR_IO_PENDING: + timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE + res = _winapi.WaitForSingleObject(ov.event, timeout) + if res != _winapi.WAIT_OBJECT_0: + raise IPCException(f"Bad result from I/O wait: {res}") + except BaseException: + ov.cancel() + raise + _, err = ov.GetOverlappedResult(True) + more = ov.getbuffer() + if more: + self.buffer.extend(more) + bdata = self.frame_from_buffer() + if bdata is not None: + break + if err == 0: + # we are done! + break + elif err == _winapi.ERROR_MORE_DATA: + # read again + continue + elif err == _winapi.ERROR_OPERATION_ABORTED: + raise IPCException("ReadFile operation aborted.") + else: + while True: + # Check if we already have a message in the buffer before + # receiving any more data from the socket. + bdata = self.frame_from_buffer() + if bdata is not None: + break + + # Receive more data into the buffer. + more = self.connection.recv(size) + if not more: + # Connection closed + break + self.buffer.extend(more) + + if not bdata: + # Socket was empty, and we didn't get any frame. + # This should only happen if the socket was closed. + return b"" + return bdata + + def write(self, data: str) -> None: + self.write_bytes(data.encode("utf-8")) + + def write_bytes(self, data: bytes) -> None: + """Write to an IPC connection.""" + + # Frame the data by adding fixed size header. + encoded_data = struct.pack("!L", len(data)) + data + + if sys.platform == "win32": + try: + ov, err = _winapi.WriteFile(self.connection, encoded_data, overlapped=True) + try: + if err == _winapi.ERROR_IO_PENDING: + timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE + res = _winapi.WaitForSingleObject(ov.event, timeout) + if res != _winapi.WAIT_OBJECT_0: + raise IPCException(f"Bad result from I/O wait: {res}") + elif err != 0: + raise IPCException(f"Failed writing to pipe with error: {err}") + except BaseException: + ov.cancel() + raise + bytes_written, err = ov.GetOverlappedResult(True) + assert err == 0, err + assert bytes_written == len(encoded_data) + except OSError as e: + raise IPCException(f"Failed to write with error: {e.winerror}") from e + else: + self.connection.sendall(encoded_data) + + def close(self) -> None: + if sys.platform == "win32": + if self.connection != _winapi.NULL: + _winapi.CloseHandle(self.connection) + else: + self.connection.close() + + +class IPCClient(IPCBase): + """The client side of an IPC connection.""" + + def __init__(self, name: str, timeout: float | None) -> None: + super().__init__(name, timeout) + if sys.platform == "win32": + timeout = int(self.timeout * 1000) if self.timeout else _winapi.NMPWAIT_WAIT_FOREVER + try: + _winapi.WaitNamedPipe(self.name, timeout) + except FileNotFoundError as e: + raise IPCException(f"The NamedPipe at {self.name} was not found.") from e + except OSError as e: + if e.winerror == _winapi.ERROR_SEM_TIMEOUT: + raise IPCException("Timed out waiting for connection.") from e + else: + raise + try: + self.connection = _winapi.CreateFile( + self.name, + _winapi.GENERIC_READ | _winapi.GENERIC_WRITE, + 0, + _winapi.NULL, + _winapi.OPEN_EXISTING, + _winapi.FILE_FLAG_OVERLAPPED, + _winapi.NULL, + ) + except OSError as e: + if e.winerror == _winapi.ERROR_PIPE_BUSY: + raise IPCException("The connection is busy.") from e + else: + raise + _winapi.SetNamedPipeHandleState( + self.connection, _winapi.PIPE_READMODE_MESSAGE, None, None + ) + else: + self.connection = socket.socket(socket.AF_UNIX) + self.connection.settimeout(timeout) + self.connection.connect(name) + + def __enter__(self) -> IPCClient: + return self + + def __exit__( + self, + exc_ty: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> None: + self.close() + + +class IPCServer(IPCBase): + BUFFER_SIZE: Final = 2**16 + + def __init__(self, name: str, timeout: float | None = None) -> None: + if sys.platform == "win32": + name = r"\\.\pipe\{}-{}.pipe".format(name, urlsafe_b64encode(os.urandom(6)).decode()) + else: + name = f"{name}.sock" + super().__init__(name, timeout) + if sys.platform == "win32": + self.connection = _winapi.CreateNamedPipe( + self.name, + _winapi.PIPE_ACCESS_DUPLEX + | _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE + | _winapi.FILE_FLAG_OVERLAPPED, + _winapi.PIPE_READMODE_MESSAGE + | _winapi.PIPE_TYPE_MESSAGE + | _winapi.PIPE_WAIT + | 0x8, # PIPE_REJECT_REMOTE_CLIENTS + 1, # one instance + self.BUFFER_SIZE, + self.BUFFER_SIZE, + _winapi.NMPWAIT_WAIT_FOREVER, + 0, # Use default security descriptor + ) + if self.connection == -1: # INVALID_HANDLE_VALUE + err = _winapi.GetLastError() + raise IPCException(f"Invalid handle to pipe: {err}") + else: + self.sock_directory = tempfile.mkdtemp() + sockfile = os.path.join(self.sock_directory, self.name) + self.sock = socket.socket(socket.AF_UNIX) + self.sock.bind(sockfile) + self.sock.listen(1) + if timeout is not None: + self.sock.settimeout(timeout) + + def __enter__(self) -> IPCServer: + if sys.platform == "win32": + # NOTE: It is theoretically possible that this will hang forever if the + # client never connects, though this can be "solved" by killing the server + try: + ov = _winapi.ConnectNamedPipe(self.connection, overlapped=True) + except OSError as e: + # Don't raise if the client already exists, or the client already connected + if e.winerror not in (_winapi.ERROR_PIPE_CONNECTED, _winapi.ERROR_NO_DATA): + raise + else: + try: + timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE + res = _winapi.WaitForSingleObject(ov.event, timeout) + assert res == _winapi.WAIT_OBJECT_0 + except BaseException: + ov.cancel() + _winapi.CloseHandle(self.connection) + raise + _, err = ov.GetOverlappedResult(True) + assert err == 0 + else: + try: + self.connection, _ = self.sock.accept() + except TimeoutError as e: + raise IPCException("The socket timed out") from e + return self + + def __exit__( + self, + exc_ty: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> None: + if sys.platform == "win32": + try: + # Wait for the client to finish reading the last write before disconnecting + if not FlushFileBuffers(self.connection): + raise IPCException( + "Failed to flush NamedPipe buffer, maybe the client hung up?" + ) + finally: + DisconnectNamedPipe(self.connection) + else: + self.close() + + def cleanup(self) -> None: + if sys.platform == "win32": + self.close() + else: + shutil.rmtree(self.sock_directory) + + @property + def connection_name(self) -> str: + if sys.platform == "win32": + return self.name + elif sys.platform == "gnu0": + # GNU/Hurd returns empty string from getsockname() + # for AF_UNIX sockets + return os.path.join(self.sock_directory, self.name) + else: + name = self.sock.getsockname() + assert isinstance(name, str) + return name + + +class BadStatus(Exception): + """Exception raised when there is something wrong with the status file. + + For example: + - No status file found + - Status file malformed + - Process whose pid is in the status file does not exist + """ + + +def read_status(status_file: str) -> dict[str, object]: + """Read status file. + + Raise BadStatus if the status file doesn't exist or contains + invalid JSON or the JSON is not a dict. + """ + if not os.path.isfile(status_file): + raise BadStatus("No status file found") + with open(status_file) as f: + try: + data = json.load(f) + except Exception as e: + raise BadStatus(f"Malformed status file: {str(e)}") from e + if not isinstance(data, dict): + raise BadStatus(f"Invalid status file (not a dict): {data}") + return data + + +def ready_to_read(conns: list[IPCClient], timeout: float | None = None) -> list[int]: + """Wait until some connections are readable. + + Return index of each readable connection in the original list. + """ + if sys.platform == "win32": + # Windows doesn't support select() on named pipes. Instead, start an overlapped + # ReadFile on each pipe (which internally creates an event via CreateEventW), + # then WaitForMultipleObjects on those events for efficient OS-level waiting. + # Any data consumed by the probe reads is stored into each connection's buffer + # so the subsequent read_bytes() call will find it via frame_from_buffer(). + WAIT_FAILED = 0xFFFFFFFF + pending: list[tuple[int, _winapi.Overlapped]] = [] + events: list[int] = [] + ready: list[int] = [] + + for i, conn in enumerate(conns): + try: + ov, err = _winapi.ReadFile(conn.connection, 1, overlapped=True) + except OSError: + # Broken/closed pipe. Mimic Linux behavior here, caller will get + # the exception when trying to read from this socket. + ready.append(i) + continue + if err == _winapi.ERROR_IO_PENDING: + events.append(ov.event) + pending.append((i, ov)) + else: + # Data was immediately available (err == 0 or ERROR_MORE_DATA) + _, err = ov.GetOverlappedResult(True) + data = ov.getbuffer() + if data: + conn.buffer.extend(data) + ready.append(i) + + # Wait only if nothing is immediately ready and there are pending operations + if not ready and events: + timeout_ms = int(timeout * 1000) if timeout is not None else _winapi.INFINITE + res = _winapi.WaitForMultipleObjects(events, False, timeout_ms) + if res == WAIT_FAILED: + for _, ov in pending: + ov.cancel() + raise IPCException(f"Failed to wait for connections: {_winapi.GetLastError()}") + + # Check which pending operations completed, cancel the rest + for i, ov in pending: + if _winapi.WaitForSingleObject(ov.event, 0) == _winapi.WAIT_OBJECT_0: + _, err = ov.GetOverlappedResult(True) + data = ov.getbuffer() + if data: + conns[i].buffer.extend(data) + ready.append(i) + else: + ov.cancel() + + return ready + + else: + connections = [conn.connection for conn in conns] + ready, _, _ = select(connections, [], [], timeout) + return [connections.index(r) for r in ready] + + +def send(connection: IPCBase, data: IPCMessage) -> None: + """Send data to a connection encoded and framed. + + The data must be a non-abstract IPCMessage. We assume that a single send call is a + single frame to be sent. + """ + buf = WriteBuffer() + data.write(buf) + connection.write_bytes(buf.getvalue()) + + +def receive(connection: IPCBase) -> ReadBuffer: + """Receive single encoded IPCMessage frame from a connection. + + Raise OSError if the data received is not valid. + """ + bdata = connection.read_bytes() + if not bdata: + raise OSError("No data received") + return ReadBuffer(bdata) + + +class IPCMessage: + @classmethod + @abstractmethod + def read(cls, buf: ReadBuffer) -> Self: + raise NotImplementedError + + @abstractmethod + def write(self, buf: WriteBuffer) -> None: + raise NotImplementedError diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/join.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/join.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a09d55c63069c59c99870b58a6c9294d770a7229 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/join.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/join.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/join.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c9910e60bb733df732ca42a66a49416dd9e349 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/join.py @@ -0,0 +1,916 @@ +"""Calculation of the least upper bound types (joins).""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import overload + +import mypy.typeops +from mypy.expandtype import expand_type +from mypy.maptype import map_instance_to_supertype +from mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT, VARIANCE_NOT_READY, TypeInfo +from mypy.state import state +from mypy.subtypes import ( + SubtypeContext, + find_member, + is_equivalent, + is_proper_subtype, + is_protocol_implementation, + is_subtype, +) +from mypy.types import ( + AnyType, + CallableType, + DeletedType, + ErasedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + get_proper_type, + get_proper_types, + split_with_prefix_and_suffix, +) + + +class InstanceJoiner: + def __init__(self) -> None: + self.seen_instances: list[tuple[Instance, Instance]] = [] + + def join_instances(self, t: Instance, s: Instance) -> ProperType: + if (t, s) in self.seen_instances or (s, t) in self.seen_instances: + return object_from_instance(t) + + self.seen_instances.append((t, s)) + + # Calculate the join of two instance types + if t.type == s.type: + # Simplest case: join two types with the same base type (but + # potentially different arguments). + + # Combine type arguments. + args: list[Type] = [] + # N.B: We use zip instead of indexing because the lengths might have + # mismatches during daemon reprocessing. + if t.type.has_type_var_tuple_type: + # We handle joins of variadic instances by simply creating correct mapping + # for type arguments and compute the individual joins same as for regular + # instances. All the heavy lifting is done in the join of tuple types. + assert s.type.type_var_tuple_prefix is not None + assert s.type.type_var_tuple_suffix is not None + prefix = s.type.type_var_tuple_prefix + suffix = s.type.type_var_tuple_suffix + tvt = s.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix(s.args, prefix, suffix) + t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(t.args, prefix, suffix) + s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix + t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix + else: + t_args = t.args + s_args = s.args + for ta, sa, type_var in zip(t_args, s_args, t.type.defn.type_vars): + ta_proper = get_proper_type(ta) + sa_proper = get_proper_type(sa) + new_type: Type | None = None + if isinstance(ta_proper, AnyType): + new_type = AnyType(TypeOfAny.from_another_any, ta_proper) + elif isinstance(sa_proper, AnyType): + new_type = AnyType(TypeOfAny.from_another_any, sa_proper) + elif isinstance(type_var, TypeVarType): + if type_var.variance in (COVARIANT, VARIANCE_NOT_READY): + new_type = join_types(ta, sa, self) + if len(type_var.values) != 0 and new_type not in type_var.values: + self.seen_instances.pop() + return object_from_instance(t) + if not is_subtype(new_type, type_var.upper_bound): + self.seen_instances.pop() + return object_from_instance(t) + # TODO: contravariant case should use meet but pass seen instances as + # an argument to keep track of recursive checks. + elif type_var.variance in (INVARIANT, CONTRAVARIANT): + if isinstance(ta_proper, UninhabitedType) and ta_proper.ambiguous: + new_type = sa + elif isinstance(sa_proper, UninhabitedType) and sa_proper.ambiguous: + new_type = ta + elif not is_equivalent(ta, sa): + self.seen_instances.pop() + return object_from_instance(t) + else: + # If the types are different but equivalent, then an Any is involved + # so using a join in the contravariant case is also OK. + new_type = join_types(ta, sa, self) + elif isinstance(type_var, TypeVarTupleType): + new_type = get_proper_type(join_types(ta, sa, self)) + # Put the joined arguments back into instance in the normal form: + # a) Tuple[X, Y, Z] -> [X, Y, Z] + # b) tuple[X, ...] -> [*tuple[X, ...]] + if isinstance(new_type, Instance): + assert new_type.type.fullname == "builtins.tuple" + new_type = UnpackType(new_type) + else: + assert isinstance(new_type, TupleType) + args.extend(new_type.items) + continue + else: + # ParamSpec type variables behave the same, independent of variance + if not is_equivalent(ta, sa): + return get_proper_type(type_var.upper_bound) + new_type = join_types(ta, sa, self) + assert new_type is not None + args.append(new_type) + result: ProperType = Instance(t.type, args) + elif t.type.bases and is_proper_subtype( + t, s, subtype_context=SubtypeContext(ignore_type_params=True) + ): + result = self.join_instances_via_supertype(t, s) + else: + # Now t is not a subtype of s, and t != s. Now s could be a subtype + # of t; alternatively, we need to find a common supertype. This works + # in of the both cases. + result = self.join_instances_via_supertype(s, t) + + self.seen_instances.pop() + return result + + def join_instances_via_supertype(self, t: Instance, s: Instance) -> ProperType: + # Give preference to joins via duck typing relationship, so that + # join(int, float) == float, for example. + for p in t.type._promote: + if is_subtype(p, s): + return join_types(p, s, self) + for p in s.type._promote: + if is_subtype(p, t): + return join_types(t, p, self) + + # Compute the "best" supertype of t when joined with s. + # The definition of "best" may evolve; for now it is the one with + # the longest MRO. Ties are broken by using the earlier base. + + # Go over both sets of bases in case there's an explicit Protocol base. This is important + # to ensure commutativity of join (although in cases where both classes have relevant + # Protocol bases this maybe might still not be commutative) + base_types: dict[TypeInfo, None] = {} # dict to deduplicate but preserve order + for base in t.type.bases: + base_types[base.type] = None + for base in s.type.bases: + if base.type.is_protocol and is_subtype(t, base): + base_types[base.type] = None + + best: ProperType | None = None + for base_type in base_types: + mapped = map_instance_to_supertype(t, base_type) + res = self.join_instances(mapped, s) + if best is None or is_better(res, best): + best = res + assert best is not None + for promote in t.type._promote: + if isinstance(promote, Instance): + res = self.join_instances(promote, s) + if is_better(res, best): + best = res + return best + + +def trivial_join(s: Type, t: Type) -> Type: + """Return one of types (expanded) if it is a supertype of other, otherwise top type.""" + if is_subtype(s, t): + return t + elif is_subtype(t, s): + return s + else: + return object_or_any_from_type(get_proper_type(t)) + + +@overload +def join_types( + s: ProperType, t: ProperType, instance_joiner: InstanceJoiner | None = None +) -> ProperType: ... + + +@overload +def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: ... + + +def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: + """Return the least upper bound of s and t. + + For example, the join of 'int' and 'object' is 'object'. + """ + if mypy.typeops.is_recursive_pair(s, t): + # This case can trigger an infinite recursion, general support for this will be + # tricky so we use a trivial join (like for protocols). + return trivial_join(s, t) + s = get_proper_type(s) + t = get_proper_type(t) + + if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false): + # if types are restricted in different ways, use the more general versions + s = mypy.typeops.true_or_false(s) + t = mypy.typeops.true_or_false(t) + + if isinstance(s, UnionType) and not isinstance(t, UnionType): + s, t = t, s + + if isinstance(s, AnyType): + return s + + if isinstance(s, ErasedType): + return t + + if isinstance(s, NoneType) and not isinstance(t, NoneType): + s, t = t, s + + if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType): + s, t = t, s + + # Meets/joins require callable type normalization. + s, t = normalize_callables(s, t) + + # Use a visitor to handle non-trivial cases. + return t.accept(TypeJoinVisitor(s, instance_joiner)) + + +class TypeJoinVisitor(TypeVisitor[ProperType]): + """Implementation of the least upper bound algorithm. + + Attributes: + s: The other (left) type operand. + """ + + def __init__(self, s: ProperType, instance_joiner: InstanceJoiner | None = None) -> None: + self.s = s + self.instance_joiner = instance_joiner + + def visit_unbound_type(self, t: UnboundType) -> ProperType: + return AnyType(TypeOfAny.special_form) + + def visit_union_type(self, t: UnionType) -> ProperType: + if is_proper_subtype(self.s, t): + return t + else: + return mypy.typeops.make_simplified_union([self.s, t]) + + def visit_any(self, t: AnyType) -> ProperType: + return t + + def visit_none_type(self, t: NoneType) -> ProperType: + if state.strict_optional: + if isinstance(self.s, (NoneType, UninhabitedType)): + return t + elif isinstance(self.s, (UnboundType, AnyType)): + return AnyType(TypeOfAny.special_form) + else: + return mypy.typeops.make_simplified_union([self.s, t]) + else: + return self.s + + def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType: + return self.s + + def visit_deleted_type(self, t: DeletedType) -> ProperType: + return self.s + + def visit_erased_type(self, t: ErasedType) -> ProperType: + return self.s + + def visit_type_var(self, t: TypeVarType) -> ProperType: + if isinstance(self.s, TypeVarType): + if self.s.id == t.id: + if self.s.upper_bound == t.upper_bound: + return self.s + return self.s.copy_modified( + upper_bound=join_types(self.s.upper_bound, t.upper_bound) + ) + # Fix non-commutative joins + return get_proper_type(join_types(self.s.upper_bound, t.upper_bound)) + else: + return self.default(self.s) + + def visit_param_spec(self, t: ParamSpecType) -> ProperType: + if self.s == t: + return t + return self.default(self.s) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType: + if self.s == t: + return t + if isinstance(self.s, Instance) and is_subtype(t.upper_bound, self.s): + # TODO: should we do this more generally and for all TypeVarLikeTypes? + return self.s + return self.default(self.s) + + def visit_unpack_type(self, t: UnpackType) -> UnpackType: + raise NotImplementedError + + def visit_parameters(self, t: Parameters) -> ProperType: + if isinstance(self.s, Parameters): + if not is_similar_params(t, self.s): + # TODO: it would be prudent to return [*object, **object] instead of Any. + return self.default(self.s) + from mypy.meet import meet_types + + return t.copy_modified( + arg_types=[ + meet_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types) + ], + arg_names=combine_arg_names(self.s, t), + ) + else: + return self.default(self.s) + + def visit_instance(self, t: Instance) -> ProperType: + if isinstance(self.s, Instance): + if self.instance_joiner is None: + self.instance_joiner = InstanceJoiner() + nominal = self.instance_joiner.join_instances(t, self.s) + structural: Instance | None = None + if t.type.is_protocol and is_protocol_implementation(self.s, t): + structural = t + elif self.s.type.is_protocol and is_protocol_implementation(t, self.s): + structural = self.s + # Structural join is preferred in the case where we have found both + # structural and nominal and they have same MRO length (see two comments + # in join_instances_via_supertype). Otherwise, just return the nominal join. + if not structural or is_better(nominal, structural): + return nominal + return structural + elif isinstance(self.s, FunctionLike): + if t.type.is_protocol: + call = unpack_callback_protocol(t) + if call: + return join_types(call, self.s) + return join_types(t, self.s.fallback) + elif isinstance(self.s, TypeType): + return join_types(t, self.s) + elif isinstance(self.s, TypedDictType): + return join_types(t, self.s) + elif isinstance(self.s, TupleType): + return join_types(t, self.s) + elif isinstance(self.s, LiteralType): + return join_types(t, self.s) + elif isinstance(self.s, TypeVarTupleType) and is_subtype(self.s.upper_bound, t): + return t + else: + return self.default(self.s) + + def visit_callable_type(self, t: CallableType) -> ProperType: + if isinstance(self.s, CallableType): + if is_similar_callables(t, self.s): + if is_equivalent(t, self.s): + return combine_similar_callables(t, self.s) + result = join_similar_callables(t, self.s) + if any( + isinstance(tp, (NoneType, UninhabitedType)) + for tp in get_proper_types(result.arg_types) + ): + # We don't want to return unusable Callable, attempt fallback instead. + return join_types(t.fallback, self.s) + # We set the from_type_type flag to suppress error when a collection of + # concrete class objects gets inferred as their common abstract superclass. + if not ( + (t.is_type_obj() and t.type_object().is_abstract) + or (self.s.is_type_obj() and self.s.type_object().is_abstract) + ): + result.from_type_type = True + return result + else: + s2, t2 = self.s, t + if t2.is_var_arg: + s2, t2 = t2, s2 + if is_subtype(s2, t2): + return t2.copy_modified() + elif is_subtype(t2, s2): + return s2.copy_modified() + return join_types(t.fallback, self.s) + elif isinstance(self.s, Overloaded): + # Switch the order of arguments to that we'll get to visit_overloaded. + return join_types(t, self.s) + elif isinstance(self.s, Instance) and self.s.type.is_protocol: + call = unpack_callback_protocol(self.s) + if call: + return join_types(t, call) + return join_types(t.fallback, self.s) + + def visit_overloaded(self, t: Overloaded) -> ProperType: + # This is more complex than most other cases. Here are some + # examples that illustrate how this works. + # + # First let's define a concise notation: + # - Cn are callable types (for n in 1, 2, ...) + # - Ov(C1, C2, ...) is an overloaded type with items C1, C2, ... + # - Callable[[T, ...], S] is written as [T, ...] -> S. + # + # We want some basic properties to hold (assume Cn are all + # unrelated via Any-similarity): + # + # join(Ov(C1, C2), C1) == C1 + # join(Ov(C1, C2), Ov(C1, C2)) == Ov(C1, C2) + # join(Ov(C1, C2), Ov(C1, C3)) == C1 + # join(Ov(C2, C2), C3) == join of fallback types + # + # The presence of Any types makes things more interesting. The join is the + # most general type we can get with respect to Any: + # + # join(Ov([int] -> int, [str] -> str), [Any] -> str) == Any -> str + # + # We could use a simplification step that removes redundancies, but that's not + # implemented right now. Consider this example, where we get a redundancy: + # + # join(Ov([int, Any] -> Any, [str, Any] -> Any), [Any, int] -> Any) == + # Ov([Any, int] -> Any, [Any, int] -> Any) + # + # TODO: Consider more cases of callable subtyping. + result: list[CallableType] = [] + s = self.s + if isinstance(s, FunctionLike): + # The interesting case where both types are function types. + for t_item in t.items: + for s_item in s.items: + if is_similar_callables(t_item, s_item): + if is_equivalent(t_item, s_item): + result.append(combine_similar_callables(t_item, s_item)) + elif is_subtype(t_item, s_item): + result.append(s_item) + if result: + # TODO: Simplify redundancies from the result. + if len(result) == 1: + return result[0] + else: + return Overloaded(result) + return join_types(t.fallback, s.fallback) + elif isinstance(s, Instance) and s.type.is_protocol: + call = unpack_callback_protocol(s) + if call: + return join_types(t, call) + return join_types(t.fallback, s) + + def join_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None: + """Join two tuple types while handling variadic entries. + + This is surprisingly tricky, and we don't handle some tricky corner cases. + Most of the trickiness comes from the variadic tuple items like *tuple[X, ...] + since they can have arbitrary partial overlaps (while *Ts can't be split). + """ + s_unpack_index = find_unpack_in_list(s.items) + t_unpack_index = find_unpack_in_list(t.items) + if s_unpack_index is None and t_unpack_index is None: + if s.length() == t.length(): + items: list[Type] = [] + for i in range(t.length()): + items.append(join_types(t.items[i], s.items[i])) + return items + return None + if s_unpack_index is not None and t_unpack_index is not None: + # The most complex case: both tuples have an unpack item. + s_unpack = s.items[s_unpack_index] + assert isinstance(s_unpack, UnpackType) + s_unpacked = get_proper_type(s_unpack.type) + t_unpack = t.items[t_unpack_index] + assert isinstance(t_unpack, UnpackType) + t_unpacked = get_proper_type(t_unpack.type) + if s.length() == t.length() and s_unpack_index == t_unpack_index: + # We can handle a case where arity is perfectly aligned, e.g. + # join(Tuple[X1, *tuple[Y1, ...], Z1], Tuple[X2, *tuple[Y2, ...], Z2]). + # We can essentially perform the join elementwise. + prefix_len = t_unpack_index + suffix_len = t.length() - t_unpack_index - 1 + items = [] + for si, ti in zip(s.items[:prefix_len], t.items[:prefix_len]): + items.append(join_types(si, ti)) + joined = join_types(s_unpacked, t_unpacked) + if isinstance(joined, TypeVarTupleType): + items.append(UnpackType(joined)) + elif isinstance(joined, Instance) and joined.type.fullname == "builtins.tuple": + items.append(UnpackType(joined)) + else: + if isinstance(t_unpacked, Instance): + assert t_unpacked.type.fullname == "builtins.tuple" + tuple_instance = t_unpacked + else: + assert isinstance(t_unpacked, TypeVarTupleType) + tuple_instance = t_unpacked.tuple_fallback + items.append( + UnpackType( + tuple_instance.copy_modified( + args=[object_from_instance(tuple_instance)] + ) + ) + ) + if suffix_len: + for si, ti in zip(s.items[-suffix_len:], t.items[-suffix_len:]): + items.append(join_types(si, ti)) + return items + if s.length() == 1 or t.length() == 1: + # Another case we can handle is when one of tuple is purely variadic + # (i.e. a non-normalized form of tuple[X, ...]), in this case the join + # will be again purely variadic. + if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)): + return None + assert s_unpacked.type.fullname == "builtins.tuple" + assert t_unpacked.type.fullname == "builtins.tuple" + mid_joined = join_types(s_unpacked.args[0], t_unpacked.args[0]) + t_other = [a for i, a in enumerate(t.items) if i != t_unpack_index] + s_other = [a for i, a in enumerate(s.items) if i != s_unpack_index] + other_joined = join_type_list(s_other + t_other) + mid_joined = join_types(mid_joined, other_joined) + return [UnpackType(s_unpacked.copy_modified(args=[mid_joined]))] + # TODO: are there other case we can handle (e.g. both prefix/suffix are shorter)? + return None + if s_unpack_index is not None: + variadic = s + unpack_index = s_unpack_index + fixed = t + else: + assert t_unpack_index is not None + variadic = t + unpack_index = t_unpack_index + fixed = s + # Case where one tuple has variadic item and the other one doesn't. The join will + # be variadic, since fixed tuple is a subtype of variadic, but not vice versa. + unpack = variadic.items[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + if not isinstance(unpacked, Instance): + return None + if fixed.length() < variadic.length() - 1: + # There are no non-trivial types that are supertype of both. + return None + prefix_len = unpack_index + suffix_len = variadic.length() - prefix_len - 1 + prefix, middle, suffix = split_with_prefix_and_suffix( + tuple(fixed.items), prefix_len, suffix_len + ) + items = [] + for fi, vi in zip(prefix, variadic.items[:prefix_len]): + items.append(join_types(fi, vi)) + mid_joined = join_type_list(list(middle)) + mid_joined = join_types(mid_joined, unpacked.args[0]) + items.append(UnpackType(unpacked.copy_modified(args=[mid_joined]))) + if suffix_len: + for fi, vi in zip(suffix, variadic.items[-suffix_len:]): + items.append(join_types(fi, vi)) + return items + + def visit_tuple_type(self, t: TupleType) -> ProperType: + # When given two fixed-length tuples: + # * If they have the same length, join their subtypes item-wise: + # Tuple[int, bool] + Tuple[bool, bool] becomes Tuple[int, bool] + # * If lengths do not match, return a variadic tuple: + # Tuple[bool, int] + Tuple[bool] becomes Tuple[int, ...] + # + # Otherwise, `t` is a fixed-length tuple but `self.s` is NOT: + # * Joining with a variadic tuple returns variadic tuple: + # Tuple[int, bool] + Tuple[bool, ...] becomes Tuple[int, ...] + # * Joining with any Sequence also returns a Sequence: + # Tuple[int, bool] + List[bool] becomes Sequence[int] + if isinstance(self.s, TupleType): + if self.instance_joiner is None: + self.instance_joiner = InstanceJoiner() + fallback = self.instance_joiner.join_instances( + mypy.typeops.tuple_fallback(self.s), mypy.typeops.tuple_fallback(t) + ) + assert isinstance(fallback, Instance) + items = self.join_tuples(self.s, t) + if items is not None: + if len(items) == 1 and isinstance(item := items[0], UnpackType): + if isinstance(unpacked := get_proper_type(item.type), Instance): + # Avoid double-wrapping tuple[*tuple[X, ...]] + return unpacked + return TupleType(items, fallback) + else: + # TODO: should this be a default fallback behaviour like for meet? + if is_proper_subtype(self.s, t): + return t + if is_proper_subtype(t, self.s): + return self.s + return fallback + else: + return join_types(self.s, mypy.typeops.tuple_fallback(t)) + + def visit_typeddict_type(self, t: TypedDictType) -> ProperType: + if isinstance(self.s, TypedDictType): + items = { + item_name: s_item_type + for (item_name, s_item_type, t_item_type) in self.s.zip(t) + if ( + is_equivalent(s_item_type, t_item_type) + and (item_name in t.required_keys) == (item_name in self.s.required_keys) + ) + } + fallback = self.s.create_anonymous_fallback() + all_keys = set(items.keys()) + # We need to filter by items.keys() since some required keys present in both t and + # self.s might be missing from the join if the types are incompatible. + required_keys = all_keys & t.required_keys & self.s.required_keys + # If one type has a key as readonly, we mark it as readonly for both: + readonly_keys = (t.readonly_keys | t.readonly_keys) & all_keys + return TypedDictType(items, required_keys, readonly_keys, fallback) + elif isinstance(self.s, Instance): + return join_types(self.s, t.fallback) + else: + return self.default(self.s) + + def visit_literal_type(self, t: LiteralType) -> ProperType: + if isinstance(self.s, LiteralType): + if t == self.s: + return t + if self.s.fallback.type.is_enum and t.fallback.type.is_enum: + return mypy.typeops.make_simplified_union([self.s, t]) + return join_types(self.s.fallback, t.fallback) + elif isinstance(self.s, Instance) and self.s.last_known_value == t: + return t + else: + return join_types(self.s, t.fallback) + + def visit_partial_type(self, t: PartialType) -> ProperType: + # We only have partial information so we can't decide the join result. We should + # never get here. + assert False, "Internal error" + + def visit_type_type(self, t: TypeType) -> ProperType: + if isinstance(self.s, TypeType): + return TypeType.make_normalized( + join_types(t.item, self.s.item), + line=t.line, + is_type_form=self.s.is_type_form or t.is_type_form, + ) + elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type": + return self.s + else: + return self.default(self.s) + + def visit_type_alias_type(self, t: TypeAliasType) -> ProperType: + assert False, f"This should be never called, got {t}" + + def default(self, typ: Type) -> ProperType: + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return object_from_instance(typ) + elif isinstance(typ, TypeType): + return self.default(typ.item) + elif isinstance(typ, UnboundType): + return AnyType(TypeOfAny.special_form) + elif isinstance(typ, TupleType): + return self.default(mypy.typeops.tuple_fallback(typ)) + elif isinstance(typ, TypedDictType): + return self.default(typ.fallback) + elif isinstance(typ, FunctionLike): + return self.default(typ.fallback) + elif isinstance(typ, TypeVarType): + return self.default(typ.upper_bound) + elif isinstance(typ, ParamSpecType): + return self.default(typ.upper_bound) + else: + return AnyType(TypeOfAny.special_form) + + +def is_better(t: Type, s: Type) -> bool: + # Given two possible results from join_instances_via_supertype(), + # indicate whether t is the better one. + t = get_proper_type(t) + s = get_proper_type(s) + + if isinstance(t, Instance): + if not isinstance(s, Instance): + return True + if t.type.is_protocol != s.type.is_protocol: + if t.type.fullname != "builtins.object" and s.type.fullname != "builtins.object": + # mro of protocol is not really relevant + return not t.type.is_protocol + # Use len(mro) as a proxy for the better choice. + if len(t.type.mro) > len(s.type.mro): + return True + return False + + +def normalize_callables(s: ProperType, t: ProperType) -> tuple[ProperType, ProperType]: + if isinstance(s, (CallableType, Overloaded)): + s = s.with_unpacked_kwargs() + if isinstance(t, (CallableType, Overloaded)): + t = t.with_unpacked_kwargs() + return s, t + + +def is_similar_callables(t: CallableType, s: CallableType) -> bool: + """Return True if t and s have identical numbers of + arguments, default arguments and varargs. + """ + return ( + len(t.arg_types) == len(s.arg_types) + and t.min_args == s.min_args + and t.is_var_arg == s.is_var_arg + ) + + +def is_similar_params(t: Parameters, s: Parameters) -> bool: + # This matches the logic in is_similar_callables() above. + return ( + len(t.arg_types) == len(s.arg_types) + and t.min_args == s.min_args + and (t.var_arg() is not None) == (s.var_arg() is not None) + ) + + +def update_callable_ids(c: CallableType, ids: list[TypeVarId]) -> CallableType: + tv_map = {} + tvs = [] + for tv, new_id in zip(c.variables, ids): + new_tv = tv.copy_modified(id=new_id) + tvs.append(new_tv) + tv_map[tv.id] = new_tv + return expand_type(c, tv_map).copy_modified(variables=tvs) + + +def match_generic_callables(t: CallableType, s: CallableType) -> tuple[CallableType, CallableType]: + # The case where we combine/join/meet similar callables, situation where both are generic + # requires special care. A more principled solution may involve unify_generic_callable(), + # but it would have two problems: + # * This adds risk of infinite recursion: e.g. join -> unification -> solver -> join + # * Using unification is an incorrect thing for meets, as it "widens" the types + # Finally, this effectively falls back to an old behaviour before namespaces were added to + # type variables, and it worked relatively well. + max_len = max(len(t.variables), len(s.variables)) + min_len = min(len(t.variables), len(s.variables)) + if min_len == 0: + return t, s + new_ids = [TypeVarId.new(meta_level=0) for _ in range(max_len)] + # Note: this relies on variables being in order they appear in function definition. + return update_callable_ids(t, new_ids), update_callable_ids(s, new_ids) + + +def join_similar_callables(t: CallableType, s: CallableType) -> CallableType: + t, s = match_generic_callables(t, s) + arg_types: list[Type] = [] + for i in range(len(t.arg_types)): + arg_types.append(safe_meet(t.arg_types[i], s.arg_types[i])) + # TODO in combine_similar_callables also applies here (names and kinds; user metaclasses) + # The fallback type can be either 'function', 'type', or some user-provided metaclass. + # The result should always use 'function' as a fallback if either operands are using it. + if t.fallback.type.fullname == "builtins.function": + fallback = t.fallback + else: + fallback = s.fallback + return t.copy_modified( + arg_types=arg_types, + arg_names=combine_arg_names(t, s), + ret_type=join_types(t.ret_type, s.ret_type), + fallback=fallback, + name=None, + ) + + +def safe_join(t: Type, s: Type) -> Type: + # This is a temporary solution to prevent crashes in combine_similar_callables() etc., + # until relevant TODOs on handling arg_kinds will be addressed there. + if not isinstance(t, UnpackType) and not isinstance(s, UnpackType): + return join_types(t, s) + if isinstance(t, UnpackType) and isinstance(s, UnpackType): + return UnpackType(join_types(t.type, s.type)) + return object_or_any_from_type(get_proper_type(t)) + + +def safe_meet(t: Type, s: Type) -> Type: + # Similar to above but for meet_types(). + from mypy.meet import meet_types + + if not isinstance(t, UnpackType) and not isinstance(s, UnpackType): + return meet_types(t, s) + if isinstance(t, UnpackType) and isinstance(s, UnpackType): + unpacked = get_proper_type(t.type) + if isinstance(unpacked, TypeVarTupleType): + fallback_type = unpacked.tuple_fallback.type + elif isinstance(unpacked, TupleType): + fallback_type = unpacked.partial_fallback.type + else: + assert isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple" + fallback_type = unpacked.type + res = meet_types(t.type, s.type) + if isinstance(res, UninhabitedType): + res = Instance(fallback_type, [res]) + return UnpackType(res) + return UninhabitedType() + + +def combine_similar_callables(t: CallableType, s: CallableType) -> CallableType: + t, s = match_generic_callables(t, s) + arg_types: list[Type] = [] + for i in range(len(t.arg_types)): + arg_types.append(safe_join(t.arg_types[i], s.arg_types[i])) + # TODO kinds and argument names + # TODO what should happen if one fallback is 'type' and the other is a user-provided metaclass? + # The fallback type can be either 'function', 'type', or some user-provided metaclass. + # The result should always use 'function' as a fallback if either operands are using it. + if t.fallback.type.fullname == "builtins.function": + fallback = t.fallback + else: + fallback = s.fallback + return t.copy_modified( + arg_types=arg_types, + arg_names=combine_arg_names(t, s), + ret_type=join_types(t.ret_type, s.ret_type), + fallback=fallback, + name=None, + ) + + +def combine_arg_names( + t: CallableType | Parameters, s: CallableType | Parameters +) -> list[str | None]: + """Produces a list of argument names compatible with both callables. + + For example, suppose 't' and 's' have the following signatures: + + - t: (a: int, b: str, X: str) -> None + - s: (a: int, b: str, Y: str) -> None + + This function would return ["a", "b", None]. This information + is then used above to compute the join of t and s, which results + in a signature of (a: int, b: str, str) -> None. + + Note that the third argument's name is omitted and 't' and 's' + are both valid subtypes of this inferred signature. + + Precondition: is_similar_types(t, s) is true. + """ + num_args = len(t.arg_types) + new_names = [] + for i in range(num_args): + t_name = t.arg_names[i] + s_name = s.arg_names[i] + if t_name == s_name or t.arg_kinds[i].is_named() or s.arg_kinds[i].is_named(): + new_names.append(t_name) + else: + new_names.append(None) + return new_names + + +def object_from_instance(instance: Instance) -> Instance: + """Construct the type 'builtins.object' from an instance type.""" + # Use the fact that 'object' is always the last class in the mro. + res = Instance(instance.type.mro[-1], []) + return res + + +def object_or_any_from_type(typ: ProperType) -> ProperType: + # Similar to object_from_instance() but tries hard for all types. + # TODO: find a better way to get object, or make this more reliable. + if isinstance(typ, Instance): + return object_from_instance(typ) + elif isinstance(typ, (CallableType, TypedDictType, LiteralType)): + return object_from_instance(typ.fallback) + elif isinstance(typ, TupleType): + return object_from_instance(typ.partial_fallback) + elif isinstance(typ, TypeType): + return object_or_any_from_type(typ.item) + elif isinstance(typ, TypeVarLikeType) and isinstance(typ.upper_bound, ProperType): + return object_or_any_from_type(typ.upper_bound) + elif isinstance(typ, UnionType): + for item in typ.items: + if isinstance(item, ProperType): + candidate = object_or_any_from_type(item) + if isinstance(candidate, Instance): + return candidate + elif isinstance(typ, UnpackType): + object_or_any_from_type(get_proper_type(typ.type)) + return AnyType(TypeOfAny.implementation_artifact) + + +def join_type_list(types: Sequence[Type]) -> Type: + if not types: + # This is a little arbitrary but reasonable. Any empty tuple should be compatible + # with all variable length tuples, and this makes it possible. + return UninhabitedType() + joined = types[0] + for t in types[1:]: + joined = join_types(joined, t) + return joined + + +def unpack_callback_protocol(t: Instance) -> ProperType | None: + assert t.type.is_protocol + if t.type.protocol_members == ["__call__"]: + return get_proper_type(find_member("__call__", t, t, is_operator=True)) + return None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..625116cb3519a8dada45c3010c5f59f74a87f062 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/literals.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/literals.py new file mode 100644 index 0000000000000000000000000000000000000000..f572a6f9c624fed778c64ec082418c6150f20dcc --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/literals.py @@ -0,0 +1,327 @@ +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any, Final, TypeAlias as _TypeAlias + +from mypy.nodes import ( + LITERAL_NO, + LITERAL_TYPE, + LITERAL_YES, + AssertTypeExpr, + AssignmentExpr, + AwaitExpr, + BytesExpr, + CallExpr, + CastExpr, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + FloatExpr, + GeneratorExpr, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MemberExpr, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + OpExpr, + ParamSpecExpr, + PromoteExpr, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TupleExpr, + TypeAliasExpr, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + YieldExpr, + YieldFromExpr, +) +from mypy.visitor import ExpressionVisitor + +# [Note Literals and literal_hash] +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Mypy uses the term "literal" to refer to any expression built out of +# the following: +# +# * Plain literal expressions, like `1` (integer, float, string, etc.) +# +# * Compound literal expressions, like `(lit1, lit2)` (list, dict, +# set, or tuple) +# +# * Operator expressions, like `lit1 + lit2` +# +# * Variable references, like `x` +# +# * Member references, like `lit.m` +# +# * Index expressions, like `lit[0]` +# +# A typical "literal" looks like `x[(i,j+1)].m`. +# +# An expression that is a literal has a `literal_hash`, with the +# following properties. +# +# * `literal_hash` is a Key: a tuple containing basic data types and +# possibly other Keys. So it can be used as a key in a dictionary +# that will be compared by value (as opposed to the Node itself, +# which is compared by identity). +# +# * Two expressions have equal `literal_hash`es if and only if they +# are syntactically equal expressions. (NB: Actually, we also +# identify as equal expressions like `3` and `3.0`; is this a good +# idea?) +# +# * The elements of `literal_hash` that are tuples are exactly the +# subexpressions of the original expression (e.g. the base and index +# of an index expression, or the operands of an operator expression). + + +Key: _TypeAlias = tuple[Any, ...] + + +def literal_hash(e: Expression) -> Key | None: + """Generate a hashable, (mostly) opaque key for expressions supported by the binder. + + These allow using expressions as dictionary keys based on structural/value + matching (instead of based on expression identity). + + Return None if the expression type is not supported (it cannot be narrowed). + + See the comment above for more information. + + NOTE: This is not directly related to literal types. + """ + return e.accept(_hasher) + + +def literal(e: Expression) -> int: + """Return the literal kind for an expression.""" + + if isinstance(e, ComparisonExpr): + return min(literal(o) for o in e.operands) + + elif isinstance(e, OpExpr): + return min(literal(e.left), literal(e.right)) + + elif isinstance(e, (MemberExpr, UnaryExpr, StarExpr)): + return literal(e.expr) + + elif isinstance(e, AssignmentExpr): + return literal(e.target) + + elif isinstance(e, IndexExpr): + if literal(e.index) == LITERAL_YES: + return literal(e.base) + else: + return LITERAL_NO + + elif isinstance(e, NameExpr): + if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None: + return LITERAL_YES + return LITERAL_TYPE + + if isinstance(e, (IntExpr, FloatExpr, ComplexExpr, StrExpr, BytesExpr)): + return LITERAL_YES + + if literal_hash(e): + return LITERAL_YES + + return LITERAL_NO + + +def subkeys(key: Key) -> Iterable[Key]: + return [elt for elt in key if isinstance(elt, tuple)] + + +def extract_var_from_literal_hash(key: Key) -> Var | None: + """If key refers to a Var node, return it. + + Return None otherwise. + """ + if len(key) == 2 and key[0] == "Var" and isinstance(key[1], Var): + return key[1] + return None + + +class _Hasher(ExpressionVisitor[Key | None]): + def visit_int_expr(self, e: IntExpr) -> Key: + return ("Literal", e.value) + + def visit_str_expr(self, e: StrExpr) -> Key: + return ("Literal", e.value) + + def visit_bytes_expr(self, e: BytesExpr) -> Key: + return ("Literal", e.value) + + def visit_float_expr(self, e: FloatExpr) -> Key: + return ("Literal", e.value) + + def visit_complex_expr(self, e: ComplexExpr) -> Key: + return ("Literal", e.value) + + def visit_star_expr(self, e: StarExpr) -> Key: + return ("Star", literal_hash(e.expr)) + + def visit_name_expr(self, e: NameExpr) -> Key: + if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None: + return ("Literal", e.node.final_value) + # N.B: We use the node itself as the key, and not the name, + # because using the name causes issues when there is shadowing + # (for example, in list comprehensions). + return ("Var", e.node) + + def visit_member_expr(self, e: MemberExpr) -> Key: + return ("Member", literal_hash(e.expr), e.name) + + def visit_op_expr(self, e: OpExpr) -> Key: + return ("Binary", e.op, literal_hash(e.left), literal_hash(e.right)) + + def visit_comparison_expr(self, e: ComparisonExpr) -> Key: + rest: tuple[str | Key | None, ...] = tuple(e.operators) + rest += tuple(literal_hash(o) for o in e.operands) + return ("Comparison",) + rest + + def visit_unary_expr(self, e: UnaryExpr) -> Key: + return ("Unary", e.op, literal_hash(e.expr)) + + def seq_expr(self, e: ListExpr | TupleExpr | SetExpr, name: str) -> Key | None: + if all(literal(x) == LITERAL_YES for x in e.items): + rest: tuple[Key | None, ...] = tuple(literal_hash(x) for x in e.items) + return (name,) + rest + return None + + def visit_list_expr(self, e: ListExpr) -> Key | None: + return self.seq_expr(e, "List") + + def visit_dict_expr(self, e: DictExpr) -> Key | None: + if all(a and literal(a) == literal(b) == LITERAL_YES for a, b in e.items): + rest: tuple[Key | None, ...] = tuple( + (literal_hash(a) if a else None, literal_hash(b)) for a, b in e.items + ) + return ("Dict",) + rest + return None + + def visit_tuple_expr(self, e: TupleExpr) -> Key | None: + return self.seq_expr(e, "Tuple") + + def visit_set_expr(self, e: SetExpr) -> Key | None: + return self.seq_expr(e, "Set") + + def visit_index_expr(self, e: IndexExpr) -> Key | None: + if literal(e.index) == LITERAL_YES: + return ("Index", literal_hash(e.base), literal_hash(e.index)) + return None + + def visit_assignment_expr(self, e: AssignmentExpr) -> Key | None: + return literal_hash(e.target) + + def visit_call_expr(self, e: CallExpr) -> None: + return None + + def visit_slice_expr(self, e: SliceExpr) -> None: + return None + + def visit_cast_expr(self, e: CastExpr) -> None: + return None + + def visit_type_form_expr(self, e: TypeFormExpr) -> None: + return None + + def visit_assert_type_expr(self, e: AssertTypeExpr) -> None: + return None + + def visit_conditional_expr(self, e: ConditionalExpr) -> None: + return None + + def visit_ellipsis(self, e: EllipsisExpr) -> None: + return None + + def visit_yield_from_expr(self, e: YieldFromExpr) -> None: + return None + + def visit_yield_expr(self, e: YieldExpr) -> None: + return None + + def visit_reveal_expr(self, e: RevealExpr) -> None: + return None + + def visit_super_expr(self, e: SuperExpr) -> None: + return None + + def visit_type_application(self, e: TypeApplication) -> None: + return None + + def visit_lambda_expr(self, e: LambdaExpr) -> None: + return None + + def visit_list_comprehension(self, e: ListComprehension) -> None: + return None + + def visit_set_comprehension(self, e: SetComprehension) -> None: + return None + + def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None: + return None + + def visit_generator_expr(self, e: GeneratorExpr) -> None: + return None + + def visit_type_var_expr(self, e: TypeVarExpr) -> None: + return None + + def visit_paramspec_expr(self, e: ParamSpecExpr) -> None: + return None + + def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> None: + return None + + def visit_type_alias_expr(self, e: TypeAliasExpr) -> None: + return None + + def visit_namedtuple_expr(self, e: NamedTupleExpr) -> None: + return None + + def visit_enum_call_expr(self, e: EnumCallExpr) -> None: + return None + + def visit_typeddict_expr(self, e: TypedDictExpr) -> None: + return None + + def visit_newtype_expr(self, e: NewTypeExpr) -> None: + return None + + def visit__promote_expr(self, e: PromoteExpr) -> None: + return None + + def visit_await_expr(self, e: AwaitExpr) -> None: + return None + + def visit_template_str_expr(self, e: TemplateStrExpr) -> None: + return None + + def visit_temp_node(self, e: TempNode) -> None: + return None + + +_hasher: Final = _Hasher() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..47bb4264ddc2caf58b8517d67362314c29c4ab43 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/lookup.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/lookup.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b195567fa0d0a9656bdb9ebbe61c38fbffdb07 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/lookup.py @@ -0,0 +1,68 @@ +""" +This is a module for various lookup functions: +functions that will find a semantic node by its name. +""" + +from __future__ import annotations + +from mypy.nodes import MypyFile, SymbolTableNode, TypeInfo + +# TODO: gradually move existing lookup functions to this module. + + +def lookup_fully_qualified( + name: str, modules: dict[str, MypyFile], *, raise_on_missing: bool = False +) -> SymbolTableNode | None: + """Find a symbol using it fully qualified name. + + The algorithm has two steps: first we try splitting the name on '.' to find + the module, then iteratively look for each next chunk after a '.' (e.g. for + nested classes). + + This function should *not* be used to find a module. Those should be looked + in the modules dictionary. + """ + # 1. Exclude the names of ad hoc instance intersections from step 2. + i = name.find(" os.stat_result: + try: + st = orig_stat(path) + except OSError as err: + print(f"stat({path!r}) -> {err}") + raise + else: + print( + "stat(%r) -> (st_mode=%o, st_mtime=%d, st_size=%d)" + % (path, st.st_mode, st.st_mtime, st.st_size) + ) + return st + + +def main( + *, + args: list[str] | None = None, + stdout: TextIO = sys.stdout, + stderr: TextIO = sys.stderr, + clean_exit: bool = False, +) -> None: + """Main entry point to the type checker. + + Args: + args: Custom command-line arguments. If not given, sys.argv[1:] will + be used. + clean_exit: Don't hard kill the process on exit. This allows catching + SystemExit. + """ + util.check_python_version("mypy") + t0 = time.time() + # To log stat() calls: os.stat = stat_proxy + sys.setrecursionlimit(RECURSION_LIMIT) + if args is None: + args = sys.argv[1:] + + # Write an escape sequence instead of raising an exception on encoding errors. + if isinstance(stdout, TextIOWrapper) and stdout.errors == "strict": + stdout.reconfigure(errors="backslashreplace") + + fscache = FileSystemCache() + sources, options = process_options(args, stdout=stdout, stderr=stderr, fscache=fscache) + if clean_exit: + options.fast_exit = False + + formatter = util.FancyFormatter( + stdout, stderr, options.hide_error_codes, hide_success=bool(options.output) + ) + + if options.num_workers: + # Supporting both parsers would be really tricky, so just support the new one. + options.native_parser = True + + if options.allow_redefinition_new and not options.local_partial_types: + fail( + "error: --local-partial-types must be enabled if using --allow-redefinition-new", + stderr, + options, + ) + + if options.allow_redefinition_new and options.allow_redefinition_old: + fail( + "--allow-redefinition-old and --allow-redefinition-new should not be used together", + stderr, + options, + ) + + if options.install_types and (stdout is not sys.stdout or stderr is not sys.stderr): + # Since --install-types performs user input, we want regular stdout and stderr. + fail("error: --install-types not supported in this mode of running mypy", stderr, options) + + if options.non_interactive and not options.install_types: + fail("error: --non-interactive is only supported with --install-types", stderr, options) + + if options.install_types and not options.incremental: + fail( + "error: --install-types not supported with incremental mode disabled", stderr, options + ) + + if options.install_types and options.python_executable is None: + fail( + "error: --install-types not supported without python executable or site packages", + stderr, + options, + ) + + if options.install_types and not sources: + install_types(formatter, options, non_interactive=options.non_interactive) + return + + res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr) + + if options.non_interactive: + missing_pkgs = read_types_packages_to_install(options.cache_dir, after_run=True) + if missing_pkgs: + # Install missing type packages and rerun build. + install_types(formatter, options, after_run=True, non_interactive=True) + fscache.flush() + print() + res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr) + show_messages(messages, stderr, formatter, options) + + if MEM_PROFILE: + from mypy.memprofile import print_memory_profile + + print_memory_profile() + + code = 0 + n_errors, n_notes, n_files = util.count_stats(messages) + if messages and n_notes < len(messages): + code = 2 if blockers else 1 + if options.error_summary: + if n_errors: + summary = formatter.format_error( + n_errors, n_files, len(sources), blockers=blockers, use_color=options.color_output + ) + stdout.write(summary + "\n") + # Only notes should also output success + elif not messages or n_notes == len(messages): + stdout.write(formatter.format_success(len(sources), options.color_output) + "\n") + stdout.flush() + + if options.install_types and not options.non_interactive: + result = install_types(formatter, options, after_run=True, non_interactive=False) + if result: + print() + print("note: Run mypy again for up-to-date results with installed types") + code = 2 + + if options.fast_exit: + # Exit without freeing objects -- it's faster. + # + # NOTE: We don't flush all open files on exit (or run other destructors)! + util.hard_exit(code) + elif code: + sys.exit(code) + + # HACK: keep res alive so that mypyc won't free it before the hard_exit + list([res]) # noqa: C410 + + +class BuildResultThunk: + # We pass this around so that we avoid freeing memory, which is slow + def __init__(self, build_result: build.BuildResult | None) -> None: + self._result = build_result + + +def run_build( + sources: list[BuildSource], + options: Options, + fscache: FileSystemCache, + t0: float, + stdout: TextIO, + stderr: TextIO, +) -> tuple[BuildResultThunk | None, list[str], bool]: + formatter = util.FancyFormatter( + stdout, stderr, options.hide_error_codes, hide_success=bool(options.output) + ) + + messages = [] + messages_by_file = defaultdict(list) + + def flush_errors(filename: str | None, new_messages: list[str], serious: bool) -> None: + if options.pretty: + new_messages = formatter.fit_in_terminal(new_messages) + messages.extend(new_messages) + if new_messages: + messages_by_file[filename].extend(new_messages) + if options.non_interactive: + # Collect messages and possibly show them later. + return + f = stderr if serious else stdout + show_messages(new_messages, f, formatter, options) + + serious = False + blockers = False + res = None + try: + # Keep a dummy reference (res) for memory profiling afterwards, as otherwise + # the result could be freed. + res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr) + except CompileError as e: + blockers = True + if not e.use_stdout: + serious = True + + if res: + res.manager.metastore.close() + + maybe_write_junit_xml(time.time() - t0, serious, messages, messages_by_file, options) + return BuildResultThunk(res), messages, blockers + + +def show_messages( + messages: list[str], f: TextIO, formatter: util.FancyFormatter, options: Options +) -> None: + for msg in messages: + if options.color_output: + msg = formatter.colorize(msg) + f.write(msg + "\n") + f.flush() + + +# Make the help output a little less jarring. +class AugmentedHelpFormatter(argparse.RawDescriptionHelpFormatter): + def __init__(self, prog: str, **kwargs: Any) -> None: + super().__init__(prog=prog, max_help_position=28, **kwargs) + + def _fill_text(self, text: str, width: int, indent: str) -> str: + if "\n" in text: + # Assume we want to manually format the text + return super()._fill_text(text, width, indent) + # Format the text like argparse, but overflow rather than + # breaking long words (like URLs) + text = self._whitespace_matcher.sub(" ", text).strip() + import textwrap + + return textwrap.fill( + text, + width, + initial_indent=indent, + subsequent_indent=indent, + break_on_hyphens=False, + break_long_words=False, + ) + + +# Define pairs of flag prefixes with inverse meaning. +flag_prefix_pairs: Final = [("allow", "disallow"), ("show", "hide")] +flag_prefix_map: Final[dict[str, str]] = {} +for a, b in flag_prefix_pairs: + flag_prefix_map[a] = b + flag_prefix_map[b] = a + + +def invert_flag_name(flag: str) -> str: + split = flag[2:].split("-", 1) + if len(split) == 2: + prefix, rest = split + if prefix in flag_prefix_map: + return f"--{flag_prefix_map[prefix]}-{rest}" + elif prefix == "no": + return f"--{rest}" + + return f"--no-{flag[2:]}" + + +class PythonExecutableInferenceError(Exception): + """Represents a failure to infer the version or executable while searching.""" + + +def python_executable_prefix(v: str) -> list[str]: + if sys.platform == "win32": + # on Windows, all Python executables are named `python`. To handle this, there + # is the `py` launcher, which can be passed a version e.g. `py -3.8`, and it will + # execute an installed Python 3.8 interpreter. See also: + # https://docs.python.org/3/using/windows.html#python-launcher-for-windows + return ["py", f"-{v}"] + else: + return [f"python{v}"] + + +def _python_executable_from_version(python_version: tuple[int, int]) -> str: + if sys.version_info[:2] == python_version: + return sys.executable + str_ver = ".".join(map(str, python_version)) + try: + sys_exe = ( + subprocess.check_output( + python_executable_prefix(str_ver) + ["-c", "import sys; print(sys.executable)"], + stderr=subprocess.STDOUT, + ) + .decode() + .strip() + ) + return sys_exe + except (subprocess.CalledProcessError, FileNotFoundError) as e: + raise PythonExecutableInferenceError( + "failed to find a Python executable matching version {}," + " perhaps try --python-executable, or --no-site-packages?".format(python_version) + ) from e + + +def infer_python_executable(options: Options, special_opts: argparse.Namespace) -> None: + """Infer the Python executable from the given version. + + This function mutates options based on special_opts to infer the correct Python executable + to use. + """ + # TODO: (ethanhs) Look at folding these checks and the site packages subprocess calls into + # one subprocess call for speed. + + # Use the command line specified executable, or fall back to one set in the + # config file. If an executable is not specified, infer it from the version + # (unless no_executable is set) + python_executable = special_opts.python_executable or options.python_executable + + if python_executable is None: + if not special_opts.no_executable and not options.no_site_packages: + python_executable = _python_executable_from_version(options.python_version) + options.python_executable = python_executable + + +HEADER: Final = """%(prog)s [-h] [-v] [-V] [more options; see below] + [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]""" + + +DESCRIPTION: Final = """ +Mypy is a program that will type check your Python code. + +Pass in any files or folders you want to type check. Mypy will +recursively traverse any provided folders to find .py files: + + $ mypy my_program.py my_src_folder + +For more information on getting started, see: + +- https://mypy.readthedocs.io/en/stable/getting_started.html + +For more details on both running mypy and using the flags below, see: + +- https://mypy.readthedocs.io/en/stable/running_mypy.html +- https://mypy.readthedocs.io/en/stable/command_line.html + +You can also use a config file to configure mypy instead of using +command line flags. For more details, see: + +- https://mypy.readthedocs.io/en/stable/config_file.html +""" + +FOOTER: Final = """Environment variables: + Define MYPYPATH for additional module search path entries. + Define MYPY_CACHE_DIR to override configuration cache_dir path.""" + + +class CapturableArgumentParser(argparse.ArgumentParser): + """Override ArgumentParser methods that use sys.stdout/sys.stderr directly. + + This is needed because hijacking sys.std* is not thread-safe, + yet output must be captured to properly support mypy.api.run. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self.stdout = kwargs.pop("stdout", sys.stdout) + self.stderr = kwargs.pop("stderr", sys.stderr) + super().__init__(*args, **kwargs) + + # ===================== + # Help-printing methods + # ===================== + def print_usage(self, file: SupportsWrite[str] | None = None) -> None: + if file is None: + file = self.stdout + self._print_message(self.format_usage(), file) + + def print_help(self, file: SupportsWrite[str] | None = None) -> None: + if file is None: + file = self.stdout + self._print_message(self.format_help(), file) + + def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: + if message: + if file is None: + file = self.stderr + file.write(message) + + # =============== + # Exiting methods + # =============== + def exit(self, status: int = 0, message: str | None = None) -> NoReturn: + if message: + self._print_message(message, self.stderr) + sys.exit(status) + + def error(self, message: str) -> NoReturn: + """error(message: string) + + Prints a usage message incorporating the message to stderr and + exits. + + If you override this in a subclass, it should not return -- it + should either exit or raise an exception. + """ + self.print_usage(self.stderr) + args = {"prog": self.prog, "message": message} + self.exit(2, gettext("%(prog)s: error: %(message)s\n") % args) + + +class CapturableVersionAction(argparse.Action): + """Supplement CapturableArgumentParser to handle --version. + + This is nearly identical to argparse._VersionAction except, + like CapturableArgumentParser, it allows output to be captured. + + Another notable difference is that version is mandatory. + This allows removing a line in __call__ that falls back to parser.version + (which does not appear to exist). + """ + + def __init__( + self, + option_strings: Sequence[str], + version: str, + dest: str = argparse.SUPPRESS, + default: str = argparse.SUPPRESS, + help: str = "show program's version number and exit", + stdout: IO[str] | None = None, + ) -> None: + super().__init__( + option_strings=option_strings, dest=dest, default=default, nargs=0, help=help + ) + self.version = version + self.stdout = stdout or sys.stdout + + def __call__( + self, + parser: argparse.ArgumentParser, + namespace: argparse.Namespace, + values: str | Sequence[Any] | None, + option_string: str | None = None, + ) -> NoReturn: + formatter = parser._get_formatter() + formatter.add_text(self.version) + parser._print_message(formatter.format_help(), self.stdout) + parser.exit() + + +def define_options( + program: str = "mypy", + header: str = HEADER, + stdout: TextIO = sys.stdout, + stderr: TextIO = sys.stderr, + server_options: bool = False, +) -> tuple[CapturableArgumentParser, list[str], list[tuple[str, bool]]]: + """Define the options in the parser (by calling a bunch of methods that express/build our desired command-line flags). + Returns a tuple of: + a parser object, that can parse command line arguments to mypy (expected consumer: main's process_options), + a list of what flags are strict (expected consumer: docs' html_builder's _add_strict_list), + strict_flag_assignments (expected consumer: main's process_options).""" + parser = CapturableArgumentParser( + prog=program, + usage=header, + description=DESCRIPTION, + epilog=FOOTER, + fromfile_prefix_chars="@", + formatter_class=AugmentedHelpFormatter, + add_help=False, + stdout=stdout, + stderr=stderr, + ) + + strict_flag_names: list[str] = [] + strict_flag_assignments: list[tuple[str, bool]] = [] + + def add_invertible_flag( + flag: str, + *, + inverse: str | None = None, + default: bool, + dest: str | None = None, + help: str, + strict_flag: bool = False, + group: argparse._ActionsContainer | None = None, + ) -> None: + if inverse is None: + inverse = invert_flag_name(flag) + if group is None: + group = parser + + if help is not argparse.SUPPRESS: + help += f" (inverse: {inverse})" + + arg = group.add_argument( + flag, action="store_false" if default else "store_true", dest=dest, help=help + ) + dest = arg.dest + group.add_argument( + inverse, + action="store_true" if default else "store_false", + dest=dest, + help=argparse.SUPPRESS, + ) + if strict_flag: + assert dest is not None + strict_flag_names.append(flag) + strict_flag_assignments.append((dest, not default)) + + # Unless otherwise specified, arguments will be parsed directly onto an + # Options object. Options that require further processing should have + # their `dest` prefixed with `special-opts:`, which will cause them to be + # parsed into the separate special_opts namespace object. + + # Our style guide for formatting the output of running `mypy --help`: + # Flags: + # 1. The flag help text should start with a capital letter but never end with a period. + # 2. Keep the flag help text brief -- ideally just a single sentence. + # 3. All flags must be a part of a group, unless the flag is deprecated or suppressed. + # 4. Avoid adding new flags to the "miscellaneous" groups -- instead add them to an + # existing group or, if applicable, create a new group. Feel free to move existing + # flags to a new group: just be sure to also update the documentation to match. + # + # Groups: + # 1. The group title and description should start with a capital letter. + # 2. The first sentence of a group description should be written in the bare infinitive. + # Tip: try substituting the group title and description into the following sentence: + # > {group_title}: these flags will {group_description} + # Feel free to add subsequent sentences that add additional details. + # 3. If you cannot think of a meaningful description for a new group, omit it entirely. + # (E.g. see the "miscellaneous" sections). + # 4. The text of the group description should end with a period, optionally followed + # by a documentation reference (URL). + # 5. If you want to include a documentation reference, place it at the end of the + # description. Feel free to open with a brief reference ("See also:", "For more + # information:", etc.), followed by a space, then the entire URL including + # "https://" scheme identifier and fragment ("#some-target-heading"), if any. + # Do not end with a period (or any other characters not part of the URL). + # URLs longer than the available terminal width will overflow without being + # broken apart. This facilitates both URL detection, and manual copy-pasting. + + general_group = parser.add_argument_group(title="Optional arguments") + general_group.add_argument( + "-h", "--help", action="help", help="Show this help message and exit" + ) + general_group.add_argument( + "-v", "--verbose", action="count", dest="verbosity", help="More verbose messages" + ) + + compilation_status = "no" if __file__.endswith(".py") else "yes" + general_group.add_argument( + "-V", + "--version", + action=CapturableVersionAction, + version="%(prog)s " + __version__ + f" (compiled: {compilation_status})", + help="Show program's version number and exit", + stdout=stdout, + ) + + general_group.add_argument( + "-O", + "--output", + metavar="FORMAT", + help="Set a custom output format", + choices=OUTPUT_CHOICES, + ) + + config_group = parser.add_argument_group( + title="Config file", + description="Use a config file instead of command line arguments. " + "This is useful if you are using many flags or want " + "to set different options per each module.", + ) + config_group.add_argument( + "--config-file", + help=( + f"Configuration file, must have a [mypy] section " + f"(defaults to {', '.join(defaults.CONFIG_NAMES + defaults.SHARED_CONFIG_NAMES)})" + ), + ) + add_invertible_flag( + "--warn-unused-configs", + default=False, + help="Warn about unused '[mypy-]' or '[[tool.mypy.overrides]]' config sections", + group=config_group, + ) + + imports_group = parser.add_argument_group( + title="Import discovery", description="Configure how imports are discovered and followed." + ) + add_invertible_flag( + "--no-namespace-packages", + dest="namespace_packages", + default=True, + help="Disable support for namespace packages (PEP 420, __init__.py-less)", + group=imports_group, + ) + imports_group.add_argument( + "--ignore-missing-imports", + action="store_true", + help="Silently ignore imports of missing modules", + ) + imports_group.add_argument( + "--follow-untyped-imports", + action="store_true", + help="Typecheck modules without stubs or py.typed marker", + ) + imports_group.add_argument( + "--follow-imports", + choices=["normal", "silent", "skip", "error"], + default="normal", + help="How to treat imports (default normal)", + ) + imports_group.add_argument( + "--python-executable", + action="store", + metavar="EXECUTABLE", + help="Python executable used for finding PEP 561 compliant installed packages and stubs", + dest="special-opts:python_executable", + ) + imports_group.add_argument( + "--no-site-packages", + action="store_true", + dest="special-opts:no_executable", + help="Do not search for installed PEP 561 compliant packages", + ) + imports_group.add_argument( + "--no-silence-site-packages", + action="store_true", + help="Do not silence errors in PEP 561 compliant installed packages", + ) + + platform_group = parser.add_argument_group( + title="Platform configuration", + description="Type check code assuming it will be run under certain " + "runtime conditions. By default, mypy assumes your code " + "will be run using the same operating system and Python " + "version you are using to run mypy itself.", + ) + platform_group.add_argument( + "--python-version", + type=parse_version, + metavar="x.y", + help="Type check code assuming it will be running on Python x.y", + dest="special-opts:python_version", + ) + platform_group.add_argument( + "--platform", + action="store", + metavar="PLATFORM", + help="Type check special-cased code for the given OS platform (defaults to sys.platform)", + ) + platform_group.add_argument( + "--always-true", + metavar="NAME", + action="append", + default=[], + help="Additional variable to be considered True (may be repeated)", + ) + platform_group.add_argument( + "--always-false", + metavar="NAME", + action="append", + default=[], + help="Additional variable to be considered False (may be repeated)", + ) + + disallow_any_group = parser.add_argument_group( + title="Disallow dynamic typing", + description="Disallow the use of the dynamic 'Any' type under certain conditions.", + ) + disallow_any_group.add_argument( + "--disallow-any-expr", + default=False, + action="store_true", + help="Disallow all expressions that have type Any", + ) + disallow_any_group.add_argument( + "--disallow-any-decorated", + default=False, + action="store_true", + help="Disallow functions that have Any in their signature after decorator transformation", + ) + disallow_any_group.add_argument( + "--disallow-any-explicit", + default=False, + action="store_true", + help="Disallow explicit Any in type positions", + ) + add_invertible_flag( + "--disallow-any-generics", + default=False, + strict_flag=True, + help="Disallow usage of generic types that do not specify explicit type parameters", + group=disallow_any_group, + ) + add_invertible_flag( + "--disallow-any-unimported", + default=False, + help="Disallow Any types resulting from unfollowed imports", + group=disallow_any_group, + ) + add_invertible_flag( + "--disallow-subclassing-any", + default=False, + strict_flag=True, + help="Disallow subclassing values of type 'Any' when defining classes", + group=disallow_any_group, + ) + + untyped_group = parser.add_argument_group( + title="Untyped definitions and calls", + description="Configure how untyped definitions and calls are handled. " + "Note: by default, mypy ignores any untyped function definitions " + "and assumes any calls to such functions have a return " + "type of 'Any'.", + ) + add_invertible_flag( + "--disallow-untyped-calls", + default=False, + strict_flag=True, + help="Disallow calling functions without type annotations" + " from functions with type annotations", + group=untyped_group, + ) + untyped_group.add_argument( + "--untyped-calls-exclude", + metavar="MODULE", + action="append", + default=[], + help="Disable --disallow-untyped-calls for functions/methods coming" + " from specific package, module, or class", + ) + add_invertible_flag( + "--disallow-untyped-defs", + default=False, + strict_flag=True, + help="Disallow defining functions without type annotations" + " or with incomplete type annotations", + group=untyped_group, + ) + add_invertible_flag( + "--disallow-incomplete-defs", + default=False, + strict_flag=True, + help="Disallow defining functions with incomplete type annotations " + "(while still allowing entirely unannotated definitions)", + group=untyped_group, + ) + add_invertible_flag( + "--check-untyped-defs", + default=False, + strict_flag=True, + help="Type check the interior of functions without type annotations", + group=untyped_group, + ) + add_invertible_flag( + "--disallow-untyped-decorators", + default=False, + strict_flag=True, + help="Disallow decorating typed functions with untyped decorators", + group=untyped_group, + ) + + none_group = parser.add_argument_group( + title="None and Optional handling", + description="Adjust how values of type 'None' are handled. For more context on " + "how mypy handles values of type 'None', see: " + "https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type", + ) + add_invertible_flag( + "--implicit-optional", + default=False, + help="Assume arguments with default values of None are Optional", + group=none_group, + ) + none_group.add_argument("--strict-optional", action="store_true", help=argparse.SUPPRESS) + none_group.add_argument( + "--no-strict-optional", + action="store_false", + dest="strict_optional", + help="Disable strict Optional checks (inverse: --strict-optional)", + ) + + lint_group = parser.add_argument_group( + title="Configuring warnings", + description="Detect code that is sound but redundant or problematic.", + ) + add_invertible_flag( + "--warn-redundant-casts", + default=False, + strict_flag=True, + help="Warn about casting an expression to its inferred type", + group=lint_group, + ) + add_invertible_flag( + "--warn-unused-ignores", + default=False, + strict_flag=True, + help="Warn about unneeded '# type: ignore' comments", + group=lint_group, + ) + add_invertible_flag( + "--no-warn-no-return", + dest="warn_no_return", + default=True, + help="Do not warn about functions that end without returning", + group=lint_group, + ) + add_invertible_flag( + "--warn-return-any", + default=False, + strict_flag=True, + help="Warn about returning values of type Any from non-Any typed functions", + group=lint_group, + ) + add_invertible_flag( + "--warn-unreachable", + default=False, + strict_flag=False, + help="Warn about statements or expressions inferred to be unreachable", + group=lint_group, + ) + add_invertible_flag( + "--report-deprecated-as-note", + default=False, + strict_flag=False, + help="Report importing or using deprecated features as notes instead of errors", + group=lint_group, + ) + lint_group.add_argument( + "--deprecated-calls-exclude", + metavar="MODULE", + action="append", + default=[], + help="Disable deprecated warnings for functions/methods coming" + " from specific package, module, or class", + ) + + # Note: this group is intentionally added here even though we don't add + # --strict to this group near the end. + # + # That way, this group will appear after the various strictness groups + # but before the remaining flags. + # We add `--strict` near the end so we don't accidentally miss any strictness + # flags that are added after this group. + strictness_group = parser.add_argument_group(title="Miscellaneous strictness flags") + + add_invertible_flag( + "--allow-untyped-globals", + default=False, + strict_flag=False, + help="Suppress toplevel errors caused by missing annotations", + group=strictness_group, + ) + + add_invertible_flag( + "--allow-redefinition", + default=False, + strict_flag=False, + help="Alias to --allow-redefinition-old; will point to --allow-redefinition-new in v2.0", + group=strictness_group, + dest="allow_redefinition_old", + ) + + add_invertible_flag( + "--allow-redefinition-old", + default=False, + strict_flag=False, + help="Allow restricted, unconditional variable redefinition with a new type", + group=strictness_group, + ) + + add_invertible_flag( + "--allow-redefinition-new", + default=False, + strict_flag=False, + help="Allow more flexible variable redefinition semantics", + group=strictness_group, + ) + + add_invertible_flag( + "--no-implicit-reexport", + default=True, + strict_flag=True, + dest="implicit_reexport", + help="Treat imports as private unless aliased", + group=strictness_group, + ) + + add_invertible_flag( + "--strict-equality", + default=False, + strict_flag=True, + help="Prohibit equality, identity, and container checks for non-overlapping types " + "(except `None`)", + group=strictness_group, + ) + + add_invertible_flag( + "--strict-equality-for-none", + default=False, + strict_flag=False, + help="Extend `--strict-equality` for `None` checks", + group=strictness_group, + ) + + add_invertible_flag( + "--strict-bytes", + default=False, + strict_flag=True, + help="Disable treating bytearray and memoryview as subtypes of bytes", + group=strictness_group, + ) + + add_invertible_flag( + "--extra-checks", + default=False, + strict_flag=True, + help="Enable additional checks that are technically correct but may be impractical " + "in real code. For example, this prohibits partial overlap in TypedDict updates, " + "and makes arguments prepended via Concatenate positional-only", + group=strictness_group, + ) + + strict_help = "Strict mode; enables the following flags: {}".format( + ", ".join(strict_flag_names) + ) + strictness_group.add_argument( + "--strict", action="store_true", dest="special-opts:strict", help=strict_help + ) + + strictness_group.add_argument( + "--disable-error-code", + metavar="NAME", + action="append", + default=[], + help="Disable a specific error code", + ) + strictness_group.add_argument( + "--enable-error-code", + metavar="NAME", + action="append", + default=[], + help="Enable a specific error code", + ) + + error_group = parser.add_argument_group( + title="Configuring error messages", + description="Adjust the amount of detail shown in error messages.", + ) + add_invertible_flag( + "--show-error-context", + default=False, + dest="show_error_context", + help='Precede errors with "note:" messages explaining context', + group=error_group, + ) + add_invertible_flag( + "--show-column-numbers", + default=False, + help="Show column numbers in error messages", + group=error_group, + ) + add_invertible_flag( + "--show-error-end", + default=False, + help="Show end line/end column numbers in error messages." + " This implies --show-column-numbers", + group=error_group, + ) + add_invertible_flag( + "--hide-error-codes", + default=False, + help="Hide error codes in error messages", + group=error_group, + ) + add_invertible_flag( + "--show-error-code-links", + default=False, + help="Show links to error code documentation", + group=error_group, + ) + add_invertible_flag( + "--pretty", + default=False, + help="Use visually nicer output in error messages:" + " Use soft word wrap, show source code snippets," + " and show error location markers", + group=error_group, + ) + add_invertible_flag( + "--no-color-output", + dest="color_output", + default=True, + help="Do not colorize error messages", + group=error_group, + ) + add_invertible_flag( + "--no-error-summary", + dest="error_summary", + default=True, + help="Do not show error stats summary", + group=error_group, + ) + add_invertible_flag( + "--show-absolute-path", + default=False, + help="Show absolute paths to files", + group=error_group, + ) + error_group.add_argument( + "--soft-error-limit", + default=defaults.MANY_ERRORS_THRESHOLD, + type=int, + dest="many_errors_threshold", + help=argparse.SUPPRESS, + ) + + incremental_group = parser.add_argument_group( + title="Incremental mode", + description="Adjust how mypy incrementally type checks and caches modules. " + "Mypy caches type information about modules into a cache to " + "let you speed up future invocations of mypy. Also see " + "mypy's daemon mode: " + "https://mypy.readthedocs.io/en/stable/mypy_daemon.html#mypy-daemon", + ) + incremental_group.add_argument( + "-i", "--incremental", action="store_true", help=argparse.SUPPRESS + ) + incremental_group.add_argument( + "--no-incremental", + action="store_false", + dest="incremental", + help="Disable module cache (inverse: --incremental)", + ) + incremental_group.add_argument( + "--cache-dir", + action="store", + metavar="DIR", + help="Store module cache info in the given folder in incremental mode " + "(defaults to '{}')".format(defaults.CACHE_DIR), + ) + add_invertible_flag( + "--sqlite-cache", + default=False, + help="Use a sqlite database to store the cache", + group=incremental_group, + ) + incremental_group.add_argument( + "--cache-fine-grained", + action="store_true", + help="Include fine-grained dependency information in the cache for the mypy daemon", + ) + add_invertible_flag( + "--no-fixed-format-cache", + dest="fixed_format_cache", + default=True, + help="Do not use new fixed format cache", + group=incremental_group, + ) + incremental_group.add_argument( + "--skip-version-check", + action="store_true", + help="Allow using cache written by older mypy version", + ) + incremental_group.add_argument( + "--skip-cache-mtime-checks", + action="store_true", + help="Skip cache internal consistency checks based on mtime", + ) + + internals_group = parser.add_argument_group( + title="Advanced options", description="Debug and customize mypy internals." + ) + internals_group.add_argument("--pdb", action="store_true", help="Invoke pdb on fatal error") + internals_group.add_argument( + "--show-traceback", "--tb", action="store_true", help="Show traceback on fatal error" + ) + internals_group.add_argument( + "--raise-exceptions", action="store_true", help="Raise exception on fatal error" + ) + internals_group.add_argument( + "--custom-typing-module", + metavar="MODULE", + dest="custom_typing_module", + help="Use a custom typing module", + ) + internals_group.add_argument( + "--old-type-inference", action="store_true", help=argparse.SUPPRESS + ) + internals_group.add_argument( + "--disable-expression-cache", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--enable-incomplete-feature", + action="append", + metavar="{" + ",".join(sorted(INCOMPLETE_FEATURES)) + "}", + help="Enable support of incomplete/experimental features for early preview", + ) + internals_group.add_argument( + "--custom-typeshed-dir", metavar="DIR", help="Use the custom typeshed in DIR" + ) + add_invertible_flag( + "--warn-incomplete-stub", + default=False, + help="Warn if missing type annotation in typeshed, only relevant with" + " --disallow-untyped-defs or --disallow-incomplete-defs enabled", + group=internals_group, + ) + internals_group.add_argument( + "--shadow-file", + nargs=2, + metavar=("SOURCE_FILE", "SHADOW_FILE"), + dest="shadow_file", + action="append", + help="When encountering SOURCE_FILE, read and type check " + "the contents of SHADOW_FILE instead.", + ) + internals_group.add_argument("--fast-exit", action="store_true", help=argparse.SUPPRESS) + internals_group.add_argument( + "--no-fast-exit", action="store_false", dest="fast_exit", help=argparse.SUPPRESS + ) + # This flag is useful for mypy tests, where function bodies may be omitted. Plugin developers + # may want to use this as well in their tests. + add_invertible_flag( + "--allow-empty-bodies", default=False, help=argparse.SUPPRESS, group=internals_group + ) + # This undocumented feature exports limited line-level dependency information. + internals_group.add_argument("--export-ref-info", action="store_true", help=argparse.SUPPRESS) + + # Experimental parallel type-checking support. + internals_group.add_argument( + "-n", "--num-workers", type=int, default=0, help=argparse.SUPPRESS + ) + + report_group = parser.add_argument_group( + title="Report generation", description="Generate a report in the specified format." + ) + for report_type in sorted(defaults.REPORTER_NAMES): + if report_type not in {"memory-xml"}: + report_group.add_argument( + f"--{report_type.replace('_', '-')}-report", + metavar="DIR", + dest=f"special-opts:{report_type}_report", + ) + + # Undocumented mypyc feature: generate annotated HTML source file + report_group.add_argument( + "-a", dest="mypyc_annotation_file", type=str, default=None, help=argparse.SUPPRESS + ) + # Hidden mypyc feature: do not write any C files (keep existing ones and assume they exist). + # This can be useful when debugging mypyc bugs. + report_group.add_argument( + "--skip-c-gen", dest="mypyc_skip_c_generation", action="store_true", help=argparse.SUPPRESS + ) + + misc_group = parser.add_argument_group(title="Miscellaneous") + misc_group.add_argument("--quickstart-file", help=argparse.SUPPRESS) + misc_group.add_argument( + "--junit-xml", + metavar="JUNIT_XML_OUTPUT_FILE", + help="Write a JUnit XML test result document with type checking results to the given file", + ) + misc_group.add_argument( + "--junit-format", + choices=["global", "per_file"], + default="global", + help="If --junit-xml is set, specifies format. global (default): single test with all errors; per_file: one test entry per file with failures", + ) + misc_group.add_argument( + "--find-occurrences", + metavar="CLASS.MEMBER", + dest="special-opts:find_occurrences", + help="Print out all usages of a class member (experimental)", + ) + misc_group.add_argument( + "--scripts-are-modules", + action="store_true", + help="Script x becomes module x instead of __main__", + ) + + add_invertible_flag( + "--install-types", + default=False, + strict_flag=False, + help="Install detected missing library stub packages using pip", + group=misc_group, + ) + add_invertible_flag( + "--non-interactive", + default=False, + strict_flag=False, + help=( + "Install stubs without asking for confirmation and hide " + + "errors, with --install-types" + ), + group=misc_group, + inverse="--interactive", + ) + + if server_options: + misc_group.add_argument( + "--use-fine-grained-cache", + action="store_true", + help="Use the cache in fine-grained incremental mode", + ) + + # hidden options + parser.add_argument( + "--stats", action="store_true", dest="dump_type_stats", help=argparse.SUPPRESS + ) + parser.add_argument( + "--inferstats", action="store_true", dest="dump_inference_stats", help=argparse.SUPPRESS + ) + parser.add_argument("--dump-build-stats", action="store_true", help=argparse.SUPPRESS) + # Dump timing stats for each processed file into the given output file + parser.add_argument("--timing-stats", dest="timing_stats", help=argparse.SUPPRESS) + # Dump per line type checking timing stats for each processed file into the given + # output file. Only total time spent in each top level expression will be shown. + # Times are show in microseconds. + parser.add_argument( + "--line-checking-stats", dest="line_checking_stats", help=argparse.SUPPRESS + ) + # --debug-cache will disable any cache-related compressions/optimizations, + # which will make the cache writing process output pretty-printed JSON (which + # is easier to debug). + parser.add_argument("--debug-cache", action="store_true", help=argparse.SUPPRESS) + # --dump-deps will dump all fine-grained dependencies to stdout + parser.add_argument("--dump-deps", action="store_true", help=argparse.SUPPRESS) + # --dump-graph will dump the contents of the graph of SCCs and exit. + parser.add_argument("--dump-graph", action="store_true", help=argparse.SUPPRESS) + # --semantic-analysis-only does exactly that. + parser.add_argument("--semantic-analysis-only", action="store_true", help=argparse.SUPPRESS) + # Some tests use this to tell mypy that we are running a test. + parser.add_argument("--test-env", action="store_true", help=argparse.SUPPRESS) + # --local-partial-types disallows partial types spanning module top level and a function + # (implicitly defined in fine-grained incremental mode) + add_invertible_flag("--local-partial-types", default=False, help=argparse.SUPPRESS) + # --native-parser enables the native parser (experimental) + add_invertible_flag("--native-parser", default=False, help=argparse.SUPPRESS) + # --logical-deps adds some more dependencies that are not semantically needed, but + # may be helpful to determine relative importance of classes and functions for overall + # type precision in a code base. It also _removes_ some deps, so this flag should be never + # used except for generating code stats. This also automatically enables --cache-fine-grained. + # NOTE: This is an experimental option that may be modified or removed at any time. + parser.add_argument("--logical-deps", action="store_true", help=argparse.SUPPRESS) + # --bazel changes some behaviors for use with Bazel (https://bazel.build). + parser.add_argument("--bazel", action="store_true", help=argparse.SUPPRESS) + # --package-root adds a directory below which directories are considered + # packages even without __init__.py. May be repeated. + parser.add_argument( + "--package-root", metavar="ROOT", action="append", default=[], help=argparse.SUPPRESS + ) + # --cache-map FILE ... gives a mapping from source files to cache files. + # Each triple of arguments is a source file, a cache meta file, and a cache data file. + # Modules not mentioned in the file will go through cache_dir. + # Must be followed by another flag or by '--' (and then only file args may follow). + parser.add_argument( + "--cache-map", nargs="+", dest="special-opts:cache_map", help=argparse.SUPPRESS + ) + # --debug-serialize will run tree.serialize() even if cache generation is disabled. + # Useful for mypy_primer to detect serialize errors earlier. + parser.add_argument("--debug-serialize", action="store_true", help=argparse.SUPPRESS) + + parser.add_argument( + "--disable-bytearray-promotion", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--disable-memoryview-promotion", action="store_true", help=argparse.SUPPRESS + ) + # This flag is deprecated, it has been moved to --extra-checks + parser.add_argument("--strict-concatenate", action="store_true", help=argparse.SUPPRESS) + + # options specifying code to check + code_group = parser.add_argument_group( + title="Running code", + description="Specify the code you want to type check. For more details, see " + "https://mypy.readthedocs.io/en/stable/running_mypy.html#running-mypy", + ) + add_invertible_flag( + "--explicit-package-bases", + default=False, + help="Use current directory and MYPYPATH to determine module names of files passed", + group=code_group, + ) + add_invertible_flag( + "--fast-module-lookup", default=False, help=argparse.SUPPRESS, group=code_group + ) + code_group.add_argument( + "--exclude", + action="append", + metavar="PATTERN", + default=[], + help=( + "Regular expression to match file names, directory names or paths which mypy should " + "ignore while recursively discovering files to check, e.g. --exclude '/setup\\.py$'. " + "May be specified more than once, eg. --exclude a --exclude b" + ), + ) + add_invertible_flag( + "--exclude-gitignore", + default=False, + help=( + "Use .gitignore file(s) to exclude files from checking " + "(in addition to any explicit --exclude if present)" + ), + group=code_group, + ) + code_group.add_argument( + "-m", + "--module", + action="append", + metavar="MODULE", + default=[], + dest="special-opts:modules", + help="Type-check module; can repeat for more modules", + ) + code_group.add_argument( + "-p", + "--package", + action="append", + metavar="PACKAGE", + default=[], + dest="special-opts:packages", + help="Type-check package recursively; can be repeated", + ) + code_group.add_argument( + "-c", + "--command", + action="append", + metavar="PROGRAM_TEXT", + dest="special-opts:command", + help="Type-check program passed in as string", + ) + code_group.add_argument( + metavar="files", + nargs="*", + dest="special-opts:files", + help="Type-check given files or directories", + ) + return parser, strict_flag_names, strict_flag_assignments + + +def process_options( + args: list[str], + stdout: TextIO | None = None, + stderr: TextIO | None = None, + require_targets: bool = True, + server_options: bool = False, + fscache: FileSystemCache | None = None, + program: str = "mypy", + header: str = HEADER, + mypyc: bool = False, +) -> tuple[list[BuildSource], Options]: + """Parse command line arguments. + + If a FileSystemCache is passed in, and package_root options are given, + call fscache.set_package_root() to set the cache's package root. + + Returns a tuple of: a list of source files, an Options collected from flags. + """ + stdout = stdout if stdout is not None else sys.stdout + stderr = stderr if stderr is not None else sys.stderr + + parser, _, strict_flag_assignments = define_options( + program, header, stdout, stderr, server_options + ) + + # Parse arguments once into a dummy namespace so we can get the + # filename for the config file and know if the user requested all strict options. + dummy = argparse.Namespace() + parser.parse_args(args, dummy) + config_file = dummy.config_file + # Don't explicitly test if "config_file is not None" for this check. + # This lets `--config-file=` (an empty string) be used to disable all config files. + if config_file and not os.path.exists(config_file): + parser.error(f"Cannot find config file '{config_file}'") + + options = Options() + strict_option_set = False + if mypyc: + # Mypyc has strict_bytes enabled by default + options.strict_bytes = True + + def set_strict_flags() -> None: + nonlocal strict_option_set + strict_option_set = True + for dest, value in strict_flag_assignments: + setattr(options, dest, value) + + # Parse config file first, so command line can override. + parse_config_file(options, set_strict_flags, config_file, stdout, stderr) + + # Set strict flags before parsing (if strict mode enabled), so other command + # line options can override. + if getattr(dummy, "special-opts:strict"): + set_strict_flags() + + # Override cache_dir if provided in the environment + environ_cache_dir = os.getenv("MYPY_CACHE_DIR", "") + if environ_cache_dir.strip(): + options.cache_dir = environ_cache_dir + options.cache_dir = os.path.expanduser(options.cache_dir) + + # Parse command line for real, using a split namespace. + special_opts = argparse.Namespace() + parser.parse_args(args, SplitNamespace(options, special_opts, "special-opts:")) + + # The python_version is either the default, which can be overridden via a config file, + # or stored in special_opts and is passed via the command line. + options.python_version = special_opts.python_version or options.python_version + if options.python_version < (3,): + parser.error( + "Mypy no longer supports checking Python 2 code. " + "Consider pinning to mypy<0.980 if you need to check Python 2 code." + ) + try: + infer_python_executable(options, special_opts) + except PythonExecutableInferenceError as e: + parser.error(str(e)) + + if special_opts.no_executable or options.no_site_packages: + options.python_executable = None + + # Paths listed in the config file will be ignored if any paths, modules or packages + # are passed on the command line. + if not (special_opts.files or special_opts.packages or special_opts.modules): + if options.files: + special_opts.files = options.files + if options.packages: + special_opts.packages = options.packages + if options.modules: + special_opts.modules = options.modules + + # Check for invalid argument combinations. + if require_targets: + code_methods = sum( + bool(c) + for c in [ + special_opts.modules + special_opts.packages, + special_opts.command, + special_opts.files, + ] + ) + if code_methods == 0 and not options.install_types: + parser.error("Missing target module, package, files, or command.") + elif code_methods > 1: + parser.error("May only specify one of: module/package, files, or command.") + if options.explicit_package_bases and not options.namespace_packages: + parser.error( + "Can only use --explicit-package-bases with --namespace-packages, since otherwise " + "examining __init__.py's is sufficient to determine module names for files" + ) + + # Check for overlapping `--always-true` and `--always-false` flags. + overlap = set(options.always_true) & set(options.always_false) + if overlap: + parser.error( + "You can't make a variable always true and always false (%s)" + % ", ".join(sorted(overlap)) + ) + + validate_package_allow_list(options.untyped_calls_exclude) + validate_package_allow_list(options.deprecated_calls_exclude) + + options.process_incomplete_features(error_callback=parser.error, warning_callback=print) + + # Compute absolute path for custom typeshed (if present). + if options.custom_typeshed_dir is not None: + options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir) + + # Set build flags. + if special_opts.find_occurrences: + _find_occurrences = tuple(special_opts.find_occurrences.split(".")) + if len(_find_occurrences) < 2: + parser.error("Can only find occurrences of class members.") + if len(_find_occurrences) != 2: + parser.error("Can only find occurrences of non-nested class members.") + state.find_occurrences = _find_occurrences + + # Set reports. + for flag, val in vars(special_opts).items(): + if flag.endswith("_report") and val is not None: + report_type = flag[:-7].replace("_", "-") + report_dir = val + options.report_dirs[report_type] = report_dir + + # Process --package-root. + if options.package_root: + process_package_roots(fscache, parser, options) + + # Process --cache-map. + if special_opts.cache_map: + if options.sqlite_cache: + parser.error("--cache-map is incompatible with --sqlite-cache") + + process_cache_map(parser, special_opts, options) + + # Process --strict-bytes + options.process_strict_bytes() + + # An explicitly specified cache_fine_grained implies local_partial_types + # (because otherwise the cache is not compatible with dmypy) + if options.cache_fine_grained: + options.local_partial_types = True + + # Implicitly show column numbers if error location end is shown + if options.show_error_end: + options.show_column_numbers = True + + # Let logical_deps imply cache_fine_grained (otherwise the former is useless). + if options.logical_deps: + options.cache_fine_grained = True + + if options.strict_concatenate and not strict_option_set: + print("Warning: --strict-concatenate is deprecated; use --extra-checks instead") + + # Set target. + if special_opts.modules + special_opts.packages: + options.build_type = BuildType.MODULE + sys_path, _ = get_search_dirs(options.python_executable) + search_paths = SearchPaths( + (os.getcwd(),), tuple(mypy_path() + options.mypy_path), tuple(sys_path), () + ) + targets = [] + # TODO: use the same cache that the BuildManager will + cache = FindModuleCache(search_paths, fscache, options) + for p in special_opts.packages: + if os.sep in p or os.altsep and os.altsep in p: + fail(f"Package name '{p}' cannot have a slash in it.", stderr, options) + p_targets = cache.find_modules_recursive(p) + if not p_targets: + reason = cache.find_module(p) + if reason is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + fail( + f"Package '{p}' cannot be type checked due to missing py.typed marker. See https://mypy.readthedocs.io/en/stable/installed_packages.html for more details", + stderr, + options, + ) + else: + fail(f"Can't find package '{p}'", stderr, options) + targets.extend(p_targets) + for m in special_opts.modules: + targets.append(BuildSource(None, m, None)) + elif special_opts.command: + options.build_type = BuildType.PROGRAM_TEXT + targets = [BuildSource(None, None, "\n".join(special_opts.command))] + else: + try: + targets = create_source_list(special_opts.files, options, fscache) + # Variable named e2 instead of e to work around mypyc bug #620 + # which causes issues when using the same variable to catch + # exceptions of different types. + except InvalidSourceList as e2: + fail(str(e2), stderr, options) + return targets, options + + +def process_package_roots( + fscache: FileSystemCache | None, parser: argparse.ArgumentParser, options: Options +) -> None: + """Validate and normalize package_root.""" + if fscache is None: + parser.error("--package-root does not work here (no fscache)") + assert fscache is not None # Since mypy doesn't know parser.error() raises. + # Do some stuff with drive letters to make Windows happy (esp. tests). + current_drive, _ = os.path.splitdrive(os.getcwd()) + dot = os.curdir + dotslash = os.curdir + os.sep + dotdotslash = os.pardir + os.sep + trivial_paths = {dot, dotslash} + package_root = [] + for root in options.package_root: + if os.path.isabs(root): + parser.error(f"Package root cannot be absolute: {root!r}") + drive, root = os.path.splitdrive(root) + if drive and drive != current_drive: + parser.error(f"Package root must be on current drive: {drive + root!r}") + # Empty package root is always okay. + if root: + root = os.path.relpath(root) # Normalize the heck out of it. + if not root.endswith(os.sep): + root = root + os.sep + if root.startswith(dotdotslash): + parser.error(f"Package root cannot be above current directory: {root!r}") + if root in trivial_paths: + root = "" + package_root.append(root) + options.package_root = package_root + # Pass the package root on the filesystem cache. + fscache.set_package_root(package_root) + + +def process_cache_map( + parser: argparse.ArgumentParser, special_opts: argparse.Namespace, options: Options +) -> None: + """Validate cache_map and copy into options.cache_map.""" + n = len(special_opts.cache_map) + if n % 3 != 0: + parser.error("--cache-map requires one or more triples (see source)") + for i in range(0, n, 3): + source, meta_file, data_file = special_opts.cache_map[i : i + 3] + if source in options.cache_map: + parser.error(f"Duplicate --cache-map source {source})") + if not source.endswith(".py") and not source.endswith(".pyi"): + parser.error(f"Invalid --cache-map source {source} (triple[0] must be *.py[i])") + if not meta_file.endswith(".meta.json"): + parser.error( + "Invalid --cache-map meta_file %s (triple[1] must be *.meta.json)" % meta_file + ) + if not data_file.endswith(".data.json"): + parser.error( + "Invalid --cache-map data_file %s (triple[2] must be *.data.json)" % data_file + ) + options.cache_map[source] = (meta_file, data_file) + + +def maybe_write_junit_xml( + td: float, + serious: bool, + all_messages: list[str], + messages_by_file: dict[str | None, list[str]], + options: Options, +) -> None: + if options.junit_xml: + py_version = f"{options.python_version[0]}_{options.python_version[1]}" + if options.junit_format == "global": + util.write_junit_xml( + td, + serious, + {None: all_messages} if all_messages else {}, + options.junit_xml, + py_version, + options.platform, + ) + else: + # per_file + util.write_junit_xml( + td, serious, messages_by_file, options.junit_xml, py_version, options.platform + ) + + +def fail(msg: str, stderr: TextIO, options: Options) -> NoReturn: + """Fail with a serious error.""" + stderr.write(f"{msg}\n") + maybe_write_junit_xml( + 0.0, serious=True, all_messages=[msg], messages_by_file={None: [msg]}, options=options + ) + sys.exit(2) + + +def read_types_packages_to_install(cache_dir: str, after_run: bool) -> list[str]: + if not os.path.isdir(cache_dir): + if not after_run: + sys.stderr.write( + "error: Can't determine which types to install with no files to check " + + "(and no cache from previous mypy run)\n" + ) + else: + sys.stderr.write( + "error: --install-types failed (an error blocked analysis of which types to install)\n" + ) + fnam = build.missing_stubs_file(cache_dir) + if not os.path.isfile(fnam): + # No missing stubs. + return [] + with open(fnam) as f: + return [line.strip() for line in f] + + +def install_types( + formatter: util.FancyFormatter, + options: Options, + *, + after_run: bool = False, + non_interactive: bool = False, +) -> bool: + """Install stub packages using pip if some missing stubs were detected.""" + packages = read_types_packages_to_install(options.cache_dir, after_run) + if not packages: + # If there are no missing stubs, generate no output. + return False + if after_run and not non_interactive: + print() + print("Installing missing stub packages:") + assert options.python_executable, "Python executable required to install types" + cmd = [options.python_executable, "-m", "pip", "install"] + packages + print(formatter.style(" ".join(cmd), "none", bold=True)) + print() + if not non_interactive: + x = input("Install? [yN] ") + if not x.strip() or not x.lower().startswith("y"): + print(formatter.style("mypy: Skipping installation", "red", bold=True)) + sys.exit(2) + print() + subprocess.run(cmd) + return True diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/maptype.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/maptype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e4f7b1b530764c620c9b9fbc684d7b78937a6f8b Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/maptype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/maptype.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/maptype.py new file mode 100644 index 0000000000000000000000000000000000000000..59ecb2bc9993025e435b83ceef15acc5becef859 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/maptype.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +from mypy.expandtype import expand_type_by_instance +from mypy.nodes import TypeInfo +from mypy.types import AnyType, Instance, TupleType, TypeOfAny, has_type_vars + + +def map_instance_to_supertype(instance: Instance, superclass: TypeInfo) -> Instance: + """Produce a supertype of `instance` that is an Instance + of `superclass`, mapping type arguments up the chain of bases. + + If `superclass` is not a nominal superclass of `instance.type`, + then all type arguments are mapped to 'Any'. + """ + if instance.type == superclass: + # Fast path: `instance` already belongs to `superclass`. + return instance + + if superclass.fullname == "builtins.tuple" and instance.type.tuple_type: + if has_type_vars(instance.type.tuple_type): + # We special case mapping generic tuple types to tuple base, because for + # such tuples fallback can't be calculated before applying type arguments. + alias = instance.type.special_alias + assert alias is not None + if not alias._is_recursive: + # Unfortunately we can't support this for generic recursive tuples. + # If we skip this special casing we will fall back to tuple[Any, ...]. + tuple_type = expand_type_by_instance(instance.type.tuple_type, instance) + if isinstance(tuple_type, TupleType): + # Make the import here to avoid cyclic imports. + import mypy.typeops + + return mypy.typeops.tuple_fallback(tuple_type) + elif isinstance(tuple_type, Instance): + # This can happen after normalizing variadic tuples. + return tuple_type + + if not superclass.type_vars: + # Fast path: `superclass` has no type variables to map to. + return Instance(superclass, []) + + return map_instance_to_supertypes(instance, superclass)[0] + + +def map_instance_to_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]: + # FIX: Currently we should only have one supertype per interface, so no + # need to return an array + result: list[Instance] = [] + for path in class_derivation_paths(instance.type, supertype): + types = [instance] + for sup in path: + a: list[Instance] = [] + for t in types: + a.extend(map_instance_to_direct_supertypes(t, sup)) + types = a + result.extend(types) + if result: + return result + else: + # Nothing. Presumably due to an error. Construct a dummy using Any. + any_type = AnyType(TypeOfAny.from_error) + return [Instance(supertype, [any_type] * len(supertype.type_vars))] + + +def class_derivation_paths(typ: TypeInfo, supertype: TypeInfo) -> list[list[TypeInfo]]: + """Return an array of non-empty paths of direct base classes from + type to supertype. Return [] if no such path could be found. + + InterfaceImplementationPaths(A, B) == [[B]] if A inherits B + InterfaceImplementationPaths(A, C) == [[B, C]] if A inherits B and + B inherits C + """ + # FIX: Currently we might only ever have a single path, so this could be + # simplified + result: list[list[TypeInfo]] = [] + + for base in typ.bases: + btype = base.type + if btype == supertype: + result.append([btype]) + else: + # Try constructing a longer path via the base class. + for path in class_derivation_paths(btype, supertype): + result.append([btype] + path) + + return result + + +def map_instance_to_direct_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]: + # FIX: There should only be one supertypes, always. + typ = instance.type + result: list[Instance] = [] + + for b in typ.bases: + if b.type == supertype: + t = expand_type_by_instance(b, instance) + assert isinstance(t, Instance) + result.append(t) + + if result: + return result + else: + # Relationship with the supertype not specified explicitly. Use dynamic + # type arguments implicitly. + any_type = AnyType(TypeOfAny.unannotated) + return [Instance(supertype, [any_type] * len(supertype.type_vars))] diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/meet.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/meet.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0fa5233afc44965824438ecb5902354ab7d2a024 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/meet.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/meet.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/meet.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c54bbe03b32b5b60d3f0d362d49cc303a5d71e --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/meet.py @@ -0,0 +1,1286 @@ +from __future__ import annotations + +from collections.abc import Callable + +from mypy import join +from mypy.erasetype import erase_type +from mypy.maptype import map_instance_to_supertype +from mypy.state import state +from mypy.subtypes import ( + are_parameters_compatible, + find_member, + is_callable_compatible, + is_equivalent, + is_proper_subtype, + is_same_type, + is_subtype, +) +from mypy.typeops import is_recursive_pair, make_simplified_union, tuple_fallback +from mypy.types import ( + MYPYC_NATIVE_INT_NAMES, + TUPLE_LIKE_INSTANCE_NAMES, + AnyType, + CallableType, + DeletedType, + ErasedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeGuardedType, + TypeOfAny, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + get_proper_type, + get_proper_types, + has_type_vars, + is_named_instance, + split_with_prefix_and_suffix, +) + +# TODO Describe this module. + + +def trivial_meet(s: Type, t: Type) -> ProperType: + """Return one of types (expanded) if it is a subtype of other, otherwise bottom type.""" + if is_subtype(s, t): + return get_proper_type(s) + elif is_subtype(t, s): + return get_proper_type(t) + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + + +def meet_types(s: Type, t: Type) -> ProperType: + """Return the greatest lower bound of two types.""" + if is_recursive_pair(s, t): + # This case can trigger an infinite recursion, general support for this will be + # tricky, so we use a trivial meet (like for protocols). + return trivial_meet(s, t) + s = get_proper_type(s) + t = get_proper_type(t) + + if isinstance(s, Instance) and isinstance(t, Instance) and s.type == t.type: + # Code in checker.py should merge any extra_items where possible, so we + # should have only compatible extra_items here. We check this before + # the below subtype check, so that extra_attrs will not get erased. + if (s.extra_attrs or t.extra_attrs) and is_same_type(s, t): + if s.extra_attrs and t.extra_attrs: + if len(s.extra_attrs.attrs) > len(t.extra_attrs.attrs): + # Return the one that has more precise information. + return s + return t + if s.extra_attrs: + return s + return t + + if not isinstance(s, UnboundType) and not isinstance(t, UnboundType): + if is_proper_subtype(s, t, ignore_promotions=True): + return s + if is_proper_subtype(t, s, ignore_promotions=True): + return t + + if isinstance(s, ErasedType): + return s + if isinstance(s, AnyType): + return t + if isinstance(s, UnionType) and not isinstance(t, UnionType): + s, t = t, s + + # Meets/joins require callable type normalization. + s, t = join.normalize_callables(s, t) + + return t.accept(TypeMeetVisitor(s)) + + +def narrow_declared_type(declared: Type, narrowed: Type) -> Type: + """Return the declared type narrowed down to another type.""" + # TODO: check infinite recursion for aliases here. + if isinstance(narrowed, TypeGuardedType): + # A type guard forces the new type even if it doesn't overlap the old... + if is_proper_subtype(declared, narrowed.type_guard, ignore_promotions=True): + # ...unless it is a proper supertype of declared type. + return declared + return narrowed.type_guard + + original_declared = declared + original_narrowed = narrowed + declared = get_proper_type(declared) + narrowed = get_proper_type(narrowed) + + if declared == narrowed: + return original_declared + if isinstance(declared, UnionType): + declared_items = declared.relevant_items() + if isinstance(narrowed, UnionType): + narrowed_items = narrowed.relevant_items() + else: + narrowed_items = [narrowed] + return make_simplified_union( + [ + narrow_declared_type(d, n) + for d in declared_items + for n in narrowed_items + # This (ugly) special-casing is needed to support checking + # branches like this: + # x: Union[float, complex] + # if isinstance(x, int): + # ... + # And assignments like this: + # x: float | None + # y: int | None + # x = y + if ( + is_overlapping_types(d, n, ignore_promotions=True) + or is_subtype(n, d, ignore_promotions=False) + ) + ] + ) + if is_enum_overlapping_union(declared, narrowed): + # Quick check before reaching `is_overlapping_types`. If it's enum/literal overlap, + # avoid full expansion and make it faster. + assert isinstance(narrowed, UnionType) + return make_simplified_union( + [narrow_declared_type(declared, x) for x in narrowed.relevant_items()] + ) + elif ( + isinstance(declared, TypeVarType) + and not has_type_vars(original_narrowed) + and is_subtype(original_narrowed, declared.upper_bound) + ): + # We put this branch early to get T(bound=Union[A, B]) instead of + # Union[T(bound=A), T(bound=B)] that will be confusing for users. + return declared.copy_modified( + upper_bound=narrow_declared_type(declared.upper_bound, original_narrowed) + ) + elif not is_overlapping_types(declared, narrowed): + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + elif isinstance(narrowed, UnionType): + return make_simplified_union( + [narrow_declared_type(declared, x) for x in narrowed.relevant_items()] + ) + elif isinstance(narrowed, AnyType): + return original_narrowed + elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared): + return narrowed + elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType): + return TypeType.make_normalized( + narrow_declared_type(declared.item, narrowed.item), + is_type_form=declared.is_type_form and narrowed.is_type_form, + ) + elif ( + isinstance(declared, TypeType) + and isinstance(narrowed, Instance) + and narrowed.type.is_metaclass() + ): + if declared.is_type_form: + # The declared TypeForm[T] after narrowing must be a kind of + # type object at least as narrow as Type[T] + return narrow_declared_type( + TypeType.make_normalized( + declared.item, line=declared.line, column=declared.column, is_type_form=False + ), + original_narrowed, + ) + # We'd need intersection types, so give up. + return original_declared + elif isinstance(declared, Instance): + if declared.type.alt_promote: + # Special case: low-level integer type can't be narrowed + return original_declared + if ( + isinstance(narrowed, Instance) + and narrowed.type.alt_promote + and narrowed.type.alt_promote.type is declared.type + ): + # Special case: 'int' can't be narrowed down to a native int type such as + # i64, since they have different runtime representations. + return original_declared + return meet_types(original_declared, original_narrowed) + elif isinstance(declared, (TupleType, TypeType, LiteralType)): + return meet_types(original_declared, original_narrowed) + elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance): + # Special case useful for selecting TypedDicts from unions using isinstance(x, dict). + if narrowed.type.fullname == "builtins.dict" and all( + isinstance(t, AnyType) for t in get_proper_types(narrowed.args) + ): + return original_declared + return meet_types(original_declared, original_narrowed) + elif ( + isinstance(declared, CallableType) + and isinstance(narrowed, CallableType) + and has_type_vars(declared.ret_type) + ): + return narrowed.copy_modified( + ret_type=narrow_declared_type(declared.ret_type, narrowed.ret_type) + ) + + return original_narrowed + + +def get_possible_variants(typ: Type) -> list[Type]: + """This function takes any "Union-like" type and returns a list of the available "options". + + Specifically, there are currently exactly three different types that can have + "variants" or are "union-like": + + - Unions + - TypeVars with value restrictions + - Overloads + + This function will return a list of each "option" present in those types. + + If this function receives any other type, we return a list containing just that + original type. (E.g. pretend the type was contained within a singleton union). + + The only current exceptions are regular TypeVars and ParamSpecs. For these "TypeVarLike"s, + we return a list containing that TypeVarLike's upper bound. + + This function is useful primarily when checking to see if two types are overlapping: + the algorithm to check if two unions are overlapping is fundamentally the same as + the algorithm for checking if two overloads are overlapping. + + Normalizing both kinds of types in the same way lets us reuse the same algorithm + for both. + """ + typ = get_proper_type(typ) + + if isinstance(typ, TypeVarType): + if len(typ.values) > 0: + return typ.values + else: + return [typ.upper_bound] + elif isinstance(typ, ParamSpecType): + # Extract 'object' from the final mro item + upper_bound = get_proper_type(typ.upper_bound) + if isinstance(upper_bound, Instance): + return [Instance(upper_bound.type.mro[-1], [])] + return [AnyType(TypeOfAny.implementation_artifact)] + elif isinstance(typ, TypeVarTupleType): + return [typ.upper_bound] + elif isinstance(typ, UnionType): + return list(typ.items) + elif isinstance(typ, Overloaded): + # Note: doing 'return typ.items()' makes mypy + # infer a too-specific return type of List[CallableType] + return list(typ.items) + else: + return [typ] + + +def is_enum_overlapping_union(x: ProperType, y: ProperType) -> bool: + """Return True if x is an Enum, and y is an Union with at least one Literal from x""" + return ( + isinstance(x, Instance) + and x.type.is_enum + and isinstance(y, UnionType) + and any( + isinstance(p := get_proper_type(z), LiteralType) and x.type == p.fallback.type + for z in y.relevant_items() + ) + ) + + +def is_literal_in_union(x: ProperType, y: ProperType) -> bool: + """Return True if x is a Literal and y is an Union that includes x""" + return ( + isinstance(x, LiteralType) + and isinstance(y, UnionType) + and any(x == get_proper_type(z) for z in y.items) + ) + + +def is_object(t: ProperType) -> bool: + return isinstance(t, Instance) and t.type.fullname == "builtins.object" + + +def is_none_object_overlap(t1: ProperType, t2: ProperType) -> bool: + return ( + isinstance(t1, NoneType) + and isinstance(t2, Instance) + and t2.type.fullname == "builtins.object" + ) + + +def are_related_types( + left: Type, right: Type, *, proper_subtype: bool, ignore_promotions: bool +) -> bool: + if proper_subtype: + return is_proper_subtype( + left, right, ignore_promotions=ignore_promotions + ) or is_proper_subtype(right, left, ignore_promotions=ignore_promotions) + else: + return is_subtype(left, right, ignore_promotions=ignore_promotions) or is_subtype( + right, left, ignore_promotions=ignore_promotions + ) + + +def is_overlapping_types( + left: Type, + right: Type, + ignore_promotions: bool = False, + overlap_for_overloads: bool = False, + seen_types: set[tuple[Type, Type]] | None = None, +) -> bool: + """Can a value of type 'left' also be of type 'right' or vice-versa? + + If 'ignore_promotions' is True, we ignore promotions while checking for overlaps. + If 'overlap_for_overloads' is True, we check for overlaps more strictly (to avoid false + positives), for example: None only overlaps with explicitly optional types, Any + doesn't overlap with anything except object, we don't ignore positional argument names. + """ + if isinstance(left, TypeGuardedType) or isinstance(right, TypeGuardedType): + # A type guard forces the new type even if it doesn't overlap the old. + return True + + if seen_types is None: + seen_types = set() + elif (left, right) in seen_types: + return True + if is_recursive_pair(left, right): + seen_types.add((left, right)) + + left, right = get_proper_types((left, right)) + + # We should never encounter this type. + if isinstance(left, PartialType) or isinstance(right, PartialType): + assert False, "Unexpectedly encountered partial type" + + # We should also never encounter these types, but it's possible a few + # have snuck through due to unrelated bugs. For now, we handle these + # in the same way we handle 'Any'. + # + # TODO: Replace these with an 'assert False' once we are more confident. + illegal_types = (UnboundType, ErasedType, DeletedType) + if isinstance(left, illegal_types) or isinstance(right, illegal_types): + return True + + # When running under non-strict optional mode, simplify away types of + # the form 'Union[A, B, C, None]' into just 'Union[A, B, C]'. + + if not state.strict_optional: + if isinstance(left, UnionType): + left = UnionType.make_union(left.relevant_items()) + if isinstance(right, UnionType): + right = UnionType.make_union(right.relevant_items()) + left, right = get_proper_types((left, right)) + + # 'Any' may or may not be overlapping with the other type + if isinstance(left, AnyType) or isinstance(right, AnyType): + return not overlap_for_overloads or is_object(left) or is_object(right) + + # We check for complete overlaps next as a general-purpose failsafe. + # If this check fails, we start checking to see if there exists a + # *partial* overlap between types. + # + # These checks will also handle the NoneType and UninhabitedType cases for us. + + # enums are sometimes expanded into an Union of Literals + # when that happens we want to make sure we treat the two as overlapping + # and crucially, we want to do that *fast* in case the enum is large + # so we do it before expanding variants below to avoid O(n**2) behavior + if ( + is_enum_overlapping_union(left, right) + or is_enum_overlapping_union(right, left) + or is_literal_in_union(left, right) + or is_literal_in_union(right, left) + ): + return True + + if overlap_for_overloads: + if is_none_object_overlap(left, right) or is_none_object_overlap(right, left): + return False + + if are_related_types( + left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions + ): + return True + + # See the docstring for 'get_possible_variants' for more info on what the + # following lines are doing. + + left_possible = get_possible_variants(left) + right_possible = get_possible_variants(right) + + # Now move on to checking multi-variant types like Unions. We also perform + # the same logic if either type happens to be a TypeVar/ParamSpec/TypeVarTuple. + # + # Handling the TypeVarLikes now lets us simulate having them bind to the corresponding + # type -- if we deferred these checks, the "return-early" logic of the other + # checks will prevent us from detecting certain overlaps. + # + # If both types are singleton variants (and are not TypeVarLikes), we've hit the base case: + # we skip these checks to avoid infinitely recursing. + + def _is_overlapping_types(left: Type, right: Type) -> bool: + """Encode the kind of overlapping check to perform. + + This function mostly exists, so we don't have to repeat keyword arguments everywhere. + """ + return is_overlapping_types( + left, + right, + ignore_promotions=ignore_promotions, + overlap_for_overloads=overlap_for_overloads, + seen_types=seen_types.copy(), + ) + + if ( + len(left_possible) > 1 + or len(right_possible) > 1 + or isinstance(left, TypeVarLikeType) + or isinstance(right, TypeVarLikeType) + ): + for l in left_possible: + for r in right_possible: + if _is_overlapping_types(l, r): + return True + return False + + # Now that we've finished handling TypeVarLikes, we're free to end early + # if one one of the types is None and we're running in strict-optional mode. + # (None only overlaps with None in strict-optional mode). + # + # We must perform this check after the TypeVarLike checks because + # a TypeVar could be bound to None, for example. + + if state.strict_optional and isinstance(left, NoneType) != isinstance(right, NoneType): + return False + + # Next, we handle single-variant types that may be inherently partially overlapping: + # + # - TypedDicts + # - Tuples + # + # If we cannot identify a partial overlap and end early, we degrade these two types + # into their 'Instance' fallbacks. + + if isinstance(left, TypedDictType) and isinstance(right, TypedDictType): + return are_typed_dicts_overlapping(left, right, _is_overlapping_types) + elif typed_dict_mapping_pair(left, right): + # Overlaps between TypedDicts and Mappings require dedicated logic. + return typed_dict_mapping_overlap(left, right, overlapping=_is_overlapping_types) + elif isinstance(left, TypedDictType): + left = left.fallback + elif isinstance(right, TypedDictType): + right = right.fallback + + if is_tuple(left) and is_tuple(right): + return are_tuples_overlapping(left, right, _is_overlapping_types) + elif isinstance(left, TupleType): + left = tuple_fallback(left) + elif isinstance(right, TupleType): + right = tuple_fallback(right) + + # Next, we handle single-variant types that cannot be inherently partially overlapping, + # but do require custom logic to inspect. + # + # As before, we degrade into 'Instance' whenever possible. + + if isinstance(left, TypeType) and isinstance(right, TypeType): + return _is_overlapping_types(left.item, right.item) + + if isinstance(left, TypeType) or isinstance(right, TypeType): + + def _type_object_overlap(left: Type, right: Type) -> bool: + """Special cases for type object types overlaps.""" + # TODO: these checks are a bit in gray area, adjust if they cause problems. + left, right = get_proper_types((left, right)) + # 1. Type[C] vs Callable[..., C] overlap even if the latter is not class object. + if isinstance(left, TypeType) and isinstance(right, CallableType): + return _is_overlapping_types(left.item, right.ret_type) + # 2. Type[C] vs Meta, where Meta is a metaclass for C. + if isinstance(left, TypeType) and isinstance(right, Instance): + if isinstance(left.item, Instance): + left_meta = left.item.type.metaclass_type + if left_meta is not None: + return _is_overlapping_types(left_meta, right) + # builtins.type (default metaclass) overlaps with all metaclasses + return right.type.has_base("builtins.type") + elif isinstance(left.item, AnyType): + return right.type.has_base("builtins.type") + # 3. Callable[..., C] vs Meta is considered below, when we switch to fallbacks. + return False + + return _type_object_overlap(left, right) or _type_object_overlap(right, left) + + if isinstance(left, Parameters) and isinstance(right, Parameters): + return are_parameters_compatible( + left, + right, + is_compat=_is_overlapping_types, + is_proper_subtype=False, + ignore_pos_arg_names=not overlap_for_overloads, + allow_partial_overlap=True, + ) + # A `Parameters` does not overlap with anything else, however + if isinstance(left, Parameters) or isinstance(right, Parameters): + return False + + if isinstance(left, CallableType) and isinstance(right, CallableType): + # We run is_callable_compatible in both directions, similar to the logic + # in is_unsafe_overlapping_overload_signatures + # See comments in https://github.com/python/mypy/pull/5476 + return is_callable_compatible( + left, + right, + is_compat=_is_overlapping_types, + is_proper_subtype=False, + ignore_pos_arg_names=not overlap_for_overloads, + allow_partial_overlap=True, + ) or is_callable_compatible( + right, + left, + is_compat=_is_overlapping_types, + is_proper_subtype=False, + ignore_pos_arg_names=not overlap_for_overloads, + check_args_covariantly=True, + allow_partial_overlap=True, + ) + + call = None + other = None + if isinstance(left, CallableType) and isinstance(right, Instance): + call = find_member("__call__", right, right, is_operator=True) + other = left + if isinstance(right, CallableType) and isinstance(left, Instance): + call = find_member("__call__", left, left, is_operator=True) + other = right + if isinstance(get_proper_type(call), FunctionLike): + assert call is not None and other is not None + return _is_overlapping_types(call, other) + + if isinstance(left, CallableType): + left = left.fallback + if isinstance(right, CallableType): + right = right.fallback + + if isinstance(left, LiteralType) and isinstance(right, LiteralType): + if left.value == right.value: + # If values are the same, we still need to check if fallbacks are overlapping, + # this is done below. + left = left.fallback + right = right.fallback + else: + return False + elif isinstance(left, LiteralType): + left = left.fallback + elif isinstance(right, LiteralType): + right = right.fallback + + # Finally, we handle the case where left and right are instances. + + if isinstance(left, Instance) and isinstance(right, Instance): + # First we need to handle promotions and structural compatibility for instances + # that came as fallbacks, so simply call is_subtype() to avoid code duplication. + if are_related_types( + left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions + ): + return True + + if right.type.fullname == "builtins.int" and left.type.fullname in MYPYC_NATIVE_INT_NAMES: + return True + + # Two unrelated types cannot be partially overlapping: they're disjoint. + if left.type.has_base(right.type.fullname): + left = map_instance_to_supertype(left, right.type) + elif right.type.has_base(left.type.fullname): + right = map_instance_to_supertype(right, left.type) + else: + return False + + if right.type.has_type_var_tuple_type: + # Similar to subtyping, we delegate the heavy lifting to the tuple overlap. + assert right.type.type_var_tuple_prefix is not None + assert right.type.type_var_tuple_suffix is not None + prefix = right.type.type_var_tuple_prefix + suffix = right.type.type_var_tuple_suffix + tvt = right.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix( + left.args, prefix, suffix + ) + right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix( + right.args, prefix, suffix + ) + left_args = left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix + right_args = right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix + else: + left_args = left.args + right_args = right.args + if len(left_args) == len(right_args): + # Note: we don't really care about variance here, since the overlapping check + # is symmetric and since we want to return 'True' even for partial overlaps. + # + # For example, suppose we have two types Wrapper[Parent] and Wrapper[Child]. + # It doesn't matter whether Wrapper is covariant or contravariant since + # either way, one of the two types will overlap with the other. + # + # Similarly, if Wrapper was invariant, the two types could still be partially + # overlapping -- what if Wrapper[Parent] happened to contain only instances of + # specifically Child? + # + # Or, to use a more concrete example, List[Union[A, B]] and List[Union[B, C]] + # would be considered partially overlapping since it's possible for both lists + # to contain only instances of B at runtime. + if all( + _is_overlapping_types(left_arg, right_arg) + for left_arg, right_arg in zip(left_args, right_args) + ): + return True + + return False + + # We ought to have handled every case by now: we conclude the + # two types are not overlapping, either completely or partially. + # + # Note: it's unclear however, whether returning False is the right thing + # to do when inferring reachability -- see https://github.com/python/mypy/issues/5529 + + assert type(left) != type(right), f"{type(left)} vs {type(right)}" + return False + + +def is_overlapping_erased_types( + left: Type, right: Type, *, ignore_promotions: bool = False +) -> bool: + """The same as 'is_overlapping_erased_types', except the types are erased first.""" + return is_overlapping_types( + erase_type(left), erase_type(right), ignore_promotions=ignore_promotions + ) + + +def are_typed_dicts_overlapping( + left: TypedDictType, right: TypedDictType, is_overlapping: Callable[[Type, Type], bool] +) -> bool: + """Returns 'true' if left and right are overlapping TypeDictTypes.""" + # All required keys in left are present and overlapping with something in right + for key in left.required_keys: + if key not in right.items: + return False + if not is_overlapping(left.items[key], right.items[key]): + return False + + # Repeat check in the other direction + for key in right.required_keys: + if key not in left.items: + return False + if not is_overlapping(left.items[key], right.items[key]): + return False + + # The presence of any additional optional keys does not affect whether the two + # TypedDicts are partially overlapping: the dicts would be overlapping if the + # keys happened to be missing. + return True + + +def are_tuples_overlapping( + left: Type, right: Type, is_overlapping: Callable[[Type, Type], bool] +) -> bool: + """Returns true if left and right are overlapping tuples.""" + left, right = get_proper_types((left, right)) + left = adjust_tuple(left, right) or left + right = adjust_tuple(right, left) or right + assert isinstance(left, TupleType), f"Type {left} is not a tuple" + assert isinstance(right, TupleType), f"Type {right} is not a tuple" + + # This algorithm works well if only one tuple is variadic, if both are + # variadic we may get rare false negatives for overlapping prefix/suffix. + # Also, this ignores empty unpack case, but it is probably consistent with + # how we handle e.g. empty lists in overload overlaps. + # TODO: write a more robust algorithm for cases where both types are variadic. + left_unpack = find_unpack_in_list(left.items) + right_unpack = find_unpack_in_list(right.items) + if left_unpack is not None: + left = expand_tuple_if_possible(left, len(right.items)) + if right_unpack is not None: + right = expand_tuple_if_possible(right, len(left.items)) + + if len(left.items) != len(right.items): + return False + if not all(is_overlapping(l, r) for l, r in zip(left.items, right.items)): + return False + + # Check that the tuples aren't from e.g. different NamedTuples. + if is_named_instance(right.partial_fallback, "builtins.tuple") or is_named_instance( + left.partial_fallback, "builtins.tuple" + ): + return True + else: + return is_overlapping(left.partial_fallback, right.partial_fallback) + + +def expand_tuple_if_possible(tup: TupleType, target: int) -> TupleType: + if len(tup.items) > target + 1: + return tup + extra = target + 1 - len(tup.items) + new_items = [] + for it in tup.items: + if not isinstance(it, UnpackType): + new_items.append(it) + continue + unpacked = get_proper_type(it.type) + if isinstance(unpacked, TypeVarTupleType): + instance = unpacked.tuple_fallback + else: + # Nested non-variadic tuples should be normalized at this point. + assert isinstance(unpacked, Instance) + instance = unpacked + assert instance.type.fullname == "builtins.tuple" + new_items.extend([instance.args[0]] * extra) + return tup.copy_modified(items=new_items) + + +def adjust_tuple(left: ProperType, r: ProperType) -> TupleType | None: + """Find out if `left` is a Tuple[A, ...], and adjust its length to `right`""" + if isinstance(left, Instance) and left.type.fullname == "builtins.tuple": + n = r.length() if isinstance(r, TupleType) else 1 + return TupleType([left.args[0]] * n, left) + return None + + +def is_tuple(typ: Type) -> bool: + typ = get_proper_type(typ) + return isinstance(typ, TupleType) or ( + isinstance(typ, Instance) and typ.type.fullname == "builtins.tuple" + ) + + +class TypeMeetVisitor(TypeVisitor[ProperType]): + def __init__(self, s: ProperType) -> None: + self.s = s + + def visit_unbound_type(self, t: UnboundType) -> ProperType: + if isinstance(self.s, NoneType): + if state.strict_optional: + return UninhabitedType() + else: + return self.s + elif isinstance(self.s, UninhabitedType): + return self.s + else: + return AnyType(TypeOfAny.special_form) + + def visit_any(self, t: AnyType) -> ProperType: + return self.s + + def visit_union_type(self, t: UnionType) -> ProperType: + if isinstance(self.s, UnionType): + meets: list[Type] = [] + for x in t.items: + for y in self.s.items: + meets.append(meet_types(x, y)) + else: + meets = [meet_types(x, self.s) for x in t.items] + return make_simplified_union(meets) + + def visit_none_type(self, t: NoneType) -> ProperType: + if state.strict_optional: + if isinstance(self.s, NoneType) or ( + isinstance(self.s, Instance) and self.s.type.fullname == "builtins.object" + ): + return t + else: + return UninhabitedType() + else: + return t + + def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType: + return t + + def visit_deleted_type(self, t: DeletedType) -> ProperType: + if isinstance(self.s, NoneType): + if state.strict_optional: + return t + else: + return self.s + elif isinstance(self.s, UninhabitedType): + return self.s + else: + return t + + def visit_erased_type(self, t: ErasedType) -> ProperType: + return self.s + + def visit_type_var(self, t: TypeVarType) -> ProperType: + if isinstance(self.s, TypeVarType) and self.s.id == t.id: + if self.s.upper_bound == t.upper_bound: + return self.s + return self.s.copy_modified(upper_bound=self.meet(self.s.upper_bound, t.upper_bound)) + else: + return self.default(self.s) + + def visit_param_spec(self, t: ParamSpecType) -> ProperType: + if self.s == t: + return self.s + else: + return self.default(self.s) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType: + if isinstance(self.s, TypeVarTupleType) and self.s.id == t.id: + return self.s if self.s.min_len > t.min_len else t + else: + return self.default(self.s) + + def visit_unpack_type(self, t: UnpackType) -> ProperType: + raise NotImplementedError + + def visit_parameters(self, t: Parameters) -> ProperType: + if isinstance(self.s, Parameters): + if len(t.arg_types) != len(self.s.arg_types): + return self.default(self.s) + from mypy.join import join_types + + return t.copy_modified( + arg_types=[join_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types)] + ) + else: + return self.default(self.s) + + def visit_instance(self, t: Instance) -> ProperType: + if isinstance(self.s, Instance): + if t.type == self.s.type: + if is_subtype(t, self.s) or is_subtype(self.s, t): + # Combine type arguments. We could have used join below + # equivalently. + args: list[Type] = [] + # N.B: We use zip instead of indexing because the lengths might have + # mismatches during daemon reprocessing. + if t.type.has_type_var_tuple_type: + # We handle meet of variadic instances by simply creating correct mapping + # for type arguments and compute the individual meets same as for regular + # instances. All the heavy lifting is done in the meet of tuple types. + s = self.s + assert s.type.type_var_tuple_prefix is not None + assert s.type.type_var_tuple_suffix is not None + prefix = s.type.type_var_tuple_prefix + suffix = s.type.type_var_tuple_suffix + tvt = s.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix( + s.args, prefix, suffix + ) + t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix( + t.args, prefix, suffix + ) + s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix + t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix + else: + t_args = t.args + s_args = self.s.args + for ta, sa, tv in zip(t_args, s_args, t.type.defn.type_vars): + meet = self.meet(ta, sa) + if isinstance(tv, TypeVarTupleType): + # Correctly unpack possible outcomes of meets of tuples: it can be + # either another tuple type or Never (normalized as *tuple[Never, ...]) + if isinstance(meet, TupleType): + args.extend(meet.items) + continue + else: + assert isinstance(meet, UninhabitedType) + meet = UnpackType(tv.tuple_fallback.copy_modified(args=[meet])) + args.append(meet) + return Instance(t.type, args) + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + else: + alt_promote = t.type.alt_promote + if alt_promote and alt_promote.type is self.s.type: + return t + alt_promote = self.s.type.alt_promote + if alt_promote and alt_promote.type is t.type: + return self.s + if is_subtype(t, self.s): + return t + elif is_subtype(self.s, t): + # See also above comment. + return self.s + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + elif isinstance(self.s, FunctionLike) and t.type.is_protocol: + call = join.unpack_callback_protocol(t) + if call: + return meet_types(call, self.s) + elif isinstance(self.s, FunctionLike) and self.s.is_type_obj() and t.type.is_metaclass(): + if is_subtype(self.s.fallback, t): + return self.s + return self.default(self.s) + elif isinstance(self.s, TypeType): + return meet_types(t, self.s) + elif isinstance(self.s, TupleType): + return meet_types(t, self.s) + elif isinstance(self.s, LiteralType): + return meet_types(t, self.s) + elif isinstance(self.s, TypedDictType): + return meet_types(t, self.s) + return self.default(self.s) + + def visit_callable_type(self, t: CallableType) -> ProperType: + if isinstance(self.s, CallableType) and join.is_similar_callables(t, self.s): + if is_equivalent(t, self.s): + return join.combine_similar_callables(t, self.s) + result = meet_similar_callables(t, self.s) + # We set the from_type_type flag to suppress error when a collection of + # concrete class objects gets inferred as their common abstract superclass. + if not ( + (t.is_type_obj() and t.type_object().is_abstract) + or (self.s.is_type_obj() and self.s.type_object().is_abstract) + ): + result.from_type_type = True + if isinstance(get_proper_type(result.ret_type), UninhabitedType): + # Return a plain None or instead of a weird function. + return self.default(self.s) + return result + elif isinstance(self.s, TypeType) and t.is_type_obj() and not t.is_generic(): + # In this case we are able to potentially produce a better meet. + res = meet_types(self.s.item, t.ret_type) + if not isinstance(res, (NoneType, UninhabitedType)): + return TypeType.make_normalized(res) + return self.default(self.s) + elif isinstance(self.s, Instance) and self.s.type.is_protocol: + call = join.unpack_callback_protocol(self.s) + if call: + return meet_types(t, call) + return self.default(self.s) + + def visit_overloaded(self, t: Overloaded) -> ProperType: + # TODO: Implement a better algorithm that covers at least the same cases + # as TypeJoinVisitor.visit_overloaded(). + s = self.s + if isinstance(s, FunctionLike): + if s.items == t.items: + return Overloaded(t.items) + elif is_subtype(s, t): + return s + elif is_subtype(t, s): + return t + else: + return meet_types(t.fallback, s.fallback) + elif isinstance(self.s, Instance) and self.s.type.is_protocol: + call = join.unpack_callback_protocol(self.s) + if call: + return meet_types(t, call) + return meet_types(t.fallback, s) + + def meet_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None: + """Meet two tuple types while handling variadic entries. + + This is surprisingly tricky, and we don't handle some tricky corner cases. + Most of the trickiness comes from the variadic tuple items like *tuple[X, ...] + since they can have arbitrary partial overlaps (while *Ts can't be split). This + function is roughly a mirror of join_tuples() w.r.t. to the fact that fixed + tuples are subtypes of variadic ones but not vice versa. + """ + s_unpack_index = find_unpack_in_list(s.items) + t_unpack_index = find_unpack_in_list(t.items) + if s_unpack_index is None and t_unpack_index is None: + if s.length() == t.length(): + items: list[Type] = [] + for i in range(t.length()): + items.append(self.meet(t.items[i], s.items[i])) + return items + return None + if s_unpack_index is not None and t_unpack_index is not None: + # The only simple case we can handle if both tuples are variadic + # is when their structure fully matches. Other cases are tricky because + # a variadic item is effectively a union of tuples of all length, thus + # potentially causing overlap between a suffix in `s` and a prefix + # in `t` (see how this is handled in is_subtype() for details). + # TODO: handle more cases (like when both prefix/suffix are shorter in s or t). + if s.length() == t.length() and s_unpack_index == t_unpack_index: + unpack_index = s_unpack_index + s_unpack = s.items[unpack_index] + assert isinstance(s_unpack, UnpackType) + s_unpacked = get_proper_type(s_unpack.type) + t_unpack = t.items[unpack_index] + assert isinstance(t_unpack, UnpackType) + t_unpacked = get_proper_type(t_unpack.type) + if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)): + return None + meet = self.meet(s_unpacked, t_unpacked) + if not isinstance(meet, Instance): + return None + m_prefix: list[Type] = [] + for si, ti in zip(s.items[:unpack_index], t.items[:unpack_index]): + m_prefix.append(meet_types(si, ti)) + m_suffix: list[Type] = [] + for si, ti in zip(s.items[unpack_index + 1 :], t.items[unpack_index + 1 :]): + m_suffix.append(meet_types(si, ti)) + return m_prefix + [UnpackType(meet)] + m_suffix + return None + if s_unpack_index is not None: + variadic = s + unpack_index = s_unpack_index + fixed = t + else: + assert t_unpack_index is not None + variadic = t + unpack_index = t_unpack_index + fixed = s + # If one tuple is variadic one, and the other one is fixed, the meet will be fixed. + unpack = variadic.items[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + if not isinstance(unpacked, Instance): + return None + if fixed.length() < variadic.length() - 1: + return None + prefix_len = unpack_index + suffix_len = variadic.length() - prefix_len - 1 + prefix, middle, suffix = split_with_prefix_and_suffix( + tuple(fixed.items), prefix_len, suffix_len + ) + items = [] + for fi, vi in zip(prefix, variadic.items[:prefix_len]): + items.append(self.meet(fi, vi)) + for mi in middle: + items.append(self.meet(mi, unpacked.args[0])) + if suffix_len: + for fi, vi in zip(suffix, variadic.items[-suffix_len:]): + items.append(self.meet(fi, vi)) + return items + + def visit_tuple_type(self, t: TupleType) -> ProperType: + if isinstance(self.s, TupleType): + items = self.meet_tuples(self.s, t) + if items is None: + return self.default(self.s) + # TODO: What if the fallbacks are different? + return TupleType(items, tuple_fallback(t)) + elif isinstance(self.s, Instance): + # meet(Tuple[t1, t2, <...>], Tuple[s, ...]) == Tuple[meet(t1, s), meet(t2, s), <...>]. + if self.s.type.fullname in TUPLE_LIKE_INSTANCE_NAMES and self.s.args: + return t.copy_modified(items=[meet_types(it, self.s.args[0]) for it in t.items]) + elif is_proper_subtype(t, self.s): + # A named tuple that inherits from a normal class + return t + elif self.s.type.has_type_var_tuple_type and is_subtype(t, self.s): + # This is a bit ad-hoc but more principled handling is tricky, and this + # special case is important for type narrowing in binder to work. + return t + return self.default(self.s) + + def visit_typeddict_type(self, t: TypedDictType) -> ProperType: + if isinstance(self.s, TypedDictType): + for name, l, r in self.s.zip(t): + if not is_equivalent(l, r) or (name in t.required_keys) != ( + name in self.s.required_keys + ): + return self.default(self.s) + item_list: list[tuple[str, Type]] = [] + for item_name, s_item_type, t_item_type in self.s.zipall(t): + if s_item_type is not None: + item_list.append((item_name, s_item_type)) + else: + # at least one of s_item_type and t_item_type is not None + assert t_item_type is not None + item_list.append((item_name, t_item_type)) + items = dict(item_list) + fallback = self.s.create_anonymous_fallback() + required_keys = t.required_keys | self.s.required_keys + readonly_keys = t.readonly_keys | self.s.readonly_keys + return TypedDictType(items, required_keys, readonly_keys, fallback) + elif isinstance(self.s, Instance) and is_subtype(t, self.s): + return t + else: + return self.default(self.s) + + def visit_literal_type(self, t: LiteralType) -> ProperType: + if isinstance(self.s, LiteralType) and self.s == t: + return t + elif isinstance(self.s, Instance) and is_subtype(t.fallback, self.s): + return t + else: + return self.default(self.s) + + def visit_partial_type(self, t: PartialType) -> ProperType: + # We can't determine the meet of partial types. We should never get here. + assert False, "Internal error" + + def visit_type_type(self, t: TypeType) -> ProperType: + if isinstance(self.s, TypeType): + typ = self.meet(t.item, self.s.item) + if not isinstance(typ, NoneType): + typ = TypeType.make_normalized( + typ, line=t.line, is_type_form=self.s.is_type_form and t.is_type_form + ) + return typ + elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type": + return t + elif isinstance(self.s, CallableType): + return self.meet(t, self.s) + else: + return self.default(self.s) + + def visit_type_alias_type(self, t: TypeAliasType) -> ProperType: + assert False, f"This should be never called, got {t}" + + def meet(self, s: Type, t: Type) -> ProperType: + return meet_types(s, t) + + def default(self, typ: Type) -> ProperType: + if isinstance(typ, UnboundType): + return AnyType(TypeOfAny.special_form) + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + + +def meet_similar_callables(t: CallableType, s: CallableType) -> CallableType: + from mypy.join import match_generic_callables, safe_join + + t, s = match_generic_callables(t, s) + arg_types: list[Type] = [] + for i in range(len(t.arg_types)): + arg_types.append(safe_join(t.arg_types[i], s.arg_types[i])) + # TODO in combine_similar_callables also applies here (names and kinds) + # The fallback type can be either 'function' or 'type'. The result should have 'function' as + # fallback only if both operands have it as 'function'. + if t.fallback.type.fullname != "builtins.function": + fallback = t.fallback + else: + fallback = s.fallback + return t.copy_modified( + arg_types=arg_types, + ret_type=meet_types(t.ret_type, s.ret_type), + fallback=fallback, + name=None, + ) + + +def meet_type_list(types: list[Type]) -> Type: + if not types: + # This should probably be builtins.object but that is hard to get and + # it doesn't matter for any current users. + return AnyType(TypeOfAny.implementation_artifact) + met = types[0] + for t in types[1:]: + met = meet_types(met, t) + return met + + +def typed_dict_mapping_pair(left: Type, right: Type) -> bool: + """Is this a pair where one type is a TypedDict and another one is an instance of Mapping? + + This case requires a precise/principled consideration because there are two use cases + that push the boundary the opposite ways: we need to avoid spurious overlaps to avoid + false positives for overloads, but we also need to avoid spuriously non-overlapping types + to avoid false positives with --strict-equality. + """ + left, right = get_proper_types((left, right)) + assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType) + + if isinstance(left, TypedDictType): + _, other = left, right + elif isinstance(right, TypedDictType): + _, other = right, left + else: + return False + return isinstance(other, Instance) and other.type.has_base("typing.Mapping") + + +def typed_dict_mapping_overlap( + left: Type, right: Type, overlapping: Callable[[Type, Type], bool] +) -> bool: + """Check if a TypedDict type is overlapping with a Mapping. + + The basic logic here consists of two rules: + + * A TypedDict with some required keys is overlapping with Mapping[str, ] + if and only if every key type is overlapping with . For example: + + - TypedDict(x=int, y=str) overlaps with Dict[str, Union[str, int]] + - TypedDict(x=int, y=str) doesn't overlap with Dict[str, int] + + Note that any additional non-required keys can't change the above result. + + * A TypedDict with no required keys overlaps with Mapping[str, ] if and + only if at least one of key types overlaps with . For example: + + - TypedDict(x=str, y=str, total=False) overlaps with Dict[str, str] + - TypedDict(x=str, y=str, total=False) doesn't overlap with Dict[str, int] + - TypedDict(x=int, y=str, total=False) overlaps with Dict[str, str] + + * A TypedDict with at least one ReadOnly[] key does not overlap + with Dict or MutableMapping, because they assume mutable data. + + As usual empty, dictionaries lie in a gray area. In general, List[str] and List[str] + are considered non-overlapping despite empty list belongs to both. However, List[int] + and List[Never] are considered overlapping. + + So here we follow the same logic: a TypedDict with no required keys is considered + non-overlapping with Mapping[str, ], but is considered overlapping with + Mapping[Never, Never]. This way we avoid false positives for overloads, and also + avoid false positives for comparisons like SomeTypedDict == {} under --strict-equality. + """ + left, right = get_proper_types((left, right)) + assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType) + + if isinstance(left, TypedDictType): + assert isinstance(right, Instance) + typed, other = left, right + else: + assert isinstance(left, Instance) + assert isinstance(right, TypedDictType) + typed, other = right, left + + mutable_mapping = next( + (base for base in other.type.mro if base.fullname == "typing.MutableMapping"), None + ) + if mutable_mapping is not None and typed.readonly_keys: + return False + + mapping = next(base for base in other.type.mro if base.fullname == "typing.Mapping") + other = map_instance_to_supertype(other, mapping) + key_type, value_type = get_proper_types(other.args) + + # TODO: is there a cleaner way to get str_type here? + fallback = typed.create_anonymous_fallback() + str_type = fallback.type.bases[0].args[0] # typing._TypedDict inherits Mapping[str, object] + + # Special case: a TypedDict with no required keys overlaps with an empty dict. + if isinstance(key_type, UninhabitedType) and isinstance(value_type, UninhabitedType): + return not typed.required_keys + + if typed.required_keys: + if not overlapping(key_type, str_type): + return False + return all(overlapping(typed.items[k], value_type) for k in typed.required_keys) + else: + if not overlapping(key_type, str_type): + return False + non_required = set(typed.items.keys()) - typed.required_keys + return any(overlapping(typed.items[k], value_type) for k in non_required) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/memprofile.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/memprofile.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..12906dd879e658f2aa6052a7afd4edb45fd85eea Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/memprofile.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/memprofile.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/memprofile.py new file mode 100644 index 0000000000000000000000000000000000000000..4bab4ecb262eec7127f896ccdf977e2c6dfd7d94 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/memprofile.py @@ -0,0 +1,122 @@ +"""Utility for dumping memory usage stats. + +This is tailored to mypy and knows (a little) about which list objects are +owned by particular AST nodes, etc. +""" + +from __future__ import annotations + +import gc +import sys +from collections import defaultdict +from collections.abc import Iterable +from typing import cast + +from mypy.nodes import FakeInfo, Node +from mypy.types import Type +from mypy.util import get_class_descriptors + + +def collect_memory_stats() -> tuple[dict[str, int], dict[str, int]]: + """Return stats about memory use. + + Return a tuple with these items: + - Dict from object kind to number of instances of that kind + - Dict from object kind to total bytes used by all instances of that kind + """ + objs = gc.get_objects() + find_recursive_objects(objs) + + inferred = {} + for obj in objs: + if type(obj) is FakeInfo: + # Processing these would cause a crash. + continue + n = type(obj).__name__ + if hasattr(obj, "__dict__"): + # Keep track of which class a particular __dict__ is associated with. + inferred[id(obj.__dict__)] = f"{n} (__dict__)" + if isinstance(obj, (Node, Type)): # type: ignore[misc] + if hasattr(obj, "__dict__"): + for x in obj.__dict__.values(): + if isinstance(x, list): + # Keep track of which node a list is associated with. + inferred[id(x)] = f"{n} (list)" + if isinstance(x, tuple): + # Keep track of which node a list is associated with. + inferred[id(x)] = f"{n} (tuple)" + + for k in get_class_descriptors(type(obj)): + x = getattr(obj, k, None) + if isinstance(x, list): + inferred[id(x)] = f"{n} (list)" + if isinstance(x, tuple): + inferred[id(x)] = f"{n} (tuple)" + + freqs: dict[str, int] = {} + memuse: dict[str, int] = {} + for obj in objs: + if id(obj) in inferred: + name = inferred[id(obj)] + else: + name = type(obj).__name__ + freqs[name] = freqs.get(name, 0) + 1 + memuse[name] = memuse.get(name, 0) + sys.getsizeof(obj) + + return freqs, memuse + + +def print_memory_profile(run_gc: bool = True) -> None: + if not sys.platform.startswith("win"): + import resource + + system_memuse = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + else: + system_memuse = -1 # TODO: Support this on Windows + if run_gc: + gc.collect() + freqs, memuse = collect_memory_stats() + print("%7s %7s %7s %s" % ("Freq", "Size(k)", "AvgSize", "Type")) + print("-------------------------------------------") + totalmem = 0 + i = 0 + for n, mem in sorted(memuse.items(), key=lambda x: -x[1]): + f = freqs[n] + if i < 50: + print("%7d %7d %7.0f %s" % (f, mem // 1024, mem / f, n)) + i += 1 + totalmem += mem + print() + print("Mem usage RSS ", system_memuse // 1024) + print("Total reachable ", totalmem // 1024) + + +def find_recursive_objects(objs: list[object]) -> None: + """Find additional objects referenced by objs and append them to objs. + + We use this since gc.get_objects() does not return objects without pointers + in them such as strings. + """ + seen = {id(o) for o in objs} + + def visit(o: object) -> None: + if id(o) not in seen: + objs.append(o) + seen.add(id(o)) + + for obj in objs.copy(): + if type(obj) is FakeInfo: + # Processing these would cause a crash. + continue + if type(obj) in (dict, defaultdict): + for key, val in cast(dict[object, object], obj).items(): + visit(key) + visit(val) + if type(obj) in (list, tuple, set): + for x in cast(Iterable[object], obj): + visit(x) + if hasattr(obj, "__slots__"): + for base in type.mro(type(obj)): + for slot in getattr(base, "__slots__", ()): + if hasattr(obj, slot): + visit(getattr(obj, slot)) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/message_registry.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/message_registry.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..807e7e8492c42f375a39e81e4be582185486522f Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/message_registry.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/message_registry.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/message_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..8140e28e16d7a21aed7482fe22e0ae5313929632 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/message_registry.py @@ -0,0 +1,376 @@ +"""Message constants for generating error messages during type checking. + +Literal messages should be defined as constants in this module so they won't get out of sync +if used in more than one place, and so that they can be easily introspected. These messages are +ultimately consumed by messages.MessageBuilder.fail(). For more non-trivial message generation, +add a method to MessageBuilder and call this instead. +""" + +from __future__ import annotations + +from typing import Final, NamedTuple + +from mypy import errorcodes as codes +from mypy.errorcodes import ErrorCode + + +class ErrorMessage(NamedTuple): + value: str + code: ErrorCode | None = None + + def format(self, *args: object, **kwargs: object) -> ErrorMessage: + return ErrorMessage(self.value.format(*args, **kwargs), code=self.code) + + def with_additional_msg(self, info: str) -> ErrorMessage: + return ErrorMessage(self.value + info, code=self.code) + + +# Invalid types +INVALID_TYPE_RAW_ENUM_VALUE: Final = ErrorMessage( + "Invalid type: try using Literal[{}.{}] instead?", codes.VALID_TYPE +) + +# Type checker error message constants +NO_RETURN_VALUE_EXPECTED: Final = ErrorMessage("No return value expected", codes.RETURN_VALUE) +MISSING_RETURN_STATEMENT: Final = ErrorMessage("Missing return statement", codes.RETURN) +EMPTY_BODY_ABSTRACT: Final = ErrorMessage( + "If the method is meant to be abstract, use @abc.abstractmethod", codes.EMPTY_BODY +) +INVALID_IMPLICIT_RETURN: Final = ErrorMessage("Implicit return in function which does not return") +INCOMPATIBLE_RETURN_VALUE_TYPE: Final = ErrorMessage( + "Incompatible return value type", codes.RETURN_VALUE +) +RETURN_VALUE_EXPECTED: Final = ErrorMessage("Return value expected", codes.RETURN_VALUE) +NO_RETURN_EXPECTED: Final = ErrorMessage("Return statement in function which does not return") +INVALID_EXCEPTION: Final = ErrorMessage("Exception must be derived from BaseException") +INVALID_EXCEPTION_TYPE: Final = ErrorMessage( + "Exception type must be derived from BaseException (or be a tuple of exception classes)" +) +INVALID_EXCEPTION_GROUP: Final = ErrorMessage( + "Exception type in except* cannot derive from BaseExceptionGroup" +) +RETURN_IN_ASYNC_GENERATOR: Final = ErrorMessage( + '"return" with value in async generator is not allowed' +) +INVALID_RETURN_TYPE_FOR_GENERATOR: Final = ErrorMessage( + 'The return type of a generator function should be "Generator" or one of its supertypes' +) +INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR: Final = ErrorMessage( + 'The return type of an async generator function should be "AsyncGenerator" or one of its ' + "supertypes" +) +YIELD_VALUE_EXPECTED: Final = ErrorMessage("Yield value expected") +INCOMPATIBLE_TYPES: Final = ErrorMessage("Incompatible types") +INCOMPATIBLE_TYPES_IN_ASSIGNMENT: Final = ErrorMessage( + "Incompatible types in assignment", code=codes.ASSIGNMENT +) +COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE: Final = ErrorMessage( + "Covariant override of a mutable attribute", code=codes.MUTABLE_OVERRIDE +) +INCOMPATIBLE_TYPES_IN_AWAIT: Final = ErrorMessage('Incompatible types in "await"') +INCOMPATIBLE_REDEFINITION: Final = ErrorMessage("Incompatible redefinition") +INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER: Final = ( + 'Incompatible types in "async with" for "__aenter__"' +) +INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT: Final = ( + 'Incompatible types in "async with" for "__aexit__"' +) +INCOMPATIBLE_TYPES_IN_ASYNC_FOR: Final = 'Incompatible types in "async for"' +INVALID_TYPE_FOR_SLOTS: Final = 'Invalid type for "__slots__"' + +ASYNC_FOR_OUTSIDE_COROUTINE: Final = '"async for" outside async function' +ASYNC_WITH_OUTSIDE_COROUTINE: Final = '"async with" outside async function' + +INCOMPATIBLE_TYPES_IN_YIELD: Final = ErrorMessage('Incompatible types in "yield"') +INCOMPATIBLE_TYPES_IN_YIELD_FROM: Final = ErrorMessage('Incompatible types in "yield from"') +INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION: Final = "Incompatible types in string interpolation" +INCOMPATIBLE_TYPES_IN_CAPTURE: Final = ErrorMessage("Incompatible types in capture pattern") +MUST_HAVE_NONE_RETURN_TYPE: Final = ErrorMessage('The return type of "{}" must be None') +TUPLE_INDEX_OUT_OF_RANGE: Final = ErrorMessage("Tuple index out of range") +AMBIGUOUS_SLICE_OF_VARIADIC_TUPLE: Final = ErrorMessage("Ambiguous slice of a variadic tuple") +TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK: Final = ErrorMessage( + "Too many assignment targets for variadic unpack" +) +INVALID_SLICE_INDEX: Final = ErrorMessage("Slice index must be an integer, SupportsIndex or None") +CANNOT_INFER_LAMBDA_TYPE: Final = ErrorMessage("Cannot infer type of lambda") +CANNOT_ACCESS_INIT: Final = ( + 'Accessing "__init__" on an instance is unsound, since instance.__init__ could be from' + " an incompatible subclass" +) +NON_INSTANCE_NEW_TYPE: Final = ErrorMessage('"__new__" must return a class instance (got {})') +INVALID_NEW_TYPE: Final = ErrorMessage('Incompatible return type for "__new__"') +BAD_CONSTRUCTOR_TYPE: Final = ErrorMessage("Unsupported decorated constructor type") +CANNOT_ASSIGN_TO_METHOD: Final = "Cannot assign to a method" +CANNOT_ASSIGN_TO_TYPE: Final = "Cannot assign to a type" +INCONSISTENT_ABSTRACT_OVERLOAD: Final = ErrorMessage( + "Overloaded method has both abstract and non-abstract variants" +) +MULTIPLE_OVERLOADS_REQUIRED: Final = ErrorMessage("Single overload definition, multiple required") +READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE: Final = ErrorMessage( + "Read-only property cannot override read-write property" +) +FORMAT_REQUIRES_MAPPING: Final = "Format requires a mapping" +RETURN_TYPE_CANNOT_BE_CONTRAVARIANT: Final = ErrorMessage( + "Cannot use a contravariant type variable as return type" +) +FUNCTION_PARAMETER_CANNOT_BE_COVARIANT: Final = ErrorMessage( + "Cannot use a covariant type variable as a parameter" +) +INCOMPATIBLE_IMPORT_OF: Final = ErrorMessage('Incompatible import of "{}"', code=codes.ASSIGNMENT) +FUNCTION_TYPE_EXPECTED: Final = ErrorMessage( + "Function is missing a type annotation", codes.NO_UNTYPED_DEF +) +ONLY_CLASS_APPLICATION: Final = ErrorMessage( + "Type application is only supported for generic classes" +) +RETURN_TYPE_EXPECTED: Final = ErrorMessage( + "Function is missing a return type annotation", codes.NO_UNTYPED_DEF +) +PARAM_TYPE_EXPECTED: Final = ErrorMessage( + "Function is missing a type annotation for one or more parameters", codes.NO_UNTYPED_DEF +) +KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE: Final = ErrorMessage( + 'Keyword argument only valid with "str" key type in call to "dict"' +) +ALL_MUST_BE_SEQ_STR: Final = ErrorMessage("Type of __all__ must be {}, not {}") +INVALID_TYPEDDICT_ARGS: Final = ErrorMessage( + "Expected keyword arguments, {...}, or dict(...) in TypedDict constructor" +) +TYPEDDICT_KEY_MUST_BE_STRING_LITERAL: Final = ErrorMessage( + "Expected TypedDict key to be string literal" +) +TYPEDDICT_OVERRIDE_MERGE: Final = 'Overwriting TypedDict field "{}" while merging' +MALFORMED_ASSERT: Final = ErrorMessage("Assertion is always true, perhaps remove parentheses?") +DUPLICATE_TYPE_SIGNATURES: Final = ErrorMessage("Function has duplicate type signatures") +DESCRIPTOR_SET_NOT_CALLABLE: Final = ErrorMessage("{}.__set__ is not callable") +DESCRIPTOR_GET_NOT_CALLABLE: Final = "{}.__get__ is not callable" +MODULE_LEVEL_GETATTRIBUTE: Final = ErrorMessage( + "__getattribute__ is not valid at the module level" +) +CLASS_VAR_CONFLICTS_SLOTS: Final = '"{}" in __slots__ conflicts with class variable access' +NAME_NOT_IN_SLOTS: Final = ErrorMessage( + 'Trying to assign name "{}" that is not in "__slots__" of type "{}"' +) +TYPE_ALWAYS_TRUE: Final = ErrorMessage( + "{} which does not implement __bool__ or __len__ " + "so it could always be true in boolean context", + code=codes.TRUTHY_BOOL, +) +TYPE_ALWAYS_TRUE_UNIONTYPE: Final = ErrorMessage( + "{} of which no members implement __bool__ or __len__ " + "so it could always be true in boolean context", + code=codes.TRUTHY_BOOL, +) +FUNCTION_ALWAYS_TRUE: Final = ErrorMessage( + "Function {} could always be true in boolean context", code=codes.TRUTHY_FUNCTION +) +ITERABLE_ALWAYS_TRUE: Final = ErrorMessage( + "{} which can always be true in boolean context. Consider using {} instead.", + code=codes.TRUTHY_ITERABLE, +) +NOT_CALLABLE: Final = "{} not callable" +TYPE_MUST_BE_USED: Final = "Value of type {} must be used" + +# Generic +GENERIC_INSTANCE_VAR_CLASS_ACCESS: Final = ( + "Access to generic instance variables via class is ambiguous" +) +GENERIC_CLASS_VAR_ACCESS: Final = "Access to generic class variables is ambiguous" +BARE_GENERIC: Final = "Missing type arguments for generic type {}" +IMPLICIT_GENERIC_ANY_BUILTIN: Final = ( + 'Implicit generic "Any". Use "{}" and specify generic parameters' +) +INVALID_UNPACK: Final = "{} cannot be unpacked (must be tuple or TypeVarTuple)" +INVALID_UNPACK_POSITION: Final = "Unpack is only valid in a variadic position" +INVALID_PARAM_SPEC_LOCATION: Final = "Invalid location for ParamSpec {}" +INVALID_PARAM_SPEC_LOCATION_NOTE: Final = ( + 'You can use ParamSpec as the first argument to Callable, e.g., "Callable[{}, int]"' +) + +# TypeVar +INCOMPATIBLE_TYPEVAR_VALUE: Final = 'Value of type variable "{}" of {} cannot be {}' +INVALID_TYPEVAR_AS_TYPEARG: Final = 'Type variable "{}" not valid as type argument value for "{}"' +INVALID_TYPEVAR_ARG_BOUND: Final = 'Type argument {} of "{}" must be a subtype of {}' +INVALID_TYPEVAR_ARG_VALUE: Final = 'Invalid type argument value for "{}"' +TYPEVAR_VARIANCE_DEF: Final = 'TypeVar "{}" may only be a literal bool' +TYPEVAR_ARG_MUST_BE_TYPE: Final = '{} "{}" must be a type' +TYPEVAR_UNEXPECTED_ARGUMENT: Final = 'Unexpected argument to "TypeVar()"' +UNBOUND_TYPEVAR: Final = ( + "A function returning TypeVar should receive at least one argument containing the same TypeVar" +) +TYPE_PARAMETERS_SHOULD_BE_DECLARED: Final = ( + "All type parameters should be declared ({} not declared)" +) + +# Super +TOO_MANY_ARGS_FOR_SUPER: Final = ErrorMessage('Too many arguments for "super"') +SUPER_WITH_SINGLE_ARG_NOT_SUPPORTED: Final = ErrorMessage( + '"super" with a single argument not supported' +) +UNSUPPORTED_ARG_1_FOR_SUPER: Final = ErrorMessage('Unsupported argument 1 for "super"') +UNSUPPORTED_ARG_2_FOR_SUPER: Final = ErrorMessage('Unsupported argument 2 for "super"') +SUPER_VARARGS_NOT_SUPPORTED: Final = ErrorMessage('Varargs not supported with "super"') +SUPER_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage('"super" only accepts positional arguments') +SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1: Final = ErrorMessage( + 'Argument 2 for "super" not an instance of argument 1' +) +TARGET_CLASS_HAS_NO_BASE_CLASS: Final = ErrorMessage("Target class has no base class") +SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED: Final = ErrorMessage( + '"super()" outside of a method is not supported' +) +SUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage( + '"super()" requires one or two positional arguments in enclosing function' +) + +# Self-type +MISSING_OR_INVALID_SELF_TYPE: Final = ErrorMessage( + '"self" parameter missing for a non-static method (or an invalid type for self)' +) +ERASED_SELF_TYPE_NOT_SUPERTYPE: Final = ErrorMessage( + 'The erased type of self "{}" is not a supertype of its class "{}"' +) + +# Final +CANNOT_INHERIT_FROM_FINAL: Final = ErrorMessage('Cannot inherit from final class "{}"') +DEPENDENT_FINAL_IN_CLASS_BODY: Final = ErrorMessage( + "Final name declared in class body cannot depend on type variables" +) +CANNOT_ACCESS_FINAL_INSTANCE_ATTR: Final = ( + 'Cannot access final instance attribute "{}" on class object' +) +CANNOT_ACCESS_INSTANCE_ONLY_ATTR: Final = ( + 'Cannot access instance-only attribute "{}" on class object' +) +CANNOT_MAKE_DELETABLE_FINAL: Final = ErrorMessage("Deletable attribute cannot be final") + +# Disjoint bases +INCOMPATIBLE_DISJOINT_BASES: Final = ErrorMessage('Class "{}" has incompatible disjoint bases') + +# Enum +ENUM_MEMBERS_ATTR_WILL_BE_OVERRIDDEN: Final = ErrorMessage( + 'Assigned "__members__" will be overridden by "Enum" internally' +) + +# ClassVar +CANNOT_OVERRIDE_INSTANCE_VAR: Final = ErrorMessage( + 'Cannot override instance variable (previously declared on base class "{}") with class ' + "variable" +) +CANNOT_OVERRIDE_CLASS_VAR: Final = ErrorMessage( + 'Cannot override class variable (previously declared on base class "{}") with instance ' + "variable" +) +CLASS_VAR_WITH_GENERIC_SELF: Final = "ClassVar cannot contain Self type in generic classes" +CLASS_VAR_OUTSIDE_OF_CLASS: Final = "ClassVar can only be used for assignments in class body" + +# Protocol +RUNTIME_PROTOCOL_EXPECTED: Final = ErrorMessage( + "Only @runtime_checkable protocols can be used with instance and class checks" +) +CANNOT_INSTANTIATE_PROTOCOL: Final = ErrorMessage('Cannot instantiate protocol class "{}"') +TOO_MANY_UNION_COMBINATIONS: Final = ErrorMessage( + "Not all union combinations were tried because there are too many unions" +) + +CONTIGUOUS_ITERABLE_EXPECTED: Final = ErrorMessage("Contiguous iterable with same type expected") +ITERABLE_TYPE_EXPECTED: Final = ErrorMessage("Invalid type '{}' for *expr (iterable expected)") +TYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage("Type {} requires positional argument") + +# Match Statement +MISSING_MATCH_ARGS: Final = 'Class "{}" doesn\'t define "__match_args__"' +OR_PATTERN_ALTERNATIVE_NAMES: Final = "Alternative patterns bind different names" +CLASS_PATTERN_GENERIC_TYPE_ALIAS: Final = ( + "Class pattern class must not be a type alias with type parameters" +) +CLASS_PATTERN_TYPE_REQUIRED: Final = 'Expected type in class pattern; found "{}"' +CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS: Final = "Too many positional patterns for class pattern" +CLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL: Final = ( + 'Keyword "{}" already matches a positional pattern' +) +CLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN: Final = 'Duplicate keyword pattern "{}"' +CLASS_PATTERN_UNKNOWN_KEYWORD: Final = 'Class "{}" has no attribute "{}"' +CLASS_PATTERN_CLASS_OR_STATIC_METHOD: Final = "Cannot have both classmethod and staticmethod" +MULTIPLE_ASSIGNMENTS_IN_PATTERN: Final = 'Multiple assignments to name "{}" in pattern' +CANNOT_MODIFY_MATCH_ARGS: Final = 'Cannot assign to "__match_args__"' + +DATACLASS_FIELD_ALIAS_MUST_BE_LITERAL: Final = ( + '"alias" argument to dataclass field must be a string literal' +) +DATACLASS_POST_INIT_MUST_BE_A_FUNCTION: Final = '"__post_init__" method must be an instance method' + +# fastparse +FAILED_TO_MERGE_OVERLOADS: Final = ErrorMessage( + "Condition can't be inferred, unable to merge overloads" +) +TYPE_IGNORE_WITH_ERRCODE_ON_MODULE: Final = ErrorMessage( + "Type ignore with error code is not supported for modules; " + 'use `# mypy: disable-error-code="{}"`', + codes.SYNTAX, +) +INVALID_TYPE_IGNORE: Final = ErrorMessage('Invalid "type: ignore" comment', codes.SYNTAX) +TYPE_COMMENT_SYNTAX_ERROR_VALUE: Final = ErrorMessage( + 'Syntax error in type comment "{}"', codes.SYNTAX +) +ELLIPSIS_WITH_OTHER_TYPEPARAMS: Final = ErrorMessage( + "Ellipses cannot accompany other parameter types in function type signature", codes.SYNTAX +) +TYPE_SIGNATURE_TOO_MANY_PARAMS: Final = ErrorMessage( + "Type signature has too many parameters", codes.SYNTAX +) +TYPE_SIGNATURE_TOO_FEW_PARAMS: Final = ErrorMessage( + "Type signature has too few parameters", codes.SYNTAX +) +ARG_CONSTRUCTOR_NAME_EXPECTED: Final = ErrorMessage("Expected arg constructor name", codes.SYNTAX) +ARG_CONSTRUCTOR_TOO_MANY_ARGS: Final = ErrorMessage( + "Too many arguments for argument constructor", codes.SYNTAX +) +MULTIPLE_VALUES_FOR_NAME_KWARG: Final = ErrorMessage( + '"{}" gets multiple values for keyword argument "name"', codes.SYNTAX +) +MULTIPLE_VALUES_FOR_TYPE_KWARG: Final = ErrorMessage( + '"{}" gets multiple values for keyword argument "type"', codes.SYNTAX +) +ARG_CONSTRUCTOR_UNEXPECTED_ARG: Final = ErrorMessage( + 'Unexpected argument "{}" for argument constructor', codes.SYNTAX +) +ARG_NAME_EXPECTED_STRING_LITERAL: Final = ErrorMessage( + "Expected string literal for argument name, got {}", codes.SYNTAX +) +NARROWED_TYPE_NOT_SUBTYPE: Final = ErrorMessage( + "Narrowed type {} is not a subtype of input type {}", codes.NARROWED_TYPE_NOT_SUBTYPE +) +TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES: Final = ErrorMessage( + "Type variable must have at least two constrained types", codes.MISC +) + +TYPE_VAR_YIELD_EXPRESSION_IN_BOUND: Final = ErrorMessage( + "Yield expression cannot be used as a type variable bound", codes.SYNTAX +) + +TYPE_VAR_NAMED_EXPRESSION_IN_BOUND: Final = ErrorMessage( + "Named expression cannot be used as a type variable bound", codes.SYNTAX +) + +TYPE_VAR_AWAIT_EXPRESSION_IN_BOUND: Final = ErrorMessage( + "Await expression cannot be used as a type variable bound", codes.SYNTAX +) + +TYPE_VAR_GENERIC_CONSTRAINT_TYPE: Final = ErrorMessage( + "TypeVar constraint type cannot be parametrized by type variables", codes.MISC +) + +TYPE_VAR_REDECLARED_IN_NESTED_CLASS: Final = ErrorMessage( + 'Type variable "{}" is bound by an outer class', codes.VALID_TYPE +) + +TYPE_ALIAS_WITH_YIELD_EXPRESSION: Final = ErrorMessage( + "Yield expression cannot be used within a type alias", codes.SYNTAX +) + +TYPE_ALIAS_WITH_NAMED_EXPRESSION: Final = ErrorMessage( + "Named expression cannot be used within a type alias", codes.SYNTAX +) + +TYPE_ALIAS_WITH_AWAIT_EXPRESSION: Final = ErrorMessage( + "Await expression cannot be used within a type alias", codes.SYNTAX +) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/messages.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/messages.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e2e629ee755f1f511c3c1ad36b414cd3256834d4 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/messages.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/messages.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..51bb0b7ee9be62e0208540dedb30992d89bbcce1 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/messages.py @@ -0,0 +1,3427 @@ +"""Facilities for generating error messages during type checking. + +Don't add any non-trivial message construction logic to the type +checker, as it can compromise clarity and make messages less +consistent. Add such logic to this module instead. Literal messages, including those +with format args, should be defined as constants in mypy.message_registry. + +Historically we tried to avoid all message string literals in the type +checker but we are moving away from this convention. +""" + +from __future__ import annotations + +import difflib +import itertools +import re +from collections.abc import Callable, Collection, Iterable, Iterator, Sequence +from contextlib import contextmanager +from textwrap import dedent +from typing import Any, Final, cast + +import mypy.typeops +from mypy import errorcodes as codes, message_registry +from mypy.erasetype import erase_type +from mypy.errorcodes import ErrorCode +from mypy.errors import ( + ErrorInfo, + Errors, + ErrorWatcher, + IterationDependentErrors, + IterationErrorWatcher, + NonOverlapErrorInfo, +) +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR, + ARG_STAR2, + CONTRAVARIANT, + COVARIANT, + SYMBOL_FUNCBASE_TYPES, + ArgKind, + CallExpr, + Context, + Expression, + FuncDef, + IndexExpr, + MypyFile, + NameExpr, + ReturnStmt, + StrExpr, + SymbolNode, + SymbolTable, + TypeInfo, + Var, + get_func_def, + reverse_builtin_aliases, +) +from mypy.operators import op_methods, op_methods_to_symbols +from mypy.options import Options +from mypy.subtypes import ( + IS_CLASS_OR_STATIC, + IS_CLASSVAR, + IS_EXPLICIT_SETTER, + IS_SETTABLE, + IS_VAR, + find_member, + get_member_flags, + is_same_type, + is_subtype, +) +from mypy.typeops import separate_union_literals +from mypy.types import ( + AnyType, + CallableType, + DeletedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeStrVisitor, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + get_proper_types, +) +from mypy.typetraverser import TypeTraverserVisitor +from mypy.util import plural_s, unmangle + +TYPES_FOR_UNIMPORTED_HINTS: Final = { + "typing.Any", + "typing.Callable", + "typing.Dict", + "typing.Iterable", + "typing.Iterator", + "typing.List", + "typing.Optional", + "typing.Set", + "typing.Tuple", + "typing.TypeVar", + "typing.Union", + "typing.cast", +} + + +ARG_CONSTRUCTOR_NAMES: Final = { + ARG_POS: "Arg", + ARG_OPT: "DefaultArg", + ARG_NAMED: "NamedArg", + ARG_NAMED_OPT: "DefaultNamedArg", + ARG_STAR: "VarArg", + ARG_STAR2: "KwArg", +} + + +# Map from the full name of a missing definition to the test fixture (under +# test-data/unit/fixtures/) that provides the definition. This is used for +# generating better error messages when running mypy tests only. +SUGGESTED_TEST_FIXTURES: Final = { + "builtins.set": "set.pyi", + "builtins.tuple": "tuple.pyi", + "builtins.bool": "bool.pyi", + "builtins.Exception": "exception.pyi", + "builtins.BaseException": "exception.pyi", + "builtins.isinstance": "isinstancelist.pyi", + "builtins.property": "property.pyi", + "builtins.classmethod": "classmethod.pyi", + "typing._SpecialForm": "typing-medium.pyi", +} + +UNSUPPORTED_NUMBERS_TYPES: Final = { + "numbers.Number", + "numbers.Complex", + "numbers.Real", + "numbers.Rational", + "numbers.Integral", +} + +MAX_TUPLE_ITEMS = 10 +MAX_UNION_ITEMS = 10 + + +class MessageBuilder: + """Helper class for reporting type checker error messages with parameters. + + The methods of this class need to be provided with the context within a + file; the errors member manages the wider context. + + IDEA: Support a 'verbose mode' that includes full information about types + in error messages and that may otherwise produce more detailed error + messages. + """ + + # Report errors using this instance. It knows about the current file and + # import context. + errors: Errors + + modules: dict[str, MypyFile] + + # Hack to deduplicate error messages from union types + _disable_type_names: list[bool] + + def __init__(self, errors: Errors, modules: dict[str, MypyFile]) -> None: + self.errors = errors + self.options = errors.options + self.modules = modules + self._disable_type_names = [] + + # + # Helpers + # + + def filter_errors( + self, + *, + filter_errors: bool | Callable[[str, ErrorInfo], bool] = True, + save_filtered_errors: bool = False, + filter_deprecated: bool = False, + filter_revealed_type: bool = False, + ) -> ErrorWatcher: + return ErrorWatcher( + self.errors, + filter_errors=filter_errors, + save_filtered_errors=save_filtered_errors, + filter_deprecated=filter_deprecated, + filter_revealed_type=filter_revealed_type, + ) + + def add_errors(self, errors: list[ErrorInfo]) -> None: + """Add errors in messages to this builder.""" + for info in errors: + self.errors.add_error_info(info) + + @contextmanager + def disable_type_names(self) -> Iterator[None]: + self._disable_type_names.append(True) + try: + yield + finally: + self._disable_type_names.pop() + + def are_type_names_disabled(self) -> bool: + return len(self._disable_type_names) > 0 and self._disable_type_names[-1] + + def prefer_simple_messages(self) -> bool: + """Should we generate simple/fast error messages? + + If errors aren't shown to the user, we don't want to waste cycles producing + complex error messages. + """ + return self.errors.prefer_simple_messages() + + def span_from_context(self, ctx: Context) -> Iterable[int]: + """This determines where a type: ignore for a given context has effect.""" + if not isinstance(ctx, Expression): + return [ctx.line] + return range(ctx.line, (ctx.end_line or ctx.line) + 1) + + def report( + self, + msg: str, + context: Context, + severity: str, + offset: int = 0, + *, + code: ErrorCode | None = None, + origin_context: Context | None, + parent_error: ErrorInfo | None = None, + ) -> ErrorInfo: + """Report an error or note (unless disabled). + + Note that context controls where error is reported, while origin_context + controls where # type: ignore comments have effect. + """ + + origin_span = self.span_from_context(context) + if origin_context is not None: + origin_span = itertools.chain(origin_span, self.span_from_context(origin_context)) + + return self.errors.report( + context.line if context else -1, + context.column if context else -1, + msg, + code=code, + severity=severity, + offset=offset, + origin_span=origin_span, + end_line=context.end_line if context else -1, + end_column=context.end_column if context else -1, + parent_error=parent_error, + ) + + def fail( + self, + msg: str, + context: Context, + *, + code: ErrorCode | None = None, + origin_context: Context | None = None, + ) -> ErrorInfo: + """Report an error message (unless disabled).""" + return self.report(msg, context, "error", code=code, origin_context=origin_context) + + def note( + self, + msg: str, + context: Context, + offset: int = 0, + *, + code: ErrorCode | None = None, + origin_context: Context | None = None, + parent_error: ErrorInfo | None = None, + ) -> None: + """Report a note (unless disabled).""" + self.report( + msg, + context, + "note", + offset=offset, + code=code, + origin_context=origin_context, + parent_error=parent_error, + ) + + def note_multiline( + self, + messages: str, + context: Context, + offset: int = 0, + *, + code: ErrorCode | None = None, + origin_context: Context | None = None, + parent_error: ErrorInfo | None = None, + ) -> None: + """Report as many notes as lines in the message (unless disabled).""" + for msg in dedent(messages.lstrip("\n")).splitlines(): + self.report( + msg, + context, + "note", + offset, + code=code, + origin_context=origin_context, + parent_error=parent_error, + ) + + # + # Specific operations + # + + # The following operations are for generating specific error messages. They + # get some information as arguments, and they build an error message based + # on them. + + def has_no_attr( + self, + original_type: Type, + typ: Type, + member: str, + context: Context, + module_symbol_table: SymbolTable | None = None, + ) -> ErrorCode | None: + """Report a missing or non-accessible member. + + original_type is the top-level type on which the error occurred. + typ is the actual type that is missing the member. These can be + different, e.g., in a union, original_type will be the union and typ + will be the specific item in the union that does not have the member + attribute. + + 'module_symbol_table' is passed to this function if the type for which we + are trying to get a member was originally a module. The SymbolTable allows + us to look up and suggests attributes of the module since they are not + directly available on original_type + + If member corresponds to an operator, use the corresponding operator + name in the messages. Return the error code that was produced, if any. + """ + original_type = get_proper_type(original_type) + typ = get_proper_type(typ) + + if isinstance(original_type, Instance) and original_type.type.has_readable_member(member): + self.fail(f'Member "{member}" is not assignable', context) + return None + elif member == "__contains__": + self.fail( + f"Unsupported right operand type for in ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member in op_methods.values(): + # Access to a binary operator member (e.g. _add). This case does + # not handle indexing operations. + for op, method in op_methods.items(): + if method == member: + self.unsupported_left_operand(op, original_type, context) + return codes.OPERATOR + elif member == "__neg__": + self.fail( + f"Unsupported operand type for unary - ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member == "__pos__": + self.fail( + f"Unsupported operand type for unary + ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member == "__invert__": + self.fail( + f"Unsupported operand type for ~ ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member == "__getitem__": + # Indexed get. + # TODO: Fix this consistently in format_type + if isinstance(original_type, FunctionLike) and original_type.is_type_obj(): + self.fail( + "The type {} is not generic and not indexable".format( + format_type(original_type, self.options) + ), + context, + ) + return None + else: + self.fail( + f"Value of type {format_type(original_type, self.options)} is not indexable", + context, + code=codes.INDEX, + ) + return codes.INDEX + elif member == "__setitem__": + # Indexed set. + self.fail( + "Unsupported target for indexed assignment ({})".format( + format_type(original_type, self.options) + ), + context, + code=codes.INDEX, + ) + return codes.INDEX + elif member == "__call__": + if isinstance(original_type, Instance) and ( + original_type.type.fullname == "builtins.function" + ): + # "'function' not callable" is a confusing error message. + # Explain that the problem is that the type of the function is not known. + self.fail("Cannot call function of unknown type", context, code=codes.OPERATOR) + return codes.OPERATOR + else: + self.fail( + message_registry.NOT_CALLABLE.format(format_type(original_type, self.options)), + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + else: + # The non-special case: a missing ordinary attribute. + extra = "" + if member == "__iter__": + extra = " (not iterable)" + elif member == "__aiter__": + extra = " (not async iterable)" + if not self.are_type_names_disabled(): + failed = False + if isinstance(original_type, Instance) and original_type.type.names: + if ( + module_symbol_table is not None + and member in module_symbol_table + and not module_symbol_table[member].module_public + ): + self.fail( + f"{format_type(original_type, self.options, module_names=True)} does not " + f'explicitly export attribute "{member}"', + context, + code=codes.ATTR_DEFINED, + ) + failed = True + else: + alternatives = set(original_type.type.names.keys()) + if module_symbol_table is not None: + alternatives |= { + k for k, v in module_symbol_table.items() if v.module_public + } + # Rare but possible, see e.g. testNewAnalyzerCyclicDefinitionCrossModule + alternatives.discard(member) + + matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives] + matches.extend(best_matches(member, alternatives, n=3)) + if member == "__aiter__" and matches == ["__iter__"]: + matches = [] # Avoid misleading suggestion + if matches: + self.fail( + '{} has no attribute "{}"; maybe {}?{}'.format( + format_type(original_type, self.options), + member, + pretty_seq(matches, "or"), + extra, + ), + context, + code=codes.ATTR_DEFINED, + ) + failed = True + if not failed: + self.fail( + '{} has no attribute "{}"{}'.format( + format_type(original_type, self.options), member, extra + ), + context, + code=codes.ATTR_DEFINED, + ) + return codes.ATTR_DEFINED + elif isinstance(original_type, UnionType): + # The checker passes "object" in lieu of "None" for attribute + # checks, so we manually convert it back. + typ_format, orig_type_format = format_type_distinctly( + typ, original_type, options=self.options + ) + if typ_format == '"object"' and any( + type(item) == NoneType for item in original_type.items + ): + typ_format = '"None"' + self.fail( + 'Item {} of {} has no attribute "{}"{}'.format( + typ_format, orig_type_format, member, extra + ), + context, + code=codes.UNION_ATTR, + ) + return codes.UNION_ATTR + elif isinstance(original_type, TypeVarType): + bound = get_proper_type(original_type.upper_bound) + if isinstance(bound, UnionType): + typ_fmt, bound_fmt = format_type_distinctly(typ, bound, options=self.options) + original_type_fmt = format_type(original_type, self.options) + self.fail( + "Item {} of the upper bound {} of type variable {} has no " + 'attribute "{}"{}'.format( + typ_fmt, bound_fmt, original_type_fmt, member, extra + ), + context, + code=codes.UNION_ATTR, + ) + return codes.UNION_ATTR + else: + self.fail( + '{} has no attribute "{}"{}'.format( + format_type(original_type, self.options), member, extra + ), + context, + code=codes.ATTR_DEFINED, + ) + return codes.ATTR_DEFINED + return None + + def unsupported_operand_types( + self, + op: str, + left_type: Any, + right_type: Any, + context: Context, + *, + code: ErrorCode = codes.OPERATOR, + ) -> ErrorInfo: + """Report unsupported operand types for a binary operation. + + Types can be Type objects or strings. + """ + left_str = "" + if isinstance(left_type, str): + left_str = left_type + else: + left_str = format_type(left_type, self.options) + + right_str = "" + if isinstance(right_type, str): + right_str = right_type + else: + right_str = format_type(right_type, self.options) + + if self.are_type_names_disabled(): + msg = f"Unsupported operand types for {op} (likely involving Union)" + else: + msg = f"Unsupported operand types for {op} ({left_str} and {right_str})" + return self.fail(msg, context, code=code) + + def unsupported_left_operand(self, op: str, typ: Type, context: Context) -> None: + if self.are_type_names_disabled(): + msg = f"Unsupported left operand type for {op} (some union)" + else: + msg = f"Unsupported left operand type for {op} ({format_type(typ, self.options)})" + self.fail(msg, context, code=codes.OPERATOR) + + def not_callable(self, typ: Type, context: Context) -> Type: + self.fail(message_registry.NOT_CALLABLE.format(format_type(typ, self.options)), context) + return AnyType(TypeOfAny.from_error) + + def untyped_function_call(self, callee: CallableType, context: Context) -> Type: + name = callable_name(callee) or "(unknown)" + self.fail( + f"Call to untyped function {name} in typed context", + context, + code=codes.NO_UNTYPED_CALL, + ) + return AnyType(TypeOfAny.from_error) + + def incompatible_argument( + self, + n: int, + m: int, + callee: CallableType, + arg_type: Type, + arg_kind: ArgKind, + object_type: Type | None, + context: Context, + outer_context: Context, + ) -> ErrorInfo: + """Report an error about an incompatible argument type. + + The argument type is arg_type, argument number is n and the + callee type is 'callee'. If the callee represents a method + that corresponds to an operator, use the corresponding + operator name in the messages. + + Return the error code that used for the argument (multiple error + codes are possible). + """ + arg_type = get_proper_type(arg_type) + + target = "" + callee_name = callable_name(callee) + if callee_name is not None: + name = callee_name + if object_type is not None: + base = format_type(object_type, self.options) + else: + base = extract_type(name) + + if name.startswith('"__getitem__" of'): + return self.invalid_index_type( + arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX + ) + elif name.startswith('"__setitem__" of'): + if n == 1: + return self.invalid_index_type( + arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX + ) + else: + arg_type_str, callee_type_str = format_type_distinctly( + arg_type, callee.arg_types[n - 1], options=self.options + ) + info = ( + f" (expression has type {arg_type_str}, target has type {callee_type_str})" + ) + error_msg = ( + message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT.with_additional_msg(info) + ) + return self.fail(error_msg.value, context, code=error_msg.code) + elif name.startswith('"__'): + for method, op in op_methods_to_symbols.items(): + for variant in method, "__r" + method[2:]: + # FIX: do not rely on textual formatting + if name.startswith(f'"{variant}" of'): + if op == "in" or variant != method: + # Reversed order of base/argument. + return self.unsupported_operand_types( + op, arg_type, base, context, code=codes.OPERATOR + ) + else: + return self.unsupported_operand_types( + op, base, arg_type, context, code=codes.OPERATOR + ) + + target = f"to {name} " + + msg = "" + code = codes.MISC + notes: list[str] = [] + if callee_name == "": + name = callee_name[1:-1] + n -= 1 + actual_type_str, expected_type_str = format_type_distinctly( + arg_type, callee.arg_types[0], options=self.options + ) + msg = "{} item {} has incompatible type {}; expected {}".format( + name.title(), n, actual_type_str, expected_type_str + ) + code = codes.LIST_ITEM + elif callee_name == "" and isinstance( + get_proper_type(callee.arg_types[n - 1]), TupleType + ): + name = callee_name[1:-1] + n -= 1 + key_type, value_type = cast(TupleType, arg_type).items + expected_key_type, expected_value_type = cast(TupleType, callee.arg_types[n]).items + + # don't increase verbosity unless there is need to do so + if is_subtype(key_type, expected_key_type): + key_type_str = format_type(key_type, self.options) + expected_key_type_str = format_type(expected_key_type, self.options) + else: + key_type_str, expected_key_type_str = format_type_distinctly( + key_type, expected_key_type, options=self.options + ) + if is_subtype(value_type, expected_value_type): + value_type_str = format_type(value_type, self.options) + expected_value_type_str = format_type(expected_value_type, self.options) + else: + value_type_str, expected_value_type_str = format_type_distinctly( + value_type, expected_value_type, options=self.options + ) + + msg = "{} entry {} has incompatible type {}: {}; expected {}: {}".format( + name.title(), + n, + key_type_str, + value_type_str, + expected_key_type_str, + expected_value_type_str, + ) + code = codes.DICT_ITEM + elif callee_name == "": + value_type_str, expected_value_type_str = format_type_distinctly( + arg_type, callee.arg_types[n - 1], options=self.options + ) + msg = "Unpacked dict entry {} has incompatible type {}; expected {}".format( + n - 1, value_type_str, expected_value_type_str + ) + code = codes.DICT_ITEM + elif callee_name == "": + actual_type_str, expected_type_str = map( + strip_quotes, + format_type_distinctly(arg_type, callee.arg_types[0], options=self.options), + ) + msg = "List comprehension has incompatible type List[{}]; expected List[{}]".format( + actual_type_str, expected_type_str + ) + elif callee_name == "": + actual_type_str, expected_type_str = map( + strip_quotes, + format_type_distinctly(arg_type, callee.arg_types[0], options=self.options), + ) + msg = "Set comprehension has incompatible type Set[{}]; expected Set[{}]".format( + actual_type_str, expected_type_str + ) + elif callee_name == "": + actual_type_str, expected_type_str = format_type_distinctly( + arg_type, callee.arg_types[n - 1], options=self.options + ) + msg = ( + "{} expression in dictionary comprehension has incompatible type {}; " + "expected type {}" + ).format("Key" if n == 1 else "Value", actual_type_str, expected_type_str) + elif callee_name == "": + actual_type_str, expected_type_str = format_type_distinctly( + arg_type, callee.arg_types[0], options=self.options + ) + msg = "Generator has incompatible item type {}; expected {}".format( + actual_type_str, expected_type_str + ) + else: + if self.prefer_simple_messages(): + msg = "Argument has incompatible type" + else: + try: + expected_type = callee.arg_types[m - 1] + except IndexError: # Varargs callees + expected_type = callee.arg_types[-1] + arg_type_str, expected_type_str = format_type_distinctly( + arg_type, expected_type, bare=True, options=self.options + ) + if arg_kind == ARG_STAR: + arg_type_str = "*" + arg_type_str + elif arg_kind == ARG_STAR2: + arg_type_str = "**" + arg_type_str + + # For function calls with keyword arguments, display the argument name rather + # than the number. + arg_label = str(n) + if isinstance(outer_context, CallExpr) and len(outer_context.arg_names) >= n: + arg_name = outer_context.arg_names[n - 1] + if arg_name is not None: + arg_label = f'"{arg_name}"' + if ( + arg_kind == ARG_STAR2 + and isinstance(arg_type, TypedDictType) + and m <= len(callee.arg_names) + and callee.arg_names[m - 1] is not None + and callee.arg_kinds[m - 1] != ARG_STAR2 + ): + arg_name = callee.arg_names[m - 1] + assert arg_name is not None + arg_type_str, expected_type_str = format_type_distinctly( + arg_type.items[arg_name], expected_type, bare=True, options=self.options + ) + arg_label = f'"{arg_name}"' + if isinstance(outer_context, IndexExpr) and isinstance( + outer_context.index, StrExpr + ): + msg = 'Value of "{}" has incompatible type {}; expected {}'.format( + outer_context.index.value, + quote_type_string(arg_type_str), + quote_type_string(expected_type_str), + ) + else: + msg = "Argument {} {}has incompatible type {}; expected {}".format( + arg_label, + target, + quote_type_string(arg_type_str), + quote_type_string(expected_type_str), + ) + expected_type = get_proper_type(expected_type) + if isinstance(expected_type, UnionType): + expected_types = get_proper_types(expected_type.items) + else: + expected_types = [expected_type] + for type in expected_types: + if isinstance(arg_type, Instance) and isinstance(type, Instance): + notes = append_invariance_notes(notes, arg_type, type) + notes = append_numbers_notes(notes, arg_type, type) + object_type = get_proper_type(object_type) + if isinstance(object_type, TypedDictType): + code = codes.TYPEDDICT_ITEM + else: + code = codes.ARG_TYPE + error = self.fail(msg, context, code=code) + if notes: + for note_msg in notes: + self.note(note_msg, context, code=code) + return error + + def incompatible_argument_note( + self, + original_caller_type: ProperType, + callee_type: ProperType, + context: Context, + parent_error: ErrorInfo, + ) -> None: + if self.prefer_simple_messages(): + return + if isinstance( + original_caller_type, (Instance, TupleType, TypedDictType, TypeType, CallableType) + ): + if isinstance(callee_type, Instance) and callee_type.type.is_protocol: + self.report_protocol_problems( + original_caller_type, callee_type, context, parent_error=parent_error + ) + if isinstance(callee_type, UnionType): + for item in callee_type.items: + item = get_proper_type(item) + if isinstance(item, Instance) and item.type.is_protocol: + self.report_protocol_problems( + original_caller_type, item, context, parent_error=parent_error + ) + if isinstance(callee_type, CallableType) and isinstance(original_caller_type, Instance): + call = find_member( + "__call__", original_caller_type, original_caller_type, is_operator=True + ) + if call: + self.note_call(original_caller_type, call, context, code=parent_error.code) + if isinstance(callee_type, Instance) and callee_type.type.is_protocol: + call = find_member("__call__", callee_type, callee_type, is_operator=True) + if call: + self.note_call(callee_type, call, context, code=parent_error.code) + self.maybe_note_concatenate_pos_args( + original_caller_type, callee_type, context, parent_error.code + ) + + def maybe_note_concatenate_pos_args( + self, + original_caller_type: ProperType, + callee_type: ProperType, + context: Context, + code: ErrorCode | None = None, + ) -> None: + # pos-only vs positional can be confusing, with Concatenate + if ( + isinstance(callee_type, CallableType) + and isinstance(original_caller_type, CallableType) + and (original_caller_type.from_concatenate or callee_type.from_concatenate) + ): + names: list[str] = [] + for c, o in zip( + callee_type.formal_arguments(), original_caller_type.formal_arguments() + ): + if None in (c.pos, o.pos): + # non-positional + continue + if c.name != o.name and c.name is None and o.name is not None: + names.append(o.name) + + if names: + missing_arguments = '"' + '", "'.join(names) + '"' + self.note( + f'This is likely because "{original_caller_type.name}" has named arguments: ' + f"{missing_arguments}. Consider marking them positional-only", + context, + code=code, + ) + + def invalid_index_type( + self, + index_type: Type, + expected_type: Type, + base_str: str, + context: Context, + *, + code: ErrorCode, + ) -> ErrorInfo: + index_str, expected_str = format_type_distinctly( + index_type, expected_type, options=self.options + ) + return self.fail( + "Invalid index type {} for {}; expected type {}".format( + index_str, base_str, expected_str + ), + context, + code=code, + ) + + def readonly_keys_mutated(self, keys: set[str], context: Context) -> None: + if len(keys) == 1: + suffix = "is" + else: + suffix = "are" + self.fail( + "ReadOnly {} TypedDict {} mutated".format(format_key_list(sorted(keys)), suffix), + code=codes.TYPEDDICT_READONLY_MUTATED, + context=context, + ) + + def too_few_arguments( + self, callee: CallableType, context: Context, argument_names: Sequence[str | None] | None + ) -> None: + if self.prefer_simple_messages(): + msg = "Too few arguments" + elif argument_names is not None: + num_positional_args = sum(k is None for k in argument_names) + arguments_left = callee.arg_names[num_positional_args : callee.min_args] + diff = [k for k in arguments_left if k not in argument_names] + if len(diff) == 1: + msg = "Missing positional argument" + else: + msg = "Missing positional arguments" + callee_name = callable_name(callee) + if callee_name is not None and diff and all(d is not None for d in diff): + args = '", "'.join(cast(list[str], diff)) + msg += f' "{args}" in call to {callee_name}' + else: + msg = "Too few arguments" + for_function(callee) + + else: + msg = "Too few arguments" + for_function(callee) + self.fail(msg, context, code=codes.CALL_ARG) + + def missing_named_argument(self, callee: CallableType, context: Context, name: str) -> None: + msg = f'Missing named argument "{name}"' + for_function(callee) + self.fail(msg, context, code=codes.CALL_ARG) + self.note_defined_here(callee, context) + + def too_many_arguments(self, callee: CallableType, context: Context) -> None: + if self.prefer_simple_messages(): + msg = "Too many arguments" + else: + msg = "Too many arguments" + for_function(callee) + self.fail(msg, context, code=codes.CALL_ARG) + self.maybe_note_about_special_args(callee, context) + + def too_many_arguments_from_typed_dict( + self, callee: CallableType, arg_type: TypedDictType, context: Context + ) -> None: + # Try to determine the name of the extra argument. + for key in arg_type.items: + if key not in callee.arg_names: + msg = f'Extra argument "{key}" from **args' + for_function(callee) + break + else: + self.too_many_arguments(callee, context) + return + self.fail(msg, context) + + def too_many_positional_arguments(self, callee: CallableType, context: Context) -> None: + if self.prefer_simple_messages(): + msg = "Too many positional arguments" + else: + msg = "Too many positional arguments" + for_function(callee) + self.fail(msg, context) + self.maybe_note_about_special_args(callee, context) + + def maybe_note_about_special_args(self, callee: CallableType, context: Context) -> None: + if self.prefer_simple_messages(): + return + # https://github.com/python/mypy/issues/11309 + first_arg = get_first_arg(callee) + if first_arg and first_arg not in {"self", "cls", "mcs"}: + self.note( + "Looks like the first special argument in a method " + 'is not named "self", "cls", or "mcs", ' + "maybe it is missing?", + context, + ) + + def unexpected_keyword_argument_for_function( + self, for_func: str, name: str, context: Context, *, matches: list[str] | None = None + ) -> None: + msg = f'Unexpected keyword argument "{name}"' + for_func + if matches: + msg += f"; did you mean {pretty_seq(matches, 'or')}?" + self.fail(msg, context, code=codes.CALL_ARG) + + def unexpected_keyword_argument( + self, callee: CallableType, name: str, arg_type: Type, context: Context + ) -> None: + # Suggest intended keyword, look for type match else fallback on any match. + matching_type_args = [] + not_matching_type_args = [] + for i, kwarg_type in enumerate(callee.arg_types): + callee_arg_name = callee.arg_names[i] + if callee_arg_name is not None and callee.arg_kinds[i] != ARG_STAR: + if is_subtype(arg_type, kwarg_type): + matching_type_args.append(callee_arg_name) + else: + not_matching_type_args.append(callee_arg_name) + matches = best_matches(name, matching_type_args, n=3) + if not matches: + matches = best_matches(name, not_matching_type_args, n=3) + self.unexpected_keyword_argument_for_function( + for_function(callee), name, context, matches=matches + ) + self.note_defined_here(callee, context) + + def note_defined_here(self, callee: CallableType, context: Context) -> None: + module = find_defining_module(self.modules, callee) + if ( + module + and module.path != self.errors.file + and module.fullname not in ("builtins", "typing") + ): + assert callee.definition is not None + fname = callable_name(callee) + if not fname: # an alias to function with a different name + fname = "Called function" + else: + fname = fname.split(" of ")[0] # use short method names in the note + self.note(f'{fname} defined in "{module.fullname}"', context, code=codes.CALL_ARG) + + def duplicate_argument_value(self, callee: CallableType, index: int, context: Context) -> None: + self.fail( + '{} gets multiple values for keyword argument "{}"'.format( + callable_name(callee) or "Function", callee.arg_names[index] + ), + context, + ) + + def does_not_return_value(self, callee_type: Type | None, context: Context) -> None: + """Report an error about use of an unusable type.""" + callee_type = get_proper_type(callee_type) + callee_name = callable_name(callee_type) if isinstance(callee_type, FunctionLike) else None + name = callee_name or "Function" + message = f"{name} does not return a value (it only ever returns None)" + self.fail(message, context, code=codes.FUNC_RETURNS_VALUE) + + def deleted_as_rvalue(self, typ: DeletedType, context: Context) -> None: + """Report an error about using an deleted type as an rvalue.""" + if typ.source is None: + s = "" + else: + s = f' "{typ.source}"' + self.fail(f"Trying to read deleted variable{s}", context) + + def deleted_as_lvalue(self, typ: DeletedType, context: Context) -> None: + """Report an error about using an deleted type as an lvalue. + + Currently, this only occurs when trying to assign to an + exception variable outside the local except: blocks. + """ + if typ.source is None: + s = "" + else: + s = f' "{typ.source}"' + self.fail(f"Assignment to variable{s} outside except: block", context) + + def no_variant_matches_arguments( + self, + overload: Overloaded, + arg_types: list[Type], + context: Context, + *, + code: ErrorCode | None = None, + ) -> None: + code = code or codes.CALL_OVERLOAD + name = callable_name(overload) + if name: + name_str = f" of {name}" + else: + name_str = "" + arg_types_str = ", ".join(format_type(arg, self.options) for arg in arg_types) + num_args = len(arg_types) + if num_args == 0: + self.fail( + f"All overload variants{name_str} require at least one argument", + context, + code=code, + ) + elif num_args == 1: + self.fail( + f"No overload variant{name_str} matches argument type {arg_types_str}", + context, + code=code, + ) + else: + self.fail( + f"No overload variant{name_str} matches argument types {arg_types_str}", + context, + code=code, + ) + + self.note(f"Possible overload variant{plural_s(len(overload.items))}:", context, code=code) + for item in overload.items: + self.note(pretty_callable(item, self.options), context, offset=4, code=code) + + def wrong_number_values_to_unpack( + self, provided: int, expected: int, context: Context + ) -> None: + if provided < expected: + if provided == 1: + self.fail(f"Need more than 1 value to unpack ({expected} expected)", context) + else: + self.fail( + f"Need more than {provided} values to unpack ({expected} expected)", context + ) + elif provided > expected: + self.fail( + f"Too many values to unpack ({expected} expected, {provided} provided)", context + ) + + def unpacking_strings_disallowed(self, context: Context) -> None: + self.fail("Unpacking a string is disallowed", context, code=codes.STR_UNPACK) + + def type_not_iterable(self, type: Type, context: Context) -> None: + self.fail(f"{format_type(type, self.options)} object is not iterable", context) + + def possible_missing_await(self, context: Context, code: ErrorCode | None) -> None: + self.note('Maybe you forgot to use "await"?', context, code=code) + + def incompatible_operator_assignment(self, op: str, context: Context) -> None: + self.fail(f"Result type of {op} incompatible in assignment", context) + + def overload_signature_incompatible_with_supertype( + self, name: str, name_in_super: str, supertype: str, context: Context + ) -> None: + target = self.override_target(name, name_in_super, supertype) + self.fail( + f'Signature of "{name}" incompatible with {target}', context, code=codes.OVERRIDE + ) + + note_template = 'Overload variants must be defined in the same order as they are in "{}"' + self.note(note_template.format(supertype), context, code=codes.OVERRIDE) + + def incompatible_setter_override( + self, defn: Context, typ: Type, original_type: Type, base: TypeInfo + ) -> None: + self.fail("Incompatible override of a setter type", defn, code=codes.OVERRIDE) + base_str, override_str = format_type_distinctly(original_type, typ, options=self.options) + self.note( + f' (base class "{base.name}" defined the type as {base_str},', + defn, + code=codes.OVERRIDE, + ) + self.note(f" override has type {override_str})", defn, code=codes.OVERRIDE) + if is_subtype(typ, original_type): + self.note(" Setter types should behave contravariantly", defn, code=codes.OVERRIDE) + + def signature_incompatible_with_supertype( + self, + name: str, + name_in_super: str, + supertype: str, + context: Context, + *, + original: ProperType, + override: ProperType, + ) -> None: + target = self.override_target(name, name_in_super, supertype) + error = self.fail( + f'Signature of "{name}" incompatible with {target}', context, code=codes.OVERRIDE + ) + + original_str, override_str = format_type_distinctly( + original, override, options=self.options, bare=True + ) + + INCLUDE_DECORATOR = True # Include @classmethod and @staticmethod decorators, if any + ALIGN_OFFSET = 1 # One space, to account for the difference between error and note + OFFSET = 4 # Four spaces, so that notes will look like this: + # error: Signature of "f" incompatible with supertype "A" + # note: Superclass: + # note: def f(self) -> str + # note: Subclass: + # note: def f(self, x: str) -> None + self.note("Superclass:", context, offset=ALIGN_OFFSET + OFFSET, parent_error=error) + if isinstance(original, (CallableType, Overloaded)): + self.pretty_callable_or_overload( + original, + context, + offset=ALIGN_OFFSET + 2 * OFFSET, + add_class_or_static_decorator=INCLUDE_DECORATOR, + parent_error=error, + ) + else: + self.note(original_str, context, offset=ALIGN_OFFSET + 2 * OFFSET, parent_error=error) + + self.note("Subclass:", context, offset=ALIGN_OFFSET + OFFSET, parent_error=error) + if isinstance(override, (CallableType, Overloaded)): + self.pretty_callable_or_overload( + override, + context, + offset=ALIGN_OFFSET + 2 * OFFSET, + add_class_or_static_decorator=INCLUDE_DECORATOR, + parent_error=error, + ) + else: + self.note(override_str, context, offset=ALIGN_OFFSET + 2 * OFFSET, parent_error=error) + + def pretty_callable_or_overload( + self, + tp: CallableType | Overloaded, + context: Context, + *, + parent_error: ErrorInfo, + offset: int = 0, + add_class_or_static_decorator: bool = False, + ) -> None: + if isinstance(tp, CallableType): + if add_class_or_static_decorator: + decorator = pretty_class_or_static_decorator(tp) + if decorator is not None: + self.note(decorator, context, offset=offset, parent_error=parent_error) + self.note( + pretty_callable(tp, self.options), + context, + offset=offset, + parent_error=parent_error, + ) + elif isinstance(tp, Overloaded): + self.pretty_overload( + tp, + context, + offset, + add_class_or_static_decorator=add_class_or_static_decorator, + parent_error=parent_error, + ) + + def argument_incompatible_with_supertype( + self, + arg_num: int, + name: str, + type_name: str | None, + name_in_supertype: str, + arg_type_in_supertype: Type, + supertype: str, + context: Context, + origin_context: Context, + ) -> None: + target = self.override_target(name, name_in_supertype, supertype) + arg_type_in_supertype_f = format_type_bare(arg_type_in_supertype, self.options) + self.fail( + 'Argument {} of "{}" is incompatible with {}; ' + 'supertype defines the argument type as "{}"'.format( + arg_num, name, target, arg_type_in_supertype_f + ), + context, + code=codes.OVERRIDE, + origin_context=origin_context, + ) + if name != "__post_init__": + # `__post_init__` is special, it can be incompatible by design. + # So, this note is misleading. + invariant_message = """ + This violates the Liskov substitution principle + See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides + """ + self.note_multiline( + invariant_message, context, code=codes.OVERRIDE, origin_context=origin_context + ) + if name == "__eq__" and type_name: + eq_message = """ + It is recommended for "__eq__" to work with arbitrary objects, for example: + def __eq__(self, other: object) -> bool: + if not isinstance(other, {class_name}): + return NotImplemented + return + """.format(class_name=type_name) + self.note_multiline( + eq_message, context, code=codes.OVERRIDE, origin_context=origin_context + ) + + def return_type_incompatible_with_supertype( + self, + name: str, + name_in_supertype: str, + supertype: str, + original: Type, + override: Type, + context: Context, + ) -> None: + target = self.override_target(name, name_in_supertype, supertype) + override_str, original_str = format_type_distinctly( + override, original, options=self.options + ) + self.fail( + 'Return type {} of "{}" incompatible with return type {} in {}'.format( + override_str, name, original_str, target + ), + context, + code=codes.OVERRIDE, + ) + + original = get_proper_type(original) + override = get_proper_type(override) + if ( + isinstance(original, Instance) + and isinstance(override, Instance) + and override.type.fullname == "typing.AsyncIterator" + and original.type.fullname == "typing.Coroutine" + and len(original.args) == 3 + and original.args[2] == override + ): + self.note(f'Consider declaring "{name}" in {target} without "async"', context) + self.note( + "See https://mypy.readthedocs.io/en/stable/more_types.html#asynchronous-iterators", + context, + ) + + def override_target(self, name: str, name_in_super: str, supertype: str) -> str: + target = f'supertype "{supertype}"' + if name_in_super != name: + target = f'"{name_in_super}" of {target}' + return target + + def incompatible_type_application( + self, min_arg_count: int, max_arg_count: int, actual_arg_count: int, context: Context + ) -> None: + if max_arg_count == 0: + self.fail("Type application targets a non-generic function or class", context) + return + + if min_arg_count == max_arg_count: + s = f"{max_arg_count} expected" + else: + s = f"expected between {min_arg_count} and {max_arg_count}" + + if actual_arg_count > max_arg_count: + self.fail(f"Type application has too many types ({s})", context) + else: + self.fail(f"Type application has too few types ({s})", context) + + def could_not_infer_type_arguments( + self, callee_type: CallableType, tv: TypeVarLikeType, context: Context + ) -> None: + callee_name = callable_name(callee_type) + if callee_name is not None: + self.fail( + f"Cannot infer value of type parameter {format_type(tv, self.options)} of {callee_name}", + context, + ) + if callee_name == "": + # Invariance in key type causes more of these errors than we would want. + self.note( + "Try assigning the literal to a variable annotated as dict[, ]", + context, + ) + else: + self.fail("Cannot infer function type argument", context) + + def invalid_var_arg(self, typ: Type, context: Context) -> None: + self.fail("Expected iterable as variadic argument", context) + + def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None: + typ = get_proper_type(typ) + if isinstance(typ, Instance) and is_mapping: + self.fail("Argument after ** must have string keys", context, code=codes.ARG_TYPE) + else: + self.fail( + f"Argument after ** must be a mapping, not {format_type(typ, self.options)}", + context, + code=codes.ARG_TYPE, + ) + + def undefined_in_superclass(self, member: str, context: Context) -> None: + self.fail(f'"{member}" undefined in superclass', context) + + def variable_may_be_undefined(self, name: str, context: Context) -> None: + self.fail(f'Name "{name}" may be undefined', context, code=codes.POSSIBLY_UNDEFINED) + + def var_used_before_def(self, name: str, context: Context) -> None: + self.fail(f'Name "{name}" is used before definition', context, code=codes.USED_BEFORE_DEF) + + def first_argument_for_super_must_be_type(self, actual: Type, context: Context) -> None: + actual = get_proper_type(actual) + if isinstance(actual, Instance): + # Don't include type of instance, because it can look confusingly like a type + # object. + type_str = "a non-type instance" + else: + type_str = format_type(actual, self.options) + self.fail( + f'Argument 1 for "super" must be a type object; got {type_str}', + context, + code=codes.ARG_TYPE, + ) + + def unsafe_super(self, method: str, cls: str, ctx: Context) -> None: + self.fail( + f'Call to abstract method "{method}" of "{cls}" with trivial body via super() is unsafe', + ctx, + code=codes.SAFE_SUPER, + ) + + def too_few_string_formatting_arguments(self, context: Context) -> None: + self.fail("Not enough arguments for format string", context, code=codes.STRING_FORMATTING) + + def too_many_string_formatting_arguments(self, context: Context) -> None: + self.fail( + "Not all arguments converted during string formatting", + context, + code=codes.STRING_FORMATTING, + ) + + def unsupported_placeholder(self, placeholder: str, context: Context) -> None: + self.fail( + f'Unsupported format character "{placeholder}"', context, code=codes.STRING_FORMATTING + ) + + def string_interpolation_with_star_and_key(self, context: Context) -> None: + self.fail( + "String interpolation contains both stars and mapping keys", + context, + code=codes.STRING_FORMATTING, + ) + + def requires_int_or_single_byte(self, context: Context, format_call: bool = False) -> None: + self.fail( + '"{}c" requires an integer in range(256) or a single byte'.format( + ":" if format_call else "%" + ), + context, + code=codes.STRING_FORMATTING, + ) + + def requires_int_or_char(self, context: Context, format_call: bool = False) -> None: + self.fail( + '"{}c" requires int or char'.format(":" if format_call else "%"), + context, + code=codes.STRING_FORMATTING, + ) + + def key_not_in_mapping(self, key: str, context: Context) -> None: + self.fail(f'Key "{key}" not found in mapping', context, code=codes.STRING_FORMATTING) + + def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None: + self.fail( + "String interpolation mixes specifier with and without mapping keys", + context, + code=codes.STRING_FORMATTING, + ) + + def cannot_determine_type(self, name: str, context: Context) -> None: + self.fail(f'Cannot determine type of "{name}"', context, code=codes.HAS_TYPE) + + def cannot_determine_type_in_base(self, name: str, base: str, context: Context) -> None: + self.fail(f'Cannot determine type of "{name}" in base class "{base}"', context) + + def no_formal_self(self, name: str, item: CallableType, context: Context) -> None: + type = format_type(item, self.options) + self.fail( + f'Attribute function "{name}" with type {type} does not accept self argument', context + ) + + def incompatible_self_argument( + self, name: str, arg: Type, sig: CallableType, is_classmethod: bool, context: Context + ) -> None: + kind = "class attribute function" if is_classmethod else "attribute function" + arg_type = format_type(arg, self.options) + sig_type = format_type(sig, self.options) + self.fail( + f'Invalid self argument {arg_type} to {kind} "{name}" with type {sig_type}', context + ) + + def incompatible_conditional_function_def( + self, defn: FuncDef, old_type: FunctionLike, new_type: FunctionLike + ) -> None: + error = self.fail("All conditional function variants must have identical signatures", defn) + if isinstance(old_type, (CallableType, Overloaded)) and isinstance( + new_type, (CallableType, Overloaded) + ): + self.note("Original:", defn) + self.pretty_callable_or_overload(old_type, defn, offset=4, parent_error=error) + self.note("Redefinition:", defn) + self.pretty_callable_or_overload(new_type, defn, offset=4, parent_error=error) + + def cannot_instantiate_abstract_class( + self, class_name: str, abstract_attributes: dict[str, bool], context: Context + ) -> None: + attrs = format_string_list([f'"{a}"' for a in abstract_attributes]) + self.fail( + f'Cannot instantiate abstract class "{class_name}" with abstract ' + f"attribute{plural_s(abstract_attributes)} {attrs}", + context, + code=codes.ABSTRACT, + ) + attrs_with_none = [ + f'"{a}"' + for a, implicit_and_can_return_none in abstract_attributes.items() + if implicit_and_can_return_none + ] + if not attrs_with_none: + return + if len(attrs_with_none) == 1: + note = ( + f"{attrs_with_none[0]} is implicitly abstract because it has an empty function " + "body. If it is not meant to be abstract, explicitly `return` or `return None`." + ) + else: + note = ( + "The following methods were marked implicitly abstract because they have empty " + f"function bodies: {format_string_list(attrs_with_none)}. " + "If they are not meant to be abstract, explicitly `return` or `return None`." + ) + self.note(note, context, code=codes.ABSTRACT) + + def base_class_definitions_incompatible( + self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context + ) -> None: + self.fail( + 'Definition of "{}" in base class "{}" is incompatible ' + 'with definition in base class "{}"'.format(name, base1.name, base2.name), + context, + ) + + def cant_assign_to_method(self, context: Context) -> None: + self.fail(message_registry.CANNOT_ASSIGN_TO_METHOD, context, code=codes.METHOD_ASSIGN) + + def cant_assign_to_classvar(self, name: str, context: Context) -> None: + self.fail(f'Cannot assign to class variable "{name}" via instance', context) + + def no_overridable_method(self, name: str, context: Context) -> None: + self.fail( + f'Method "{name}" is marked as an override, ' + "but no base method was found with this name", + context, + ) + + def explicit_override_decorator_missing( + self, name: str, base_name: str, context: Context + ) -> None: + self.fail( + f'Method "{name}" is not using @override ' + f'but is overriding a method in class "{base_name}"', + context, + code=codes.EXPLICIT_OVERRIDE_REQUIRED, + ) + + def final_cant_override_writable(self, name: str, ctx: Context) -> None: + self.fail(f'Cannot override writable attribute "{name}" with a final one', ctx) + + def cant_override_final(self, name: str, base_name: str, ctx: Context) -> None: + self.fail( + ( + f'Cannot override final attribute "{name}" ' + f'(previously declared in base class "{base_name}")' + ), + ctx, + ) + + def cant_assign_to_final(self, name: str, attr_assign: bool, ctx: Context) -> None: + """Warn about a prohibited assignment to a final attribute. + + Pass `attr_assign=True` if the assignment assigns to an attribute. + """ + kind = "attribute" if attr_assign else "name" + self.fail(f'Cannot assign to final {kind} "{unmangle(name)}"', ctx) + + def protocol_members_cant_be_final(self, ctx: Context) -> None: + self.fail("Protocol member cannot be final", ctx) + + def final_without_value(self, ctx: Context) -> None: + self.fail("Final name must be initialized with a value", ctx) + + def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None: + self.fail(f'Property "{name}" defined in "{type.name}" is read-only', context) + + def incompatible_typevar_value( + self, callee: CallableType, typ: Type, typevar_name: str, context: Context + ) -> None: + self.fail( + message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format( + typevar_name, callable_name(callee) or "function", format_type(typ, self.options) + ), + context, + code=codes.TYPE_VAR, + ) + + def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None: + # In loops (and similar cases), the same expression might be analysed multiple + # times and thereby confronted with different types. We only want to raise a + # `comparison-overlap` error if it occurs in all cases and therefore collect the + # respective types of the current iteration here so that we can report the error + # later if it is persistent over all iteration steps: + for watcher in self.errors.get_watchers(): + if watcher._filter: + break + if isinstance(watcher, IterationErrorWatcher): + watcher.iteration_dependent_errors.nonoverlapping_types[-1][ + NonOverlapErrorInfo( + line=ctx.line, + column=ctx.column, + end_line=ctx.end_line, + end_column=ctx.end_column, + kind=kind, + ) + ] = (left, right) + return + + left_str = "element" if kind == "container" else "left operand" + right_str = "container item" if kind == "container" else "right operand" + message = "Non-overlapping {} check ({} type: {}, {} type: {})" + left_typ, right_typ = format_type_distinctly(left, right, options=self.options) + self.fail( + message.format(kind, left_str, left_typ, right_str, right_typ), + ctx, + code=codes.COMPARISON_OVERLAP, + ) + + def overload_inconsistently_applies_decorator(self, decorator: str, context: Context) -> None: + self.fail( + f'Overload does not consistently use the "@{decorator}" ' + + "decorator on all function signatures.", + context, + ) + + def overloaded_signatures_overlap( + self, index1: int, index2: int, flip_note: bool, context: Context + ) -> None: + self.fail( + "Overloaded function signatures {} and {} overlap with " + "incompatible return types".format(index1, index2), + context, + code=codes.OVERLOAD_OVERLAP, + ) + if flip_note: + self.note( + "Flipping the order of overloads will fix this error", + context, + code=codes.OVERLOAD_OVERLAP, + ) + + def overloaded_signature_will_never_match( + self, index1: int, index2: int, context: Context + ) -> None: + self.fail( + "Overloaded function signature {index2} will never be matched: " + "signature {index1}'s parameter type(s) are the same or broader".format( + index1=index1, index2=index2 + ), + context, + code=codes.OVERLOAD_CANNOT_MATCH, + ) + + def overloaded_signatures_typevar_specific(self, index: int, context: Context) -> None: + self.fail( + f"Overloaded function implementation cannot satisfy signature {index} " + + "due to inconsistencies in how they use type variables", + context, + ) + + def overloaded_signatures_param_specific(self, index: int, context: Context) -> None: + self.fail( + ( + f"Overloaded function implementation does not accept all possible parameters " + f"of signature {index}" + ), + context, + ) + + def overloaded_signatures_ret_specific(self, index: int, context: Context) -> None: + self.fail( + f"Overloaded function implementation cannot produce return type of signature {index}", + context, + ) + + def warn_both_operands_are_from_unions(self, context: Context) -> None: + self.note("Both left and right operands are unions", context, code=codes.OPERATOR) + + def warn_operand_was_from_union(self, side: str, original: Type, context: Context) -> None: + self.note( + f"{side} operand is of type {format_type(original, self.options)}", + context, + code=codes.OPERATOR, + ) + + def operator_method_signatures_overlap( + self, + reverse_class: TypeInfo, + reverse_method: str, + forward_class: Type, + forward_method: str, + context: Context, + ) -> None: + self.fail( + 'Signatures of "{}" of "{}" and "{}" of {} are unsafely overlapping'.format( + reverse_method, + reverse_class.name, + forward_method, + format_type(forward_class, self.options), + ), + context, + ) + + def forward_operator_not_callable(self, forward_method: str, context: Context) -> None: + self.fail(f'Forward operator "{forward_method}" is not callable', context) + + def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None: + self.fail(f'Signatures of "{method}" and "{other_method}" are incompatible', context) + + def yield_from_invalid_operand_type(self, expr: Type, context: Context) -> Type: + text = ( + format_type(expr, self.options) + if format_type(expr, self.options) != "object" + else expr + ) + self.fail(f'"yield from" can\'t be applied to {text}', context) + return AnyType(TypeOfAny.from_error) + + def invalid_signature(self, func_type: Type, context: Context) -> None: + self.fail(f"Invalid signature {format_type(func_type, self.options)}", context) + + def invalid_signature_for_special_method( + self, func_type: Type, context: Context, method_name: str + ) -> None: + self.fail( + f'Invalid signature {format_type(func_type, self.options)} for "{method_name}"', + context, + ) + + def reveal_type(self, typ: Type, context: Context) -> None: + + # Search for an error watcher that modifies the "normal" behaviour (we do not + # rely on the normal `ErrorWatcher` filtering approach because we might need to + # collect the original types for a later unionised response): + for watcher in self.errors.get_watchers(): + # The `reveal_type` statement should be ignored: + if watcher.filter_revealed_type: + return + # The `reveal_type` statement might be visited iteratively due to being + # placed in a loop or so. Hence, we collect the respective types of + # individual iterations so that we can report them all in one step later: + if isinstance(watcher, IterationErrorWatcher): + watcher.iteration_dependent_errors.revealed_types[ + (context.line, context.column, context.end_line, context.end_column) + ].append(typ) + return + + # Nothing special here; just create the note: + visitor = TypeStrVisitor(options=self.options) + self.note(f'Revealed type is "{typ.accept(visitor)}"', context) + + def reveal_locals(self, type_map: dict[str, Type | None], context: Context) -> None: + # To ensure that the output is predictable on Python < 3.6, + # use an ordered dictionary sorted by variable name + sorted_locals = dict(sorted(type_map.items(), key=lambda t: t[0])) + if sorted_locals: + self.note("Revealed local types are:", context) + for k, v in sorted_locals.items(): + visitor = TypeStrVisitor(options=self.options) + self.note(f" {k}: {v.accept(visitor) if v is not None else None}", context) + else: + self.note("There are no locals to reveal", context) + + def unsupported_type_type(self, item: Type, context: Context) -> None: + self.fail( + f'Cannot instantiate type "type[{format_type_bare(item, self.options)}]"', context + ) + + def redundant_cast(self, typ: Type, context: Context) -> None: + self.fail( + f"Redundant cast to {format_type(typ, self.options)}", + context, + code=codes.REDUNDANT_CAST, + ) + + def assert_type_fail(self, source_type: Type, target_type: Type, context: Context) -> None: + source, target = format_type_distinctly(source_type, target_type, options=self.options) + self.fail(f"Expression is of type {source}, not {target}", context, code=codes.ASSERT_TYPE) + + def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None: + self.fail( + f"{prefix} becomes {format_type(typ, self.options)} due to an unfollowed import", + ctx, + code=codes.NO_ANY_UNIMPORTED, + ) + + def need_annotation_for_var( + self, node: SymbolNode, context: Context, options: Options | None = None + ) -> None: + hint = "" + # type to recommend the user adds + recommended_type = None + # Only gives hint if it's a variable declaration and the partial type is a builtin type + if options and isinstance(node, Var) and isinstance(node.type, PartialType): + type_dec = "" + if not node.type.type: + # partial None + recommended_type = f"{type_dec} | None" + elif node.type.type.fullname in reverse_builtin_aliases: + # partial types other than partial None + name = node.type.type.fullname.partition(".")[2] + if name == "dict": + type_dec = f"{type_dec}, {type_dec}" + recommended_type = f"{name}[{type_dec}]" + if recommended_type is not None: + hint = f' (hint: "{node.name}: {recommended_type} = ...")' + + self.fail( + f'Need type annotation for "{unmangle(node.name)}"{hint}', + context, + code=codes.VAR_ANNOTATED, + ) + + def explicit_any(self, ctx: Context) -> None: + self.fail('Explicit "Any" is not allowed', ctx, code=codes.EXPLICIT_ANY) + + def unsupported_target_for_star_typeddict(self, typ: Type, ctx: Context) -> None: + self.fail( + "Unsupported type {} for ** expansion in TypedDict".format( + format_type(typ, self.options) + ), + ctx, + code=codes.TYPEDDICT_ITEM, + ) + + def non_required_keys_absent_with_star(self, keys: list[str], ctx: Context) -> None: + self.fail( + "Non-required {} not explicitly found in any ** item".format( + format_key_list(keys, short=True) + ), + ctx, + code=codes.TYPEDDICT_ITEM, + ) + + def unexpected_typeddict_keys( + self, + typ: TypedDictType, + expected_keys: list[str], + actual_keys: list[str], + context: Context, + ) -> None: + actual_set = set(actual_keys) + expected_set = set(expected_keys) + if not typ.is_anonymous(): + # Generate simpler messages for some common special cases. + # Use list comprehension instead of set operations to preserve order. + missing = [key for key in expected_keys if key not in actual_set] + if missing: + self.fail( + "Missing {} for TypedDict {}".format( + format_key_list(missing, short=True), format_type(typ, self.options) + ), + context, + code=codes.TYPEDDICT_ITEM, + ) + extra = [key for key in actual_keys if key not in expected_set] + if extra: + self.fail( + "Extra {} for TypedDict {}".format( + format_key_list(extra, short=True), format_type(typ, self.options) + ), + context, + code=codes.TYPEDDICT_UNKNOWN_KEY, + ) + if missing or extra: + # No need to check for further errors + return + found = format_key_list(actual_keys, short=True) + if not expected_keys: + self.fail(f"Unexpected TypedDict {found}", context) + return + expected = format_key_list(expected_keys) + if actual_keys and actual_set < expected_set: + found = f"only {found}" + self.fail(f"Expected {expected} but found {found}", context, code=codes.TYPEDDICT_ITEM) + + def typeddict_key_must_be_string_literal(self, typ: TypedDictType, context: Context) -> None: + self.fail( + "TypedDict key must be a string literal; expected one of {}".format( + format_item_name_list(typ.items.keys()) + ), + context, + code=codes.LITERAL_REQ, + ) + + def typeddict_key_not_found( + self, typ: TypedDictType, item_name: str, context: Context, setitem: bool = False + ) -> None: + """Handle error messages for TypedDicts that have unknown keys. + + Note, that we differentiate in between reading a value and setting a + value. + Setting a value on a TypedDict is an 'unknown-key' error, whereas + reading it is the more serious/general 'item' error. + """ + if typ.is_anonymous(): + self.fail( + '"{}" is not a valid TypedDict key; expected one of {}'.format( + item_name, format_item_name_list(typ.items.keys()) + ), + context, + ) + else: + err_code = codes.TYPEDDICT_UNKNOWN_KEY if setitem else codes.TYPEDDICT_ITEM + self.fail( + f'TypedDict {format_type(typ, self.options)} has no key "{item_name}"', + context, + code=err_code, + ) + matches = best_matches(item_name, typ.items.keys(), n=3) + if matches: + self.note( + "Did you mean {}?".format(pretty_seq(matches, "or")), context, code=err_code + ) + + def typeddict_context_ambiguous(self, types: list[TypedDictType], context: Context) -> None: + formatted_types = ", ".join(list(format_type_distinctly(*types, options=self.options))) + self.fail( + f"Type of TypedDict is ambiguous, none of ({formatted_types}) matches cleanly", context + ) + + def typeddict_key_cannot_be_deleted( + self, typ: TypedDictType, item_name: str, context: Context + ) -> None: + if typ.is_anonymous(): + self.fail(f'TypedDict key "{item_name}" cannot be deleted', context) + else: + self.fail( + f'Key "{item_name}" of TypedDict {format_type(typ, self.options)} cannot be deleted', + context, + ) + + def typeddict_setdefault_arguments_inconsistent( + self, default: Type, expected: Type, context: Context + ) -> None: + msg = 'Argument 2 to "setdefault" of "TypedDict" has incompatible type {}; expected {}' + self.fail( + msg.format(format_type(default, self.options), format_type(expected, self.options)), + context, + code=codes.TYPEDDICT_ITEM, + ) + + def type_arguments_not_allowed(self, context: Context) -> None: + self.fail("Parameterized generics cannot be used with class or instance checks", context) + + def disallowed_any_type(self, typ: Type, context: Context) -> None: + typ = get_proper_type(typ) + if isinstance(typ, AnyType): + message = 'Expression has type "Any"' + else: + message = f'Expression type contains "Any" (has type {format_type(typ, self.options)})' + self.fail(message, context) + + def incorrectly_returning_any(self, typ: Type, context: Context) -> None: + message = ( + f"Returning Any from function declared to return {format_type(typ, self.options)}" + ) + self.fail(message, context, code=codes.NO_ANY_RETURN) + + def incorrect__exit__return(self, context: Context) -> None: + self.fail( + '"bool" is invalid as return type for "__exit__" that always returns False', + context, + code=codes.EXIT_RETURN, + ) + self.note( + 'Use "typing.Literal[False]" as the return type or change it to "None"', + context, + code=codes.EXIT_RETURN, + ) + self.note( + 'If return type of "__exit__" implies that it may return True, ' + "the context manager may swallow exceptions", + context, + code=codes.EXIT_RETURN, + ) + + def untyped_decorated_function(self, typ: Type, context: Context) -> None: + typ = get_proper_type(typ) + if isinstance(typ, AnyType): + self.fail("Function is untyped after decorator transformation", context) + else: + self.fail( + f'Type of decorated function contains type "Any" ({format_type(typ, self.options)})', + context, + ) + + def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None: + self.fail( + f'Untyped decorator makes function "{func_name}" untyped', + context, + code=codes.UNTYPED_DECORATOR, + ) + + def bad_proto_variance( + self, actual: int, tvar_name: str, expected: int, context: Context + ) -> None: + msg = capitalize( + '{} type variable "{}" used in protocol where {} one is expected'.format( + variance_string(actual), tvar_name, variance_string(expected) + ) + ) + self.fail(msg, context) + + def concrete_only_assign(self, typ: Type, context: Context) -> None: + self.fail( + f"Can only assign concrete classes to a variable of type {format_type(typ, self.options)}", + context, + code=codes.TYPE_ABSTRACT, + ) + + def concrete_only_call(self, typ: Type, context: Context) -> None: + self.fail( + f"Only concrete class can be given where {format_type(typ, self.options)} is expected", + context, + code=codes.TYPE_ABSTRACT, + ) + + def cannot_use_function_with_type( + self, method_name: str, type_name: str, context: Context + ) -> None: + self.fail(f"Cannot use {method_name}() with {type_name} type", context) + + def report_non_method_protocol( + self, tp: TypeInfo, members: list[str], context: Context + ) -> None: + self.fail( + "Only protocols that don't have non-method members can be used with issubclass()", + context, + ) + if len(members) < 3: + attrs = ", ".join(members) + self.note(f'Protocol "{tp.name}" has non-method member(s): {attrs}', context) + + def note_call( + self, subtype: Type, call: Type, context: Context, *, code: ErrorCode | None + ) -> None: + self.note( + '"{}.__call__" has type {}'.format( + format_type_bare(subtype, self.options), + format_type(call, self.options, verbosity=1), + ), + context, + code=code, + ) + + def unreachable_statement(self, context: Context) -> None: + self.fail("Statement is unreachable", context, code=codes.UNREACHABLE) + + def redundant_left_operand(self, op_name: str, context: Context) -> None: + """Indicates that the left operand of a boolean expression is redundant: + it does not change the truth value of the entire condition as a whole. + 'op_name' should either be the string "and" or the string "or". + """ + self.redundant_expr(f'Left operand of "{op_name}"', op_name == "and", context) + + def unreachable_right_operand(self, op_name: str, context: Context) -> None: + """Indicates that the right operand of a boolean expression is redundant: + it does not change the truth value of the entire condition as a whole. + 'op_name' should either be the string "and" or the string "or". + """ + self.fail( + f'Right operand of "{op_name}" is never evaluated', context, code=codes.UNREACHABLE + ) + + def redundant_condition_in_comprehension(self, truthiness: bool, context: Context) -> None: + self.redundant_expr("If condition in comprehension", truthiness, context) + + def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None: + self.redundant_expr("If condition", truthiness, context) + + def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None: + self.fail( + f"{description} is always {str(truthiness).lower()}", + context, + code=codes.REDUNDANT_EXPR, + ) + + def impossible_intersection( + self, formatted_base_class_list: str, reason: str, context: Context + ) -> None: + template = "Subclass of {} cannot exist: {}" + self.fail( + template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE + ) + + def tvar_without_default_type( + self, tvar_name: str, last_tvar_name_with_default: str, context: Context + ) -> None: + self.fail( + f'"{tvar_name}" cannot appear after "{last_tvar_name_with_default}" ' + "in type parameter list because it has no default type", + context, + ) + + def report_protocol_problems( + self, + subtype: Instance | TupleType | TypedDictType | TypeType | CallableType, + supertype: Instance, + context: Context, + *, + parent_error: ErrorInfo, + ) -> None: + """Report possible protocol conflicts between 'subtype' and 'supertype'. + + This includes missing members, incompatible types, and incompatible + attribute flags, such as settable vs read-only or class variable vs + instance variable. + """ + OFFSET = 4 # Four spaces, so that notes will look like this: + # note: 'Cls' is missing following 'Proto' members: + # note: method, attr + MAX_ITEMS = 2 # Maximum number of conflicts, missing members, and overloads shown + # List of special situations where we don't want to report additional problems + exclusions: dict[type, list[str]] = { + TypedDictType: ["typing.Mapping"], + TupleType: ["typing.Iterable", "typing.Sequence"], + } + if supertype.type.fullname in exclusions.get(type(subtype), []): + return + if any(isinstance(tp, UninhabitedType) for tp in get_proper_types(supertype.args)): + # We don't want to add notes for failed inference (e.g. Iterable[Never]). + # This will be only confusing a user even more. + return + + class_obj = False + is_module = False + skip = [] + if isinstance(subtype, TupleType): + subtype = subtype.partial_fallback + elif isinstance(subtype, TypedDictType): + subtype = subtype.fallback + elif isinstance(subtype, TypeType): + if not isinstance(subtype.item, Instance): + return + class_obj = True + subtype = subtype.item + elif isinstance(subtype, CallableType): + if subtype.is_type_obj(): + ret_type = get_proper_type(subtype.ret_type) + if isinstance(ret_type, TupleType): + ret_type = ret_type.partial_fallback + if not isinstance(ret_type, Instance): + return + class_obj = True + subtype = ret_type + else: + subtype = subtype.fallback + skip = ["__call__"] + if subtype.extra_attrs and subtype.extra_attrs.mod_name: + is_module = True + + # Report missing members + missing = get_missing_protocol_members(subtype, supertype, skip=skip) + if ( + missing + and (len(missing) < len(supertype.type.protocol_members) or missing == ["__call__"]) + and len(missing) <= MAX_ITEMS + ): + if missing == ["__call__"] and class_obj: + self.note( + '"{}" has constructor incompatible with "__call__" of "{}"'.format( + subtype.type.name, supertype.type.name + ), + context, + parent_error=parent_error, + ) + else: + self.note( + '"{}" is missing following "{}" protocol member{}:'.format( + subtype.type.name, supertype.type.name, plural_s(missing) + ), + context, + parent_error=parent_error, + ) + self.note(", ".join(missing), context, offset=OFFSET, parent_error=parent_error) + elif len(missing) > MAX_ITEMS or len(missing) == len(supertype.type.protocol_members): + # This is an obviously wrong type: too many missing members + return + + # Report member type conflicts + conflict_types = get_conflict_protocol_types( + subtype, supertype, class_obj=class_obj, options=self.options + ) + if conflict_types and ( + not is_subtype(subtype, erase_type(supertype), options=self.options) + or not subtype.type.defn.type_vars + or not supertype.type.defn.type_vars + # Always show detailed message for ParamSpec + or subtype.type.has_param_spec_type + or supertype.type.has_param_spec_type + ): + type_name = format_type(subtype, self.options, module_names=True) + self.note( + f"Following member(s) of {type_name} have conflicts:", + context, + parent_error=parent_error, + ) + for name, got, exp, is_lvalue in conflict_types[:MAX_ITEMS]: + exp = get_proper_type(exp) + got = get_proper_type(got) + setter_suffix = " setter type" if is_lvalue else "" + if ( + not isinstance(exp, (CallableType, Overloaded)) + or not isinstance(got, (CallableType, Overloaded)) + # If expected type is a type object, it means it is a nested class. + # Showing constructor signature in errors would be confusing in this case, + # since we don't check the signature, only subclassing of type objects. + or exp.is_type_obj() + ): + self.note( + "{}: expected{} {}, got {}".format( + name, + setter_suffix, + *format_type_distinctly(exp, got, options=self.options), + ), + context, + offset=OFFSET, + parent_error=parent_error, + ) + if is_lvalue and is_subtype(got, exp, options=self.options): + self.note( + "Setter types should behave contravariantly", + context, + offset=OFFSET, + parent_error=parent_error, + ) + else: + self.note( + "Expected{}:".format(setter_suffix), + context, + offset=OFFSET, + parent_error=parent_error, + ) + if isinstance(exp, CallableType): + self.note( + pretty_callable(exp, self.options, skip_self=class_obj or is_module), + context, + offset=2 * OFFSET, + parent_error=parent_error, + ) + else: + assert isinstance(exp, Overloaded) + self.pretty_overload( + exp, + context, + 2 * OFFSET, + parent_error=parent_error, + skip_self=class_obj or is_module, + ) + self.note("Got:", context, offset=OFFSET, parent_error=parent_error) + if isinstance(got, CallableType): + self.note( + pretty_callable(got, self.options, skip_self=class_obj or is_module), + context, + offset=2 * OFFSET, + parent_error=parent_error, + ) + else: + assert isinstance(got, Overloaded) + self.pretty_overload( + got, + context, + 2 * OFFSET, + parent_error=parent_error, + skip_self=class_obj or is_module, + ) + self.print_more(conflict_types, context, OFFSET, MAX_ITEMS, code=parent_error.code) + + # Report flag conflicts (i.e. settable vs read-only etc.) + conflict_flags = get_bad_protocol_flags(subtype, supertype, class_obj=class_obj) + for name, subflags, superflags in conflict_flags[:MAX_ITEMS]: + if not class_obj and IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags: + self.note( + "Protocol member {}.{} expected instance variable, got class variable".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + if not class_obj and IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags: + self.note( + "Protocol member {}.{} expected class variable, got instance variable".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + if IS_SETTABLE in superflags and IS_SETTABLE not in subflags: + self.note( + "Protocol member {}.{} expected settable variable," + " got read-only attribute".format(supertype.type.name, name), + context, + parent_error=parent_error, + ) + if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags: + self.note( + "Protocol member {}.{} expected class or static method".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + if ( + class_obj + and IS_VAR in superflags + and (IS_VAR in subflags and IS_CLASSVAR not in subflags) + ): + self.note( + "Only class variables allowed for class object access on protocols," + ' {} is an instance variable of "{}"'.format(name, subtype.type.name), + context, + parent_error=parent_error, + ) + if class_obj and IS_CLASSVAR in superflags: + self.note( + "ClassVar protocol member {}.{} can never be matched by a class object".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=parent_error.code) + + def pretty_overload( + self, + tp: Overloaded, + context: Context, + offset: int, + *, + parent_error: ErrorInfo, + add_class_or_static_decorator: bool = False, + skip_self: bool = False, + ) -> None: + for item in tp.items: + self.note("@overload", context, offset=offset, parent_error=parent_error) + + if add_class_or_static_decorator: + decorator = pretty_class_or_static_decorator(item) + if decorator is not None: + self.note(decorator, context, offset=offset, parent_error=parent_error) + + self.note( + pretty_callable(item, self.options, skip_self=skip_self), + context, + offset=offset, + parent_error=parent_error, + ) + + def print_more( + self, + conflicts: Sequence[Any], + context: Context, + offset: int, + max_items: int, + *, + code: ErrorCode | None = None, + ) -> None: + if len(conflicts) > max_items: + self.note( + f"<{len(conflicts) - max_items} more conflict(s) not shown>", + context, + offset=offset, + code=code, + ) + + def try_report_long_tuple_assignment_error( + self, + subtype: ProperType, + supertype: ProperType, + context: Context, + msg: message_registry.ErrorMessage, + subtype_label: str | None = None, + supertype_label: str | None = None, + ) -> bool: + """Try to generate meaningful error message for very long tuple assignment + + Returns a bool: True when generating long tuple assignment error, + False when no such error reported + """ + if isinstance(subtype, TupleType): + if ( + len(subtype.items) > MAX_TUPLE_ITEMS + and isinstance(supertype, Instance) + and supertype.type.fullname == "builtins.tuple" + ): + lhs_type = supertype.args[0] + lhs_types = [lhs_type] * len(subtype.items) + self.generate_incompatible_tuple_error(lhs_types, subtype.items, context, msg) + return True + elif isinstance(supertype, TupleType) and ( + len(subtype.items) > MAX_TUPLE_ITEMS or len(supertype.items) > MAX_TUPLE_ITEMS + ): + if len(subtype.items) != len(supertype.items): + if supertype_label is not None and subtype_label is not None: + msg = msg.with_additional_msg( + " ({} {}, {} {})".format( + subtype_label, + self.format_long_tuple_type(subtype), + supertype_label, + self.format_long_tuple_type(supertype), + ) + ) + self.fail(msg.value, context, code=msg.code) + return True + self.generate_incompatible_tuple_error( + supertype.items, subtype.items, context, msg + ) + return True + return False + + def format_long_tuple_type(self, typ: TupleType) -> str: + """Format very long tuple type using an ellipsis notation""" + item_cnt = len(typ.items) + if item_cnt > MAX_TUPLE_ITEMS: + return '"tuple[{}, {}, ... <{} more items>]"'.format( + format_type_bare(typ.items[0], self.options), + format_type_bare(typ.items[1], self.options), + str(item_cnt - 2), + ) + else: + return format_type(typ, self.options) + + def generate_incompatible_tuple_error( + self, + lhs_types: list[Type], + rhs_types: list[Type], + context: Context, + msg: message_registry.ErrorMessage, + ) -> None: + """Generate error message for individual incompatible tuple pairs""" + error_cnt = 0 + notes: list[str] = [] + for i, (lhs_t, rhs_t) in enumerate(zip(lhs_types, rhs_types)): + if not is_subtype(rhs_t, lhs_t): + if error_cnt < 3: + notes.append( + "Expression tuple item {} has type {}; {} expected; ".format( + str(i), + format_type(rhs_t, self.options), + format_type(lhs_t, self.options), + ) + ) + error_cnt += 1 + + info = f" ({str(error_cnt)} tuple items are incompatible" + if error_cnt - 3 > 0: + info += f"; {str(error_cnt - 3)} items are omitted)" + else: + info += ")" + msg = msg.with_additional_msg(info) + self.fail(msg.value, context, code=msg.code) + for note in notes: + self.note(note, context, code=msg.code) + + def add_fixture_note(self, fullname: str, ctx: Context) -> None: + self.note(f'Maybe your test fixture does not define "{fullname}"?', ctx) + if fullname in SUGGESTED_TEST_FIXTURES: + self.note( + "Consider adding [builtins fixtures/{}] to your test description".format( + SUGGESTED_TEST_FIXTURES[fullname] + ), + ctx, + ) + + def annotation_in_unchecked_function(self, context: Context) -> None: + self.note( + "By default the bodies of untyped functions are not checked," + " consider using --check-untyped-defs", + context, + code=codes.ANNOTATION_UNCHECKED, + ) + + def type_parameters_should_be_declared(self, undeclared: list[str], context: Context) -> None: + names = ", ".join('"' + n + '"' for n in undeclared) + self.fail( + message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(names), + context, + code=codes.VALID_TYPE, + ) + + def match_statement_inexhaustive_match(self, typ: Type, context: Context) -> None: + type_str = format_type(typ, self.options) + msg = f"Match statement has unhandled case for values of type {type_str}" + self.fail(msg, context, code=codes.EXHAUSTIVE_MATCH) + self.note( + "If match statement is intended to be non-exhaustive, add `case _: pass`", + context, + code=codes.EXHAUSTIVE_MATCH, + ) + + def iteration_dependent_errors(self, iter_errors: IterationDependentErrors) -> None: + for error_info in iter_errors.yield_uselessness_error_infos(): + self.fail(*error_info[:2], code=error_info[2]) + for nonoverlaps, kind, context in iter_errors.yield_nonoverlapping_types(): + self.dangerous_comparison( + mypy.typeops.make_simplified_union(nonoverlaps[0]), + mypy.typeops.make_simplified_union(nonoverlaps[1]), + kind, + context, + ) + for types, context in iter_errors.yield_revealed_type_infos(): + self.reveal_type(mypy.typeops.make_simplified_union(types), context) + + +def quote_type_string(type_string: str) -> str: + """Quotes a type representation for use in messages.""" + if ( + type_string in ["Module", "overloaded function", ""] + or type_string.startswith("Module ") + or type_string.endswith("?") + ): + # These messages are easier to read if these aren't quoted. + return type_string + return f'"{type_string}"' + + +def should_format_arg_as_type(arg_kind: ArgKind, arg_name: str | None, verbosity: int) -> bool: + """ + Determine whether a function argument should be formatted as its Type or with name. + """ + return (arg_kind == ARG_POS and arg_name is None) or ( + verbosity == 0 and arg_kind.is_positional() + ) + + +def format_callable_args( + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: list[str | None], + format: Callable[[Type], str], + verbosity: int, +) -> str: + """Format a bunch of Callable arguments into a string""" + arg_strings = [] + for arg_name, arg_type, arg_kind in zip(arg_names, arg_types, arg_kinds): + if should_format_arg_as_type(arg_kind, arg_name, verbosity): + arg_strings.append(format(arg_type)) + else: + constructor = ARG_CONSTRUCTOR_NAMES[arg_kind] + if arg_kind.is_star() or arg_name is None: + arg_strings.append(f"{constructor}({format(arg_type)})") + else: + arg_strings.append(f"{constructor}({format(arg_type)}, {repr(arg_name)})") + + return ", ".join(arg_strings) + + +def format_type_inner( + typ: Type, + verbosity: int, + options: Options, + fullnames: set[str] | None, + module_names: bool = False, + use_pretty_callable: bool = True, +) -> str: + """ + Convert a type to a relatively short string suitable for error messages. + + Args: + typ: type to be formatted + verbosity: a coarse grained control on the verbosity of the type + options: Options object controlling formatting + fullnames: a set of names that should be printed in full + module_names: whether to show module names for module types + use_pretty_callable: use pretty_callable to format Callable types. + """ + + def format(typ: Type) -> str: + return format_type_inner(typ, verbosity, options, fullnames) + + def format_list(types: Sequence[Type]) -> str: + return ", ".join(format(typ) for typ in types) + + def format_union_items(types: Sequence[Type]) -> list[str]: + formatted = [format(typ) for typ in types if format(typ) != "None"] + if len(formatted) > MAX_UNION_ITEMS and verbosity == 0: + more = len(formatted) - MAX_UNION_ITEMS // 2 + formatted = formatted[: MAX_UNION_ITEMS // 2] + else: + more = 0 + if more: + formatted.append(f"<{more} more items>") + if any(format(typ) == "None" for typ in types): + formatted.append("None") + return formatted + + def format_union(types: Sequence[Type]) -> str: + return " | ".join(format_union_items(types)) + + def format_literal_value(typ: LiteralType) -> str: + if typ.is_enum_literal(): + underlying_type = format(typ.fallback) + return f"{underlying_type}.{typ.value}" + else: + return typ.value_repr() + + if isinstance(typ, TypeAliasType) and typ.is_recursive: + if typ.alias is None: + type_str = "" + else: + if verbosity >= 2 or (fullnames and typ.alias.fullname in fullnames): + type_str = typ.alias.fullname + else: + type_str = typ.alias.name + if typ.args: + type_str += f"[{format_list(typ.args)}]" + return type_str + + # TODO: always mention type alias names in errors. + typ = get_proper_type(typ) + + if isinstance(typ, Instance): + itype = typ + # Get the short name of the type. + if itype.type.fullname == "types.ModuleType": + # Make some common error messages simpler and tidier. + base_str = "Module" + if itype.extra_attrs and itype.extra_attrs.mod_name and module_names: + return f'{base_str} "{itype.extra_attrs.mod_name}"' + return base_str + if itype.type.fullname == "typing._SpecialForm": + # This is not a real type but used for some typing-related constructs. + return "" + if verbosity >= 2 or (fullnames and itype.type.fullname in fullnames): + base_str = itype.type.fullname + else: + base_str = itype.type.name + if not itype.args: + if itype.type.has_type_var_tuple_type and len(itype.type.type_vars) == 1: + return base_str + "[()]" + # No type arguments, just return the type name + return base_str + elif itype.type.fullname == "builtins.tuple": + item_type_str = format(itype.args[0]) + return f"tuple[{item_type_str}, ...]" + else: + # There are type arguments. Convert the arguments to strings. + return f"{base_str}[{format_list(itype.args)}]" + elif isinstance(typ, UnpackType): + if options.use_star_unpack(): + return f"*{format(typ.type)}" + return f"Unpack[{format(typ.type)}]" + elif isinstance(typ, TypeVarType): + # This is similar to non-generic instance types. + fullname = scoped_type_var_name(typ) + if verbosity >= 2 or (fullnames and fullname in fullnames): + return fullname + return typ.name + elif isinstance(typ, TypeVarTupleType): + # This is similar to non-generic instance types. + fullname = scoped_type_var_name(typ) + if verbosity >= 2 or (fullnames and fullname in fullnames): + return fullname + return typ.name + elif isinstance(typ, ParamSpecType): + # Concatenate[..., P] + if typ.prefix.arg_types: + args = format_callable_args( + typ.prefix.arg_types, typ.prefix.arg_kinds, typ.prefix.arg_names, format, verbosity + ) + + return f"[{args}, **{typ.name_with_suffix()}]" + else: + # TODO: better disambiguate ParamSpec name clashes. + return typ.name_with_suffix() + elif isinstance(typ, TupleType): + # Prefer the name of the fallback class (if not tuple), as it's more informative. + if typ.partial_fallback.type.fullname != "builtins.tuple": + return format(typ.partial_fallback) + type_items = format_list(typ.items) or "()" + return f"tuple[{type_items}]" + elif isinstance(typ, TypedDictType): + # If the TypedDictType is named, return the name + if not typ.is_anonymous(): + return format(typ.fallback) + items = [] + for item_name, item_type in typ.items.items(): + modifier = "" + if item_name not in typ.required_keys: + modifier += "?" + if item_name in typ.readonly_keys: + modifier += "=" + items.append(f"{item_name!r}{modifier}: {format(item_type)}") + return f"TypedDict({{{', '.join(items)}}})" + elif isinstance(typ, LiteralType): + return f"Literal[{format_literal_value(typ)}]" + elif isinstance(typ, UnionType): + typ = get_proper_type(ignore_last_known_values(typ)) + if not isinstance(typ, UnionType): + return format(typ) + literal_items, union_items = separate_union_literals(typ) + + # Coalesce multiple Literal[] members. This also changes output order. + # If there's just one Literal item, retain the original ordering. + if len(literal_items) > 1: + literal_str = "Literal[{}]".format( + ", ".join(format_literal_value(t) for t in literal_items) + ) + + if len(union_items) == 1 and isinstance(get_proper_type(union_items[0]), NoneType): + return f"{literal_str} | None" + elif union_items: + return f"{literal_str} | {format_union(union_items)}" + else: + return literal_str + else: + # Only print Union as Optional if the Optional wouldn't have to contain another Union + print_as_optional = ( + len(typ.items) - sum(isinstance(get_proper_type(t), NoneType) for t in typ.items) + == 1 + ) + if print_as_optional: + rest = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)] + return f"{format(rest[0])} | None" + else: + s = format_union(typ.items) + return s + elif isinstance(typ, NoneType): + return "None" + elif isinstance(typ, AnyType): + return "Any" + elif isinstance(typ, DeletedType): + return "" + elif isinstance(typ, UninhabitedType): + return "Never" + elif isinstance(typ, TypeType): + if typ.is_type_form: + type_name = "TypeForm" + else: + type_name = "type" + return f"{type_name}[{format(typ.item)}]" + elif isinstance(typ, FunctionLike): + func = typ + if func.is_type_obj(): + # The type of a type object type can be derived from the + # return type (this always works). + return format(TypeType.make_normalized(func.items[0].ret_type)) + elif isinstance(func, CallableType): + if func.type_guard is not None: + return_type = f"TypeGuard[{format(func.type_guard)}]" + elif func.type_is is not None: + return_type = f"TypeIs[{format(func.type_is)}]" + else: + return_type = format(func.ret_type) + if func.is_ellipsis_args: + return f"Callable[..., {return_type}]" + param_spec = func.param_spec() + if param_spec is not None: + return f"Callable[{format(param_spec)}, {return_type}]" + + # Use pretty format (def-style) for complex signatures with named, optional, or star args. + # Use compact Callable[[...], ...] only for signatures with all simple positional args. + if use_pretty_callable: + if any( + not should_format_arg_as_type(kind, name, verbosity) + for kind, name in zip(func.arg_kinds, func.arg_names) + ): + return pretty_callable(func, options) + + args = format_callable_args( + func.arg_types, func.arg_kinds, func.arg_names, format, verbosity + ) + return f"Callable[[{args}], {return_type}]" + else: + # Use a simple representation for function types; proper + # function types may result in long and difficult-to-read + # error messages. + return "overloaded function" + elif isinstance(typ, UnboundType): + return typ.accept(TypeStrVisitor(options=options)) + elif isinstance(typ, Parameters): + args = format_callable_args(typ.arg_types, typ.arg_kinds, typ.arg_names, format, verbosity) + return f"[{args}]" + elif typ is None: + raise RuntimeError("Type is None") + else: + # Default case; we simply have to return something meaningful here. + return "object" + + +def collect_all_named_types(t: Type) -> list[Type]: + """Return all instances/aliases/type variables that `t` contains (including `t`). + + This is similar to collect_all_inner_types from typeanal but only + returns instances and will recurse into fallbacks. + """ + visitor = CollectAllNamedTypesQuery() + t.accept(visitor) + return visitor.types + + +class CollectAllNamedTypesQuery(TypeTraverserVisitor): + def __init__(self) -> None: + self.types: list[Type] = [] + + def visit_instance(self, t: Instance) -> None: + self.types.append(t) + super().visit_instance(t) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + if t.alias and not t.is_recursive: + get_proper_type(t).accept(self) + else: + self.types.append(t) + super().visit_type_alias_type(t) + + def visit_type_var(self, t: TypeVarType) -> None: + self.types.append(t) + super().visit_type_var(t) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: + self.types.append(t) + super().visit_type_var_tuple(t) + + def visit_param_spec(self, t: ParamSpecType) -> None: + self.types.append(t) + super().visit_param_spec(t) + + +def scoped_type_var_name(t: TypeVarLikeType) -> str: + if not t.id.namespace: + return t.name + # TODO: support rare cases when both TypeVar name and namespace suffix coincide. + *_, suffix = t.id.namespace.split(".") + return f"{t.name}@{suffix}" + + +def find_type_overlaps(*types: Type) -> set[str]: + """Return a set of fullnames that share a short name and appear in either type. + + This is used to ensure that distinct types with the same short name are printed + with their fullname. + """ + d: dict[str, set[str]] = {} + for type in types: + for t in collect_all_named_types(type): + if isinstance(t, ProperType) and isinstance(t, Instance): + d.setdefault(t.type.name, set()).add(t.type.fullname) + elif isinstance(t, TypeAliasType) and t.alias: + d.setdefault(t.alias.name, set()).add(t.alias.fullname) + else: + assert isinstance(t, TypeVarLikeType) + d.setdefault(t.name, set()).add(scoped_type_var_name(t)) + for shortname in d.keys(): + if f"typing.{shortname}" in TYPES_FOR_UNIMPORTED_HINTS: + d[shortname].add(f"typing.{shortname}") + + overlaps: set[str] = set() + for fullnames in d.values(): + if len(fullnames) > 1: + overlaps.update(fullnames) + return overlaps + + +def format_type( + typ: Type, options: Options, verbosity: int = 0, module_names: bool = False +) -> str: + """ + Convert a type to a relatively short string suitable for error messages. + + `verbosity` is a coarse-grained control on the verbosity of the type + + This function returns a string appropriate for unmodified use in error + messages; this means that it will be quoted in most cases. If + modification of the formatted string is required, callers should use + format_type_bare. + """ + return quote_type_string(format_type_bare(typ, options, verbosity, module_names)) + + +def format_type_bare( + typ: Type, options: Options, verbosity: int = 0, module_names: bool = False +) -> str: + """ + Convert a type to a relatively short string suitable for error messages. + + `verbosity` is a coarse-grained control on the verbosity of the type + `fullnames` specifies a set of names that should be printed in full + + This function will return an unquoted string. If a caller doesn't need to + perform post-processing on the string output, format_type should be used + instead. (The caller may want to use quote_type_string after + processing has happened, to maintain consistent quoting in messages.) + """ + return format_type_inner(typ, verbosity, options, find_type_overlaps(typ), module_names) + + +def format_type_distinctly(*types: Type, options: Options, bare: bool = False) -> tuple[str, ...]: + """Jointly format types to distinct strings. + + Increase the verbosity of the type strings until they become distinct + while also requiring that distinct types with the same short name are + formatted distinctly. + + By default, the returned strings are created using format_type() and will be + quoted accordingly. If ``bare`` is True, the returned strings will not + be quoted; callers who need to do post-processing of the strings before + quoting them (such as prepending * or **) should use this. + """ + overlapping = find_type_overlaps(*types) + + def format_single(arg: Type) -> str: + return format_type_inner(arg, verbosity=0, options=options, fullnames=overlapping) + + min_verbosity = 0 + # Prevent emitting weird errors like: + # ... has incompatible type "Callable[[int], Child]"; expected "Callable[[int], Parent]" + if len(types) == 2: + left, right = types + left = get_proper_type(left) + right = get_proper_type(right) + # If the right type has named arguments, they may be the reason for incompatibility. + # This excludes cases when right is Callable[[Something], None] without named args, + # because that's usually the right thing to do. + if ( + isinstance(left, CallableType) + and isinstance(right, CallableType) + and any(right.arg_names) + and is_subtype(left, right, ignore_pos_arg_names=True) + ): + min_verbosity = 1 + + for verbosity in range(min_verbosity, 2): + strs = [ + format_type_inner(type, verbosity=verbosity, options=options, fullnames=overlapping) + for type in types + ] + if len(set(strs)) == len(strs): + break + if bare: + return tuple(strs) + else: + return tuple(quote_type_string(s) for s in strs) + + +def pretty_class_or_static_decorator(tp: CallableType) -> str | None: + """Return @classmethod or @staticmethod, if any, for the given callable type.""" + definition = get_func_def(tp) + if definition is not None and isinstance(definition, SYMBOL_FUNCBASE_TYPES): + if definition.is_class: + return "@classmethod" + if definition.is_static: + return "@staticmethod" + return None + + +def pretty_callable(tp: CallableType, options: Options, skip_self: bool = False) -> str: + """Return a nice easily-readable representation of a callable type. + For example: + def [T <: int] f(self, x: int, y: T) -> None + + If skip_self is True, print an actual callable type, as it would appear + when bound on an instance/class, rather than how it would appear in the + defining statement. + """ + s = "" + asterisk = False + slash = False + for i in range(len(tp.arg_types)): + if s: + s += ", " + if tp.arg_kinds[i].is_named() and not asterisk: + s += "*, " + asterisk = True + if tp.arg_kinds[i] == ARG_STAR: + s += "*" + asterisk = True + if tp.arg_kinds[i] == ARG_STAR2: + s += "**" + name = tp.arg_names[i] + if not name and not options.reveal_verbose_types: + # Avoid ambiguous (and weird) formatting for anonymous args/kwargs. + if tp.arg_kinds[i] == ARG_STAR and isinstance(tp.arg_types[i], UnpackType): + name = "args" + elif tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs: + name = "kwargs" + if name: + s += name + ": " + type_str = format_type_bare(tp.arg_types[i], options) + if tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs: + if options.reveal_verbose_types: + type_str = f"Unpack[{type_str}]" + else: + type_str = f"**{type_str}" + s += type_str + if tp.arg_kinds[i].is_optional(): + s += " = ..." + if ( + not slash + and tp.arg_kinds[i].is_positional() + and name is None + and ( + i == len(tp.arg_types) - 1 + or (tp.arg_names[i + 1] is not None or not tp.arg_kinds[i + 1].is_positional()) + ) + ): + s += ", /" + slash = True + + definition = get_func_def(tp) + + # Extract function name, prefer the "human-readable" name if available. + func_name = None + if tp.name: + func_name = tp.name.split()[0] # skip "of Class" part + elif isinstance(definition, FuncDef): + func_name = definition.name + + # If we got a "special arg" (i.e: self, cls, etc...), prepend it to the arg list + first_arg = None + if ( + isinstance(definition, FuncDef) + and hasattr(definition, "arguments") + and not tp.from_concatenate + ): + definition_arg_names = [arg.variable.name for arg in definition.arguments] + if len(definition_arg_names) > len(tp.arg_names) and definition_arg_names[0]: + first_arg = definition_arg_names[0] + else: + # TODO: avoid different logic for incremental runs. + first_arg = get_first_arg(tp) + + if tp.is_type_obj(): + skip_self = True + if first_arg and not skip_self: + if s: + s = ", " + s + s = first_arg + s + if func_name: + s = f"{func_name}({s})" + else: + s = f"({s})" + + s += " -> " + if tp.type_guard is not None: + s += f"TypeGuard[{format_type_bare(tp.type_guard, options)}]" + elif tp.type_is is not None: + s += f"TypeIs[{format_type_bare(tp.type_is, options)}]" + else: + s += format_type_bare(tp.ret_type, options) + + if tp.variables: + tvars = [] + for tvar in tp.variables: + if isinstance(tvar, TypeVarType): + upper_bound = get_proper_type(tvar.upper_bound) + if not ( + isinstance(upper_bound, Instance) + and upper_bound.type.fullname == "builtins.object" + ): + tvars.append(f"{tvar.name}: {format_type_bare(upper_bound, options)}") + elif tvar.values: + tvars.append( + "{}: ({})".format( + tvar.name, + ", ".join([format_type_bare(tp, options) for tp in tvar.values]), + ) + ) + else: + tvars.append(tvar.name) + else: + # For other TypeVarLikeTypes, just use the repr + tvars.append(repr(tvar)) + s = f"[{', '.join(tvars)}] {s}" + return f"def {s}" + + +def get_first_arg(tp: CallableType) -> str | None: + definition = get_func_def(tp) + if not isinstance(definition, FuncDef) or not definition.info or definition.is_static: + return None + return definition.original_first_arg + + +def variance_string(variance: int) -> str: + if variance == COVARIANT: + return "covariant" + elif variance == CONTRAVARIANT: + return "contravariant" + else: + return "invariant" + + +def get_missing_protocol_members(left: Instance, right: Instance, skip: list[str]) -> list[str]: + """Find all protocol members of 'right' that are not implemented + (i.e. completely missing) in 'left'. + """ + assert right.type.is_protocol + missing: list[str] = [] + for member in right.type.protocol_members: + if member in skip: + continue + if not find_member(member, left, left): + missing.append(member) + return missing + + +def get_conflict_protocol_types( + left: Instance, right: Instance, class_obj: bool = False, options: Options | None = None +) -> list[tuple[str, Type, Type, bool]]: + """Find members that are defined in 'left' but have incompatible types. + Return them as a list of ('member', 'got', 'expected', 'is_lvalue'). + """ + assert right.type.is_protocol + conflicts: list[tuple[str, Type, Type, bool]] = [] + for member in right.type.protocol_members: + if member in ("__init__", "__new__"): + continue + supertype = find_member(member, right, left) + assert supertype is not None + subtype = mypy.typeops.get_protocol_member(left, member, class_obj) + if not subtype: + continue + is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True, options=options) + if not is_compat: + conflicts.append((member, subtype, supertype, False)) + superflags = get_member_flags(member, right) + if IS_SETTABLE not in superflags: + continue + different_setter = False + if IS_EXPLICIT_SETTER in superflags: + set_supertype = find_member(member, right, left, is_lvalue=True) + if set_supertype and not is_same_type(set_supertype, supertype): + different_setter = True + supertype = set_supertype + if IS_EXPLICIT_SETTER in get_member_flags(member, left): + set_subtype = mypy.typeops.get_protocol_member(left, member, class_obj, is_lvalue=True) + if set_subtype and not is_same_type(set_subtype, subtype): + different_setter = True + subtype = set_subtype + if not is_compat and not different_setter: + # We already have this conflict listed, avoid duplicates. + continue + assert supertype is not None and subtype is not None + is_compat = is_subtype(supertype, subtype, options=options) + if not is_compat: + conflicts.append((member, subtype, supertype, different_setter)) + return conflicts + + +def get_bad_protocol_flags( + left: Instance, right: Instance, class_obj: bool = False +) -> list[tuple[str, set[int], set[int]]]: + """Return all incompatible attribute flags for members that are present in both + 'left' and 'right'. + """ + assert right.type.is_protocol + all_flags: list[tuple[str, set[int], set[int]]] = [] + for member in right.type.protocol_members: + if find_member(member, left, left, class_obj=class_obj): + all_flags.append( + ( + member, + get_member_flags(member, left, class_obj=class_obj), + get_member_flags(member, right), + ) + ) + bad_flags = [] + for name, subflags, superflags in all_flags: + if ( + IS_CLASSVAR in subflags + and IS_CLASSVAR not in superflags + and IS_SETTABLE in superflags + or IS_CLASSVAR in superflags + and IS_CLASSVAR not in subflags + or IS_SETTABLE in superflags + and IS_SETTABLE not in subflags + or IS_CLASS_OR_STATIC in superflags + and IS_CLASS_OR_STATIC not in subflags + or class_obj + and IS_VAR in superflags + and IS_CLASSVAR not in subflags + or class_obj + and IS_CLASSVAR in superflags + ): + bad_flags.append((name, subflags, superflags)) + return bad_flags + + +def capitalize(s: str) -> str: + """Capitalize the first character of a string.""" + if s == "": + return "" + else: + return s[0].upper() + s[1:] + + +def extract_type(name: str) -> str: + """If the argument is the name of a method (of form C.m), return + the type portion in quotes (e.g. "y"). Otherwise, return the string + unmodified. + """ + name = re.sub('^"[a-zA-Z0-9_]+" of ', "", name) + return name + + +def strip_quotes(s: str) -> str: + """Strip a double quote at the beginning and end of the string, if any.""" + s = re.sub('^"', "", s) + s = re.sub('"$', "", s) + return s + + +def format_string_list(lst: list[str]) -> str: + assert lst + if len(lst) == 1: + return lst[0] + elif len(lst) <= 5: + return f"{', '.join(lst[:-1])} and {lst[-1]}" + else: + return "%s, ... and %s (%i methods suppressed)" % ( + ", ".join(lst[:2]), + lst[-1], + len(lst) - 3, + ) + + +def format_item_name_list(s: Iterable[str]) -> str: + lst = list(s) + if len(lst) <= 5: + return "(" + ", ".join([f'"{name}"' for name in lst]) + ")" + else: + return "(" + ", ".join([f'"{name}"' for name in lst[:5]]) + ", ...)" + + +def callable_name(type: FunctionLike) -> str | None: + name = type.get_name() + if name is not None and name[0] != "<": + return f'"{name}"'.replace(" of ", '" of "') + return name + + +def for_function(callee: CallableType) -> str: + name = callable_name(callee) + if name is not None: + return f" for {name}" + return "" + + +def wrong_type_arg_count(low: int, high: int, act: str, name: str) -> str: + if low == high: + s = f"{low} type arguments" + if low == 0: + s = "no type arguments" + elif low == 1: + s = "1 type argument" + else: + s = f"between {low} and {high} type arguments" + if act == "0": + act = "none" + return f'"{name}" expects {s}, but {act} given' + + +def find_defining_module(modules: dict[str, MypyFile], typ: CallableType) -> MypyFile | None: + if not typ.definition: + return None + fullname = typ.definition.fullname + if "." in fullname: + for i in range(fullname.count(".")): + module_name = fullname.rsplit(".", i + 1)[0] + try: + return modules[module_name] + except KeyError: + pass + assert False, "Couldn't determine module from CallableType" + return None + + +# For hard-coding suggested missing member alternatives. +COMMON_MISTAKES: Final[dict[str, Sequence[str]]] = {"add": ("append", "extend")} + + +def _real_quick_ratio(a: str, b: str) -> float: + # this is an upper bound on difflib.SequenceMatcher.ratio + # similar to difflib.SequenceMatcher.real_quick_ratio, but faster since we don't instantiate + al = len(a) + bl = len(b) + return 2.0 * min(al, bl) / (al + bl) + + +def best_matches(current: str, options: Collection[str], n: int) -> list[str]: + if not current: + return [] + # narrow down options cheaply + options = [o for o in options if _real_quick_ratio(current, o) > 0.75] + if len(options) >= 50: + options = [o for o in options if abs(len(o) - len(current)) <= 1] + + ratios = {option: difflib.SequenceMatcher(a=current, b=option).ratio() for option in options} + options = [option for option, ratio in ratios.items() if ratio > 0.75] + return sorted(options, key=lambda v: (-ratios[v], v))[:n] + + +def pretty_seq(args: Sequence[str], conjunction: str) -> str: + quoted = ['"' + a + '"' for a in args] + if len(quoted) == 1: + return quoted[0] + if len(quoted) == 2: + return f"{quoted[0]} {conjunction} {quoted[1]}" + last_sep = ", " + conjunction + " " + return ", ".join(quoted[:-1]) + last_sep + quoted[-1] + + +def append_invariance_notes( + notes: list[str], arg_type: Instance, expected_type: Instance +) -> list[str]: + """Explain that the type is invariant and give notes for how to solve the issue.""" + invariant_type = "" + covariant_suggestion = "" + if ( + arg_type.type.fullname == "builtins.list" + and expected_type.type.fullname == "builtins.list" + and is_subtype(arg_type.args[0], expected_type.args[0]) + ): + invariant_type = "list" + covariant_suggestion = 'Consider using "Sequence" instead, which is covariant' + elif ( + arg_type.type.fullname == "builtins.dict" + and expected_type.type.fullname == "builtins.dict" + and is_same_type(arg_type.args[0], expected_type.args[0]) + and is_subtype(arg_type.args[1], expected_type.args[1]) + ): + invariant_type = "dict" + covariant_suggestion = ( + 'Consider using "Mapping" instead, which is covariant in the value type' + ) + if invariant_type and covariant_suggestion: + notes.append( + f'"{invariant_type}" is invariant -- see ' + + "https://mypy.readthedocs.io/en/stable/common_issues.html#variance" + ) + notes.append(covariant_suggestion) + return notes + + +def append_union_note( + notes: list[str], arg_type: UnionType, expected_type: UnionType, options: Options +) -> list[str]: + """Point to specific union item(s) that may cause failure in subtype check.""" + non_matching = [] + items = flatten_nested_unions(arg_type.items) + if len(items) < MAX_UNION_ITEMS: + return notes + for item in items: + if not is_subtype(item, expected_type): + non_matching.append(item) + if non_matching: + types = ", ".join([format_type(typ, options) for typ in non_matching]) + notes.append(f"Item{plural_s(non_matching)} in the first union not in the second: {types}") + return notes + + +def append_numbers_notes( + notes: list[str], arg_type: Instance, expected_type: Instance +) -> list[str]: + """Explain if an unsupported type from "numbers" is used in a subtype check.""" + if expected_type.type.fullname in UNSUPPORTED_NUMBERS_TYPES: + notes.append('Types from "numbers" are not supported for static type checking') + notes.append("See https://peps.python.org/pep-0484/#the-numeric-tower") + notes.append("Consider using a protocol instead, such as typing.SupportsFloat") + return notes + + +def make_inferred_type_note( + context: Context, subtype: Type, supertype: Type, supertype_str: str +) -> str: + """Explain that the user may have forgotten to type a variable. + + The user does not expect an error if the inferred container type is the same as the return + type of a function and the argument type(s) are a subtype of the argument type(s) of the + return type. This note suggests that they add a type annotation with the return type instead + of relying on the inferred type. + """ + subtype = get_proper_type(subtype) + supertype = get_proper_type(supertype) + if ( + isinstance(subtype, Instance) + and isinstance(supertype, Instance) + and subtype.type.fullname == supertype.type.fullname + and subtype.args + and supertype.args + and isinstance(context, ReturnStmt) + and isinstance(context.expr, NameExpr) + and isinstance(context.expr.node, Var) + and context.expr.node.is_inferred + ): + for subtype_arg, supertype_arg in zip(subtype.args, supertype.args): + if not is_subtype(subtype_arg, supertype_arg): + return "" + var_name = context.expr.name + return 'Perhaps you need a type annotation for "{}"? Suggestion: {}'.format( + var_name, supertype_str + ) + return "" + + +def format_key_list(keys: list[str], *, short: bool = False) -> str: + formatted_keys = [f'"{key}"' for key in keys] + td = "" if short else "TypedDict " + if len(keys) == 0: + return f"no {td}keys" + elif len(keys) == 1: + return f"{td}key {formatted_keys[0]}" + else: + return f"{td}keys ({', '.join(formatted_keys)})" + + +def ignore_last_known_values(t: UnionType) -> Type: + """This will avoid types like str | str in error messages. + + last_known_values are kept during union simplification, but may cause + weird formatting for e.g. tuples of literals. + """ + union_items: list[Type] = [] + seen_instances = set() + for item in t.items: + if isinstance(item, ProperType) and isinstance(item, Instance): + erased = item.copy_modified(last_known_value=None) + if erased in seen_instances: + continue + seen_instances.add(erased) + union_items.append(erased) + else: + union_items.append(item) + return UnionType.make_union(union_items, t.line, t.column) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/metastore.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/metastore.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b6646c70f021deed6dd7d8a9f738c0c8e4761b67 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/metastore.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/metastore.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/metastore.py new file mode 100644 index 0000000000000000000000000000000000000000..e12c0e26588302c36952791a74bb5c4ab0732942 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/metastore.py @@ -0,0 +1,243 @@ +"""Interfaces for accessing metadata. + +We provide two implementations. + * The "classic" file system implementation, which uses a directory + structure of files. + * A hokey sqlite backed implementation, which basically simulates + the file system in an effort to work around poor file system performance + on OS X. +""" + +from __future__ import annotations + +import binascii +import os +import time +from abc import abstractmethod +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any + +from mypy.util import os_path_join + +if TYPE_CHECKING: + # We avoid importing sqlite3 unless we are using it so we can mostly work + # on semi-broken pythons that are missing it. + import sqlite3 + + +class MetadataStore: + """Generic interface for metadata storage.""" + + @abstractmethod + def getmtime(self, name: str) -> float: + """Read the mtime of a metadata entry. + + Raises FileNotFound if the entry does not exist. + """ + + @abstractmethod + def read(self, name: str) -> bytes: + """Read the contents of a metadata entry. + + Raises FileNotFound if the entry does not exist. + """ + + @abstractmethod + def write(self, name: str, data: bytes, mtime: float | None = None) -> bool: + """Write a metadata entry. + + If mtime is specified, set it as the mtime of the entry. Otherwise, + the current time is used. + + Returns True if the entry is successfully written, False otherwise. + """ + + @abstractmethod + def remove(self, name: str) -> None: + """Delete a metadata entry""" + + @abstractmethod + def commit(self) -> None: + """If the backing store requires a commit, do it. + + But N.B. that this is not *guaranteed* to do anything, and + there is no guarantee that changes are not made until it is + called. + """ + + @abstractmethod + def list_all(self) -> Iterable[str]: ... + + @abstractmethod + def close(self) -> None: + """Release any resources held by the backing store.""" + + +def random_string() -> str: + return binascii.hexlify(os.urandom(8)).decode("ascii") + + +class FilesystemMetadataStore(MetadataStore): + def __init__(self, cache_dir_prefix: str) -> None: + # We check startswith instead of equality because the version + # will have already been appended by the time the cache dir is + # passed here. + if cache_dir_prefix.startswith(os.devnull): + self.cache_dir_prefix = None + else: + self.cache_dir_prefix = cache_dir_prefix + + def getmtime(self, name: str) -> float: + if not self.cache_dir_prefix: + raise FileNotFoundError() + + return int(os.path.getmtime(os_path_join(self.cache_dir_prefix, name))) + + def read(self, name: str) -> bytes: + assert not os.path.isabs(name), "Don't use absolute paths!" + + if not self.cache_dir_prefix: + raise FileNotFoundError() + + with open(os_path_join(self.cache_dir_prefix, name), "rb", buffering=0) as f: + return f.read() + + def write(self, name: str, data: bytes, mtime: float | None = None) -> bool: + assert not os.path.isabs(name), "Don't use absolute paths!" + + if not self.cache_dir_prefix: + return False + + path = os_path_join(self.cache_dir_prefix, name) + tmp_filename = path + "." + random_string() + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(tmp_filename, "wb") as f: + f.write(data) + os.replace(tmp_filename, path) + if mtime is not None: + os.utime(path, times=(mtime, mtime)) + + except OSError: + return False + return True + + def remove(self, name: str) -> None: + if not self.cache_dir_prefix: + raise FileNotFoundError() + + os.remove(os_path_join(self.cache_dir_prefix, name)) + + def commit(self) -> None: + pass + + def list_all(self) -> Iterable[str]: + if not self.cache_dir_prefix: + return + + for dir, _, files in os.walk(self.cache_dir_prefix): + dir = os.path.relpath(dir, self.cache_dir_prefix) + for file in files: + yield os.path.normpath(os_path_join(dir, file)) + + def close(self) -> None: + pass + + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS files2 ( + path TEXT UNIQUE NOT NULL, + mtime REAL, + data BLOB +); +CREATE INDEX IF NOT EXISTS path_idx on files2(path); +""" + + +def connect_db(db_file: str, set_journal_mode: bool) -> sqlite3.Connection: + import sqlite3.dbapi2 + + db = sqlite3.dbapi2.connect(db_file) + # This is a bit unfortunate (as we may get corrupt cache after e.g. Ctrl + C), + # but without this flag, commits are *very* slow, especially when using HDDs, + # see https://www.sqlite.org/faq.html#q19 for details. + db.execute("PRAGMA synchronous=OFF") + if set_journal_mode: + db.execute("PRAGMA journal_mode=WAL") + db.executescript(SCHEMA) + return db + + +class SqliteMetadataStore(MetadataStore): + def __init__(self, cache_dir_prefix: str, set_journal_mode: bool = False) -> None: + # We check startswith instead of equality because the version + # will have already been appended by the time the cache dir is + # passed here. + self.db = None + if cache_dir_prefix.startswith(os.devnull): + return + + os.makedirs(cache_dir_prefix, exist_ok=True) + self.db = connect_db(os_path_join(cache_dir_prefix, "cache.db"), set_journal_mode) + + def _query(self, name: str, field: str) -> Any: + # Raises FileNotFound for consistency with the file system version + if not self.db: + raise FileNotFoundError() + + cur = self.db.execute(f"SELECT {field} FROM files2 WHERE path = ?", (name,)) + results = cur.fetchall() + if not results: + raise FileNotFoundError() + assert len(results) == 1 + return results[0][0] + + def getmtime(self, name: str) -> float: + mtime = self._query(name, "mtime") + assert isinstance(mtime, float) + return mtime + + def read(self, name: str) -> bytes: + data = self._query(name, "data") + assert isinstance(data, bytes) + return data + + def write(self, name: str, data: bytes, mtime: float | None = None) -> bool: + import sqlite3 + + if not self.db: + return False + try: + if mtime is None: + mtime = time.time() + self.db.execute( + "INSERT OR REPLACE INTO files2(path, mtime, data) VALUES(?, ?, ?)", + (name, mtime, data), + ) + except sqlite3.OperationalError: + return False + return True + + def remove(self, name: str) -> None: + if not self.db: + raise FileNotFoundError() + + self.db.execute("DELETE FROM files2 WHERE path = ?", (name,)) + + def commit(self) -> None: + if self.db: + self.db.commit() + + def list_all(self) -> Iterable[str]: + if self.db: + for row in self.db.execute("SELECT path FROM files2"): + yield row[0] + + def close(self) -> None: + if self.db: + db = self.db + self.db = None + db.close() + + def __del__(self) -> None: + self.close() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mixedtraverser.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mixedtraverser.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3a19c7d89cd56ffd6f3b966e3083a5ac50cf55aa Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mixedtraverser.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mixedtraverser.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mixedtraverser.py new file mode 100644 index 0000000000000000000000000000000000000000..535391886b0205936b98cc559b581e3263e98df1 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mixedtraverser.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +from mypy.nodes import ( + AssertTypeExpr, + AssignmentStmt, + CastExpr, + ClassDef, + ForStmt, + FuncItem, + NamedTupleExpr, + NewTypeExpr, + PromoteExpr, + TypeAlias, + TypeAliasExpr, + TypeAliasStmt, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + Var, + WithStmt, +) +from mypy.traverser import TraverserVisitor +from mypy.types import Type +from mypy.typetraverser import TypeTraverserVisitor + + +class MixedTraverserVisitor(TraverserVisitor, TypeTraverserVisitor): + """Recursive traversal of both Node and Type objects.""" + + def __init__(self) -> None: + self.in_type_alias_expr = False + + # Symbol nodes + + def visit_var(self, var: Var, /) -> None: + self.visit_optional_type(var.type) + + def visit_func(self, o: FuncItem, /) -> None: + super().visit_func(o) + self.visit_optional_type(o.type) + + def visit_class_def(self, o: ClassDef, /) -> None: + # TODO: Should we visit generated methods/variables as well, either here or in + # TraverserVisitor? + super().visit_class_def(o) + info = o.info + if info: + for base in info.bases: + base.accept(self) + if info.special_alias: + info.special_alias.accept(self) + + def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None: + super().visit_type_alias_expr(o) + o.node.accept(self) + + def visit_type_var_expr(self, o: TypeVarExpr, /) -> None: + super().visit_type_var_expr(o) + o.upper_bound.accept(self) + o.default.accept(self) + for value in o.values: + value.accept(self) + + def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None: + super().visit_typeddict_expr(o) + self.visit_optional_type(o.info.typeddict_type) + + def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None: + super().visit_namedtuple_expr(o) + assert o.info.tuple_type + o.info.tuple_type.accept(self) + + def visit__promote_expr(self, o: PromoteExpr, /) -> None: + super().visit__promote_expr(o) + o.type.accept(self) + + def visit_newtype_expr(self, o: NewTypeExpr, /) -> None: + super().visit_newtype_expr(o) + self.visit_optional_type(o.old_type) + + # Statements + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + super().visit_assignment_stmt(o) + self.visit_optional_type(o.type) + + def visit_type_alias_stmt(self, o: TypeAliasStmt, /) -> None: + super().visit_type_alias_stmt(o) + if o.alias_node is not None: + o.alias_node.accept(self) + + def visit_type_alias(self, o: TypeAlias, /) -> None: + super().visit_type_alias(o) + self.in_type_alias_expr = True + o.target.accept(self) + self.in_type_alias_expr = False + + def visit_for_stmt(self, o: ForStmt, /) -> None: + super().visit_for_stmt(o) + self.visit_optional_type(o.index_type) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + super().visit_with_stmt(o) + for typ in o.analyzed_types: + typ.accept(self) + + # Expressions + + def visit_cast_expr(self, o: CastExpr, /) -> None: + super().visit_cast_expr(o) + o.type.accept(self) + + def visit_type_form_expr(self, o: TypeFormExpr, /) -> None: + super().visit_type_form_expr(o) + o.type.accept(self) + + def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None: + super().visit_assert_type_expr(o) + o.type.accept(self) + + def visit_type_application(self, o: TypeApplication, /) -> None: + super().visit_type_application(o) + for t in o.types: + t.accept(self) + + # Helpers + + def visit_optional_type(self, t: Type | None, /) -> None: + if t: + t.accept(self) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/modulefinder.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/modulefinder.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ee72216908be37b06636224f7409c5a0030aefc5 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/modulefinder.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/modulefinder.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/modulefinder.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b88e5aac65772bfec64be94ce5b2954e283dc4 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/modulefinder.py @@ -0,0 +1,1002 @@ +"""Low-level infrastructure to find modules. + +This builds on fscache.py; find_sources.py builds on top of this. +""" + +from __future__ import annotations + +import ast +import collections +import functools +import os +import re +import subprocess +import sys +from enum import Enum, unique +from typing import Final, TypeAlias as _TypeAlias + +from pathspec import PathSpec +from pathspec.patterns.gitignore import GitIgnorePatternError + +from mypy import pyinfo +from mypy.errors import CompileError +from mypy.fscache import FileSystemCache +from mypy.nodes import MypyFile +from mypy.options import Options +from mypy.stubinfo import stub_distribution_name +from mypy.util import os_path_join + + +# Paths to be searched in find_module(). +class SearchPaths: + def __init__( + self, + python_path: tuple[str, ...], + mypy_path: tuple[str, ...], + package_path: tuple[str, ...], + typeshed_path: tuple[str, ...], + ) -> None: + # where user code is found + self.python_path = tuple(map(os.path.abspath, python_path)) + # from $MYPYPATH or config variable + self.mypy_path = tuple(map(os.path.abspath, mypy_path)) + # from get_site_packages_dirs() + self.package_path = tuple(map(os.path.abspath, package_path)) + # paths in typeshed + self.typeshed_path = tuple(map(os.path.abspath, typeshed_path)) + + def asdict(self) -> dict[str, tuple[str, ...]]: + return { + "python_path": self.python_path, + "mypy_path": self.mypy_path, + "package_path": self.package_path, + "typeshed_path": self.typeshed_path, + } + + +# Package dirs are a two-tuple of path to search and whether to verify the module +OnePackageDir = tuple[str, bool] +PackageDirs = list[OnePackageDir] + +# Minimum and maximum Python versions for modules in stdlib as (major, minor) +StdlibVersions: _TypeAlias = dict[str, tuple[tuple[int, int], tuple[int, int] | None]] + +PYTHON_EXTENSIONS: Final = [".pyi", ".py"] + + +# TODO: Consider adding more reasons here? +# E.g. if we deduce a module would likely be found if the user were +# to set the --namespace-packages flag. +@unique +class ModuleNotFoundReason(Enum): + # The module was not found: we found neither stubs nor a plausible code + # implementation (with or without a py.typed file). + NOT_FOUND = 0 + + # The implementation for this module plausibly exists (e.g. we + # found a matching folder or *.py file), but either the parent package + # did not contain a py.typed file or we were unable to find a + # corresponding *-stubs package. + FOUND_WITHOUT_TYPE_HINTS = 1 + + # The module was not found in the current working directory, but + # was able to be found in the parent directory. + WRONG_WORKING_DIRECTORY = 2 + + # Stub PyPI package (typically types-pkgname) known to exist but not installed. + APPROVED_STUBS_NOT_INSTALLED = 3 + + def error_message_templates(self, daemon: bool) -> tuple[str, list[str]]: + doc_link = "See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports" + if self is ModuleNotFoundReason.NOT_FOUND: + msg = 'Cannot find implementation or library stub for module named "{module}"' + notes = [doc_link] + elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY: + msg = 'Cannot find implementation or library stub for module named "{module}"' + notes = [ + "You may be running mypy in a subpackage, mypy should be run on the package root" + ] + elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + msg = ( + 'Skipping analyzing "{module}": module is installed, but missing library stubs ' + "or py.typed marker" + ) + notes = [doc_link] + elif self is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED: + msg = 'Library stubs not installed for "{module}"' + notes = ['Hint: "python3 -m pip install {stub_dist}"'] + if not daemon: + notes.append( + '(or run "mypy --install-types" to install all missing stub packages)' + ) + notes.append(doc_link) + else: + assert False + return msg, notes + + +# If we found the module, returns the path to the module as a str. +# Otherwise, returns the reason why the module wasn't found. +ModuleSearchResult = str | ModuleNotFoundReason + + +class BuildSource: + """A single source file.""" + + def __init__( + self, + path: str | None, + module: str | None, + text: str | None = None, + base_dir: str | None = None, + followed: bool = False, + ) -> None: + self.path = path # File where it's found (e.g. 'xxx/yyy/foo/bar.py') + self.module = module or "__main__" # Module name (e.g. 'foo.bar') + self.text = text # Source code, if initially supplied, else None + self.base_dir = base_dir # Directory where the package is rooted (e.g. 'xxx/yyy') + self.followed = followed # Was this found by following imports? + + def __repr__(self) -> str: + return ( + "BuildSource(path={!r}, module={!r}, has_text={}, base_dir={!r}, followed={})".format( + self.path, self.module, self.text is not None, self.base_dir, self.followed + ) + ) + + +class BuildSourceSet: + """Helper to efficiently test a file's membership in a set of build sources.""" + + def __init__(self, sources: list[BuildSource]) -> None: + self.source_text_present = False + self.source_modules: dict[str, str] = {} + self.source_paths: set[str] = set() + + for source in sources: + if source.text is not None: + self.source_text_present = True + if source.path: + self.source_paths.add(source.path) + if source.module: + self.source_modules[source.module] = source.path or "" + + def is_source(self, file: MypyFile) -> bool: + return ( + (file.path and file.path in self.source_paths) + or file._fullname in self.source_modules + or self.source_text_present + ) + + +class FindModuleCache: + """Module finder with integrated cache. + + Module locations and some intermediate results are cached internally + and can be cleared with the clear() method. + + All file system accesses are performed through a FileSystemCache, + which is not ever cleared by this class. If necessary it must be + cleared by client code. + """ + + def __init__( + self, + search_paths: SearchPaths, + fscache: FileSystemCache | None, + options: Options | None, + stdlib_py_versions: StdlibVersions | None = None, + source_set: BuildSourceSet | None = None, + ) -> None: + self.search_paths = search_paths + self.source_set = source_set + self.fscache = fscache or FileSystemCache() + # Cache for get_toplevel_possibilities: + # search_paths -> (toplevel_id -> list(package_dirs)) + self.initial_components: dict[tuple[str, ...], dict[str, list[str]]] = {} + # Cache find_module: id -> result + self.results: dict[str, ModuleSearchResult] = {} + self.ns_ancestors: dict[str, str] = {} + self.options = options + custom_typeshed_dir = None + if options: + custom_typeshed_dir = options.custom_typeshed_dir + self.stdlib_py_versions = stdlib_py_versions or load_stdlib_py_versions( + custom_typeshed_dir + ) + + def clear(self) -> None: + self.results.clear() + self.initial_components.clear() + self.ns_ancestors.clear() + + def find_module_via_source_set(self, id: str) -> ModuleSearchResult | None: + """Fast path to find modules by looking through the input sources + + This is only used when --fast-module-lookup is passed on the command line.""" + if not self.source_set: + return None + + p = self.source_set.source_modules.get(id, None) + if p and self.fscache.isfile(p): + # We need to make sure we still have __init__.py all the way up + # otherwise we might have false positives compared to slow path + # in case of deletion of init files, which is covered by some tests. + # TODO: are there some combination of flags in which this check should be skipped? + d = os.path.dirname(p) + for _ in range(id.count(".")): + if not any( + self.fscache.isfile(os_path_join(d, "__init__" + x)) for x in PYTHON_EXTENSIONS + ): + return None + d = os.path.dirname(d) + return p + + idx = id.rfind(".") + if idx != -1: + # When we're looking for foo.bar.baz and can't find a matching module + # in the source set, look up for a foo.bar module. + parent = self.find_module_via_source_set(id[:idx]) + if parent is None or not isinstance(parent, str): + return None + + basename, ext = os.path.splitext(parent) + if not any(parent.endswith("__init__" + x) for x in PYTHON_EXTENSIONS) and ( + ext in PYTHON_EXTENSIONS and not self.fscache.isdir(basename) + ): + # If we do find such a *module* (and crucially, we don't want a package, + # hence the filtering out of __init__ files, and checking for the presence + # of a folder with a matching name), then we can be pretty confident that + # 'baz' will either be a top-level variable in foo.bar, or will not exist. + # + # Either way, spelunking in other search paths for another 'foo.bar.baz' + # module should be avoided because: + # 1. in the unlikely event that one were found, it's highly likely that + # it would be unrelated to the source being typechecked and therefore + # more likely to lead to erroneous results + # 2. as described in _find_module, in some cases the search itself could + # potentially waste significant amounts of time + return ModuleNotFoundReason.NOT_FOUND + return None + + def find_lib_path_dirs(self, id: str, lib_path: tuple[str, ...]) -> PackageDirs: + """Find which elements of a lib_path have the directory a module needs to exist.""" + components = id.split(".") + dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar' + + dirs = [] + for pathitem in self.get_toplevel_possibilities(lib_path, components[0]): + # e.g., '/usr/lib/python3.4/foo/bar' + if dir_chain: + dir = os_path_join(pathitem, dir_chain) + else: + dir = pathitem + if self.fscache.isdir(dir): + dirs.append((dir, True)) + return dirs + + def get_toplevel_possibilities(self, lib_path: tuple[str, ...], id: str) -> list[str]: + """Find which elements of lib_path could contain a particular top-level module. + + In practice, almost all modules can be routed to the correct entry in + lib_path by looking at just the first component of the module name. + + We take advantage of this by enumerating the contents of all of the + directories on the lib_path and building a map of which entries in + the lib_path could contain each potential top-level module that appears. + """ + + if lib_path in self.initial_components: + return self.initial_components[lib_path].get(id, []) + + # Enumerate all the files in the directories on lib_path and produce the map + components: dict[str, list[str]] = {} + for dir in lib_path: + try: + contents = self.fscache.listdir(dir) + except OSError: + contents = [] + # False positives are fine for correctness here, since we will check + # precisely later, so we only look at the root of every filename without + # any concern for the exact details. + for name in contents: + name = os.path.splitext(name)[0] + components.setdefault(name, []).append(dir) + + self.initial_components[lib_path] = components + return components.get(id, []) + + def find_module(self, id: str, *, fast_path: bool = False) -> ModuleSearchResult: + """Return the path of the module source file or why it wasn't found. + + If fast_path is True, prioritize performance over generating detailed + error descriptions. + """ + if id not in self.results: + top_level = id.partition(".")[0] + use_typeshed = True + if id in self.stdlib_py_versions: + use_typeshed = self._typeshed_has_version(id) + elif top_level in self.stdlib_py_versions: + use_typeshed = self._typeshed_has_version(top_level) + result, should_cache = self._find_module(id, use_typeshed) + if should_cache: + if ( + not ( + fast_path or (self.options is not None and self.options.fast_module_lookup) + ) + and result is ModuleNotFoundReason.NOT_FOUND + and self._can_find_module_in_parent_dir(id) + ): + self.results[id] = ModuleNotFoundReason.WRONG_WORKING_DIRECTORY + else: + self.results[id] = result + return self.results[id] + else: + return result + return self.results[id] + + def _typeshed_has_version(self, module: str) -> bool: + if not self.options: + return True + version = typeshed_py_version(self.options) + min_version, max_version = self.stdlib_py_versions[module] + return version >= min_version and (max_version is None or version <= max_version) + + def _find_module_non_stub_helper( + self, id: str, pkg_dir: str + ) -> OnePackageDir | ModuleNotFoundReason: + plausible_match = False + dir_path = pkg_dir + components = id.split(".") + for index, component in enumerate(components): + dir_path = os_path_join(dir_path, component) + if self.fscache.isfile(os_path_join(dir_path, "py.typed")): + return os.path.join(pkg_dir, *components[:-1]), index == 0 + elif not plausible_match and ( + self.fscache.isdir(dir_path) or self.fscache.isfile(dir_path + ".py") + ): + plausible_match = True + # If this is not a directory then we can't traverse further into it + if not self.fscache.isdir(dir_path): + break + if plausible_match: + if self.options: + module_specific_options = self.options.clone_for_module(id) + if module_specific_options.follow_untyped_imports: + return os.path.join(pkg_dir, *components[:-1]), False + return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS + else: + return ModuleNotFoundReason.NOT_FOUND + + def _update_ns_ancestors(self, components: list[str], match: tuple[str, bool]) -> None: + path, verify = match + for i in range(1, len(components)): + pkg_id = ".".join(components[:-i]) + if pkg_id not in self.ns_ancestors and self.fscache.isdir(path): + self.ns_ancestors[pkg_id] = path + path = os.path.dirname(path) + + def _can_find_module_in_parent_dir(self, id: str) -> bool: + """Test if a module can be found by checking the parent directories + of the current working directory. + """ + working_dir = os.getcwd() + parent_search = FindModuleCache( + SearchPaths((), (), (), ()), + self.fscache, + self.options, + stdlib_py_versions=self.stdlib_py_versions, + ) + while any(is_init_file(file) for file in os.listdir(working_dir)): + working_dir = os.path.dirname(working_dir) + parent_search.search_paths = SearchPaths((working_dir,), (), (), ()) + if not isinstance(parent_search._find_module(id, False)[0], ModuleNotFoundReason): + return True + return False + + def _find_module(self, id: str, use_typeshed: bool) -> tuple[ModuleSearchResult, bool]: + """Try to find a module in all available sources. + + Returns: + ``(result, can_be_cached)`` pair. + """ + fscache = self.fscache + + # Fast path for any modules in the current source set. + # This is particularly important when there are a large number of search + # paths which share the first (few) component(s) due to the use of namespace + # packages, for instance: + # foo/ + # company/ + # __init__.py + # foo/ + # bar/ + # company/ + # __init__.py + # bar/ + # baz/ + # company/ + # __init__.py + # baz/ + # + # mypy gets [foo/company/foo, bar/company/bar, baz/company/baz, ...] as input + # and computes [foo, bar, baz, ...] as the module search path. + # + # This would result in O(n) search for every import of company.*, leading to + # O(n**2) behavior in load_graph as such imports are unsurprisingly present + # at least once, and usually many more times than that, in each and every file + # being parsed. + # + # Thankfully, such cases are efficiently handled by looking up the module path + # via BuildSourceSet. + p = ( + self.find_module_via_source_set(id) + if (self.options is not None and self.options.fast_module_lookup) + else None + ) + if p: + return p, True + + # If we're looking for a module like 'foo.bar.baz', it's likely that most of the + # many elements of lib_path don't even have a subdirectory 'foo/bar'. Discover + # that only once and cache it for when we look for modules like 'foo.bar.blah' + # that will require the same subdirectory. + components = id.split(".") + dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar' + + # We have two sets of folders so that we collect *all* stubs folders and + # put them in the front of the search path + third_party_inline_dirs: PackageDirs = [] + third_party_stubs_dirs: PackageDirs = [] + found_possible_third_party_missing_type_hints = False + # Third-party stub/typed packages + candidate_package_dirs = { + package_dir[0] + for component in (components[0], components[0] + "-stubs") + for package_dir in self.find_lib_path_dirs(component, self.search_paths.package_path) + } + # Caching FOUND_WITHOUT_TYPE_HINTS is not always safe. That causes issues with + # typed subpackages in namespace packages. + can_cache_any_result = True + for pkg_dir in self.search_paths.package_path: + if pkg_dir not in candidate_package_dirs: + continue + stub_name = components[0] + "-stubs" + stub_dir = os_path_join(pkg_dir, stub_name) + if fscache.isdir(stub_dir): + stub_typed_file = os_path_join(stub_dir, "py.typed") + stub_components = [stub_name] + components[1:] + path = os.path.join(pkg_dir, *stub_components[:-1]) + if fscache.isdir(path): + if fscache.isfile(stub_typed_file): + # Stub packages can have a py.typed file, which must include + # 'partial\n' to make the package partial. + # Partial here means that mypy should look at the runtime + # package if installed. + if fscache.read(stub_typed_file).decode().strip() == "partial": + runtime_path = os_path_join(pkg_dir, dir_chain) + third_party_inline_dirs.append((runtime_path, True)) + # if the package is partial, we don't verify the module, as + # the partial stub package may not have a __init__.pyi + third_party_stubs_dirs.append((path, False)) + else: + # handle the edge case where people put a py.typed file + # in a stub package, but it isn't partial + third_party_stubs_dirs.append((path, True)) + else: + third_party_stubs_dirs.append((path, True)) + non_stub_match = self._find_module_non_stub_helper(id, pkg_dir) + if isinstance(non_stub_match, ModuleNotFoundReason): + if non_stub_match is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + found_possible_third_party_missing_type_hints = True + can_cache_any_result = False + else: + third_party_inline_dirs.append(non_stub_match) + self._update_ns_ancestors(components, non_stub_match) + + if self.options and self.options.use_builtins_fixtures: + # Everything should be in fixtures. + third_party_inline_dirs.clear() + third_party_stubs_dirs.clear() + found_possible_third_party_missing_type_hints = False + python_mypy_path = self.search_paths.mypy_path + self.search_paths.python_path + candidate_base_dirs = self.find_lib_path_dirs(id, python_mypy_path) + if use_typeshed: + # Search for stdlib stubs in typeshed before installed + # stubs to avoid picking up backports (dataclasses, for + # example) when the library is included in stdlib. + candidate_base_dirs += self.find_lib_path_dirs(id, self.search_paths.typeshed_path) + candidate_base_dirs += third_party_stubs_dirs + third_party_inline_dirs + + # If we're looking for a module like 'foo.bar.baz', then candidate_base_dirs now + # contains just the subdirectories 'foo/bar' that actually exist under the + # elements of lib_path. This is probably much shorter than lib_path itself. + # Now just look for 'baz.pyi', 'baz/__init__.py', etc., inside those directories. + seplast = os.sep + components[-1] # so e.g. '/baz' + sepinit = os.sep + "__init__" + near_misses = [] # Collect near misses for namespace mode (see below). + for base_dir, verify in candidate_base_dirs: + base_path = base_dir + seplast # so e.g. '/usr/lib/python3.4/foo/bar/baz' + has_init = False + dir_prefix = base_dir + for _ in range(len(components) - 1): + dir_prefix = os.path.dirname(dir_prefix) + + # Stubs-only packages always take precedence over py.typed packages + path_stubs = f"{base_path}-stubs{sepinit}.pyi" + if fscache.isfile_case(path_stubs, dir_prefix): + if verify and not verify_module(fscache, id, path_stubs, dir_prefix): + near_misses.append((path_stubs, dir_prefix)) + else: + return path_stubs, True + + # Prefer package over module, i.e. baz/__init__.py* over baz.py*. + for extension in PYTHON_EXTENSIONS: + path = base_path + sepinit + extension + if fscache.isfile_case(path, dir_prefix): + has_init = True + if verify and not verify_module(fscache, id, path, dir_prefix): + near_misses.append((path, dir_prefix)) + continue + return path, True + + # In namespace mode, register a potential namespace package + if self.options and self.options.namespace_packages: + if ( + not has_init + and fscache.exists_case(base_path, dir_prefix) + and not fscache.isfile_case(base_path, dir_prefix) + ): + near_misses.append((base_path, dir_prefix)) + + # No package, look for module. + for extension in PYTHON_EXTENSIONS: + path = base_path + extension + if fscache.isfile_case(path, dir_prefix): + if verify and not verify_module(fscache, id, path, dir_prefix): + near_misses.append((path, dir_prefix)) + continue + return path, True + + # In namespace mode, re-check those entries that had 'verify'. + # Assume search path entries xxx, yyy and zzz, and we're + # looking for foo.bar.baz. Suppose near_misses has: + # + # - xxx/foo/bar/baz.py + # - yyy/foo/bar/baz/__init__.py + # - zzz/foo/bar/baz.pyi + # + # If any of the foo directories has __init__.py[i], it wins. + # Else, we look for foo/bar/__init__.py[i], etc. If there are + # none, the first hit wins. Note that this does not take into + # account whether the lowest-level module is a file (baz.py), + # a package (baz/__init__.py), or a stub file (baz.pyi) -- for + # these the first one encountered along the search path wins. + # + # The helper function highest_init_level() returns an int that + # indicates the highest level at which a __init__.py[i] file + # is found; if no __init__ was found it returns 0, if we find + # only foo/bar/__init__.py it returns 1, and if we have + # foo/__init__.py it returns 2 (regardless of what's in + # foo/bar). It doesn't look higher than that. + if self.options and self.options.namespace_packages and near_misses: + levels = [ + highest_init_level(fscache, id, path, dir_prefix) + for path, dir_prefix in near_misses + ] + index = levels.index(max(levels)) + return near_misses[index][0], True + + # Finally, we may be asked to produce an ancestor for an + # installed package with a py.typed marker that is a + # subpackage of a namespace package. We only fess up to these + # if we would otherwise return "not found". + ancestor = self.ns_ancestors.get(id) + if ancestor is not None: + return ancestor, True + + approved_dist_name = stub_distribution_name(id) + if approved_dist_name: + if len(components) == 1: + return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True + # If we're a missing submodule of an already installed approved stubs, we don't want to + # error with APPROVED_STUBS_NOT_INSTALLED, but rather want to return NOT_FOUND. + for i in range(1, len(components)): + parent_id = ".".join(components[:i]) + if stub_distribution_name(parent_id) == approved_dist_name: + break + else: + return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True + if self.find_module(parent_id) is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED: + return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True + return ModuleNotFoundReason.NOT_FOUND, True + + if found_possible_third_party_missing_type_hints: + return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS, can_cache_any_result + return ModuleNotFoundReason.NOT_FOUND, True + + def find_modules_recursive(self, module: str) -> list[BuildSource]: + module_path = self.find_module(module, fast_path=True) + if isinstance(module_path, ModuleNotFoundReason): + return [] + sources = [BuildSource(module_path, module, None)] + + package_path = None + if is_init_file(module_path): + package_path = os.path.dirname(module_path) + elif self.fscache.isdir(module_path): + package_path = module_path + if package_path is None: + return sources + + # This logic closely mirrors that in find_sources. One small but important difference is + # that we do not sort names with keyfunc. The recursive call to find_modules_recursive + # calls find_module, which will handle the preference between packages, pyi and py. + # Another difference is it doesn't handle nested search paths / package roots. + + seen: set[str] = set() + names = sorted(self.fscache.listdir(package_path)) + for name in names: + # Skip certain names altogether + if name in ("__pycache__", "site-packages", "node_modules") or name.startswith("."): + continue + subpath = os_path_join(package_path, name) + + if self.options and matches_exclude( + subpath, self.options.exclude, self.fscache, self.options.verbosity >= 2 + ): + continue + if ( + self.options + and self.options.exclude_gitignore + and matches_gitignore(subpath, self.fscache, self.options.verbosity >= 2) + ): + continue + + if self.fscache.isdir(subpath): + # Only recurse into packages + if (self.options and self.options.namespace_packages) or ( + self.fscache.isfile(os_path_join(subpath, "__init__.py")) + or self.fscache.isfile(os_path_join(subpath, "__init__.pyi")) + ): + seen.add(name) + sources.extend(self.find_modules_recursive(module + "." + name)) + else: + stem, suffix = os.path.splitext(name) + if stem == "__init__": + continue + if stem not in seen and "." not in stem and suffix in PYTHON_EXTENSIONS: + # (If we sorted names by keyfunc) we could probably just make the BuildSource + # ourselves, but this ensures compatibility with find_module / the cache + seen.add(stem) + sources.extend(self.find_modules_recursive(module + "." + stem)) + return sources + + +def matches_exclude( + subpath: str, excludes: list[str], fscache: FileSystemCache, verbose: bool +) -> bool: + if not excludes: + return False + subpath_str = os.path.relpath(subpath).replace(os.sep, "/") + if fscache.isdir(subpath): + subpath_str += "/" + for exclude in excludes: + try: + if re.search(exclude, subpath_str): + if verbose: + print( + f"TRACE: Excluding {subpath_str} (matches pattern {exclude})", + file=sys.stderr, + ) + return True + except re.error as e: + print( + f"error: The exclude {exclude} is an invalid regular expression, because: {e}" + + ( + "\n(Hint: use / as a path separator, even if you're on Windows!)" + if "\\" in exclude + else "" + ) + + "\nFor more information on Python's flavor of regex, see:" + + " https://docs.python.org/3/library/re.html", + file=sys.stderr, + ) + sys.exit(2) + return False + + +def matches_gitignore(subpath: str, fscache: FileSystemCache, verbose: bool) -> bool: + dir, _ = os.path.split(subpath) + for gi_path, gi_spec in find_gitignores(dir): + relative_path = os.path.relpath(subpath, gi_path) + if fscache.isdir(relative_path): + relative_path = relative_path + "/" + if gi_spec.match_file(relative_path): + if verbose: + print( + f"TRACE: Excluding {relative_path} (matches .gitignore) in {gi_path}", + file=sys.stderr, + ) + return True + return False + + +@functools.lru_cache +def find_gitignores(dir: str) -> list[tuple[str, PathSpec]]: + parent_dir = os.path.dirname(dir) + if parent_dir == dir or os.path.exists(os.path.join(dir, ".git")): + parent_gitignores = [] + else: + parent_gitignores = find_gitignores(parent_dir) + + gitignore = os.path.join(dir, ".gitignore") + if os.path.isfile(gitignore): + with open(gitignore) as f: + lines = f.readlines() + try: + return parent_gitignores + [(dir, PathSpec.from_lines("gitignore", lines))] + except GitIgnorePatternError: + print(f"error: could not parse {gitignore}", file=sys.stderr) + return parent_gitignores + return parent_gitignores + + +def is_init_file(path: str) -> bool: + return os.path.basename(path) in ("__init__.py", "__init__.pyi") + + +def verify_module(fscache: FileSystemCache, id: str, path: str, prefix: str) -> bool: + """Check that all packages containing id have a __init__ file.""" + if is_init_file(path): + path = os.path.dirname(path) + for i in range(id.count(".")): + path = os.path.dirname(path) + if not any( + fscache.isfile_case(os_path_join(path, f"__init__{extension}"), prefix) + for extension in PYTHON_EXTENSIONS + ): + return False + return True + + +def highest_init_level(fscache: FileSystemCache, id: str, path: str, prefix: str) -> int: + """Compute the highest level where an __init__ file is found.""" + if is_init_file(path): + path = os.path.dirname(path) + level = 0 + for i in range(id.count(".")): + path = os.path.dirname(path) + if any( + fscache.isfile_case(os_path_join(path, f"__init__{extension}"), prefix) + for extension in PYTHON_EXTENSIONS + ): + level = i + 1 + return level + + +def mypy_path() -> list[str]: + path_env = os.getenv("MYPYPATH") + if not path_env: + return [] + return path_env.split(os.pathsep) + + +def default_lib_path( + data_dir: str, pyversion: tuple[int, int], custom_typeshed_dir: str | None +) -> list[str]: + """Return default standard library search paths. Guaranteed to be normalised.""" + + data_dir = os.path.abspath(data_dir) + path: list[str] = [] + + if custom_typeshed_dir: + custom_typeshed_dir = os.path.abspath(custom_typeshed_dir) + typeshed_dir = os.path.join(custom_typeshed_dir, "stdlib") + mypy_extensions_dir = os.path.join(custom_typeshed_dir, "stubs", "mypy-extensions") + librt_dir = os.path.join(custom_typeshed_dir, "stubs", "librt") + versions_file = os.path.join(typeshed_dir, "VERSIONS") + if not os.path.isdir(typeshed_dir) or not os.path.isfile(versions_file): + print( + "error: --custom-typeshed-dir does not point to a valid typeshed ({})".format( + custom_typeshed_dir + ), + file=sys.stderr, + ) + sys.exit(2) + else: + auto = os.path.join(data_dir, "stubs-auto") + if os.path.isdir(auto): + data_dir = auto + typeshed_dir = os.path.join(data_dir, "typeshed", "stdlib") + mypy_extensions_dir = os.path.join(data_dir, "typeshed", "stubs", "mypy-extensions") + librt_dir = os.path.join(data_dir, "typeshed", "stubs", "librt") + path.append(typeshed_dir) + + # Get mypy-extensions and librt stubs from typeshed, since we treat them as + # "internal" libraries, similar to typing and typing-extensions. + path.append(mypy_extensions_dir) + path.append(librt_dir) + + # Add fallback path that can be used if we have a broken installation. + if sys.platform != "win32": + path.append("/usr/local/lib/mypy") + if not path: + print( + "Could not resolve typeshed subdirectories. Your mypy install is broken.\n" + "Python executable is located at {}.\nMypy located at {}".format( + sys.executable, data_dir + ), + file=sys.stderr, + ) + sys.exit(1) + return path + + +@functools.cache +def get_search_dirs(python_executable: str | None) -> tuple[list[str], list[str]]: + """Find package directories for given python. Guaranteed to return absolute paths. + + This runs a subprocess call, which generates a list of the directories in sys.path. + To avoid repeatedly calling a subprocess (which can be slow!) we + lru_cache the results. + """ + + if python_executable is None: + return ([], []) + elif python_executable == sys.executable: + # Use running Python's package dirs + sys_path, site_packages = pyinfo.getsearchdirs() + else: + # Use subprocess to get the package directory of given Python + # executable + env = {**dict(os.environ), "PYTHONSAFEPATH": "1"} + try: + sys_path, site_packages = ast.literal_eval( + subprocess.check_output( + [python_executable, pyinfo.__file__, "getsearchdirs"], + env=env, + stderr=subprocess.PIPE, + ).decode() + ) + except subprocess.CalledProcessError as err: + print(err.stderr) + print(err.stdout) + raise + except OSError as err: + assert err.errno is not None + reason = os.strerror(err.errno) + raise CompileError( + [f"mypy: Invalid python executable '{python_executable}': {reason}"] + ) from err + return sys_path, site_packages + + +def compute_search_paths( + sources: list[BuildSource], options: Options, data_dir: str, alt_lib_path: str | None = None +) -> SearchPaths: + """Compute the search paths as specified in PEP 561. + + There are the following 4 members created: + - User code (from `sources`) + - MYPYPATH (set either via config or environment variable) + - installed package directories (which will later be split into stub-only and inline) + - typeshed + """ + # Determine the default module search path. + lib_path = collections.deque( + default_lib_path( + data_dir, options.python_version, custom_typeshed_dir=options.custom_typeshed_dir + ) + ) + + if options.use_builtins_fixtures: + # Use stub builtins (to speed up test cases and to make them easier to + # debug). This is a test-only feature, so assume our files are laid out + # as in the source tree. + # We also need to allow overriding where to look for it. Argh. + root_dir = os.getenv("MYPY_TEST_PREFIX", None) + if not root_dir: + root_dir = os.path.dirname(os.path.dirname(__file__)) + root_dir = os.path.abspath(root_dir) + lib_path.appendleft(os.path.join(root_dir, "test-data", "unit", "lib-stub")) + # alt_lib_path is used by some tests to bypass the normal lib_path mechanics. + # If we don't have one, grab directories of source files. + python_path: list[str] = [] + if not alt_lib_path: + for source in sources: + # Include directory of the program file in the module search path. + if source.base_dir: + dir = source.base_dir + if dir not in python_path: + python_path.append(dir) + + # Do this even if running as a file, for sanity (mainly because with + # multiple builds, there could be a mix of files/modules, so its easier + # to just define the semantics that we always add the current director + # to the lib_path + # TODO: Don't do this in some cases; for motivation see see + # https://github.com/python/mypy/issues/4195#issuecomment-341915031 + if options.bazel: + dir = "." + else: + dir = os.getcwd() + if dir not in lib_path: + python_path.insert(0, dir) + + # Start with a MYPYPATH environment variable at the front of the mypy_path, if defined. + mypypath = mypy_path() + + # Add a config-defined mypy path. + mypypath.extend(options.mypy_path) + + # If provided, insert the caller-supplied extra module path to the + # beginning (highest priority) of the search path. + if alt_lib_path: + mypypath.insert(0, alt_lib_path) + + sys_path, site_packages = get_search_dirs(options.python_executable) + # We only use site packages for this check + for site in site_packages: + assert site not in lib_path + if ( + site in mypypath + or any(p.startswith(site + os.path.sep) for p in mypypath) + or (os.path.altsep and any(p.startswith(site + os.path.altsep) for p in mypypath)) + ): + print(f"{site} is in the MYPYPATH. Please remove it.", file=sys.stderr) + print( + "See https://mypy.readthedocs.io/en/stable/running_mypy.html" + "#how-mypy-handles-imports for more info", + file=sys.stderr, + ) + sys.exit(1) + + return SearchPaths( + python_path=tuple(reversed(python_path)), + mypy_path=tuple(mypypath), + package_path=tuple(sys_path + site_packages), + typeshed_path=tuple(lib_path), + ) + + +def load_stdlib_py_versions(custom_typeshed_dir: str | None) -> StdlibVersions: + """Return dict with minimum and maximum Python versions of stdlib modules. + + The contents look like + {..., 'secrets': ((3, 6), None), 'symbol': ((2, 7), (3, 9)), ...} + + None means there is no maximum version. + """ + typeshed_dir = custom_typeshed_dir or os_path_join(os.path.dirname(__file__), "typeshed") + stdlib_dir = os_path_join(typeshed_dir, "stdlib") + result = {} + + versions_path = os_path_join(stdlib_dir, "VERSIONS") + assert os.path.isfile(versions_path), (custom_typeshed_dir, versions_path, __file__) + with open(versions_path) as f: + for line in f: + line = line.split("#")[0].strip() + if line == "": + continue + module, version_range = line.split(":") + versions = version_range.split("-") + min_version = parse_version(versions[0]) + max_version = ( + parse_version(versions[1]) if len(versions) >= 2 and versions[1].strip() else None + ) + result[module] = min_version, max_version + return result + + +def parse_version(version: str) -> tuple[int, int]: + major, minor = version.strip().split(".") + return int(major), int(minor) + + +def typeshed_py_version(options: Options) -> tuple[int, int]: + """Return Python version used for checking whether module supports typeshed.""" + # Typeshed no longer covers Python 3.x versions before 3.9, so 3.9 is + # the earliest we can support. + return max(options.python_version, (3, 9)) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/moduleinspect.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/moduleinspect.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..cba6dd08ff927423326b2e60f98994f9a9b856f0 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/moduleinspect.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/moduleinspect.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/moduleinspect.py new file mode 100644 index 0000000000000000000000000000000000000000..35db2132f66c6a199c1003b6269e7974bb54e448 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/moduleinspect.py @@ -0,0 +1,184 @@ +"""Basic introspection of modules.""" + +from __future__ import annotations + +import importlib +import inspect +import os +import pkgutil +import queue +import sys +from multiprocessing import Queue, get_context +from types import ModuleType + + +class ModuleProperties: + # Note that all __init__ args must have default values + def __init__( + self, + name: str = "", + file: str | None = None, + path: list[str] | None = None, + all: list[str] | None = None, + is_c_module: bool = False, + subpackages: list[str] | None = None, + ) -> None: + self.name = name # __name__ attribute + self.file = file # __file__ attribute + self.path = path # __path__ attribute + self.all = all # __all__ attribute + self.is_c_module = is_c_module + self.subpackages = subpackages or [] + + +def is_c_module(module: ModuleType) -> bool: + if module.__dict__.get("__file__") is None: + # Could be a namespace package. These must be handled through + # introspection, since there is no source file. + return True + return os.path.splitext(module.__dict__["__file__"])[-1] in [".so", ".pyd", ".dll"] + + +def is_pyc_only(file: str | None) -> bool: + return bool(file and file.endswith(".pyc") and not os.path.exists(file[:-1])) + + +class InspectError(Exception): + pass + + +def get_package_properties(package_id: str) -> ModuleProperties: + """Use runtime introspection to get information about a module/package.""" + try: + package = importlib.import_module(package_id) + except BaseException as e: + raise InspectError(str(e)) from e + name = getattr(package, "__name__", package_id) + file = getattr(package, "__file__", None) + path: list[str] | None = getattr(package, "__path__", None) + if not isinstance(path, list): + path = None + pkg_all = getattr(package, "__all__", None) + if pkg_all is not None: + try: + pkg_all = list(pkg_all) + except Exception: + pkg_all = None + is_c = is_c_module(package) + + if path is None: + # Object has no path; this means it's either a module inside a package + # (and thus no sub-packages), or it could be a C extension package. + if is_c: + # This is a C extension module, now get the list of all sub-packages + # using the inspect module + subpackages = [ + package.__name__ + "." + name + for name, val in inspect.getmembers(package) + if inspect.ismodule(val) and val.__name__ == package.__name__ + "." + name + ] + else: + # It's a module inside a package. There's nothing else to walk/yield. + subpackages = [] + else: + all_packages = pkgutil.walk_packages( + path, prefix=package.__name__ + ".", onerror=lambda r: None + ) + subpackages = [qualified_name for importer, qualified_name, ispkg in all_packages] + return ModuleProperties( + name=name, file=file, path=path, all=pkg_all, is_c_module=is_c, subpackages=subpackages + ) + + +def worker(tasks: Queue[str], results: Queue[str | ModuleProperties], sys_path: list[str]) -> None: + """The main loop of a worker introspection process.""" + sys.path = sys_path + while True: + mod = tasks.get() + try: + prop = get_package_properties(mod) + except InspectError as e: + results.put(str(e)) + continue + results.put(prop) + + +class ModuleInspect: + """Perform runtime introspection of modules in a separate process. + + Reuse the process for multiple modules for efficiency. However, if there is an + error, retry using a fresh process to avoid cross-contamination of state between + modules. + + We use a separate process to isolate us from many side effects. For example, the + import of a module may kill the current process, and we want to recover from that. + + Always use in a with statement for proper clean-up: + + with ModuleInspect() as m: + p = m.get_package_properties('urllib.parse') + """ + + def __init__(self) -> None: + self._start() + + def _start(self) -> None: + if sys.platform == "linux": + ctx = get_context("forkserver") + else: + ctx = get_context("spawn") + self.tasks: Queue[str] = ctx.Queue() + self.results: Queue[ModuleProperties | str] = ctx.Queue() + self.proc = ctx.Process(target=worker, args=(self.tasks, self.results, sys.path)) + self.proc.start() + self.counter = 0 # Number of successful roundtrips + + def close(self) -> None: + """Free any resources used.""" + self.proc.terminate() + + def get_package_properties(self, package_id: str) -> ModuleProperties: + """Return some properties of a module/package using runtime introspection. + + Raise InspectError if the target couldn't be imported. + """ + self.tasks.put(package_id) + res = self._get_from_queue() + if res is None: + # The process died; recover and report error. + self._start() + raise InspectError(f"Process died when importing {package_id!r}") + if isinstance(res, str): + # Error importing module + if self.counter > 0: + # Also try with a fresh process. Maybe one of the previous imports has + # corrupted some global state. + self.close() + self._start() + return self.get_package_properties(package_id) + raise InspectError(res) + self.counter += 1 + return res + + def _get_from_queue(self) -> ModuleProperties | str | None: + """Get value from the queue. + + Return the value read from the queue, or None if the process unexpectedly died. + """ + max_iter = 600 + n = 0 + while True: + if n == max_iter: + raise RuntimeError("Timeout waiting for subprocess") + try: + return self.results.get(timeout=0.05) + except queue.Empty: + if not self.proc.is_alive(): + return None + n += 1 + + def __enter__(self) -> ModuleInspect: + return self + + def __exit__(self, *args: object) -> None: + self.close() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mro.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mro.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..666431530069a080caca0190a601a8304d0c4618 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mro.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mro.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mro.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b38cd1bedef725ee8b4c1ce79fc3092b0474a9 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/mro.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from collections.abc import Callable + +from mypy.nodes import TypeInfo +from mypy.types import Instance +from mypy.typestate import type_state + + +def calculate_mro(info: TypeInfo, obj_type: Callable[[], Instance] | None = None) -> None: + """Calculate and set mro (method resolution order). + + Raise MroError if cannot determine mro. + """ + mro = linearize_hierarchy(info, obj_type) + assert mro, f"Could not produce a MRO at all for {info}" + info.mro = mro + # The property of falling back to Any is inherited. + info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in info.mro) + type_state.reset_all_subtype_caches_for(info) + + +class MroError(Exception): + """Raised if a consistent mro cannot be determined for a class.""" + + +def linearize_hierarchy( + info: TypeInfo, obj_type: Callable[[], Instance] | None = None +) -> list[TypeInfo]: + # TODO describe + if info.mro: + return info.mro + bases = info.direct_base_classes() + if not bases and info.fullname != "builtins.object" and obj_type is not None: + # Probably an error, add a dummy `object` base class, + # otherwise MRO calculation may spuriously fail. + bases = [obj_type().type] + lin_bases = [] + for base in bases: + assert base is not None, f"Cannot linearize bases for {info.fullname} {bases}" + lin_bases.append(linearize_hierarchy(base, obj_type)) + lin_bases.append(bases) + return [info] + merge(lin_bases) + + +def merge(seqs: list[list[TypeInfo]]) -> list[TypeInfo]: + seqs = [s.copy() for s in seqs] + result: list[TypeInfo] = [] + while True: + seqs = [s for s in seqs if s] + if not seqs: + return result + for seq in seqs: + head = seq[0] + if not [s for s in seqs if head in s[1:]]: + break + else: + raise MroError() + result.append(head) + for s in seqs: + if s[0] is head: + del s[0] diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nativeparse.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nativeparse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5dfd9996e5926b7455160a09c022e2ef65455c9d Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nativeparse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nativeparse.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nativeparse.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff184155bac244c97be58957694fe41856d660e --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nativeparse.py @@ -0,0 +1,2094 @@ +# mypy: allow-redefinition-new, local-partial-types +"""Python parser that directly constructs a native AST (when compiled). + +Use a Rust extension to generate a serialized AST, and deserialize the AST directly +to a mypy AST. + +NOTE: This is work in progress. To use this, you need to manually build the + ast_serialize Rust extension. See the README at https://github.com/mypyc/ast_serialize. + +Expected benefits over mypy.fastparse: + * No intermediate non-mypyc Python-level AST created, to improve performance + * Parsing doesn't need GIL => use multithreading to construct serialized ASTs in parallel + * Produce import dependencies without having to build an AST => helps parallel type checking + * Support all Python syntax even if mypy is running on an older Python version + * Generate an AST even if there are syntax errors + * Potential to support incremental parsing (quickly process modified sections in a file) + * Stripping function bodies in third-party code can happen earlier, for extra performance +""" + +from __future__ import annotations + +import os +from typing import Any, Final, cast + +import ast_serialize # type: ignore[import-untyped, import-not-found, unused-ignore] +from librt.internal import ( + read_float as read_float_bare, + read_int as read_int_bare, + read_str as read_str_bare, +) + +from mypy import message_registry, nodes, types +from mypy.cache import ( + DICT_STR_GEN, + END_TAG, + LIST_GEN, + LIST_INT, + LITERAL_FLOAT, + LITERAL_NONE, + LITERAL_STR, + LOCATION, + ReadBuffer, + Tag, + read_bool, + read_int, + read_str, + read_str_opt, + read_tag, +) +from mypy.nodes import ( + ARG_KINDS, + ARG_POS, + IMPORT_METADATA, + IMPORTALL_METADATA, + IMPORTFROM_METADATA, + MISSING_FALLBACK, + Argument, + AssertStmt, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + Context, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + Expression, + ExpressionStmt, + FileRawData, + FloatExpr, + ForStmt, + FuncDef, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportBase, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NameExpr, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + PassStmt, + RaiseStmt, + RefExpr, + ReturnStmt, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAliasStmt, + TypeParam, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, +) +from mypy.options import Options +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + Pattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.reachability import infer_reachability_of_if_statement +from mypy.sharedparse import special_function_elide_names +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + EllipsisType, + Instance, + ProperType, + RawExpressionType, + TupleType, + Type, + TypedDictType, + TypeList, + TypeOfAny, + UnboundType, + UnionType, + UnpackType, +) +from mypy.util import unnamed_function + +TypeIgnores = list[tuple[int, list[str]]] + +# There is no way to create reasonable fallbacks at this stage, +# they must be patched later. +_dummy_fallback: Final = Instance(MISSING_FALLBACK, [], -1) + + +class State: + def __init__(self, options: Options) -> None: + self.options = options + self.errors: list[dict[str, Any]] = [] + self.num_funcs = 0 + + def add_error( + self, + message: str, + line: int, + column: int, + *, + blocker: bool = False, + code: str | None = None, + ) -> None: + """Report an error at a specific location. + + Args: + message: Error message to display + line: Line number where error occurred + column: Column number where error occurred + blocker: If True, this error blocks further analysis + code: Error code for categorization + """ + self.errors.append( + {"line": line, "column": column, "message": message, "blocker": blocker, "code": code} + ) + + +def native_parse( + filename: str, options: Options, skip_function_bodies: bool = False, imports_only: bool = False +) -> tuple[MypyFile, list[dict[str, Any]], TypeIgnores]: + """Parse a Python file using the native Rust-based parser. + + Uses the ast_serialize Rust extension to parse Python code and deserialize + the resulting AST directly into mypy's native AST representation. + + Args: + filename: Path to the Python source file to parse + options: Mypy options affecting parsing behavior (e.g., Python version) + skip_function_bodies: If True, many function and method bodies are omitted from + the AST, useful for parsing stubs or extracting signatures without full + implementation details + imports_only: If True create an empty MypyFile with actual serialized defs + stored in binary_data. + + Returns: + A tuple containing: + - MypyFile: The parsed AST as a mypy AST node + - list[dict[str, Any]]: List of parse errors and deserialization errors + - TypeIgnores: List of (line_number, ignored_codes) tuples for type: ignore comments + """ + # If the path is a directory, return empty AST (matching fastparse behavior) + # This can happen for packages that only contain .pyc files without source + if os.path.isdir(filename): + node = MypyFile([], []) + node.path = filename + return node, [], [] + + b, errors, ignores, import_bytes, is_partial_package, uses_template_strings = ( + parse_to_binary_ast(filename, options, skip_function_bodies) + ) + data = ReadBuffer(b) + n = read_int(data) + state = State(options) + if imports_only: + defs = [] + else: + defs = read_statements(state, data, n) + + imports = deserialize_imports(import_bytes) + + node = MypyFile(defs, imports) + node.path = filename + node.is_partial_stub_package = is_partial_package + if imports_only: + node.raw_data = FileRawData( + b, import_bytes, errors, dict(ignores), is_partial_package, uses_template_strings + ) + node.uses_template_strings = uses_template_strings + # Merge deserialization errors with parsing errors + all_errors = errors + state.errors + return node, all_errors, ignores + + +def expect_end_tag(data: ReadBuffer) -> None: + assert read_tag(data) == END_TAG + + +def expect_tag(data: ReadBuffer, tag: Tag) -> None: + assert (actual := read_tag(data)) == tag, actual + + +def read_statements(state: State, data: ReadBuffer, n: int) -> list[Statement]: + defs: list[Statement] = [] + old_num_funcs = state.num_funcs + for _ in range(n): + stmt = read_statement(state, data) + defs.append(stmt) + if state.num_funcs > old_num_funcs + 1: + # There were at least two functions, so we may need to merge overloads. + defs = fix_function_overloads(state, defs) + return defs + + +def parse_to_binary_ast( + filename: str, options: Options, skip_function_bodies: bool = False +) -> tuple[bytes, list[dict[str, Any]], TypeIgnores, bytes, bool, bool]: + ast_bytes, errors, ignores, import_bytes, ast_data = ast_serialize.parse( + filename, + skip_function_bodies=skip_function_bodies, + python_version=options.python_version, + platform=options.platform, + always_true=options.always_true, + always_false=options.always_false, + ) + return ( + ast_bytes, + cast("list[dict[str, Any]]", errors), + ignores, + import_bytes, + ast_data["is_partial_package"], + ast_data["uses_template_strings"], + ) + + +def read_statement(state: State, data: ReadBuffer) -> Statement: + tag = read_tag(data) + stmt: Statement + if tag == nodes.FUNC_DEF_STMT: + return read_func_def(state, data) + elif tag == nodes.DECORATOR: + expect_tag(data, LIST_GEN) + n_decorators = read_int_bare(data) + decorators = [read_expression(state, data) for i in range(n_decorators)] + line = read_int(data) + column = read_int(data) + fdef = read_statement(state, data) + assert isinstance(fdef, FuncDef) + fdef.is_decorated = True + var = Var(fdef.name) + var.line = fdef.line + var.is_ready = False + stmt = Decorator(fdef, decorators, var) + stmt.line = line + stmt.column = column + stmt.end_line = fdef.end_line + stmt.end_column = fdef.end_column + # TODO: Adjust funcdef location to start after decorator? + expect_end_tag(data) + return stmt + elif tag == nodes.EXPR_STMT: + es = ExpressionStmt(read_expression(state, data)) + set_line_column_range(es, es.expr) + expect_end_tag(data) + return es + elif tag == nodes.ASSIGNMENT_STMT: + lvalues = read_expression_list(state, data) + rvalue = read_expression(state, data) + has_type = read_bool(data) + if has_type: + type_annotation = read_type(state, data) + else: + type_annotation = None + new_syntax = read_bool(data) + a = AssignmentStmt(lvalues, rvalue, type=type_annotation, new_syntax=new_syntax) + read_loc(data, a) + # If rvalue is TempNode, copy location from AssignmentStmt + if isinstance(rvalue, TempNode): + set_line_column_range(rvalue, a) + expect_end_tag(data) + return a + elif tag == nodes.OPERATOR_ASSIGNMENT_STMT: + # Read operator string + op = read_str(data) + # Read lvalue (target) + lvalue = read_expression(state, data) + # Read rvalue (value) + rvalue = read_expression(state, data) + stmt = OperatorAssignmentStmt(op, lvalue, rvalue) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IF_STMT: + # Read the main if condition and body + expr = read_expression(state, data) + body = read_block(state, data) + + # Read elif clauses + num_elif = read_int(data) + elif_exprs = [] + elif_bodies = [] + for i in range(num_elif): + elif_exprs.append(read_expression(state, data)) + elif_bodies.append(read_block(state, data)) + + has_else = read_bool(data) + if has_else: + else_body = read_block(state, data) + else: + else_body = None + + # Normalize elif into nested if/else statements + # Build from the bottom up, starting with the final else body + current_else = else_body + + # Process elif clauses in reverse order + for i in range(len(elif_exprs) - 1, -1, -1): + elif_stmt = IfStmt([elif_exprs[i]], [elif_bodies[i]], current_else) + # Set location from the elif expression + elif_stmt.line = elif_exprs[i].line + elif_stmt.column = elif_exprs[i].column + # Set end location based on what follows + if current_else is not None: + elif_stmt.end_line = current_else.end_line + elif_stmt.end_column = current_else.end_column + else: + elif_stmt.end_line = elif_bodies[i].end_line + elif_stmt.end_column = elif_bodies[i].end_column + + # Wrap in a Block to become the else clause for the outer if + current_else = Block([elif_stmt]) + set_line_column_range(current_else, elif_stmt) + + if_stmt = IfStmt([expr], [body], current_else) + read_loc(data, if_stmt) + expect_end_tag(data) + return if_stmt + elif tag == nodes.RETURN_STMT: + has_value = read_bool(data) + if has_value: + value = read_expression(state, data) + else: + value = None + stmt = ReturnStmt(value) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.RAISE_STMT: + has_exc = read_bool(data) + if has_exc: + exc = read_expression(state, data) + else: + exc = None + has_from = read_bool(data) + if has_from: + from_expr = read_expression(state, data) + else: + from_expr = None + stmt = RaiseStmt(exc, from_expr) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.ASSERT_STMT: + test = read_expression(state, data) + has_msg = read_bool(data) + if has_msg: + msg = read_expression(state, data) + else: + msg = None + stmt = AssertStmt(test, msg) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.WHILE_STMT: + expr = read_expression(state, data) + body = read_block(state, data) + else_body = read_optional_block(state, data) + stmt = WhileStmt(expr, body, else_body) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.FOR_STMT: + index = read_expression(state, data) + expr = read_expression(state, data) + body = read_block(state, data) + else_body = read_optional_block(state, data) + is_async = read_bool(data) + stmt = ForStmt(index, expr, body, else_body) + stmt.is_async = is_async + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.WITH_STMT: + n = read_int(data) + expr_list = [] + target_list: list[Expression | None] = [] + for _ in range(n): + context_expr = read_expression(state, data) + expr_list.append(context_expr) + has_target = read_bool(data) + if has_target: + target = read_expression(state, data) + target_list.append(target) + else: + target_list.append(None) + body = read_block(state, data) + is_async = read_bool(data) + stmt = WithStmt(expr_list, target_list, body) + stmt.is_async = is_async + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.PASS_STMT: + stmt = PassStmt() + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.BREAK_STMT: + stmt = BreakStmt() + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.CONTINUE_STMT: + stmt = ContinueStmt() + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IMPORT: + n = read_int(data) + ids = [] + for _ in range(n): + name = read_str(data) + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + ids.append((name, asname)) + stmt = Import(ids) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IMPORT_FROM: + relative = read_int(data) + module_id = read_str(data) # Empty string for "from . import x" + n = read_int(data) + names = [] + for _ in range(n): + name = read_str(data) + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + names.append((name, asname)) + + stmt = ImportFrom(module_id, relative, names) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IMPORT_ALL: + module_id = read_str(data) # Empty string for "from . import *" + relative = read_int(data) + + stmt = ImportAll(module_id, relative) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.CLASS_DEF: + return read_class_def(state, data) + elif tag == nodes.TYPE_ALIAS_STMT: + return read_type_alias_stmt(state, data) + elif tag == nodes.TRY_STMT: + return read_try_stmt(state, data) + elif tag == nodes.DEL_STMT: + expr = read_expression(state, data) + stmt = DelStmt(expr) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.GLOBAL_DECL: + n = read_int(data) + decl_names = [] + for _ in range(n): + decl_names.append(read_str(data)) + stmt = GlobalDecl(decl_names) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.NONLOCAL_DECL: + n = read_int(data) + decl_names = [] + for _ in range(n): + decl_names.append(read_str(data)) + stmt = NonlocalDecl(decl_names) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.MATCH_STMT: + subject = read_expression(state, data) + n_cases = read_int(data) + patterns = [] + guards: list[Expression | None] = [] + bodies = [] + for _ in range(n_cases): + pattern = read_pattern(state, data) + patterns.append(pattern) + has_guard = read_bool(data) + if has_guard: + guard = read_expression(state, data) + guards.append(guard) + else: + guards.append(None) + body = read_block(state, data) + bodies.append(body) + stmt = MatchStmt(subject, patterns, guards, bodies) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + else: + assert False, tag + + +def read_parameters(state: State, data: ReadBuffer) -> tuple[list[Argument], bool]: + """Read function/lambda parameters from the buffer. + + Returns: + A tuple of (arguments list, has_annotations flag) + """ + expect_tag(data, LIST_GEN) + n_args = read_int_bare(data) + arguments = [] + has_ann = False + for _ in range(n_args): + arg_name = read_str(data) + arg_kind_int = read_int(data) + arg_kind = ARG_KINDS[arg_kind_int] + has_type = read_bool(data) + if has_type: + ann = read_type(state, data) + has_ann = True + else: + ann = None + has_default = read_bool(data) + if has_default: + default = read_expression(state, data) + else: + default = None + pos_only = read_bool(data) + + # Apply implicit_optional if enabled and default is None + if state.options.implicit_optional and ann is not None: + optional = isinstance(default, NameExpr) and default.name == "None" + if isinstance(ann, UnboundType): + ann.optional = optional + + var = Var(arg_name, ann) + var.is_inferred = False + var.is_argument = True + arg = Argument(var, ann, default, arg_kind, pos_only) + read_loc(data, arg) + set_line_column_range(var, arg) + arguments.append(arg) + + return arguments, has_ann + + +def read_type_params(state: State, data: ReadBuffer) -> list[TypeParam]: + """Read type parameters (PEP 695 generics).""" + type_params: list[TypeParam] = [] + n = read_int_bare(data) + for _ in range(n): + kind = read_int(data) + name = read_str(data) + has_bound = read_bool(data) + if has_bound: + upper_bound = read_type(state, data) + else: + upper_bound = None + + expect_tag(data, LIST_GEN) + n_values = read_int_bare(data) + values = [read_type(state, data) for _ in range(n_values)] + + has_default = read_bool(data) + if has_default: + default = read_type(state, data) + else: + default = None + + type_params.append(TypeParam(name, kind, upper_bound, values, default)) + + return type_params + + +def read_func_def(state: State, data: ReadBuffer) -> FuncDef: + state.num_funcs += 1 + + name = read_str(data) + arguments, has_ann = read_parameters(state, data) + + if special_function_elide_names(name): + for arg in arguments: + arg.pos_only = True + + body = read_block(state, data) + is_async = read_bool(data) + + # Type parameters (PEP 695) + has_type_params = read_bool(data) + if has_type_params: + type_params = read_type_params(state, data) + else: + type_params = None + + has_return_type = read_bool(data) + if has_return_type: + return_type = read_type(state, data) + has_ann = True + else: + return_type = None + + if has_ann: + typ = CallableType( + [ + arg.type_annotation if arg.type_annotation else AnyType(TypeOfAny.unannotated) + for arg in arguments + ], + [arg.kind for arg in arguments], + [None if arg.pos_only else arg.variable.name for arg in arguments], + return_type if return_type else AnyType(TypeOfAny.unannotated), + _dummy_fallback, + ) + else: + typ = None + + func_def = FuncDef(name, arguments, body, typ=typ, type_args=type_params) + if is_async: + func_def.is_coroutine = True + read_loc(data, func_def) + if typ: + typ.line = func_def.line + typ.column = func_def.column + typ.definition = func_def + # TODO: This seems wasteful, can we avoid it? + func_def.unanalyzed_type = typ.copy_modified() + expect_end_tag(data) + return func_def + + +def read_class_def(state: State, data: ReadBuffer) -> ClassDef: + name = read_str(data) + body = read_block(state, data) + base_type_exprs = read_expression_list(state, data) + + expect_tag(data, LIST_GEN) + n_decorators = read_int_bare(data) + decorators = [read_expression(state, data) for _ in range(n_decorators)] + + # Type parameters (PEP 695) + has_type_params = read_bool(data) + if has_type_params: + type_params = read_type_params(state, data) + else: + type_params = None + + # Keywords (all keyword arguments including metaclass) + expect_tag(data, DICT_STR_GEN) + n_keywords = read_int_bare(data) + keywords = [] + for _ in range(n_keywords): + key = read_str(data) + value = read_expression(state, data) + keywords.append((key, value)) + + # Extract metaclass from keywords if present + metaclass = dict(keywords).get("metaclass") if keywords else None + # Remove metaclass from keywords since it's passed as a separate field + filtered_keywords = [(k, v) for k, v in keywords if k != "metaclass"] if keywords else None + + class_def = ClassDef( + name, + body, + base_type_exprs=base_type_exprs if base_type_exprs else None, + metaclass=metaclass, + keywords=filtered_keywords, + type_args=type_params, + ) + class_def.decorators = decorators + read_loc(data, class_def) + expect_end_tag(data) + return class_def + + +def read_type_alias_stmt(state: State, data: ReadBuffer) -> TypeAliasStmt: + """Read PEP 695 type alias statement.""" + name = read_expression(state, data) + assert isinstance(name, NameExpr), f"Expected NameExpr for type alias name, got {type(name)}" + + n_type_params = read_int_bare(data) + if n_type_params > 0: + type_params = [] + for _ in range(n_type_params): + kind = read_int(data) + param_name = read_str(data) + has_bound = read_bool(data) + if has_bound: + upper_bound = read_type(state, data) + else: + upper_bound = None + + # Read values (for constrained TypeVar) + expect_tag(data, LIST_GEN) + n_values = read_int_bare(data) + values = [read_type(state, data) for _ in range(n_values)] + + has_default = read_bool(data) + if has_default: + default = read_type(state, data) + else: + default = None + + type_params.append(TypeParam(param_name, kind, upper_bound, values, default)) + else: + type_params = [] + + value_expr = read_expression(state, data) + + # Wrap the value expression in a LambdaExpr as expected by TypeAliasStmt + # The LambdaExpr body is a Block with a single ReturnStmt + return_stmt = ReturnStmt(value_expr) + set_line_column_range(return_stmt, value_expr) + + block = Block([return_stmt]) + block.line = -1 # Synthetic block + block.column = 0 + block.end_line = -1 + block.end_column = 0 + + lambda_expr = LambdaExpr([], block) + set_line_column_range(lambda_expr, value_expr) + + stmt = TypeAliasStmt(name, type_params, lambda_expr) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + + +def read_try_stmt(state: State, data: ReadBuffer) -> TryStmt: + body = read_block(state, data) + num_handlers = read_int(data) + + types_list: list[Expression | None] = [] + for _ in range(num_handlers): + has_type = read_bool(data) + if has_type: + exc_type = read_expression(state, data) + types_list.append(exc_type) + else: + types_list.append(None) + + vars_list: list[NameExpr | None] = [] + for _ in range(num_handlers): + has_name = read_bool(data) + if has_name: + var_name = read_str(data) + var_expr = NameExpr(var_name) + vars_list.append(var_expr) + else: + vars_list.append(None) + + handlers = [] + for _ in range(num_handlers): + handler_body = read_block(state, data) + handlers.append(handler_body) + + has_else = read_bool(data) + if has_else: + else_body = read_block(state, data) + else: + else_body = None + + has_finally = read_bool(data) + if has_finally: + finally_body = read_block(state, data) + else: + finally_body = None + + # Read is_star flag (for except* in Python 3.11+) + is_star = read_bool(data) + + stmt = TryStmt(body, vars_list, types_list, handlers, else_body, finally_body) + stmt.is_star = is_star + read_loc(data, stmt) + expect_end_tag(data) + return stmt + + +def read_type(state: State, data: ReadBuffer) -> Type: + tag = read_tag(data) + if tag == types.UNBOUND_TYPE: + name = read_str(data) + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + args = tuple(read_type(state, data) for i in range(n)) + empty_tuple_index = read_bool(data) + # Read optional original_str_expr + t = read_tag(data) + if t == LITERAL_NONE: + original_str_expr = None + elif t == LITERAL_STR: + original_str_expr = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_expr: {t}" + # Read optional original_str_fallback + t = read_tag(data) + if t == LITERAL_NONE: + original_str_fallback = None + elif t == LITERAL_STR: + original_str_fallback = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_fallback: {t}" + unbound = UnboundType( + name, + args, + empty_tuple_index=empty_tuple_index, + original_str_expr=original_str_expr, + original_str_fallback=original_str_fallback, + ) + read_loc(data, unbound) + expect_end_tag(data) + return unbound + elif tag == types.UNION_TYPE: + # Read items list + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + items = [read_type(state, data) for i in range(n)] + # Read uses_pep604_syntax flag + uses_pep604_syntax = read_bool(data) + # Read optional original_str_expr + t = read_tag(data) + if t == LITERAL_NONE: + original_str_expr = None + elif t == LITERAL_STR: + original_str_expr = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_expr: {t}" + # Read optional original_str_fallback + t = read_tag(data) + if t == LITERAL_NONE: + original_str_fallback = None + elif t == LITERAL_STR: + original_str_fallback = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_fallback: {t}" + union = UnionType(items, uses_pep604_syntax=uses_pep604_syntax) + union.original_str_expr = original_str_expr + union.original_str_fallback = original_str_fallback + union.is_evaluated = read_bool(data) + read_loc(data, union) + expect_end_tag(data) + return union + elif tag == types.LIST_TYPE: + # Read items list + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + items = [read_type(state, data) for i in range(n)] + type_list = TypeList(items) + read_loc(data, type_list) + expect_end_tag(data) + return type_list + elif tag == types.TUPLE_TYPE: + # Read items list + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + items = [read_type(state, data) for i in range(n)] + implicit = read_bool(data) + tuple_type = TupleType(items, _dummy_fallback, implicit=implicit) + read_loc(data, tuple_type) + expect_end_tag(data) + return tuple_type + elif tag == types.TYPED_DICT_TYPE: + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + keys = [read_str_opt(data) for i in range(n)] + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + values = [read_type(state, data) for i in range(n)] + td_items = {} + extra_items_from = [] + for key, val in zip(keys, values): + if key is None: + assert isinstance(val, ProperType) + extra_items_from.append(val) + else: + td_items[key] = val + typeddict_type = TypedDictType(td_items, set(), set(), _dummy_fallback) + typeddict_type.extra_items_from = extra_items_from + read_loc(data, typeddict_type) + expect_end_tag(data) + return typeddict_type + elif tag == types.ELLIPSIS_TYPE: + # EllipsisType has no attributes + ellipsis_type = EllipsisType() + read_loc(data, ellipsis_type) + expect_end_tag(data) + return ellipsis_type + elif tag == types.RAW_EXPRESSION_TYPE: + type_name = read_str(data) + value: types.LiteralValue | str | None + if type_name == "builtins.bool": + value = read_bool(data) + elif type_name == "builtins.int": + value = read_int(data) + elif type_name == "builtins.str": + value = read_str(data) + elif type_name == "builtins.bytes": + # Bytes literals are serialized as escaped strings + value = read_str(data) + elif type_name == "typing.Any": + # Invalid type - read None value + tag = read_tag(data) + assert tag == LITERAL_NONE, f"Expected LITERAL_NONE for invalid type, got {tag}" + value = None + else: + assert False, f"Unsupported RawExpressionType: {type_name}" + raw_type = RawExpressionType(value, type_name) + read_loc(data, raw_type) + expect_end_tag(data) + return raw_type + elif tag == types.UNPACK_TYPE: + inner_type = read_type(state, data) + from_star_syntax = read_bool(data) + unpack = UnpackType(inner_type, from_star_syntax=from_star_syntax) + read_loc(data, unpack) + expect_end_tag(data) + return unpack + elif tag == types.CALL_TYPE: + return read_call_type(state, data) + else: + assert False, tag + + +def stringify_type_name(typ: Type) -> str | None: + """Extract qualified name from a type (for Arg constructor detection).""" + if isinstance(typ, UnboundType): + return typ.name + return None + + +def extract_arg_name(typ: Type) -> str | None: + """Extract argument name from a type (for Arg name parameter).""" + if isinstance(typ, RawExpressionType) and typ.base_type_name == "builtins.str": + return typ.literal_value # type: ignore[return-value] + elif isinstance(typ, UnboundType): + # String literals in type context are parsed as UnboundType (forward references) + # For Arg names, these are typically simple names without dots + if typ.name == "None": + return None + # Return the name as-is (it's the argument name) + return typ.name + return None # Invalid, but let validation handle it + + +def read_call_type(state: State, data: ReadBuffer) -> Type: + """Read Call in type context - check if it's an Arg/DefaultArg/VarArg/KwArg constructor. + + This performs validation and error reporting similar to mypy/fastparse.py. + """ + callee_type = read_type(state, data) + + # Read positional arguments + expect_tag(data, LIST_GEN) + n_args = read_int_bare(data) + args = [read_type(state, data) for _ in range(n_args)] + + # Read keyword arguments + expect_tag(data, LIST_GEN) + n_kwargs = read_int_bare(data) + kwargs = [] + for _ in range(n_kwargs): + tag_kw = read_tag(data) + if tag_kw == LITERAL_NONE: + kw_name = None + elif tag_kw == LITERAL_STR: + kw_name = read_str_bare(data) + else: + assert False, f"Unexpected tag for keyword name: {tag_kw}" + kw_value = read_type(state, data) + kwargs.append((kw_name, kw_value)) + + # Try to detect Arg/DefaultArg/VarArg/KwArg pattern + constructor = stringify_type_name(callee_type) + + # We'll read location before processing errors so we can report them correctly + invalid = AnyType(TypeOfAny.from_error) + read_loc(data, invalid) + expect_end_tag(data) + + if not constructor: + # ARG_CONSTRUCTOR_NAME_EXPECTED + state.add_error( + message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED.value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + return invalid + + # Extract type and name from arguments + name: str | None = None + name_set_from_positional = False + default_type = AnyType(TypeOfAny.special_form) + typ: Type = default_type + typ_set_from_positional = False + + # Process positional arguments + for i, arg in enumerate(args): + if i == 0: + typ = arg + typ_set_from_positional = True + elif i == 1: + name = extract_arg_name(arg) + name_set_from_positional = True + else: + # ARG_CONSTRUCTOR_TOO_MANY_ARGS + state.add_error( + message_registry.ARG_CONSTRUCTOR_TOO_MANY_ARGS.value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + + # Process keyword arguments + for kw_name, kw_value in kwargs: + if kw_name == "name": + # MULTIPLE_VALUES_FOR_NAME_KWARG + if name is not None and name_set_from_positional: + state.add_error( + message_registry.MULTIPLE_VALUES_FOR_NAME_KWARG.format(constructor).value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + name = extract_arg_name(kw_value) + elif kw_name == "type": + # MULTIPLE_VALUES_FOR_TYPE_KWARG + if typ is not default_type and typ_set_from_positional: + state.add_error( + message_registry.MULTIPLE_VALUES_FOR_TYPE_KWARG.format(constructor).value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + typ = kw_value + else: + # ARG_CONSTRUCTOR_UNEXPECTED_ARG + state.add_error( + message_registry.ARG_CONSTRUCTOR_UNEXPECTED_ARG.format(kw_name).value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + + # Create CallableArgument + call_arg = CallableArgument(typ, name, constructor) + set_line_column_range(call_arg, invalid) + return call_arg + + +def read_pattern(state: State, data: ReadBuffer) -> Pattern: + """Read a pattern node from the buffer.""" + tag = read_tag(data) + if tag == nodes.AS_PATTERN: + has_pattern = read_bool(data) + if has_pattern: + pattern = read_pattern(state, data) + else: + pattern = None + has_name = read_bool(data) + if has_name: + name_str = read_str(data) + name = NameExpr(name_str) + read_loc(data, name) + else: + name = None + as_pattern = AsPattern(pattern, name) + read_loc(data, as_pattern) + expect_end_tag(data) + return as_pattern + elif tag == nodes.OR_PATTERN: + n = read_int(data) + patterns = [read_pattern(state, data) for _ in range(n)] + or_pattern = OrPattern(patterns) + read_loc(data, or_pattern) + expect_end_tag(data) + return or_pattern + elif tag == nodes.VALUE_PATTERN: + expr = read_expression(state, data) + value_pattern = ValuePattern(expr) + read_loc(data, value_pattern) + expect_end_tag(data) + return value_pattern + elif tag == nodes.SINGLETON_PATTERN: + singleton_tag = read_tag(data) + if singleton_tag == LITERAL_NONE: + value = None + else: + # It's a boolean + value = singleton_tag == 1 # TAG_LITERAL_TRUE + singleton_pattern = SingletonPattern(value) + read_loc(data, singleton_pattern) + expect_end_tag(data) + return singleton_pattern + elif tag == nodes.SEQUENCE_PATTERN: + n = read_int(data) + patterns = [read_pattern(state, data) for _ in range(n)] + sequence_pattern = SequencePattern(patterns) + read_loc(data, sequence_pattern) + expect_end_tag(data) + return sequence_pattern + elif tag == nodes.STARRED_PATTERN: + # Read optional capture name + has_name = read_bool(data) + if has_name: + name_str = read_str(data) + name = NameExpr(name_str) + read_loc(data, name) + else: + name = None + starred_pattern = StarredPattern(name) + read_loc(data, starred_pattern) + expect_end_tag(data) + return starred_pattern + elif tag == nodes.MAPPING_PATTERN: + n = read_int(data) + keys = [] + values = [] + for _ in range(n): + key = read_expression(state, data) + value = read_pattern(state, data) + keys.append(key) + values.append(value) + has_rest = read_bool(data) + if has_rest: + rest_str = read_str(data) + rest = NameExpr(rest_str) + read_loc(data, rest) + else: + rest = None + mapping_pattern = MappingPattern(keys, values, rest) + read_loc(data, mapping_pattern) + expect_end_tag(data) + return mapping_pattern + elif tag == nodes.CLASS_PATTERN: + class_ref = cast(RefExpr, read_expression(state, data)) + n_positional = read_int(data) + positionals = [read_pattern(state, data) for _ in range(n_positional)] + n_keywords = read_int(data) + keyword_keys = [] + keyword_values = [] + for _ in range(n_keywords): + key = read_str(data) + value = read_pattern(state, data) + keyword_keys.append(key) + keyword_values.append(value) + class_pattern = ClassPattern(class_ref, positionals, keyword_keys, keyword_values) + read_loc(data, class_pattern) + expect_end_tag(data) + return class_pattern + else: + assert False, f"Unknown pattern tag: {tag}" + + +def read_block(state: State, data: ReadBuffer) -> Block: + expect_tag(data, nodes.BLOCK) + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + is_unreachable = read_bool(data) + if n == 0: + # Empty block - read explicit location + b = Block([], is_unreachable=is_unreachable) + read_loc(data, b) + expect_end_tag(data) + return b + else: + # Non-empty block - read statements and set location from them + a = read_statements(state, data, n) + expect_end_tag(data) + b = Block(a, is_unreachable=is_unreachable) + b.line = a[0].line + b.column = a[0].column + b.end_line = a[-1].end_line + b.end_column = a[-1].end_column + return b + + +def read_optional_block(state: State, data: ReadBuffer) -> Block | None: + expect_tag(data, nodes.BLOCK) + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + is_unreachable = read_bool(data) + if n == 0: + b = None + else: + a = [read_statement(state, data) for i in range(n)] + b = Block(a, is_unreachable=is_unreachable) + b.line = a[0].line + b.column = a[0].column + b.end_line = a[-1].end_line + b.end_column = a[-1].end_column + expect_end_tag(data) + return b + + +bin_ops: Final = ["+", "-", "*", "@", "/", "%", "**", "<<", ">>", "|", "^", "&", "//"] +bool_ops: Final = ["and", "or"] +cmp_ops: Final = ["==", "!=", "<", "<=", ">", ">=", "is", "is not", "in", "not in"] +unary_ops: Final = ["~", "not", "+", "-"] + + +def read_expression(state: State, data: ReadBuffer) -> Expression: + tag = read_tag(data) + expr: Expression + if tag == nodes.CALL_EXPR: + callee = read_expression(state, data) + args = read_expression_list(state, data) + # Read argument kinds + expect_tag(data, LIST_INT) + n_kinds = read_int_bare(data) + arg_kinds = [ARG_KINDS[read_int_bare(data)] for _ in range(n_kinds)] + # Read argument names + expect_tag(data, LIST_GEN) + n_names = read_int_bare(data) + arg_names: list[str | None] = [] + for _ in range(n_names): + tag = read_tag(data) + if tag == LITERAL_NONE: + arg_names.append(None) + elif tag == LITERAL_STR: + arg_names.append(read_str_bare(data)) + else: + assert False, f"Unexpected tag for arg_name: {tag}" + ce = CallExpr(callee, args, arg_kinds, arg_names) + read_loc(data, ce) + expect_end_tag(data) + return ce + elif tag == nodes.NAME_EXPR: + s = read_str(data) + ne = NameExpr(s) + read_loc(data, ne) + expect_end_tag(data) + return ne + elif tag == nodes.MEMBER_EXPR: + e = read_expression(state, data) + attr = read_str(data) + m = MemberExpr(e, attr) + # Check if this is a super() call - if so, convert to SuperExpr + if isinstance(e, CallExpr) and isinstance(e.callee, NameExpr) and e.callee.name == "super": + result: Expression = SuperExpr(attr, e) + else: + result = m + read_loc(data, result) + expect_end_tag(data) + return result + elif tag == nodes.STR_EXPR: + se = StrExpr(read_str(data)) + read_loc(data, se) + expect_end_tag(data) + return se + elif tag == nodes.INT_EXPR: + ie = IntExpr(read_int(data)) + read_loc(data, ie) + expect_end_tag(data) + return ie + elif tag == nodes.FLOAT_EXPR: + expect_tag(data, LITERAL_FLOAT) + value = read_float_bare(data) + fe = FloatExpr(value) + read_loc(data, fe) + expect_end_tag(data) + return fe + elif tag == nodes.LIST_EXPR: + items = read_expression_list(state, data) + expr = ListExpr(items) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.TUPLE_EXPR: + items = read_expression_list(state, data) + t = TupleExpr(items) + read_loc(data, t) + expect_end_tag(data) + return t + elif tag == nodes.SET_EXPR: + items = read_expression_list(state, data) + expr = SetExpr(items) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.GENERATOR_EXPR: + expr = read_generator_expr(state, data) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.LIST_COMPREHENSION: + generator = read_generator_expr(state, data) + expr = ListComprehension(generator) + read_loc(data, expr) + # Also copy location to the inner generator + set_line_column_range(generator, expr) + expect_end_tag(data) + return expr + elif tag == nodes.SET_COMPREHENSION: + generator = read_generator_expr(state, data) + expr = SetComprehension(generator) + read_loc(data, expr) + # Also copy location to the inner generator + set_line_column_range(generator, expr) + expect_end_tag(data) + return expr + elif tag == nodes.DICT_COMPREHENSION: + key = read_expression(state, data) + value = read_expression(state, data) + n_generators = read_int(data) + indices = [read_expression(state, data) for _ in range(n_generators)] + sequences = [read_expression(state, data) for _ in range(n_generators)] + condlists = [read_expression_list(state, data) for _ in range(n_generators)] + is_async = [read_bool(data) for _ in range(n_generators)] + expr = DictionaryComprehension(key, value, indices, sequences, condlists, is_async) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.YIELD_EXPR: + has_value = read_bool(data) + if has_value: + value = read_expression(state, data) + else: + value = None + expr = YieldExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.YIELD_FROM_EXPR: + value = read_expression(state, data) + expr = YieldFromExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.OP_EXPR: + op = bin_ops[read_int(data)] + left = read_expression(state, data) + right = read_expression(state, data) + o = OpExpr(op, left, right) + # TODO: Store these explicitly? + o.line = left.line + o.column = left.column + o.end_line = right.end_line + o.end_column = right.end_column + expect_end_tag(data) + return o + elif tag == nodes.INDEX_EXPR: + base = read_expression(state, data) + index = read_expression(state, data) + expr = IndexExpr(base, index) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.BOOL_OP_EXPR: + op = bool_ops[read_int(data)] + values = read_expression_list(state, data) + # Convert list of values to nested OpExpr nodes + # E.g., [a, b, c] with "and" becomes OpExpr("and", OpExpr("and", a, b), c) + assert len(values) >= 2 + result = values[0] + for val in values[1:]: + result = OpExpr(op, result, val) + result.line = values[0].line + result.column = values[0].column + result.end_line = val.end_line + result.end_column = val.end_column + read_loc(data, result) + expect_end_tag(data) + return result + elif tag == nodes.COMPARISON_EXPR: + left = read_expression(state, data) + expect_tag(data, LIST_INT) + n_ops = read_int_bare(data) + ops = [cmp_ops[read_int_bare(data)] for _ in range(n_ops)] + comparators = read_expression_list(state, data) + assert len(ops) == len(comparators) + expr = ComparisonExpr(ops, [left] + comparators) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.UNARY_EXPR: + op = unary_ops[read_int(data)] + operand = read_expression(state, data) + expr = UnaryExpr(op, operand) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.DICT_EXPR: + expect_tag(data, LIST_GEN) + n_keys = read_int_bare(data) + keys: list[Expression | None] = [] + for _ in range(n_keys): + has_key = read_bool(data) + if has_key: + keys.append(read_expression(state, data)) + else: + keys.append(None) + values = read_expression_list(state, data) + # Zip keys and values into items + items = list(zip(keys, values)) + expr = DictExpr(items) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.COMPLEX_EXPR: + expect_tag(data, LITERAL_FLOAT) + real = read_float_bare(data) + expect_tag(data, LITERAL_FLOAT) + imag = read_float_bare(data) + value = complex(real, imag) + expr = ComplexExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.SLICE_EXPR: + has_begin = read_bool(data) + begin_index = read_expression(state, data) if has_begin else None + has_end = read_bool(data) + end_index = read_expression(state, data) if has_end else None + has_stride = read_bool(data) + stride = read_expression(state, data) if has_stride else None + expr = SliceExpr(begin_index, end_index, stride) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.TEMP_NODE: + # TempNode with no attributes + temp = TempNode(AnyType(TypeOfAny.special_form), no_rhs=True) + expect_end_tag(data) + return temp + elif tag == nodes.ELLIPSIS_EXPR: + expr = EllipsisExpr() + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.CONDITIONAL_EXPR: + if_expr = read_expression(state, data) + cond = read_expression(state, data) + else_expr = read_expression(state, data) + expr = ConditionalExpr(cond, if_expr, else_expr) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.FSTRING_EXPR: + # F-strings are converted into nodes representing "".join([...]), to match + # pre-existing behavior. + nparts = read_int(data) + fitems = [] + for _ in range(nparts): + b = read_bool(data) + if b: + n = read_int(data) + for i in range(n): + fitems.append(read_fstring_item(state, data)) + else: + s = StrExpr(read_str(data)) + read_loc(data, s) + fitems.append(s) + expr = build_fstring_join(state, data, fitems) + expect_end_tag(data) + return expr + elif tag == nodes.TSTRING_EXPR: + nparts = read_int(data) + titems: list[Expression | tuple[Expression, str, str | None, Expression | None]] = [] + for _ in range(nparts): + if read_bool(data): + e = read_expression(state, data) + s = read_str(data) + if read_bool(data): + conv = read_str(data) + else: + conv = None + if read_bool(data): + # Parse format spec as a JoinedStr, this matches the old parser behavior. + format_spec = read_fstring_items(state, data) + else: + format_spec = None + titems.append((e, s, conv, format_spec)) + else: + s = StrExpr(read_str(data)) + read_loc(data, s) + titems.append(s) + expr = TemplateStrExpr(titems) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.LAMBDA_EXPR: + arguments, has_ann = read_parameters(state, data) + body = read_block(state, data) + + if has_ann: + typ = CallableType( + [ + arg.type_annotation if arg.type_annotation else AnyType(TypeOfAny.unannotated) + for arg in arguments + ], + [arg.kind for arg in arguments], + [None if arg.pos_only else arg.variable.name for arg in arguments], + AnyType(TypeOfAny.unannotated), + _dummy_fallback, + ) + else: + typ = None + + expr = LambdaExpr(arguments, body) + expr.type = typ + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.NAMED_EXPR: + target = read_expression(state, data) + value = read_expression(state, data) + # AssignmentExpr expects target to be a NameExpr + if not isinstance(target, NameExpr): + # In case target is not a NameExpr, we need to handle this + # For now, we'll assert since the grammar should ensure it's a NameExpr + assert isinstance( + target, NameExpr + ), f"Expected NameExpr for target, got {type(target)}" + expr = AssignmentExpr(target, value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.STAR_EXPR: + wrapped_expr = read_expression(state, data) + expr = StarExpr(wrapped_expr) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.BYTES_EXPR: + # Read bytes literal as string + value = read_str(data) + expr = BytesExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.AWAIT_EXPR: + value = read_expression(state, data) + expr = AwaitExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.BIG_INT_EXPR: + strval = read_str(data) + ie = IntExpr(int(strval, base=0)) + read_loc(data, ie) + expect_end_tag(data) + return ie + else: + assert False, tag + + +def read_fstring_items(state: State, data: ReadBuffer) -> Expression: + items = [] + n = read_int(data) + items = [read_fstring_item(state, data) for i in range(n)] + return build_fstring_join(state, data, items) + + +def build_fstring_join(state: State, data: ReadBuffer, items: list[Expression]) -> Expression: + if len(items) == 1: + expr = items[0] + read_loc(data, expr) + return expr + if all(isinstance(item, StrExpr) for item in items): + s = "".join([cast(StrExpr, item).value for item in items]) + expr = StrExpr(s) + read_loc(data, expr) + return expr + args = ListExpr(items) + str_expr = StrExpr("") + member = MemberExpr(str_expr, "join") + call = CallExpr(member, [args], [ARG_POS], [None]) + read_loc(data, call) + set_line_column(args, call) + set_line_column(str_expr, call) + set_line_column(member, call) + return call + + +def read_fstring_item(state: State, data: ReadBuffer) -> Expression: + t = read_tag(data) + if t == LITERAL_STR: + str_expr = StrExpr(read_str_bare(data)) + read_loc(data, str_expr) + return str_expr + elif t == nodes.FSTRING_INTERPOLATION: + expr = read_expression(state, data) + + # Read conversion flag such as !r + has_conv = read_bool(data) + if has_conv: + c = read_str(data) + fmt = "{" + c + ":{}}" + else: + fmt = "{:{}}" + + # Read format spec such as <30 (which may have nested {...}) + has_spec = read_bool(data) + if has_spec: + spec = read_fstring_items(state, data) + else: + spec = StrExpr("") + + member = MemberExpr(StrExpr(fmt), "format") + set_line_column(member, expr) + call = CallExpr(member, [expr, spec], [ARG_POS, ARG_POS], [None, None]) + set_line_column(call, expr) + expect_end_tag(data) + return call + else: + raise ValueError(f"Unexpected tag {t}") + + +def set_line_column(target: Context, src: Context) -> None: + target.line = src.line + target.column = src.column + + +def set_line_column_range(target: Context, src: Context) -> None: + target.line = src.line + target.column = src.column + target.end_line = src.end_line + target.end_column = src.end_column + + +def read_expression_list(state: State, data: ReadBuffer) -> list[Expression]: + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + return [read_expression(state, data) for i in range(n)] + + +def read_generator_expr(state: State, data: ReadBuffer) -> GeneratorExpr: + """Helper function to read comprehension data (shared by Generator, ListComp, SetComp)""" + left_expr = read_expression(state, data) + n_generators = read_int(data) + indices = [read_expression(state, data) for _ in range(n_generators)] + sequences = [read_expression(state, data) for _ in range(n_generators)] + condlists = [read_expression_list(state, data) for _ in range(n_generators)] + is_async = [read_bool(data) for _ in range(n_generators)] + return GeneratorExpr(left_expr, indices, sequences, condlists, is_async) + + +def read_loc(data: ReadBuffer, node: Context) -> None: + expect_tag(data, LOCATION) + line = read_int_bare(data) + node.line = line + column = read_int_bare(data) + node.column = column + node.end_line = line + read_int_bare(data) + node.end_column = column + read_int_bare(data) + + +def strip_contents_from_if_stmt(stmt: IfStmt) -> None: + """Remove contents from IfStmt. + + Needed to still be able to check the conditions after the contents + have been merged with the surrounding function overloads. + """ + if len(stmt.body) == 1: + stmt.body[0].body = [] + if stmt.else_body and len(stmt.else_body.body) == 1: + if isinstance(stmt.else_body.body[0], IfStmt): + strip_contents_from_if_stmt(stmt.else_body.body[0]) + else: + stmt.else_body.body = [] + + +def is_stripped_if_stmt(stmt: Statement) -> bool: + """Check stmt to make sure it is a stripped IfStmt. + + See also: strip_contents_from_if_stmt + """ + if not isinstance(stmt, IfStmt): + return False + + if not (len(stmt.body) == 1 and len(stmt.body[0].body) == 0): + # Body not empty + return False + + if not stmt.else_body or len(stmt.else_body.body) == 0: + # No or empty else_body + return True + + # For elif, IfStmt are stored recursively in else_body + return is_stripped_if_stmt(stmt.else_body.body[0]) + + +def fail_merge_overload(state: State, node: IfStmt) -> None: + """Report an error when overloads cannot be merged due to unknown condition.""" + state.add_error( + message_registry.FAILED_TO_MERGE_OVERLOADS.value, + node.line, + node.column, + blocker=False, + code="misc", + ) + + +def check_ifstmt_for_overloads( + stmt: IfStmt, current_overload_name: str | None = None +) -> str | None: + """Check if IfStmt contains only overloads with the same name. + Return overload_name if found, None otherwise. + """ + # Check that block only contains a single Decorator, FuncDef, or OverloadedFuncDef. + # Multiple overloads have already been merged as OverloadedFuncDef. + if not ( + len(stmt.body[0].body) == 1 + and ( + isinstance(stmt.body[0].body[0], (Decorator, OverloadedFuncDef)) + or current_overload_name is not None + and isinstance(stmt.body[0].body[0], FuncDef) + ) + or len(stmt.body[0].body) > 1 + and isinstance(stmt.body[0].body[-1], OverloadedFuncDef) + and all(is_stripped_if_stmt(if_stmt) for if_stmt in stmt.body[0].body[:-1]) + ): + return None + + overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name + if stmt.else_body is None or stmt.else_body.is_unreachable: + return overload_name + + if len(stmt.else_body.body) == 1: + # For elif: else_body contains an IfStmt itself -> do a recursive check. + if ( + isinstance(stmt.else_body.body[0], (Decorator, FuncDef, OverloadedFuncDef)) + and stmt.else_body.body[0].name == overload_name + ): + return overload_name + if ( + isinstance(stmt.else_body.body[0], IfStmt) + and check_ifstmt_for_overloads(stmt.else_body.body[0], current_overload_name) + == overload_name + ): + return overload_name + + return None + + +def get_executable_if_block_with_overloads( + stmt: IfStmt, options: Options +) -> tuple[Block | None, IfStmt | None]: + """Return block from IfStmt that will get executed. + + Return + 0 -> A block if sure that alternative blocks are unreachable. + 1 -> An IfStmt if the reachability of it can't be inferred, + i.e. the truth value is unknown. + """ + infer_reachability_of_if_statement(stmt, options) + if stmt.else_body is None and stmt.body[0].is_unreachable is True: + # always False condition with no else + return None, None + if ( + stmt.else_body is None + or stmt.body[0].is_unreachable is False + and stmt.else_body.is_unreachable is False + ): + # The truth value is unknown, thus not conclusive + return None, stmt + if stmt.else_body.is_unreachable: + # else_body will be set unreachable if condition is always True + return stmt.body[0], None + if stmt.body[0].is_unreachable is True: + # body will be set unreachable if condition is always False + # else_body can contain an IfStmt itself (for elif) -> do a recursive check + if isinstance(stmt.else_body.body[0], IfStmt): + return get_executable_if_block_with_overloads(stmt.else_body.body[0], options) + return stmt.else_body, None + return None, stmt + + +def fix_function_overloads(state: State, stmts: list[Statement]) -> list[Statement]: + """Merge consecutive function overloads into OverloadedFuncDef nodes. + + This function processes a list of statements and combines function overloads + (marked with @overload decorator) that have the same name into a single + OverloadedFuncDef node. It also handles conditional overloads (overloads + inside if statements) when the condition can be evaluated. + """ + ret: list[Statement] = [] + current_overload: list[OverloadPart] = [] + current_overload_name: str | None = None + last_unconditional_func_def: str | None = None + last_if_stmt: IfStmt | None = None + last_if_overload: Decorator | FuncDef | OverloadedFuncDef | None = None + last_if_stmt_overload_name: str | None = None + last_if_unknown_truth_value: IfStmt | None = None + skipped_if_stmts: list[IfStmt] = [] + for stmt in stmts: + if_overload_name: str | None = None + if_block_with_overload: Block | None = None + if_unknown_truth_value: IfStmt | None = None + if isinstance(stmt, IfStmt): + # Check IfStmt block to determine if function overloads can be merged + if_overload_name = check_ifstmt_for_overloads(stmt, current_overload_name) + if if_overload_name is not None: + if_block_with_overload, if_unknown_truth_value = ( + get_executable_if_block_with_overloads(stmt, state.options) + ) + + if ( + current_overload_name is not None + and isinstance(stmt, (Decorator, FuncDef)) + and stmt.name == current_overload_name + ): + if last_if_stmt is not None: + skipped_if_stmts.append(last_if_stmt) + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if last_if_unknown_truth_value: + fail_merge_overload(state, last_if_unknown_truth_value) + last_if_unknown_truth_value = None + current_overload.append(stmt) + if isinstance(stmt, FuncDef): + # This is, strictly speaking, wrong: there might be a decorated + # implementation. However, it only affects the error message we show: + # ideally it's "already defined", but "implementation must come last" + # is also reasonable. + # TODO: can we get rid of this completely and just always emit + # "implementation must come last" instead? + last_unconditional_func_def = stmt.name + elif ( + current_overload_name is not None + and isinstance(stmt, IfStmt) + and if_overload_name == current_overload_name + and last_unconditional_func_def != current_overload_name + ): + # IfStmt only contains stmts relevant to current_overload. + # Check if stmts are reachable and add them to current_overload, + # otherwise skip IfStmt to allow subsequent overload + # or function definitions. + skipped_if_stmts.append(stmt) + if if_block_with_overload is None: + if if_unknown_truth_value is not None: + fail_merge_overload(state, if_unknown_truth_value) + continue + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef): + skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1])) + current_overload.extend(if_block_with_overload.body[-1].items) + else: + current_overload.append(cast(Decorator | FuncDef, if_block_with_overload.body[0])) + else: + if last_if_stmt is not None: + ret.append(last_if_stmt) + last_if_stmt_overload_name = current_overload_name + last_if_stmt, last_if_overload = None, None + last_if_unknown_truth_value = None + + if current_overload and current_overload_name == last_if_stmt_overload_name: + # Remove last stmt (IfStmt) from ret if the overload names matched + # Only happens if no executable block had been found in IfStmt + popped = ret.pop() + assert isinstance(popped, IfStmt) + skipped_if_stmts.append(popped) + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + skipped_if_stmts = [] + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + + # If we have multiple decorated functions named "_" next to each, we want to treat + # them as a series of regular FuncDefs instead of one OverloadedFuncDef because + # most of mypy/mypyc assumes that all the functions in an OverloadedFuncDef are + # related, but multiple underscore functions next to each other aren't necessarily + # related + last_unconditional_func_def = None + if isinstance(stmt, Decorator) and not unnamed_function(stmt.name): + current_overload = [stmt] + current_overload_name = stmt.name + elif isinstance(stmt, IfStmt) and if_overload_name is not None: + current_overload = [] + current_overload_name = if_overload_name + last_if_stmt = stmt + last_if_stmt_overload_name = None + if if_block_with_overload is not None: + skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1])) + last_if_overload = cast( + Decorator | FuncDef | OverloadedFuncDef, if_block_with_overload.body[-1] + ) + last_if_unknown_truth_value = if_unknown_truth_value + else: + current_overload = [] + current_overload_name = None + ret.append(stmt) + + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + elif last_if_overload is not None: + ret.append(last_if_overload) + elif last_if_stmt is not None: + ret.append(last_if_stmt) + return ret + + +def deserialize_imports(import_bytes: bytes) -> list[ImportBase]: + """Deserialize import metadata from bytes into mypy AST nodes. + + Args: + import_bytes: Serialized import metadata from the Rust parser + + Returns: + List of Import and ImportFrom AST nodes with location and metadata + """ + if not import_bytes: + return [] + + data = ReadBuffer(import_bytes) + + expect_tag(data, LIST_GEN) + n_imports = read_int_bare(data) + + imports: list[ImportBase] = [] + + for _ in range(n_imports): + tag = read_tag(data) + + if tag == IMPORT_METADATA: + name = read_str(data) + relative = read_int(data) + + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + + # Note: relative imports are handled via ImportFrom, so relative should be 0 here + stmt = Import([(name, asname)]) + _read_and_set_import_metadata(data, stmt) + imports.append(stmt) + + elif tag == IMPORTFROM_METADATA: + module = read_str(data) + relative = read_int(data) + + expect_tag(data, LIST_GEN) + n_names = read_int_bare(data) + names: list[tuple[str, str | None]] = [] + + for _ in range(n_names): + name = read_str(data) + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + names.append((name, asname)) + + stmt = ImportFrom(module, relative, names) + _read_and_set_import_metadata(data, stmt) + imports.append(stmt) + + elif tag == IMPORTALL_METADATA: + module = read_str(data) + relative = read_int(data) + + stmt = ImportAll(module, relative) + _read_and_set_import_metadata(data, stmt) + imports.append(stmt) + + else: + raise ValueError(f"Unexpected tag in import metadata: {tag}") + + return imports + + +def _read_and_set_import_metadata(data: ReadBuffer, stmt: Import | ImportFrom | ImportAll) -> None: + """Read location and metadata flags from buffer and set them on the import statement. + + Args: + data: Buffer containing serialized data + stmt: Import, ImportFrom, or ImportAll statement to populate with location and metadata + """ + read_loc(data, stmt) + + # Metadata flags as a single integer bitfield + flags = read_int(data) + + # Extract individual flags using bitwise operations + # Bit 0: is_top_level + # Bit 1: is_unreachable + # Bit 2: is_mypy_only + stmt.is_top_level = (flags & 0x01) != 0 + stmt.is_unreachable = (flags & 0x02) != 0 + stmt.is_mypy_only = (flags & 0x04) != 0 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nodes.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nodes.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..2cf1b2fef6cfe16979750b9a12d0f27114b56b25 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nodes.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nodes.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..37ea4d3b0d56108482e96e9eb2c409836fd4c6a7 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/nodes.py @@ -0,0 +1,5367 @@ +"""Abstract syntax tree node classes (i.e. parse tree).""" + +from __future__ import annotations + +import os +from abc import abstractmethod +from collections import defaultdict +from collections.abc import Callable, Iterator, Sequence +from contextlib import contextmanager +from enum import Enum, unique +from typing import ( + TYPE_CHECKING, + Any, + Final, + Optional, + TypeAlias as _TypeAlias, + TypeGuard, + TypeVar, + Union, + cast, +) + +from librt.internal import ( + read_float as read_float_bare, + read_int as read_int_bare, + read_str as read_str_bare, + write_int as write_int_bare, + write_str as write_str_bare, +) +from mypy_extensions import trait + +import mypy.strconv +from mypy.cache import ( + DICT_INT_GEN, + DICT_STR_GEN, + DT_SPEC, + END_TAG, + LIST_GEN, + LIST_STR, + LITERAL_COMPLEX, + LITERAL_NONE, + ReadBuffer, + Tag, + WriteBuffer, + read_bool, + read_bytes, + read_int, + read_int_list, + read_int_opt, + read_json, + read_literal, + read_str, + read_str_list, + read_str_opt, + read_str_opt_list, + read_tag, + write_bool, + write_bytes, + write_int, + write_int_list, + write_int_opt, + write_json, + write_literal, + write_str, + write_str_list, + write_str_opt, + write_str_opt_list, + write_tag, +) +from mypy.options import Options +from mypy.util import is_sunder, is_typeshed_file, short_type +from mypy.visitor import ExpressionVisitor, NodeVisitor, StatementVisitor + +if TYPE_CHECKING: + from mypy.patterns import Pattern + + +@unique +class NotParsed(Enum): + VALUE = "NotParsed" + + +class Context: + """Base type for objects that are valid as error message locations.""" + + __slots__ = ("line", "column", "end_line", "end_column") + + def __init__(self, line: int = -1, column: int = -1) -> None: + self.line = line + self.column = column + self.end_line: int | None = None + self.end_column: int | None = None + + def set_line( + self, + target: Context | int, + column: int | None = None, + end_line: int | None = None, + end_column: int | None = None, + ) -> None: + """If target is a node, pull line (and column) information + into this node. If column is specified, this will override any column + information coming from a node. + """ + if isinstance(target, int): + self.line = target + else: + self.line = target.line + self.column = target.column + self.end_line = target.end_line + self.end_column = target.end_column + + if column is not None: + self.column = column + + if end_line is not None: + self.end_line = end_line + + if end_column is not None: + self.end_column = end_column + + +if TYPE_CHECKING: + # break import cycle only needed for mypy + import mypy.types + + +T = TypeVar("T") + +JsonDict: _TypeAlias = dict[str, Any] + + +# Symbol table node kinds +# +# TODO rename to use more descriptive names + +LDEF: Final = 0 +GDEF: Final = 1 +MDEF: Final = 2 + +# Placeholder for a name imported via 'from ... import'. Second phase of +# semantic will replace this the actual imported reference. This is +# needed so that we can detect whether a name has been imported during +# XXX what? +UNBOUND_IMPORTED: Final = 3 + +# RevealExpr node kinds +REVEAL_TYPE: Final = 0 +REVEAL_LOCALS: Final = 1 + +# Kinds of 'literal' expressions. +# +# Use the function mypy.literals.literal to calculate these. +# +# TODO: Can we make these less confusing? +LITERAL_YES: Final = 2 # Value of expression known statically +LITERAL_TYPE: Final = 1 # Type of expression can be narrowed (e.g. variable reference) +LITERAL_NO: Final = 0 # None of the above + +node_kinds: Final = {LDEF: "Ldef", GDEF: "Gdef", MDEF: "Mdef", UNBOUND_IMPORTED: "UnboundImported"} +inverse_node_kinds: Final = {_kind: _name for _name, _kind in node_kinds.items()} + + +implicit_module_attrs: Final = { + "__name__": "__builtins__.str", + "__doc__": None, # depends on Python version, see semanal.py + "__path__": None, # depends on if the module is a package + "__file__": "__builtins__.str", + "__package__": "__builtins__.str", + "__annotations__": None, # dict[str, Any] bounded in add_implicit_module_attrs() + "__spec__": None, # importlib.machinery.ModuleSpec bounded in add_implicit_module_attrs() +} + + +# These aliases exist because built-in class objects are not subscriptable. +# For example `list[int]` fails at runtime. Instead List[int] should be used. +type_aliases: Final = { + "typing.List": "builtins.list", + "typing.Dict": "builtins.dict", + "typing.Set": "builtins.set", + "typing.FrozenSet": "builtins.frozenset", + "typing.ChainMap": "collections.ChainMap", + "typing.Counter": "collections.Counter", + "typing.DefaultDict": "collections.defaultdict", + "typing.Deque": "collections.deque", + "typing.OrderedDict": "collections.OrderedDict", + # HACK: a lie in lieu of actual support for PEP 675 + "typing.LiteralString": "builtins.str", +} + +# This keeps track of the oldest supported Python version where the corresponding +# alias source is available. +type_aliases_source_versions: Final = {"typing.LiteralString": (3, 11)} + +# This keeps track of aliases in `typing_extensions`, which we treat specially. +typing_extensions_aliases: Final = { + # See: https://github.com/python/mypy/issues/11528 + "typing_extensions.OrderedDict": "collections.OrderedDict", + # HACK: a lie in lieu of actual support for PEP 675 + "typing_extensions.LiteralString": "builtins.str", +} + +reverse_builtin_aliases: Final = { + "builtins.list": "typing.List", + "builtins.dict": "typing.Dict", + "builtins.set": "typing.Set", + "builtins.frozenset": "typing.FrozenSet", +} + + +RUNTIME_PROTOCOL_DECOS: Final = ( + "typing.runtime_checkable", + "typing_extensions.runtime", + "typing_extensions.runtime_checkable", +) + +LAMBDA_NAME: Final = "" + + +class Node(Context): + """Common base class for all non-type parse tree nodes.""" + + __slots__ = () + + def __str__(self) -> str: + return self.accept(mypy.strconv.StrConv(options=Options())) + + def str_with_options(self, options: Options) -> str: + a = self.accept(mypy.strconv.StrConv(options=options)) + assert a + return a + + def accept(self, visitor: NodeVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +@trait +class Statement(Node): + """A statement node.""" + + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +@trait +class Expression(Node): + """An expression node.""" + + __slots__ = () + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +class FakeExpression(Expression): + """A dummy expression. + + We need a dummy expression in one place, and can't instantiate Expression + because it is a trait and mypyc barfs. + """ + + __slots__ = () + + +# TODO: +# Lvalue = Union['NameExpr', 'MemberExpr', 'IndexExpr', 'SuperExpr', 'StarExpr' +# 'TupleExpr']; see #1783. +Lvalue: _TypeAlias = Expression + + +@trait +class SymbolNode(Node): + """Nodes that can be stored in a symbol table.""" + + __slots__ = () + + @property + @abstractmethod + def name(self) -> str: + pass + + # Fully qualified name + @property + @abstractmethod + def fullname(self) -> str: + pass + + @abstractmethod + def serialize(self) -> JsonDict: + pass + + @classmethod + def deserialize(cls, data: JsonDict) -> SymbolNode: + classname = data[".class"] + method = deserialize_map.get(classname) + if method is not None: + return method(data) + raise NotImplementedError(f"unexpected .class {classname}") + + def write(self, data: WriteBuffer) -> None: + raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance") + + @classmethod + def read(cls, data: ReadBuffer) -> SymbolNode: + raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance") + + +# Items: fullname, related symbol table node, surrounding type (if any) +Definition: _TypeAlias = tuple[str, "SymbolTableNode", Optional["TypeInfo"]] + + +class FileRawData: + """Raw (binary) data representing parsed, but not deserialized file.""" + + __slots__ = ( + "defs", + "imports", + "raw_errors", + "ignored_lines", + "is_partial_stub_package", + "uses_template_strings", + ) + + defs: bytes + imports: bytes + raw_errors: list[dict[str, Any]] # TODO: switch to more precise type here. + ignored_lines: dict[int, list[str]] + is_partial_stub_package: bool + uses_template_strings: bool + + def __init__( + self, + defs: bytes, + imports: bytes, + raw_errors: list[dict[str, Any]], + ignored_lines: dict[int, list[str]], + is_partial_stub_package: bool, + uses_template_strings: bool, + ) -> None: + self.defs = defs + self.imports = imports + self.raw_errors = raw_errors + self.ignored_lines = ignored_lines + self.is_partial_stub_package = is_partial_stub_package + self.uses_template_strings = uses_template_strings + + def write(self, data: WriteBuffer) -> None: + write_bytes(data, self.defs) + write_bytes(data, self.imports) + write_tag(data, LIST_GEN) + write_int_bare(data, len(self.raw_errors)) + for err in self.raw_errors: + write_json(data, err) + write_tag(data, DICT_INT_GEN) + write_int_bare(data, len(self.ignored_lines)) + for line, codes in self.ignored_lines.items(): + write_int(data, line) + write_str_list(data, codes) + write_bool(data, self.is_partial_stub_package) + write_bool(data, self.uses_template_strings) + + @classmethod + def read(cls, data: ReadBuffer) -> FileRawData: + defs = read_bytes(data) + imports = read_bytes(data) + assert read_tag(data) == LIST_GEN + raw_errors = [read_json(data) for _ in range(read_int_bare(data))] + assert read_tag(data) == DICT_INT_GEN + ignored_lines = {read_int(data): read_str_list(data) for _ in range(read_int_bare(data))} + return FileRawData( + defs, imports, raw_errors, ignored_lines, read_bool(data), read_bool(data) + ) + + +class MypyFile(SymbolNode): + """The abstract syntax tree of a single source file.""" + + __slots__ = ( + "_fullname", + "path", + "defs", + "alias_deps", + "module_refs", + "is_bom", + "names", + "imports", + "ignored_lines", + "skipped_lines", + "is_stub", + "is_cache_skeleton", + "is_partial_stub_package", + "uses_template_strings", + "plugin_deps", + "future_import_flags", + "_is_typeshed_file", + "raw_data", + ) + + __match_args__ = ("name", "path", "defs") + + # Fully qualified module name + _fullname: str + # Path to the file (empty string if not known) + path: str + # Top-level definitions and statements + defs: list[Statement] + # Type alias dependencies as mapping from target to set of alias full names + alias_deps: defaultdict[str, set[str]] + # The set of all dependencies (suppressed or not) that this module accesses, either + # directly or indirectly. + module_refs: set[str] + # Is there a UTF-8 BOM at the start? + is_bom: bool + names: SymbolTable + # All import nodes within the file (also ones within functions etc.) + imports: list[ImportBase] + # Lines on which to ignore certain errors when checking. + # If the value is empty, ignore all errors; otherwise, the list contains all + # error codes to ignore. + ignored_lines: dict[int, list[str]] + # Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE, + # or platform/version checks. Those lines would not be type-checked. + skipped_lines: set[int] + # Is this file represented by a stub file (.pyi)? + is_stub: bool + # Is this loaded from the cache and thus missing the actual body of the file? + is_cache_skeleton: bool + # Does this represent an __init__.pyi stub with a module __getattr__ + # (i.e. a partial stub package), for such packages we suppress any missing + # module errors in addition to missing attribute errors. + is_partial_stub_package: bool + # True if module contains at least one t-string (PEP 750 TemplateStr). + uses_template_strings: bool + # Plugin-created dependencies + plugin_deps: dict[str, set[str]] + # Future imports defined in this file. Populated during semantic analysis. + future_import_flags: set[str] + _is_typeshed_file: bool | None + # For native parser store actual serialized data here. + raw_data: FileRawData | None + + def __init__( + self, + defs: list[Statement], + imports: list[ImportBase], + is_bom: bool = False, + ignored_lines: dict[int, list[str]] | None = None, + ) -> None: + super().__init__() + self.defs = defs + self.line = 1 # Dummy line number + self.column = 0 # Dummy column + self.imports = imports + self.is_bom = is_bom + self.alias_deps = defaultdict(set) + self.module_refs = set() + self.plugin_deps = {} + if ignored_lines: + self.ignored_lines = ignored_lines + else: + self.ignored_lines = {} + self.skipped_lines = set() + + self.path = "" + self.is_stub = False + self.is_cache_skeleton = False + self.is_partial_stub_package = False + self.uses_template_strings = False + self.future_import_flags = set() + self._is_typeshed_file = None + self.raw_data = None + + def local_definitions(self) -> Iterator[Definition]: + """Return all definitions within the module (including nested). + + This doesn't include imported definitions. + """ + return local_definitions(self.names, self.fullname) + + @property + def name(self) -> str: + return "" if not self._fullname else self._fullname.split(".")[-1] + + @property + def fullname(self) -> str: + return self._fullname + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_mypy_file(self) + + def is_package_init_file(self) -> bool: + return len(self.path) != 0 and os.path.basename(self.path).startswith("__init__.") + + def is_future_flag_set(self, flag: str) -> bool: + return flag in self.future_import_flags + + def is_typeshed_file(self, options: Options) -> bool: + # Cache result since this is called a lot + if self._is_typeshed_file is None: + self._is_typeshed_file = is_typeshed_file(options.abs_custom_typeshed_dir, self.path) + return self._is_typeshed_file + + def serialize(self) -> JsonDict: + return { + ".class": "MypyFile", + "_fullname": self._fullname, + "names": self.names.serialize(self._fullname), + "is_stub": self.is_stub, + "path": self.path, + "is_partial_stub_package": self.is_partial_stub_package, + "future_import_flags": sorted(self.future_import_flags), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> MypyFile: + assert data[".class"] == "MypyFile", data + tree = MypyFile([], []) + tree._fullname = data["_fullname"] + tree.names = SymbolTable.deserialize(data["names"]) + tree.is_stub = data["is_stub"] + tree.path = data["path"] + tree.is_partial_stub_package = data["is_partial_stub_package"] + tree.is_cache_skeleton = True + tree.future_import_flags = set(data["future_import_flags"]) + return tree + + def write(self, data: WriteBuffer) -> None: + write_tag(data, MYPY_FILE) + write_str(data, self._fullname) + self.names.write(data, self._fullname) + write_bool(data, self.is_stub) + write_str(data, self.path) + write_bool(data, self.is_partial_stub_package) + write_str_list(data, sorted(self.future_import_flags)) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> MypyFile: + assert read_tag(data) == MYPY_FILE + tree = MypyFile([], []) + tree._fullname = read_str(data) + tree.names = SymbolTable.read(data) + tree.is_stub = read_bool(data) + tree.path = read_str(data) + tree.is_partial_stub_package = read_bool(data) + tree.future_import_flags = set(read_str_list(data)) + tree.is_cache_skeleton = True + assert read_tag(data) == END_TAG + return tree + + +class ImportBase(Statement): + """Base class for all import statements.""" + + __slots__ = ("is_unreachable", "is_top_level", "is_mypy_only", "assignments") + + is_unreachable: bool # Set by semanal.SemanticAnalyzerPass1 if inside `if False` etc. + is_top_level: bool # Ditto if outside any class or def + is_mypy_only: bool # Ditto if inside `if TYPE_CHECKING` or `if MYPY` + + # If an import replaces existing definitions, we construct dummy assignment + # statements that assign the imported names to the names in the current scope, + # for type checking purposes. Example: + # + # x = 1 + # from m import x <-- add assignment representing "x = m.x" + assignments: list[AssignmentStmt] + + def __init__(self) -> None: + super().__init__() + self.assignments = [] + self.is_unreachable = False + self.is_top_level = False + self.is_mypy_only = False + + +class Import(ImportBase): + """import m [as n]""" + + __slots__ = ("ids",) + + __match_args__ = ("ids",) + + ids: list[tuple[str, str | None]] # (module id, as id) + + def __init__(self, ids: list[tuple[str, str | None]]) -> None: + super().__init__() + self.ids = ids + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_import(self) + + +class ImportFrom(ImportBase): + """from m import x [as y], ...""" + + __slots__ = ("id", "names", "relative") + + __match_args__ = ("id", "names", "relative") + + id: str + relative: int + names: list[tuple[str, str | None]] # Tuples (name, as name) + + def __init__(self, id: str, relative: int, names: list[tuple[str, str | None]]) -> None: + super().__init__() + self.id = id + self.names = names + self.relative = relative + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_import_from(self) + + +class ImportAll(ImportBase): + """from m import *""" + + __slots__ = ("id", "relative") + + __match_args__ = ("id", "relative") + + id: str + relative: int + + def __init__(self, id: str, relative: int) -> None: + super().__init__() + self.id = id + self.relative = relative + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_import_all(self) + + +FUNCBASE_FLAGS: Final = ["is_property", "is_class", "is_static", "is_final"] + + +class FuncBase(Node): + """Abstract base class for function-like nodes. + + N.B: Although this has SymbolNode subclasses (FuncDef, + OverloadedFuncDef), avoid calling isinstance(..., FuncBase) on + something that is typed as SymbolNode. This is to work around + mypy bug #3603, in which mypy doesn't understand multiple + inheritance very well, and will assume that a SymbolNode + cannot be a FuncBase. + + Instead, test against SYMBOL_FUNCBASE_TYPES, which enumerates + SymbolNode subclasses that are also FuncBase subclasses. + """ + + __slots__ = ( + "type", + "unanalyzed_type", + "info", + "is_property", + "is_class", # Uses "@classmethod" (explicit or implicit) + "is_static", # Uses "@staticmethod" (explicit or implicit) + "is_final", # Uses "@final" + "is_explicit_override", # Uses "@override" + "is_type_check_only", # Uses "@type_check_only" + "def_or_infer_vars", + "_fullname", + ) + + def __init__(self) -> None: + super().__init__() + # Type signature. This is usually CallableType or Overloaded, but it can be + # something else for decorated functions. + self.type: mypy.types.ProperType | None = None + # Original, not semantically analyzed type (used for reprocessing) + self.unanalyzed_type: mypy.types.ProperType | None = None + # If method, reference to TypeInfo + self.info = FUNC_NO_INFO + self.is_property = False + self.is_class = False + # Is this a `@staticmethod` (explicit or implicit)? + # Note: use has_self_or_cls_argument to check if there is `self` or `cls` argument + self.is_static = False + self.is_final = False + self.is_explicit_override = False + self.is_type_check_only = False + # Can this function/method define variables or infer variables defined outside? + # In particular, we set this in cases like: + # x = None + # def foo() -> None: + # global x + # x = 1 + # and + # class C: + # x = None + # def foo(self) -> None: + # self.x = 1 + self.def_or_infer_vars = False + # Name with module prefix + self._fullname = "" + + @property + @abstractmethod + def name(self) -> str: + pass + + @property + def fullname(self) -> str: + return self._fullname + + @property + def has_self_or_cls_argument(self) -> bool: + """If used as a method, does it have an argument for method binding (`self`, `cls`)? + + This is true for `__new__` even though `__new__` does not undergo method binding, + because we still usually assume that `cls` corresponds to the enclosing class. + """ + return not self.is_static or self.name == "__new__" + + +OverloadPart: _TypeAlias = Union["FuncDef", "Decorator"] + + +class OverloadedFuncDef(FuncBase, SymbolNode, Statement): + """A logical node representing all the variants of a multi-declaration function. + + A multi-declaration function is often an @overload, but can also be a + @property with a setter and a/or a deleter. + + This node has no explicit representation in the source program. + Overloaded variants must be consecutive in the source file. + """ + + __slots__ = ( + "items", + "unanalyzed_items", + "impl", + "deprecated", + "setter_index", + "_is_trivial_self", + ) + + items: list[OverloadPart] + unanalyzed_items: list[OverloadPart] + impl: OverloadPart | None + deprecated: str | None + setter_index: int | None + + def __init__(self, items: list[OverloadPart]) -> None: + super().__init__() + self.items = items + self.unanalyzed_items = items.copy() + self.impl = None + self.deprecated = None + self.setter_index = None + self._is_trivial_self: bool | None = None + if items: + # TODO: figure out how to reliably set end position (we don't know the impl here). + self.set_line(items[0].line, items[0].column) + + @property + def name(self) -> str: + if self.items: + return self.items[0].name + else: + # This may happen for malformed overload + assert self.impl is not None + return self.impl.name + + @property + def is_trivial_self(self) -> bool: + """Check we can use bind_self() fast path for this overload. + + This will return False if at least one overload: + * Has an explicit self annotation, or Self in signature. + * Has a non-trivial decorator. + """ + if self._is_trivial_self is not None: + return self._is_trivial_self + for i, item in enumerate(self.items): + # Note: bare @property is removed in visit_decorator(). + trivial = 1 if i > 0 or not self.is_property else 0 + if isinstance(item, FuncDef): + if not item.is_trivial_self: + self._is_trivial_self = False + return False + elif len(item.decorators) > trivial or not item.func.is_trivial_self: + self._is_trivial_self = False + return False + self._is_trivial_self = True + return True + + @property + def setter(self) -> Decorator: + # Do some consistency checks first. + first_item = self.items[0] + assert isinstance(first_item, Decorator) + assert first_item.var.is_settable_property + assert self.setter_index is not None + item = self.items[self.setter_index] + assert isinstance(item, Decorator) + return item + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_overloaded_func_def(self) + + def serialize(self) -> JsonDict: + return { + ".class": "OverloadedFuncDef", + "items": [i.serialize() for i in self.items], + "type": None if self.type is None else self.type.serialize(), + "fullname": self._fullname, + "impl": None if self.impl is None else self.impl.serialize(), + "flags": get_flags(self, FUNCBASE_FLAGS), + "deprecated": self.deprecated, + "setter_index": self.setter_index, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> OverloadedFuncDef: + assert data[".class"] == "OverloadedFuncDef" + res = OverloadedFuncDef( + [cast(OverloadPart, SymbolNode.deserialize(d)) for d in data["items"]] + ) + if data.get("impl") is not None: + res.impl = cast(OverloadPart, SymbolNode.deserialize(data["impl"])) + # set line for empty overload items, as not set in __init__ + if len(res.items) > 0: + res.set_line(res.impl.line) + if data.get("type") is not None: + typ = mypy.types.deserialize_type(data["type"]) + assert isinstance(typ, mypy.types.ProperType) + res.type = typ + res._fullname = data["fullname"] + set_flags(res, data["flags"]) + res.deprecated = data["deprecated"] + res.setter_index = data["setter_index"] + # NOTE: res.info will be set in the fixup phase. + return res + + def write(self, data: WriteBuffer) -> None: + write_tag(data, OVERLOADED_FUNC_DEF) + write_tag(data, LIST_GEN) + write_int_bare(data, len(self.items)) + for item in self.items: + item.write(data) + mypy.types.write_type_opt(data, self.type) + write_str(data, self._fullname) + if self.impl is None: + write_tag(data, LITERAL_NONE) + else: + self.impl.write(data) + write_flags(data, [self.is_property, self.is_class, self.is_static, self.is_final]) + write_str_opt(data, self.deprecated) + write_int_opt(data, self.setter_index) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> OverloadedFuncDef: + assert read_tag(data) == LIST_GEN + res = OverloadedFuncDef([read_overload_part(data) for _ in range(read_int_bare(data))]) + typ = mypy.types.read_type_opt(data) + if typ is not None: + assert isinstance(typ, mypy.types.ProperType) + res.type = typ + res._fullname = read_str(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + res.impl = read_overload_part(data, tag) + # set line for empty overload items, as not set in __init__ + if len(res.items) > 0: + res.set_line(res.impl.line) + res.is_property, res.is_class, res.is_static, res.is_final = read_flags(data, num_flags=4) + res.deprecated = read_str_opt(data) + res.setter_index = read_int_opt(data) + # NOTE: res.info will be set in the fixup phase. + assert read_tag(data) == END_TAG + return res + + def is_dynamic(self) -> bool: + return all(item.is_dynamic() for item in self.items) + + +class Argument(Node): + """A single argument in a FuncItem.""" + + __slots__ = ("variable", "type_annotation", "initializer", "kind", "pos_only") + + __match_args__ = ("variable", "type_annotation", "initializer", "kind", "pos_only") + + def __init__( + self, + variable: Var, + type_annotation: mypy.types.Type | None, + initializer: Expression | None, + kind: ArgKind, + pos_only: bool = False, + ) -> None: + super().__init__() + self.variable = variable + self.type_annotation = type_annotation + self.initializer = initializer + self.kind = kind # must be an ARG_* constant + self.pos_only = pos_only + + def set_line( + self, + target: Context | int, + column: int | None = None, + end_line: int | None = None, + end_column: int | None = None, + ) -> None: + super().set_line(target, column, end_line, end_column) + + if self.initializer and self.initializer.line < 0: + self.initializer.set_line(self.line, self.column, self.end_line, self.end_column) + + self.variable.set_line(self.line, self.column, self.end_line, self.end_column) + + +# These specify the kind of a TypeParam +TYPE_VAR_KIND: Final = 0 +PARAM_SPEC_KIND: Final = 1 +TYPE_VAR_TUPLE_KIND: Final = 2 + + +class TypeParam: + __slots__ = ("name", "kind", "upper_bound", "values", "default") + + def __init__( + self, + name: str, + kind: int, + upper_bound: mypy.types.Type | None, + values: list[mypy.types.Type], + default: mypy.types.Type | None, + ) -> None: + self.name = name + self.kind = kind + self.upper_bound = upper_bound + self.values = values + self.default = default + + +FUNCITEM_FLAGS: Final = FUNCBASE_FLAGS + [ + "is_overload", + "is_generator", + "is_coroutine", + "is_async_generator", + "is_awaitable_coroutine", +] + + +class FuncItem(FuncBase): + """Base class for nodes usable as overloaded function items.""" + + __slots__ = ( + "arguments", # Note that can be unset if deserialized (type is a lie!) + "arg_names", # Names of arguments + "arg_kinds", # Kinds of arguments + "min_args", # Minimum number of arguments + "max_pos", # Maximum number of positional arguments, -1 if no explicit + # limit (*args not included) + "type_args", # New-style type parameters (PEP 695) + "body", # Body of the function + "is_overload", # Is this an overload variant of function with more than + # one overload variant? + "is_generator", # Contains a yield statement? + "is_coroutine", # Defined using 'async def' syntax? + "is_async_generator", # Is an async def generator? + "is_awaitable_coroutine", # Decorated with '@{typing,asyncio}.coroutine'? + "expanded", # Variants of function with type variables with values expanded + ) + + __deletable__ = ("arguments", "max_pos", "min_args") + + def __init__( + self, + arguments: list[Argument] | None = None, + body: Block | None = None, + typ: mypy.types.FunctionLike | None = None, + type_args: list[TypeParam] | None = None, + ) -> None: + super().__init__() + self.arguments = arguments or [] + self.arg_names = [None if arg.pos_only else arg.variable.name for arg in self.arguments] + self.arg_kinds: list[ArgKind] = [arg.kind for arg in self.arguments] + self.max_pos: int = self.arg_kinds.count(ARG_POS) + self.arg_kinds.count(ARG_OPT) + self.type_args: list[TypeParam] | None = type_args + self.body: Block = body or Block([]) + self.type = typ + self.unanalyzed_type = typ + self.is_overload: bool = False + self.is_generator: bool = False + self.is_coroutine: bool = False + self.is_async_generator: bool = False + self.is_awaitable_coroutine: bool = False + self.expanded: list[FuncItem] = [] + + self.min_args = 0 + for i in range(len(self.arguments)): + if self.arguments[i] is None and i < self.max_fixed_argc(): + self.min_args = i + 1 + + def max_fixed_argc(self) -> int: + return self.max_pos + + def is_dynamic(self) -> bool: + return self.type is None + + +FUNCDEF_FLAGS: Final = FUNCITEM_FLAGS + [ + "is_decorated", + "is_conditional", + "is_trivial_body", + "is_trivial_self", + "is_mypy_only", +] + +# Abstract status of a function +NOT_ABSTRACT: Final = 0 +# Explicitly abstract (with @abstractmethod or overload without implementation) +IS_ABSTRACT: Final = 1 +# Implicitly abstract: used for functions with trivial bodies defined in Protocols +IMPLICITLY_ABSTRACT: Final = 2 + + +class FuncDef(FuncItem, SymbolNode, Statement): + """Function definition. + + This is a non-lambda function defined using 'def'. + """ + + __slots__ = ( + "_name", + "is_decorated", + "is_conditional", + "abstract_status", + "original_def", + "is_trivial_body", + "is_trivial_self", + "is_mypy_only", + # Present only when a function is decorated with @typing.dataclass_transform or similar + "dataclass_transform_spec", + "docstring", + "deprecated", + "original_first_arg", + ) + + __match_args__ = ("name", "arguments", "type", "body") + + # Note that all __init__ args must have default values + def __init__( + self, + name: str = "", # Function name + arguments: list[Argument] | None = None, + body: Block | None = None, + typ: mypy.types.FunctionLike | None = None, + type_args: list[TypeParam] | None = None, + ) -> None: + super().__init__(arguments, body, typ, type_args) + self._name = name + self.is_decorated = False + self.is_conditional = False # Defined conditionally (within block)? + self.abstract_status = NOT_ABSTRACT + # Is this an abstract method with trivial body? + # Such methods can't be called via super(). + self.is_trivial_body = False + # Original conditional definition + self.original_def: None | FuncDef | Var | Decorator = None + # Definitions that appear in if TYPE_CHECKING are marked with this flag. + self.is_mypy_only = False + self.dataclass_transform_spec: DataclassTransformSpec | None = None + self.docstring: str | None = None + self.deprecated: str | None = None + # This is used to simplify bind_self() logic in trivial cases (which are + # the majority). In cases where self is not annotated and there are no Self + # in the signature we can simply drop the first argument. + self.is_trivial_self = False + # This is needed because for positional-only arguments the name is set to None, + # but we sometimes still want to show it in error messages. + if arguments: + self.original_first_arg: str | None = arguments[0].variable.name + else: + self.original_first_arg = None + + @property + def name(self) -> str: + return self._name + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_func_def(self) + + def serialize(self) -> JsonDict: + # We're deliberating omitting arguments and storing only arg_names and + # arg_kinds for space-saving reasons (arguments is not used in later + # stages of mypy). + # TODO: After a FuncDef is deserialized, the only time we use `arg_names` + # and `arg_kinds` is when `type` is None and we need to infer a type. Can + # we store the inferred type ahead of time? + return { + ".class": "FuncDef", + "name": self._name, + "fullname": self._fullname, + "arg_names": self.arg_names, + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "type": None if self.type is None else self.type.serialize(), + "flags": get_flags(self, FUNCDEF_FLAGS), + "abstract_status": self.abstract_status, + # TODO: Do we need expanded, original_def? + "dataclass_transform_spec": ( + None + if self.dataclass_transform_spec is None + else self.dataclass_transform_spec.serialize() + ), + "deprecated": self.deprecated, + "original_first_arg": self.original_first_arg, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> FuncDef: + assert data[".class"] == "FuncDef" + body = Block([]) + ret = FuncDef( + data["name"], + [], + body, + ( + None + if data["type"] is None + else cast(mypy.types.FunctionLike, mypy.types.deserialize_type(data["type"])) + ), + ) + ret._fullname = data["fullname"] + set_flags(ret, data["flags"]) + # NOTE: ret.info is set in the fixup phase. + ret.arg_names = data["arg_names"] + ret.original_first_arg = data.get("original_first_arg") + ret.arg_kinds = [ARG_KINDS[x] for x in data["arg_kinds"]] + ret.abstract_status = data["abstract_status"] + ret.dataclass_transform_spec = ( + DataclassTransformSpec.deserialize(data["dataclass_transform_spec"]) + if data["dataclass_transform_spec"] is not None + else None + ) + ret.deprecated = data["deprecated"] + # Leave these uninitialized so that future uses will trigger an error + del ret.arguments + del ret.max_pos + del ret.min_args + return ret + + def write(self, data: WriteBuffer) -> None: + write_tag(data, FUNC_DEF) + write_str(data, self._name) + mypy.types.write_type_opt(data, self.type) + write_str(data, self._fullname) + write_flags( + data, + [ + self.is_property, + self.is_class, + self.is_static, + self.is_final, + self.is_overload, + self.is_generator, + self.is_coroutine, + self.is_async_generator, + self.is_awaitable_coroutine, + self.is_decorated, + self.is_conditional, + self.is_trivial_body, + self.is_trivial_self, + self.is_mypy_only, + ], + ) + write_str_opt_list(data, self.arg_names) + write_int_list(data, [int(ak.value) for ak in self.arg_kinds]) + write_int(data, self.abstract_status) + if self.dataclass_transform_spec is None: + write_tag(data, LITERAL_NONE) + else: + self.dataclass_transform_spec.write(data) + write_str_opt(data, self.deprecated) + write_str_opt(data, self.original_first_arg) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> FuncDef: + name = read_str(data) + typ: mypy.types.FunctionLike | None = None + tag = read_tag(data) + if tag != LITERAL_NONE: + typ = mypy.types.read_function_like(data, tag) + ret = FuncDef(name, [], Block([]), typ) + ret._fullname = read_str(data) + ( + ret.is_property, + ret.is_class, + ret.is_static, + ret.is_final, + ret.is_overload, + ret.is_generator, + ret.is_coroutine, + ret.is_async_generator, + ret.is_awaitable_coroutine, + ret.is_decorated, + ret.is_conditional, + ret.is_trivial_body, + ret.is_trivial_self, + ret.is_mypy_only, + ) = read_flags(data, num_flags=14) + # NOTE: ret.info is set in the fixup phase. + ret.arg_names = read_str_opt_list(data) + ret.arg_kinds = [ARG_KINDS[ak] for ak in read_int_list(data)] + ret.abstract_status = read_int(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == DT_SPEC + ret.dataclass_transform_spec = DataclassTransformSpec.read(data) + ret.deprecated = read_str_opt(data) + ret.original_first_arg = read_str_opt(data) + # Leave these uninitialized so that future uses will trigger an error + del ret.arguments + del ret.max_pos + del ret.min_args + assert read_tag(data) == END_TAG + return ret + + +# All types that are both SymbolNodes and FuncBases. See the FuncBase +# docstring for the rationale. +# See https://github.com/python/mypy/pull/13607#issuecomment-1236357236 +# TODO: we want to remove this at some point and just use `FuncBase` ideally. +SYMBOL_FUNCBASE_TYPES: Final = (OverloadedFuncDef, FuncDef) + + +class Decorator(SymbolNode, Statement): + """A decorated function. + + A single Decorator object can include any number of function decorators. + """ + + __slots__ = ("func", "decorators", "original_decorators", "var", "is_overload") + + __match_args__ = ("decorators", "var", "func") + + func: FuncDef # Decorated function + decorators: list[Expression] # Decorators (may be empty) + # Some decorators are removed by semanal, keep the original here. + original_decorators: list[Expression] + # TODO: This is mostly used for the type; consider replacing with a 'type' attribute + var: Var # Represents the decorated function obj + is_overload: bool + + def __init__(self, func: FuncDef, decorators: list[Expression], var: Var) -> None: + super().__init__() + self.func = func + self.decorators = decorators + self.original_decorators = decorators.copy() + self.var = var + self.is_overload = False + + @property + def name(self) -> str: + return self.func.name + + @property + def fullname(self) -> str: + return self.func.fullname + + @property + def is_final(self) -> bool: + return self.func.is_final + + @property + def info(self) -> TypeInfo: + return self.func.info + + @property + def type(self) -> mypy.types.Type | None: + return self.var.type + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_decorator(self) + + def serialize(self) -> JsonDict: + return { + ".class": "Decorator", + "func": self.func.serialize(), + "var": self.var.serialize(), + "is_overload": self.is_overload, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> Decorator: + assert data[".class"] == "Decorator" + dec = Decorator(FuncDef.deserialize(data["func"]), [], Var.deserialize(data["var"])) + dec.is_overload = data["is_overload"] + return dec + + def write(self, data: WriteBuffer) -> None: + write_tag(data, DECORATOR) + self.func.write(data) + self.var.write(data) + write_bool(data, self.is_overload) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Decorator: + assert read_tag(data) == FUNC_DEF + func = FuncDef.read(data) + assert read_tag(data) == VAR + var = Var.read(data) + dec = Decorator(func, [], var) + dec.is_overload = read_bool(data) + assert read_tag(data) == END_TAG + return dec + + def is_dynamic(self) -> bool: + return self.func.is_dynamic() + + +VAR_FLAGS: Final = [ + "is_self", + "is_cls", + "is_initialized_in_class", + "is_staticmethod", + "is_classmethod", + "is_property", + "is_settable_property", + "is_suppressed_import", + "is_classvar", + "is_abstract_var", + "is_final", + "is_index_var", + "final_unset_in_class", + "final_set_in_init", + "explicit_self_type", + "is_ready", + "is_inferred", + "invalid_partial_type", + "from_module_getattr", + "has_explicit_value", + "allow_incompatible_override", +] + + +class Var(SymbolNode): + """A variable. + + It can refer to global/local variable or a data attribute. + """ + + __slots__ = ( + "_name", + "_fullname", + "info", + "type", + "setter_type", + "final_value", + "is_self", + "is_cls", + "is_ready", + "is_inferred", + "is_initialized_in_class", + "is_staticmethod", + "is_classmethod", + "is_property", + "is_settable_property", + "is_classvar", + "is_abstract_var", + "is_final", + "is_index_var", + "final_unset_in_class", + "final_set_in_init", + "is_suppressed_import", + "explicit_self_type", + "from_module_getattr", + "has_explicit_value", + "allow_incompatible_override", + "invalid_partial_type", + "is_argument", + ) + + __match_args__ = ("name", "type", "final_value") + + def __init__(self, name: str, type: mypy.types.Type | None = None) -> None: + super().__init__() + self._name = name # Name without module prefix + # TODO: Should be Optional[str] + self._fullname = "" # Name with module prefix + # TODO: Should be Optional[TypeInfo] + self.info = VAR_NO_INFO + self.type: mypy.types.Type | None = type # Declared or inferred type, or None + # The setter type for settable properties. + self.setter_type: mypy.types.CallableType | None = None + # Is this the first argument to an ordinary method (usually "self")? + self.is_self = False + # Is this the first argument to a classmethod (typically "cls")? + self.is_cls = False + self.is_ready = True # If inferred, is the inferred type available? + self.is_inferred = self.type is None + # Is this variable declared in class body? The name is confusing, but it + # is a very old attribute, and changing will break some plugins. + self.is_initialized_in_class = False + self.is_staticmethod = False + self.is_classmethod = False + self.is_property = False + self.is_settable_property = False + self.is_classvar = False + self.is_abstract_var = False + self.is_index_var = False + # Set to true when this variable refers to a module we were unable to + # parse for some reason (eg a silenced module) + self.is_suppressed_import = False + # Was this "variable" (rather a constant) defined as Final[...]? + self.is_final = False + # If constant value is a simple literal, + # store the literal value (unboxed) for the benefit of + # tools like mypyc. + self.final_value: int | float | complex | bool | str | None = None + # Where the value was set (only for class attributes) + self.final_unset_in_class = False + self.final_set_in_init = False + # This is True for a variable that was declared on self with an explicit type: + # class C: + # def __init__(self) -> None: + # self.x: int + # This case is important because this defines a new Var, even if there is one + # present in a superclass (without explicit type this doesn't create a new Var). + # See SemanticAnalyzer.analyze_member_lvalue() for details. + self.explicit_self_type = False + # If True, this is an implicit Var created due to module-level __getattr__. + self.from_module_getattr = False + # Var can be created with an explicit value `a = 1` or without one `a: int`, + # we need a way to tell which one is which. + self.has_explicit_value = False + # If True, subclasses can override this with an incompatible type. + self.allow_incompatible_override = False + # If True, this means we didn't manage to infer full type and fall back to + # something like list[Any]. We may decide to not use such types as context. + self.invalid_partial_type = False + # Is it a variable symbol for a function argument? + self.is_argument = False + + @property + def name(self) -> str: + return self._name + + @property + def fullname(self) -> str: + return self._fullname + + def __repr__(self) -> str: + name = self.fullname or self.name + return f"" + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_var(self) + + def serialize(self) -> JsonDict: + # TODO: Leave default values out? + # NOTE: Sometimes self.is_ready is False here, but we don't care. + data: JsonDict = { + ".class": "Var", + "name": self._name, + "fullname": self._fullname, + "type": None if self.type is None else self.type.serialize(), + "setter_type": None if self.setter_type is None else self.setter_type.serialize(), + "flags": get_flags(self, VAR_FLAGS), + } + if self.final_value is not None: + data["final_value"] = self.final_value + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> Var: + assert data[".class"] == "Var" + name = data["name"] + type = None if data["type"] is None else mypy.types.deserialize_type(data["type"]) + setter_type = ( + None + if data["setter_type"] is None + else mypy.types.deserialize_type(data["setter_type"]) + ) + v = Var(name, type) + assert ( + setter_type is None + or isinstance(setter_type, mypy.types.ProperType) + and isinstance(setter_type, mypy.types.CallableType) + ) + v.setter_type = setter_type + v.is_ready = False # Override True default set in __init__ + v._fullname = data["fullname"] + set_flags(v, data["flags"]) + v.final_value = data.get("final_value") + return v + + def write(self, data: WriteBuffer) -> None: + write_tag(data, VAR) + write_str(data, self._name) + mypy.types.write_type_opt(data, self.type) + mypy.types.write_type_opt(data, self.setter_type) + write_str(data, self._fullname) + write_flags( + data, + [ + self.is_initialized_in_class, + self.is_staticmethod, + self.is_classmethod, + self.is_property, + self.is_settable_property, + self.is_suppressed_import, + self.is_classvar, + self.is_abstract_var, + self.is_final, + self.is_index_var, + self.final_unset_in_class, + self.final_set_in_init, + self.explicit_self_type, + self.is_ready, + self.is_inferred, + self.invalid_partial_type, + self.from_module_getattr, + self.has_explicit_value, + self.allow_incompatible_override, + ], + ) + write_literal(data, self.final_value) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Var: + name = read_str(data) + typ = mypy.types.read_type_opt(data) + v = Var(name, typ) + setter_type: mypy.types.CallableType | None = None + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == mypy.types.CALLABLE_TYPE + setter_type = mypy.types.CallableType.read(data) + v.setter_type = setter_type + v._fullname = read_str(data) + ( + v.is_initialized_in_class, + v.is_staticmethod, + v.is_classmethod, + v.is_property, + v.is_settable_property, + v.is_suppressed_import, + v.is_classvar, + v.is_abstract_var, + v.is_final, + v.is_index_var, + v.final_unset_in_class, + v.final_set_in_init, + v.explicit_self_type, + v.is_ready, + v.is_inferred, + v.invalid_partial_type, + v.from_module_getattr, + v.has_explicit_value, + v.allow_incompatible_override, + ) = read_flags(data, num_flags=19) + tag = read_tag(data) + if tag == LITERAL_COMPLEX: + v.final_value = complex(read_float_bare(data), read_float_bare(data)) + elif tag != LITERAL_NONE: + v.final_value = read_literal(data, tag) + assert read_tag(data) == END_TAG + return v + + +class ClassDef(Statement): + """Class definition""" + + __slots__ = ( + "name", + "_fullname", + "defs", + "type_args", + "type_vars", + "base_type_exprs", + "removed_base_type_exprs", + "info", + "metaclass", + "decorators", + "keywords", + "analyzed", + "has_incompatible_baseclass", + "docstring", + "removed_statements", + ) + + __match_args__ = ("name", "defs") + + name: str # Name of the class without module prefix + _fullname: str # Fully qualified name of the class + defs: Block + # New-style type parameters (PEP 695), unanalyzed + type_args: list[TypeParam] | None + # Semantically analyzed type parameters (all syntax variants) + type_vars: list[mypy.types.TypeVarLikeType] + # Base class expressions (not semantically analyzed -- can be arbitrary expressions) + base_type_exprs: list[Expression] + # Special base classes like Generic[...] get moved here during semantic analysis + removed_base_type_exprs: list[Expression] + info: TypeInfo # Related TypeInfo + metaclass: Expression | None + decorators: list[Expression] + keywords: dict[str, Expression] + analyzed: Expression | None + has_incompatible_baseclass: bool + # Used by special forms like NamedTuple and TypedDict to store invalid statements + removed_statements: list[Statement] + + def __init__( + self, + name: str, + defs: Block, + type_vars: list[mypy.types.TypeVarLikeType] | None = None, + base_type_exprs: list[Expression] | None = None, + metaclass: Expression | None = None, + keywords: list[tuple[str, Expression]] | None = None, + type_args: list[TypeParam] | None = None, + ) -> None: + super().__init__() + self.name = name + self._fullname = "" + self.defs = defs + self.type_vars = type_vars or [] + self.type_args = type_args + self.base_type_exprs = base_type_exprs or [] + self.removed_base_type_exprs = [] + self.info = CLASSDEF_NO_INFO + self.metaclass = metaclass + self.decorators = [] + self.keywords = dict(keywords) if keywords else {} + self.analyzed = None + self.has_incompatible_baseclass = False + self.docstring: str | None = None + self.removed_statements = [] + + @property + def fullname(self) -> str: + return self._fullname + + @fullname.setter + def fullname(self, v: str) -> None: + self._fullname = v + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_class_def(self) + + def is_generic(self) -> bool: + return self.info.is_generic() + + def serialize(self) -> JsonDict: + # Not serialized: defs, base_type_exprs, metaclass, decorators, + # analyzed (for named tuples etc.) + return { + ".class": "ClassDef", + "name": self.name, + "fullname": self.fullname, + "type_vars": [v.serialize() for v in self.type_vars], + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ClassDef: + assert data[".class"] == "ClassDef" + res = ClassDef( + data["name"], + Block([]), + # https://github.com/python/mypy/issues/12257 + [ + cast(mypy.types.TypeVarLikeType, mypy.types.deserialize_type(v)) + for v in data["type_vars"] + ], + ) + res.fullname = data["fullname"] + return res + + def write(self, data: WriteBuffer) -> None: + write_tag(data, CLASS_DEF) + write_str(data, self.name) + mypy.types.write_type_list(data, self.type_vars) + write_str(data, self.fullname) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ClassDef: + res = ClassDef(read_str(data), Block([]), mypy.types.read_type_var_likes(data)) + res.fullname = read_str(data) + assert read_tag(data) == END_TAG + return res + + +class GlobalDecl(Statement): + """Declaration global x, y, ...""" + + __slots__ = ("names",) + + __match_args__ = ("names",) + + names: list[str] + + def __init__(self, names: list[str]) -> None: + super().__init__() + self.names = names + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_global_decl(self) + + +class NonlocalDecl(Statement): + """Declaration nonlocal x, y, ...""" + + __slots__ = ("names",) + + __match_args__ = ("names",) + + names: list[str] + + def __init__(self, names: list[str]) -> None: + super().__init__() + self.names = names + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_nonlocal_decl(self) + + +class Block(Statement): + __slots__ = ("body", "is_unreachable") + + __match_args__ = ("body", "is_unreachable") + + def __init__(self, body: list[Statement], *, is_unreachable: bool = False) -> None: + super().__init__() + self.body = body + # True if we can determine that this block is not executed during semantic + # analysis. For example, this applies to blocks that are protected by + # something like "if PY3:" when using Python 2. However, some code is + # only considered unreachable during type checking and this is not true + # in those cases. + self.is_unreachable = is_unreachable + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_block(self) + + +# Statements + + +class ExpressionStmt(Statement): + """An expression as a statement, such as print(s).""" + + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_expression_stmt(self) + + +class AssignmentStmt(Statement): + """Assignment statement. + + The same node class is used for single assignment, multiple assignment + (e.g. x, y = z) and chained assignment (e.g. x = y = z), assignments + that define new names, and assignments with explicit types ("# type: t" + or "x: t [= ...]"). + + An lvalue can be NameExpr, TupleExpr, ListExpr, MemberExpr, or IndexExpr. + """ + + __slots__ = ( + "lvalues", + "rvalue", + "type", + "unanalyzed_type", + "new_syntax", + "is_alias_def", + "is_final_def", + "invalid_recursive_alias", + ) + + __match_args__ = ("lvalues", "rvalues", "type") + + lvalues: list[Lvalue] + # This is a TempNode if and only if no rvalue (x: t). + rvalue: Expression + # Declared type in a comment, may be None. + type: mypy.types.Type | None + # Original, not semantically analyzed type in annotation (used for reprocessing) + unanalyzed_type: mypy.types.Type | None + # This indicates usage of PEP 526 type annotation syntax in assignment. + new_syntax: bool + # Does this assignment define a type alias? + is_alias_def: bool + # Is this a final definition? + # Final attributes can't be re-assigned once set, and can't be overridden + # in a subclass. This flag is not set if an attempted declaration was found to + # be invalid during semantic analysis. It is still set to `True` if + # a final declaration overrides another final declaration (this is checked + # during type checking when MROs are known). + is_final_def: bool + # Stop further processing of this assignment, to prevent flipping back and forth + # during semantic analysis passes. + invalid_recursive_alias: bool + + def __init__( + self, + lvalues: list[Lvalue], + rvalue: Expression, + type: mypy.types.Type | None = None, + new_syntax: bool = False, + ) -> None: + super().__init__() + self.lvalues = lvalues + self.rvalue = rvalue + self.type = type + self.unanalyzed_type = type + self.new_syntax = new_syntax + self.is_alias_def = False + self.is_final_def = False + self.invalid_recursive_alias = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_assignment_stmt(self) + + +class OperatorAssignmentStmt(Statement): + """Operator assignment statement such as x += 1""" + + __slots__ = ("op", "lvalue", "rvalue") + + __match_args__ = ("lvalue", "op", "rvalue") + + op: str # TODO: Enum? + lvalue: Lvalue + rvalue: Expression + + def __init__(self, op: str, lvalue: Lvalue, rvalue: Expression) -> None: + super().__init__() + self.op = op + self.lvalue = lvalue + self.rvalue = rvalue + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_operator_assignment_stmt(self) + + +class WhileStmt(Statement): + __slots__ = ("expr", "body", "else_body") + + __match_args__ = ("expr", "body", "else_body") + + expr: Expression + body: Block + else_body: Block | None + + def __init__(self, expr: Expression, body: Block, else_body: Block | None) -> None: + super().__init__() + self.expr = expr + self.body = body + self.else_body = else_body + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_while_stmt(self) + + +class ForStmt(Statement): + __slots__ = ( + "index", + "index_type", + "unanalyzed_index_type", + "inferred_item_type", + "inferred_iterator_type", + "expr", + "body", + "else_body", + "is_async", + ) + + __match_args__ = ("index", "index_type", "expr", "body", "else_body") + + # Index variables + index: Lvalue + # Type given by type comments for index, can be None + index_type: mypy.types.Type | None + # Original, not semantically analyzed type in annotation (used for reprocessing) + unanalyzed_index_type: mypy.types.Type | None + # Inferred iterable item type + inferred_item_type: mypy.types.Type | None + # Inferred iterator type + inferred_iterator_type: mypy.types.Type | None + # Expression to iterate + expr: Expression + body: Block + else_body: Block | None + is_async: bool # True if `async for ...` (PEP 492, Python 3.5) + + def __init__( + self, + index: Lvalue, + expr: Expression, + body: Block, + else_body: Block | None, + index_type: mypy.types.Type | None = None, + ) -> None: + super().__init__() + self.index = index + self.index_type = index_type + self.unanalyzed_index_type = index_type + self.inferred_item_type = None + self.inferred_iterator_type = None + self.expr = expr + self.body = body + self.else_body = else_body + self.is_async = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_for_stmt(self) + + +class ReturnStmt(Statement): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression | None + + def __init__(self, expr: Expression | None) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_return_stmt(self) + + +class AssertStmt(Statement): + __slots__ = ("expr", "msg") + + __match_args__ = ("expr", "msg") + + expr: Expression + msg: Expression | None + + def __init__(self, expr: Expression, msg: Expression | None = None) -> None: + super().__init__() + self.expr = expr + self.msg = msg + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_assert_stmt(self) + + +class DelStmt(Statement): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Lvalue + + def __init__(self, expr: Lvalue) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_del_stmt(self) + + +class BreakStmt(Statement): + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_break_stmt(self) + + +class ContinueStmt(Statement): + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_continue_stmt(self) + + +class PassStmt(Statement): + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_pass_stmt(self) + + +class IfStmt(Statement): + __slots__ = ("expr", "body", "else_body", "unreachable_else") + + __match_args__ = ("expr", "body", "else_body", "unreachable_else") + + expr: list[Expression] + body: list[Block] + else_body: Block | None + # (If there is actually no else statement, semantic analysis may nevertheless create an + # empty else block and mark it permanently as unreachable to tell that the control flow + # must always go through the if block.) + unreachable_else: bool + # (Type checking may modify this flag repeatedly to indicate whether an actually available + # or unavailable else block is unreachable, considering the current type information.) + + def __init__(self, expr: list[Expression], body: list[Block], else_body: Block | None) -> None: + super().__init__() + self.expr = expr + self.body = body + self.else_body = else_body + self.unreachable_else = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_if_stmt(self) + + +class RaiseStmt(Statement): + __slots__ = ("expr", "from_expr") + + __match_args__ = ("expr", "from_expr") + + # Plain 'raise' is a valid statement. + expr: Expression | None + from_expr: Expression | None + + def __init__(self, expr: Expression | None, from_expr: Expression | None) -> None: + super().__init__() + self.expr = expr + self.from_expr = from_expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_raise_stmt(self) + + +class TryStmt(Statement): + __slots__ = ("body", "types", "vars", "handlers", "else_body", "finally_body", "is_star") + + __match_args__ = ("body", "types", "vars", "handlers", "else_body", "finally_body", "is_star") + + body: Block # Try body + # Plain 'except:' also possible + types: list[Expression | None] # Except type expressions + vars: list[NameExpr | None] # Except variable names + handlers: list[Block] # Except bodies + else_body: Block | None + finally_body: Block | None + # Whether this is try ... except* (added in Python 3.11) + is_star: bool + + def __init__( + self, + body: Block, + vars: list[NameExpr | None], + types: list[Expression | None], + handlers: list[Block], + else_body: Block | None, + finally_body: Block | None, + ) -> None: + super().__init__() + self.body = body + self.vars = vars + self.types = types + self.handlers = handlers + self.else_body = else_body + self.finally_body = finally_body + self.is_star = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_try_stmt(self) + + +class WithStmt(Statement): + __slots__ = ("expr", "target", "unanalyzed_type", "analyzed_types", "body", "is_async") + + __match_args__ = ("expr", "target", "body") + + expr: list[Expression] + target: list[Lvalue | None] + # Type given by type comments for target, can be None + unanalyzed_type: mypy.types.Type | None + # Semantically analyzed types from type comment (TypeList type expanded) + analyzed_types: list[mypy.types.Type] + body: Block + is_async: bool # True if `async with ...` (PEP 492, Python 3.5) + + def __init__( + self, + expr: list[Expression], + target: list[Lvalue | None], + body: Block, + target_type: mypy.types.Type | None = None, + ) -> None: + super().__init__() + self.expr = expr + self.target = target + self.unanalyzed_type = target_type + self.analyzed_types = [] + self.body = body + self.is_async = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_with_stmt(self) + + +class MatchStmt(Statement): + __slots__ = ("subject", "subject_dummy", "patterns", "guards", "bodies") + + __match_args__ = ("subject", "patterns", "guards", "bodies") + + subject: Expression + subject_dummy: NameExpr | None + patterns: list[Pattern] + guards: list[Expression | None] + bodies: list[Block] + + def __init__( + self, + subject: Expression, + patterns: list[Pattern], + guards: list[Expression | None], + bodies: list[Block], + ) -> None: + super().__init__() + assert len(patterns) == len(guards) == len(bodies) + self.subject = subject + self.subject_dummy = None + self.patterns = patterns + self.guards = guards + self.bodies = bodies + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_match_stmt(self) + + +class TypeAliasStmt(Statement): + __slots__ = ("name", "type_args", "value", "invalid_recursive_alias", "alias_node") + + __match_args__ = ("name", "type_args", "value") + + name: NameExpr + type_args: list[TypeParam] + value: LambdaExpr # Return value will get translated into a type + invalid_recursive_alias: bool + alias_node: TypeAlias | None + + def __init__(self, name: NameExpr, type_args: list[TypeParam], value: LambdaExpr) -> None: + super().__init__() + self.name = name + self.type_args = type_args + self.value = value + self.invalid_recursive_alias = False + self.alias_node = None + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_type_alias_stmt(self) + + +# Expressions + + +class IntExpr(Expression): + """Integer literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + value: int # 0 by default + + def __init__(self, value: int) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_int_expr(self) + + +# How mypy uses StrExpr and BytesExpr: +# +# b'x' -> BytesExpr +# 'x', u'x' -> StrExpr + + +class StrExpr(Expression): + """String literal""" + + __slots__ = ("value", "as_type") + + __match_args__ = ("value",) + + value: str # '' by default + # If this value expression can also be parsed as a valid type expression, + # represents the type denoted by the type expression. + # None means "is not a type expression". + as_type: NotParsed | mypy.types.Type | None + + def __init__(self, value: str) -> None: + super().__init__() + self.value = value + self.as_type = NotParsed.VALUE + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_str_expr(self) + + +def is_StrExpr_list(seq: list[Expression]) -> TypeGuard[list[StrExpr]]: # noqa: N802 + return all(isinstance(item, StrExpr) for item in seq) + + +class BytesExpr(Expression): + """Bytes literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + # Note: we deliberately do NOT use bytes here because it ends up + # unnecessarily complicating a lot of the result logic. For example, + # we'd have to worry about converting the bytes into a format we can + # easily serialize/deserialize to and from JSON, would have to worry + # about turning the bytes into a human-readable representation in + # error messages... + # + # It's more convenient to just store the human-readable representation + # from the very start. + value: str + + def __init__(self, value: str) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_bytes_expr(self) + + +class FloatExpr(Expression): + """Float literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + value: float # 0.0 by default + + def __init__(self, value: float) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_float_expr(self) + + +class ComplexExpr(Expression): + """Complex literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + value: complex + + def __init__(self, value: complex) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_complex_expr(self) + + +class EllipsisExpr(Expression): + """Ellipsis (...)""" + + __slots__ = () + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_ellipsis(self) + + +class StarExpr(Expression): + """Star expression""" + + __slots__ = ("expr", "valid") + + __match_args__ = ("expr", "valid") + + expr: Expression + valid: bool + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + # Whether this starred expression is used in a tuple/list and as lvalue + self.valid = False + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_star_expr(self) + + +class RefExpr(Expression): + """Abstract base class for name-like constructs""" + + __slots__ = ( + "kind", + "node", + "_fullname", + "is_new_def", + "is_inferred_def", + "is_alias_rvalue", + "type_guard", + "type_is", + ) + + def __init__(self) -> None: + super().__init__() + # LDEF/GDEF/MDEF/... (None if not available) + self.kind: int | None = None + # Var, FuncDef or TypeInfo that describes this + self.node: SymbolNode | None = None + # Fully qualified name (or name if not global) + self._fullname = "" + # Does this define a new name? + self.is_new_def = False + # Does this define a new name with inferred type? + # + # For members, after semantic analysis, this does not take base + # classes into consideration at all; the type checker deals with these. + self.is_inferred_def = False + # Is this expression appears as an rvalue of a valid type alias definition? + self.is_alias_rvalue = False + # Cache type guard from callable_type.type_guard + self.type_guard: mypy.types.Type | None = None + # And same for TypeIs + self.type_is: mypy.types.Type | None = None + + @property + def fullname(self) -> str: + return self._fullname + + @fullname.setter + def fullname(self, v: str) -> None: + self._fullname = v + + +class NameExpr(RefExpr): + """Name expression + + This refers to a local name, global name or a module. + """ + + __slots__ = ("name", "is_special_form") + + __match_args__ = ("name", "node") + + def __init__(self, name: str) -> None: + super().__init__() + self.name = name # Name referred to + # Is this a l.h.s. of a special form assignment like typed dict or type variable? + self.is_special_form = False + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_name_expr(self) + + def serialize(self) -> JsonDict: + assert False, f"Serializing NameExpr: {self}" + + +class MemberExpr(RefExpr): + """Member access expression x.y""" + + __slots__ = ("expr", "name", "def_var") + + __match_args__ = ("expr", "name", "node") + + def __init__(self, expr: Expression, name: str) -> None: + super().__init__() + self.expr = expr + self.name = name + # The variable node related to a definition through 'self.x = '. + # The nodes of other kinds of member expressions are resolved during type checking. + self.def_var: Var | None = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_member_expr(self) + + +# Kinds of arguments +@unique +class ArgKind(Enum): + # Positional argument + ARG_POS = 0 + # Positional, optional argument (functions only, not calls) + ARG_OPT = 1 + # *arg argument + ARG_STAR = 2 + # Keyword argument x=y in call, or keyword-only function arg + ARG_NAMED = 3 + # **arg argument + ARG_STAR2 = 4 + # In an argument list, keyword-only and also optional + ARG_NAMED_OPT = 5 + + def is_positional(self, star: bool = False) -> bool: + return self == ARG_POS or self == ARG_OPT or (star and self == ARG_STAR) + + def is_named(self, star: bool = False) -> bool: + return self == ARG_NAMED or self == ARG_NAMED_OPT or (star and self == ARG_STAR2) + + def is_required(self) -> bool: + return self == ARG_POS or self == ARG_NAMED + + def is_optional(self) -> bool: + return self == ARG_OPT or self == ARG_NAMED_OPT + + def is_star(self) -> bool: + return self == ARG_STAR or self == ARG_STAR2 + + +ARG_POS: Final = ArgKind.ARG_POS +ARG_OPT: Final = ArgKind.ARG_OPT +ARG_STAR: Final = ArgKind.ARG_STAR +ARG_NAMED: Final = ArgKind.ARG_NAMED +ARG_STAR2: Final = ArgKind.ARG_STAR2 +ARG_NAMED_OPT: Final = ArgKind.ARG_NAMED_OPT + +ARG_KINDS: Final = (ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_STAR2, ARG_NAMED_OPT) + + +class CallExpr(Expression): + """Call expression. + + This can also represent several special forms that are syntactically calls + such as cast(...) and None # type: .... + """ + + __slots__ = ("callee", "args", "arg_kinds", "arg_names", "analyzed") + + __match_args__ = ("callee", "args", "arg_kinds", "arg_names") + + def __init__( + self, + callee: Expression, + args: list[Expression], + arg_kinds: list[ArgKind], + arg_names: list[str | None], + analyzed: Expression | None = None, + ) -> None: + super().__init__() + if not arg_names: + arg_names = [None] * len(args) + + self.callee = callee + self.args = args + self.arg_kinds = arg_kinds # ARG_ constants + # Each name can be None if not a keyword argument. + self.arg_names: list[str | None] = arg_names + # If not None, the node that represents the meaning of the CallExpr. For + # cast(...) this is a CastExpr. + self.analyzed = analyzed + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_call_expr(self) + + +class YieldFromExpr(Expression): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_yield_from_expr(self) + + +class YieldExpr(Expression): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression | None + + def __init__(self, expr: Expression | None) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_yield_expr(self) + + +class IndexExpr(Expression): + """Index expression x[y]. + + Also wraps type application such as List[int] as a special form. + """ + + __slots__ = ("base", "index", "method_type", "analyzed", "as_type") + + __match_args__ = ("base", "index") + + base: Expression + index: Expression + # Inferred __getitem__ method type + method_type: mypy.types.Type | None + # If not None, this is actually semantically a type application + # Class[type, ...] or a type alias initializer. + analyzed: TypeApplication | TypeAliasExpr | None + # If this value expression can also be parsed as a valid type expression, + # represents the type denoted by the type expression. + # None means "is not a type expression". + as_type: NotParsed | mypy.types.Type | None + + def __init__(self, base: Expression, index: Expression) -> None: + super().__init__() + self.base = base + self.index = index + self.method_type = None + self.analyzed = None + self.as_type = NotParsed.VALUE + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_index_expr(self) + + +class UnaryExpr(Expression): + """Unary operation""" + + __slots__ = ("op", "expr", "method_type") + + __match_args__ = ("op", "expr") + + op: str # TODO: Enum? + expr: Expression + # Inferred operator method type + method_type: mypy.types.Type | None + + def __init__(self, op: str, expr: Expression) -> None: + super().__init__() + self.op = op + self.expr = expr + self.method_type = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_unary_expr(self) + + +class AssignmentExpr(Expression): + """Assignment expressions in Python 3.8+, like "a := 2".""" + + __slots__ = ("target", "value") + + __match_args__ = ("target", "value") + + def __init__(self, target: NameExpr, value: Expression) -> None: + super().__init__() + self.target = target + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_assignment_expr(self) + + +class OpExpr(Expression): + """Binary operation. + + The dot (.), [] and comparison operators have more specific nodes. + """ + + __slots__ = ( + "op", + "left", + "right", + "method_type", + "right_always", + "right_unreachable", + "analyzed", + "as_type", + ) + + __match_args__ = ("left", "op", "right") + + op: str # TODO: Enum? + left: Expression + right: Expression + # Inferred type for the operator method type (when relevant). + method_type: mypy.types.Type | None + # Per static analysis only: Is the right side going to be evaluated every time? + right_always: bool + # Per static analysis only: Is the right side unreachable? + right_unreachable: bool + # Used for expressions that represent a type "X | Y" in some contexts + analyzed: TypeAliasExpr | None + # If this value expression can also be parsed as a valid type expression, + # represents the type denoted by the type expression. + # None means "is not a type expression". + as_type: NotParsed | mypy.types.Type | None + + def __init__( + self, op: str, left: Expression, right: Expression, analyzed: TypeAliasExpr | None = None + ) -> None: + super().__init__() + self.op = op + self.left = left + self.right = right + self.method_type = None + self.right_always = False + self.right_unreachable = False + self.analyzed = analyzed + self.as_type = NotParsed.VALUE + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_op_expr(self) + + +# Expression subtypes that could represent the root of a valid type expression. +# +# May have an "as_type" attribute to hold the type for a type expression parsed +# during the SemanticAnalyzer pass. +MaybeTypeExpression = (IndexExpr, MemberExpr, NameExpr, OpExpr, StrExpr) + + +class ComparisonExpr(Expression): + """Comparison expression (e.g. a < b > c < d).""" + + __slots__ = ("operators", "operands", "method_types") + + __match_args__ = ("operands", "operators") + + operators: list[str] + operands: list[Expression] + # Inferred type for the operator methods (when relevant; None for 'is'). + method_types: list[mypy.types.Type | None] + + def __init__(self, operators: list[str], operands: list[Expression]) -> None: + super().__init__() + self.operators = operators + self.operands = operands + self.method_types = [] + + def pairwise(self) -> Iterator[tuple[str, Expression, Expression]]: + """If this comparison expr is "a < b is c == d", yields the sequence + ("<", a, b), ("is", b, c), ("==", c, d) + """ + for i, operator in enumerate(self.operators): + yield operator, self.operands[i], self.operands[i + 1] + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_comparison_expr(self) + + +class SliceExpr(Expression): + """Slice expression (e.g. 'x:y', 'x:', '::2' or ':'). + + This is only valid as index in index expressions. + """ + + __slots__ = ("begin_index", "end_index", "stride") + + __match_args__ = ("begin_index", "end_index", "stride") + + begin_index: Expression | None + end_index: Expression | None + stride: Expression | None + + def __init__( + self, + begin_index: Expression | None, + end_index: Expression | None, + stride: Expression | None, + ) -> None: + super().__init__() + self.begin_index = begin_index + self.end_index = end_index + self.stride = stride + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_slice_expr(self) + + +class CastExpr(Expression): + """Cast expression cast(type, expr).""" + + __slots__ = ("expr", "type") + + __match_args__ = ("expr", "type") + + expr: Expression + type: mypy.types.Type + + def __init__(self, expr: Expression, typ: mypy.types.Type) -> None: + super().__init__() + self.expr = expr + self.type = typ + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_cast_expr(self) + + +class TypeFormExpr(Expression): + """TypeForm(type) expression.""" + + __slots__ = ("type",) + + __match_args__ = ("type",) + + type: mypy.types.Type + + def __init__(self, typ: mypy.types.Type) -> None: + super().__init__() + self.type = typ + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_form_expr(self) + + +class AssertTypeExpr(Expression): + """Represents a typing.assert_type(expr, type) call.""" + + __slots__ = ("expr", "type") + + __match_args__ = ("expr", "type") + + expr: Expression + type: mypy.types.Type + + def __init__(self, expr: Expression, typ: mypy.types.Type) -> None: + super().__init__() + self.expr = expr + self.type = typ + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_assert_type_expr(self) + + +class RevealExpr(Expression): + """Reveal type expression reveal_type(expr) or reveal_locals() expression.""" + + __slots__ = ("expr", "kind", "local_nodes", "is_imported") + + __match_args__ = ("expr", "kind", "local_nodes", "is_imported") + + expr: Expression | None + kind: int + local_nodes: list[Var] | None + + def __init__( + self, + kind: int, + expr: Expression | None = None, + local_nodes: list[Var] | None = None, + is_imported: bool = False, + ) -> None: + super().__init__() + self.expr = expr + self.kind = kind + self.local_nodes = local_nodes + self.is_imported = is_imported + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_reveal_expr(self) + + +class SuperExpr(Expression): + """Expression super().name""" + + __slots__ = ("name", "info", "call") + + __match_args__ = ("name", "call", "info") + + name: str + info: TypeInfo | None # Type that contains this super expression + call: CallExpr # The expression super(...) + + def __init__(self, name: str, call: CallExpr) -> None: + super().__init__() + self.name = name + self.call = call + self.info = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_super_expr(self) + + +class LambdaExpr(FuncItem, Expression): + """Lambda expression""" + + __match_args__ = ("arguments", "arg_names", "arg_kinds", "body") + + @property + def name(self) -> str: + return LAMBDA_NAME + + def expr(self) -> Expression: + """Return the expression (the body) of the lambda.""" + ret = self.body.body[-1] + assert isinstance(ret, ReturnStmt) + expr = ret.expr + assert expr is not None # lambda can't have empty body + return expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_lambda_expr(self) + + def is_dynamic(self) -> bool: + return False + + +class ListExpr(Expression): + """List literal expression [...].""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[Expression] + + def __init__(self, items: list[Expression]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_list_expr(self) + + +class DictExpr(Expression): + """Dictionary literal expression {key: value, ...}.""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[tuple[Expression | None, Expression]] + + def __init__(self, items: list[tuple[Expression | None, Expression]]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_dict_expr(self) + + +class TemplateStrExpr(Expression): + """Template string expression t'...'.""" + + __slots__ = ("items",) + __match_args__ = ("items",) + + # Each item is either: + # - a StrExpr (literal string segment), or + # - a tuple (value_expr, source_text, conversion, format_spec_expr) + # where conversion is str | None ("r", "s", "a", or None) + # and format_spec_expr is Expression | None + items: list[Expression | tuple[Expression, str, str | None, Expression | None]] + + def __init__( + self, items: list[Expression | tuple[Expression, str, str | None, Expression | None]] + ) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_template_str_expr(self) + + +class TupleExpr(Expression): + """Tuple literal expression (..., ...) + + Also lvalue sequences (..., ...) and [..., ...]""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[Expression] + + def __init__(self, items: list[Expression]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_tuple_expr(self) + + +class SetExpr(Expression): + """Set literal expression {value, ...}.""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[Expression] + + def __init__(self, items: list[Expression]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_set_expr(self) + + +class GeneratorExpr(Expression): + """Generator expression ... for ... in ... [ for ... in ... ] [ if ... ].""" + + __slots__ = ("left_expr", "sequences", "condlists", "is_async", "indices") + + __match_args__ = ("left_expr", "indices", "sequences", "condlists") + + left_expr: Expression + sequences: list[Expression] + condlists: list[list[Expression]] + is_async: list[bool] + indices: list[Lvalue] + + def __init__( + self, + left_expr: Expression, + indices: list[Lvalue], + sequences: list[Expression], + condlists: list[list[Expression]], + is_async: list[bool], + ) -> None: + super().__init__() + self.left_expr = left_expr + self.sequences = sequences + self.condlists = condlists + self.indices = indices + self.is_async = is_async + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_generator_expr(self) + + +class ListComprehension(Expression): + """List comprehension (e.g. [x + 1 for x in a])""" + + __slots__ = ("generator",) + + __match_args__ = ("generator",) + + generator: GeneratorExpr + + def __init__(self, generator: GeneratorExpr) -> None: + super().__init__() + self.generator = generator + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_list_comprehension(self) + + +class SetComprehension(Expression): + """Set comprehension (e.g. {x + 1 for x in a})""" + + __slots__ = ("generator",) + + __match_args__ = ("generator",) + + generator: GeneratorExpr + + def __init__(self, generator: GeneratorExpr) -> None: + super().__init__() + self.generator = generator + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_set_comprehension(self) + + +class DictionaryComprehension(Expression): + """Dictionary comprehension (e.g. {k: v for k, v in a}""" + + __slots__ = ("key", "value", "sequences", "condlists", "is_async", "indices") + + __match_args__ = ("key", "value", "indices", "sequences", "condlists") + + key: Expression + value: Expression + sequences: list[Expression] + condlists: list[list[Expression]] + is_async: list[bool] + indices: list[Lvalue] + + def __init__( + self, + key: Expression, + value: Expression, + indices: list[Lvalue], + sequences: list[Expression], + condlists: list[list[Expression]], + is_async: list[bool], + ) -> None: + super().__init__() + self.key = key + self.value = value + self.sequences = sequences + self.condlists = condlists + self.indices = indices + self.is_async = is_async + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_dictionary_comprehension(self) + + +class ConditionalExpr(Expression): + """Conditional expression (e.g. x if y else z)""" + + __slots__ = ("cond", "if_expr", "else_expr") + + __match_args__ = ("if_expr", "cond", "else_expr") + + cond: Expression + if_expr: Expression + else_expr: Expression + + def __init__(self, cond: Expression, if_expr: Expression, else_expr: Expression) -> None: + super().__init__() + self.cond = cond + self.if_expr = if_expr + self.else_expr = else_expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_conditional_expr(self) + + +class TypeApplication(Expression): + """Type application expr[type, ...]""" + + __slots__ = ("expr", "types") + + __match_args__ = ("expr", "types") + + expr: Expression + types: list[mypy.types.Type] + + def __init__(self, expr: Expression, types: list[mypy.types.Type]) -> None: + super().__init__() + self.expr = expr + self.types = types + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_application(self) + + +# Variance of a type variable. For example, T in the definition of +# List[T] is invariant, so List[int] is not a subtype of List[object], +# and also List[object] is not a subtype of List[int]. +# +# The T in Iterable[T] is covariant, so Iterable[int] is a subtype of +# Iterable[object], but not vice versa. +# +# If T is contravariant in Foo[T], Foo[object] is a subtype of +# Foo[int], but not vice versa. +INVARIANT: Final = 0 +COVARIANT: Final = 1 +CONTRAVARIANT: Final = 2 +VARIANCE_NOT_READY: Final = 3 # Variance hasn't been inferred (using Python 3.12 syntax) + + +class TypeVarLikeExpr(SymbolNode, Expression): + """Base class for TypeVarExpr, ParamSpecExpr and TypeVarTupleExpr. + + Note that they are constructed by the semantic analyzer. + """ + + __slots__ = ("_name", "_fullname", "upper_bound", "default", "variance", "is_new_style") + + _name: str + _fullname: str + # Upper bound: only subtypes of upper_bound are valid as values. By default + # this is 'object', meaning no restriction. + upper_bound: mypy.types.Type + # Default: used to resolve the TypeVar if the default is not explicitly given. + # By default this is 'AnyType(TypeOfAny.from_omitted_generics)'. See PEP 696. + default: mypy.types.Type + # Variance of the type variable. Invariant is the default. + # TypeVar(..., covariant=True) defines a covariant type variable. + # TypeVar(..., contravariant=True) defines a contravariant type + # variable. + variance: int + + def __init__( + self, + name: str, + fullname: str, + upper_bound: mypy.types.Type, + default: mypy.types.Type, + variance: int = INVARIANT, + is_new_style: bool = False, + line: int = -1, + ) -> None: + super().__init__(line=line) + self._name = name + self._fullname = fullname + self.upper_bound = upper_bound + self.default = default + self.variance = variance + self.is_new_style = is_new_style + + @property + def name(self) -> str: + return self._name + + @property + def fullname(self) -> str: + return self._fullname + + +# All types that are both SymbolNodes and Expressions. +# Use when common children of them are needed. +SYMBOL_NODE_EXPRESSION_TYPES: Final = (TypeVarLikeExpr,) + + +class TypeVarExpr(TypeVarLikeExpr): + """Type variable expression TypeVar(...). + + This is also used to represent type variables in symbol tables. + + A type variable is not valid as a type unless bound in a TypeVarLikeScope. + That happens within: + + 1. a generic class that uses the type variable as a type argument or + 2. a generic function that refers to the type variable in its signature. + """ + + __slots__ = ("values",) + + __match_args__ = ("name", "values", "upper_bound", "default") + + # Value restriction: only types in the list are valid as values. If the + # list is empty, there is no restriction. + values: list[mypy.types.Type] + + def __init__( + self, + name: str, + fullname: str, + values: list[mypy.types.Type], + upper_bound: mypy.types.Type, + default: mypy.types.Type, + variance: int = INVARIANT, + is_new_style: bool = False, + line: int = -1, + ) -> None: + super().__init__(name, fullname, upper_bound, default, variance, is_new_style, line=line) + self.values = values + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_var_expr(self) + + def serialize(self) -> JsonDict: + return { + ".class": "TypeVarExpr", + "name": self._name, + "fullname": self._fullname, + "values": [t.serialize() for t in self.values], + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarExpr: + assert data[".class"] == "TypeVarExpr" + return TypeVarExpr( + data["name"], + data["fullname"], + [mypy.types.deserialize_type(v) for v in data["values"]], + mypy.types.deserialize_type(data["upper_bound"]), + mypy.types.deserialize_type(data["default"]), + data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_EXPR) + write_str(data, self._name) + write_str(data, self._fullname) + mypy.types.write_type_list(data, self.values) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarExpr: + ret = TypeVarExpr( + read_str(data), + read_str(data), + mypy.types.read_type_list(data), + mypy.types.read_type(data), + mypy.types.read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class ParamSpecExpr(TypeVarLikeExpr): + __slots__ = () + + __match_args__ = ("name", "upper_bound", "default") + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_paramspec_expr(self) + + def serialize(self) -> JsonDict: + return { + ".class": "ParamSpecExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ParamSpecExpr: + assert data[".class"] == "ParamSpecExpr" + return ParamSpecExpr( + data["name"], + data["fullname"], + mypy.types.deserialize_type(data["upper_bound"]), + mypy.types.deserialize_type(data["default"]), + data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, PARAM_SPEC_EXPR) + write_str(data, self._name) + write_str(data, self._fullname) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ParamSpecExpr: + ret = ParamSpecExpr( + read_str(data), + read_str(data), + mypy.types.read_type(data), + mypy.types.read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class TypeVarTupleExpr(TypeVarLikeExpr): + """Type variable tuple expression TypeVarTuple(...).""" + + __slots__ = "tuple_fallback" + + tuple_fallback: mypy.types.Instance + + __match_args__ = ("name", "upper_bound", "default") + + def __init__( + self, + name: str, + fullname: str, + upper_bound: mypy.types.Type, + tuple_fallback: mypy.types.Instance, + default: mypy.types.Type, + variance: int = INVARIANT, + is_new_style: bool = False, + line: int = -1, + ) -> None: + super().__init__(name, fullname, upper_bound, default, variance, is_new_style, line=line) + self.tuple_fallback = tuple_fallback + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_var_tuple_expr(self) + + def serialize(self) -> JsonDict: + return { + ".class": "TypeVarTupleExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": self.upper_bound.serialize(), + "tuple_fallback": self.tuple_fallback.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarTupleExpr: + assert data[".class"] == "TypeVarTupleExpr" + return TypeVarTupleExpr( + data["name"], + data["fullname"], + mypy.types.deserialize_type(data["upper_bound"]), + mypy.types.Instance.deserialize(data["tuple_fallback"]), + mypy.types.deserialize_type(data["default"]), + data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_TUPLE_EXPR) + self.tuple_fallback.write(data) + write_str(data, self._name) + write_str(data, self._fullname) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarTupleExpr: + assert read_tag(data) == mypy.types.INSTANCE + fallback = mypy.types.Instance.read(data) + ret = TypeVarTupleExpr( + read_str(data), + read_str(data), + mypy.types.read_type(data), + fallback, + mypy.types.read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class TypeAliasExpr(Expression): + """Type alias expression (rvalue).""" + + __slots__ = ("node",) + + __match_args__ = ("node",) + + node: TypeAlias + + def __init__(self, node: TypeAlias) -> None: + super().__init__() + self.node = node + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_alias_expr(self) + + +class NamedTupleExpr(Expression): + """Named tuple expression namedtuple(...) or NamedTuple(...).""" + + __slots__ = ("info", "is_typed") + + __match_args__ = ("info",) + + # The class representation of this named tuple (its tuple_type attribute contains + # the tuple item types) + info: TypeInfo + is_typed: bool # whether this class was created with typing(_extensions).NamedTuple + + def __init__(self, info: TypeInfo, is_typed: bool = False) -> None: + super().__init__() + self.info = info + self.is_typed = is_typed + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_namedtuple_expr(self) + + +class TypedDictExpr(Expression): + """Typed dict expression TypedDict(...).""" + + __slots__ = ("info",) + + __match_args__ = ("info",) + + # The class representation of this typed dict + info: TypeInfo + + def __init__(self, info: TypeInfo) -> None: + super().__init__() + self.info = info + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_typeddict_expr(self) + + +class EnumCallExpr(Expression): + """Named tuple expression Enum('name', 'val1 val2 ...').""" + + __slots__ = ("info", "items", "values") + + __match_args__ = ("info", "items", "values") + + # The class representation of this enumerated type + info: TypeInfo + # The item names (for debugging) + items: list[str] + values: list[Expression | None] + + def __init__(self, info: TypeInfo, items: list[str], values: list[Expression | None]) -> None: + super().__init__() + self.info = info + self.items = items + self.values = values + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_enum_call_expr(self) + + +class PromoteExpr(Expression): + """Ducktype class decorator expression _promote(...).""" + + __slots__ = ("type",) + + type: mypy.types.ProperType + + def __init__(self, type: mypy.types.ProperType) -> None: + super().__init__() + self.type = type + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit__promote_expr(self) + + +class NewTypeExpr(Expression): + """NewType expression NewType(...).""" + + __slots__ = ("name", "old_type", "info") + + __match_args__ = ("name", "old_type", "info") + + name: str + # The base type (the second argument to NewType) + old_type: mypy.types.Type | None + # The synthesized class representing the new type (inherits old_type) + info: TypeInfo | None + + def __init__( + self, name: str, old_type: mypy.types.Type | None, line: int, column: int + ) -> None: + super().__init__(line=line, column=column) + self.name = name + self.old_type = old_type + self.info = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_newtype_expr(self) + + +class AwaitExpr(Expression): + """Await expression (await ...).""" + + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_await_expr(self) + + +# Constants + + +class TempNode(Expression): + """Temporary dummy node used during type checking. + + This node is not present in the original program; it is just an artifact + of the type checker implementation. It only represents an opaque node with + some fixed type. + """ + + __slots__ = ("type", "no_rhs") + + type: mypy.types.Type + # Is this TempNode used to indicate absence of a right hand side in an annotated assignment? + # (e.g. for 'x: int' the rvalue is TempNode(AnyType(TypeOfAny.special_form), no_rhs=True)) + no_rhs: bool + + def __init__( + self, typ: mypy.types.Type, no_rhs: bool = False, *, context: Context | None = None + ) -> None: + """Construct a dummy node; optionally borrow line/column from context object.""" + super().__init__() + self.type = typ + self.no_rhs = no_rhs + if context is not None: + self.line = context.line + self.column = context.column + + def __repr__(self) -> str: + return "TempNode:%d(%s)" % (self.line, str(self.type)) + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_temp_node(self) + + +# Special attributes not collected as protocol members by Python 3.12 +# See typing._SPECIAL_NAMES +EXCLUDED_PROTOCOL_ATTRIBUTES: Final = frozenset( + { + "__abstractmethods__", + "__annotations__", + "__dict__", + "__doc__", + "__init__", + "__module__", + "__new__", + "__slots__", + "__subclasshook__", + "__weakref__", + "__class_getitem__", # Since Python 3.9 + } +) + +# Attributes that can optionally be defined in the body of a subclass of +# enum.Enum but are removed from the class __dict__ by EnumMeta. +EXCLUDED_ENUM_ATTRIBUTES: Final = frozenset({"_ignore_", "_order_", "__order__"}) + + +class TypeInfo(SymbolNode): + """The type structure of a single class. + + Each TypeInfo corresponds one-to-one to a ClassDef, which + represents the AST of the class. + + In type-theory terms, this is a "type constructor", and if the + class is generic then it will be a type constructor of higher kind. + Where the class is used in an actual type, it's in the form of an + Instance, which amounts to a type application of the tycon to + the appropriate number of arguments. + """ + + __slots__ = ( + "_fullname", + "module_name", + "defn", + "mro", + "_mro_refs", + "bad_mro", + "is_final", + "is_disjoint_base", + "declared_metaclass", + "metaclass_type", + "names", + "is_abstract", + "is_protocol", + "runtime_protocol", + "abstract_attributes", + "deletable_attributes", + "slots", + "assuming", + "assuming_proper", + "inferring", + "is_enum", + "fallback_to_any", + "meta_fallback_to_any", + "type_vars", + "has_param_spec_type", + "bases", + "_promote", + "tuple_type", + "special_alias", + "is_named_tuple", + "typeddict_type", + "is_newtype", + "is_intersection", + "metadata", + "alt_promote", + "has_type_var_tuple_type", + "type_var_tuple_prefix", + "type_var_tuple_suffix", + "self_type", + "dataclass_transform_spec", + "is_type_check_only", + "deprecated", + "type_object_type", + ) + + _fullname: str # Fully qualified name + # Fully qualified name for the module this type was defined in. This + # information is also in the fullname, but is harder to extract in the + # case of nested class definitions. + module_name: str + defn: ClassDef # Corresponding ClassDef + # Method Resolution Order: the order of looking up attributes. The first + # value always to refers to this class. + mro: list[TypeInfo] + # Used to stash the names of the mro classes temporarily between + # deserialization and fixup. See deserialize() for why. + _mro_refs: list[str] | None + bad_mro: bool # Could not construct full MRO + is_final: bool + is_disjoint_base: bool + + declared_metaclass: mypy.types.Instance | None + metaclass_type: mypy.types.Instance | None + + names: SymbolTable # Names defined directly in this type + is_abstract: bool # Does the class have any abstract attributes? + is_protocol: bool # Is this a protocol class? + runtime_protocol: bool # Does this protocol support isinstance checks? + # List of names of abstract attributes together with their abstract status. + # The abstract status must be one of `NOT_ABSTRACT`, `IS_ABSTRACT`, `IMPLICITLY_ABSTRACT`. + abstract_attributes: list[tuple[str, int]] + deletable_attributes: list[str] # Used by mypyc only + # Does this type have concrete `__slots__` defined? + # If class does not have `__slots__` defined then it is `None`, + # if it has empty `__slots__` then it is an empty set. + slots: set[str] | None + + # The attributes 'assuming' and 'assuming_proper' represent structural subtype matrices. + # + # In languages with structural subtyping, one can keep a global subtype matrix like this: + # . A B C . + # A 1 0 0 + # B 1 1 1 + # C 1 0 1 + # . + # where 1 indicates that the type in corresponding row is a subtype of the type + # in corresponding column. This matrix typically starts filled with all 1's and + # a typechecker tries to "disprove" every subtyping relation using atomic (or nominal) types. + # However, we don't want to keep this huge global state. Instead, we keep the subtype + # information in the form of list of pairs (subtype, supertype) shared by all Instances + # with given supertype's TypeInfo. When we enter a subtype check we push a pair in this list + # thus assuming that we started with 1 in corresponding matrix element. Such algorithm allows + # to treat recursive and mutually recursive protocols and other kinds of complex situations. + # + # If concurrent/parallel type checking will be added in future, + # then there should be one matrix per thread/process to avoid false negatives + # during the type checking phase. + assuming: list[tuple[mypy.types.Instance, mypy.types.Instance]] + assuming_proper: list[tuple[mypy.types.Instance, mypy.types.Instance]] + # Ditto for temporary 'inferring' stack of recursive constraint inference. + # It contains Instances of protocol types that appeared as an argument to + # constraints.infer_constraints(). We need 'inferring' to avoid infinite recursion for + # recursive and mutually recursive protocols. + # + # We make 'assuming' and 'inferring' attributes here instead of passing they as kwargs, + # since this would require to pass them in many dozens of calls. In particular, + # there is a dependency infer_constraint -> is_subtype -> is_callable_subtype -> + # -> infer_constraints. + inferring: list[mypy.types.Instance] + # 'inferring' and 'assuming' can't be made sets, since we need to use + # is_same_type to correctly treat unions. + + # Classes inheriting from Enum shadow their true members with a __getattr__, so we + # have to treat them as a special case. + is_enum: bool + # If true, any unknown attributes should have type 'Any' instead + # of generating a type error. This would be true if there is a + # base class with type 'Any', but other use cases may be + # possible. This is similar to having __getattr__ that returns Any + # (and __setattr__), but without the __getattr__ method. + fallback_to_any: bool + + # Same as above but for cases where metaclass has type Any. This will suppress + # all attribute errors only for *class object* access. + meta_fallback_to_any: bool + + # Information related to type annotations. + + # Generic type variable names (full names) + type_vars: list[str] + + # Whether this class has a ParamSpec type variable + has_param_spec_type: bool + + # Direct base classes. + bases: list[mypy.types.Instance] + + # Another type which this type will be treated as a subtype of, + # even though it's not a subclass in Python. The non-standard + # `@_promote` decorator introduces this, and there are also + # several builtin examples, in particular `int` -> `float`. + _promote: list[mypy.types.ProperType] + + # This is used for promoting native integer types such as 'i64' to + # 'int'. (_promote is used for the other direction.) This only + # supports one-step promotions (e.g., i64 -> int, not + # i64 -> int -> float, and this isn't used to promote in joins. + # + # This results in some unintuitive results, such as that even + # though i64 is compatible with int and int is compatible with + # float, i64 is *not* compatible with float. + alt_promote: mypy.types.Instance | None + + # Representation of a Tuple[...] base class, if the class has any + # (e.g., for named tuples). If this is not None, the actual Type + # object used for this class is not an Instance but a TupleType; + # the corresponding Instance is set as the fallback type of the + # tuple type. + tuple_type: mypy.types.TupleType | None + + # Is this a named tuple type? + is_named_tuple: bool + + # If this class is defined by the TypedDict type constructor, + # then this is not None. + typeddict_type: mypy.types.TypedDictType | None + + # Is this a newtype type? + is_newtype: bool + + # Is this a synthesized intersection type? + is_intersection: bool + + # This is a dictionary that will be serialized and un-serialized as is. + # It is useful for plugins to add their data to save in the cache. + metadata: dict[str, JsonDict] + + # Store type alias representing this type (for named tuples and TypedDicts). + # Although definitions of these types are stored in symbol tables as TypeInfo, + # when a type analyzer will find them, it should construct a TupleType, or + # a TypedDict type. However, we can't use the plain types, since if the definition + # is recursive, this will create an actual recursive structure of types (i.e. as + # internal Python objects) causing infinite recursions everywhere during type checking. + # To overcome this, we create a TypeAlias node, that will point to these types. + # We store this node in the `special_alias` attribute, because it must be the same node + # in case we are doing multiple semantic analysis passes. + special_alias: TypeAlias | None + + # Shared type variable for typing.Self in this class (if used, otherwise None). + self_type: mypy.types.TypeVarType | None + + # Added if the corresponding class is directly decorated with `typing.dataclass_transform` + dataclass_transform_spec: DataclassTransformSpec | None + + # Is set to `True` when class is decorated with `@typing.type_check_only` + is_type_check_only: bool + + # The type's deprecation message (in case it is deprecated) + deprecated: str | None + + # Cached value of class constructor type, i.e. the type of class object when it + # appears in runtime context. + type_object_type: mypy.types.FunctionLike | None + + FLAGS: Final = [ + "is_abstract", + "is_enum", + "fallback_to_any", + "meta_fallback_to_any", + "is_named_tuple", + "is_newtype", + "is_protocol", + "runtime_protocol", + "is_final", + "is_disjoint_base", + "is_intersection", + ] + + def __init__(self, names: SymbolTable, defn: ClassDef, module_name: str) -> None: + """Initialize a TypeInfo.""" + super().__init__() + self._fullname = defn.fullname + self.names = names + self.defn = defn + self.module_name = module_name + self.type_vars = [] + self.has_param_spec_type = False + self.has_type_var_tuple_type = False + self.bases = [] + self.mro = [] + self._mro_refs = None + self.bad_mro = False + self.declared_metaclass = None + self.metaclass_type = None + self.is_abstract = False + self.abstract_attributes = [] + self.deletable_attributes = [] + self.slots = None + self.assuming = [] + self.assuming_proper = [] + self.inferring = [] + self.is_protocol = False + self.runtime_protocol = False + self.type_var_tuple_prefix: int | None = None + self.type_var_tuple_suffix: int | None = None + self.add_type_vars() + self.is_final = False + self.is_disjoint_base = False + self.is_enum = False + self.fallback_to_any = False + self.meta_fallback_to_any = False + self._promote = [] + self.alt_promote = None + self.tuple_type = None + self.special_alias = None + self.is_named_tuple = False + self.typeddict_type = None + self.is_newtype = False + self.is_intersection = False + self.metadata = {} + self.self_type = None + self.dataclass_transform_spec = None + self.is_type_check_only = False + self.deprecated = None + self.type_object_type = None + + def add_type_vars(self) -> None: + self.has_type_var_tuple_type = False + if self.defn.type_vars: + for i, vd in enumerate(self.defn.type_vars): + if isinstance(vd, mypy.types.ParamSpecType): + self.has_param_spec_type = True + if isinstance(vd, mypy.types.TypeVarTupleType): + assert not self.has_type_var_tuple_type + self.has_type_var_tuple_type = True + self.type_var_tuple_prefix = i + self.type_var_tuple_suffix = len(self.defn.type_vars) - i - 1 + self.type_vars.append(vd.name) + + @property + def name(self) -> str: + """Short name.""" + return self.defn.name + + @property + def fullname(self) -> str: + return self._fullname + + def is_generic(self) -> bool: + """Is the type generic (i.e. does it have type variables)?""" + return len(self.type_vars) > 0 + + def get(self, name: str) -> SymbolTableNode | None: + for cls in self.mro: + n = cls.names.get(name) + if n: + return n + return None + + def get_containing_type_info(self, name: str) -> TypeInfo | None: + for cls in self.mro: + if name in cls.names: + return cls + return None + + @property + def protocol_members(self) -> list[str]: + # Protocol members are names of all attributes/methods defined in a protocol + # and in all its supertypes (except for 'object'). + members: set[str] = set() + assert self.mro, "This property can be only accessed after MRO is (re-)calculated" + for base in self.mro[:-1]: # we skip "object" since everyone implements it + if base.is_protocol: + for name, node in base.names.items(): + if isinstance(node.node, (TypeAlias, TypeVarExpr, MypyFile)): + # These are auxiliary definitions (and type aliases are prohibited). + continue + if name in EXCLUDED_PROTOCOL_ATTRIBUTES: + continue + members.add(name) + return sorted(members) + + @property + def enum_members(self) -> list[str]: + # TODO: cache the results? + members = [] + for name, sym in self.names.items(): + # Case 1: + # + # class MyEnum(Enum): + # @member + # def some(self): ... + if isinstance(sym.node, Decorator): + if any( + dec.fullname == "enum.member" + for dec in sym.node.decorators + if isinstance(dec, RefExpr) + ): + members.append(name) + continue + # Case 2: + # + # class MyEnum(Enum): + # x = 1 + # + # Case 3: + # + # class MyEnum(Enum): + # class Other: ... + elif isinstance(sym.node, (Var, TypeInfo)): + if ( + # TODO: properly support ignored names from `_ignore_` + name in EXCLUDED_ENUM_ATTRIBUTES + or is_sunder(name) + or name.startswith("__") # dunder and private + ): + continue # name is excluded + + if isinstance(sym.node, Var): + if not sym.node.has_explicit_value: + continue # unannotated value not a member + + typ = mypy.types.get_proper_type(sym.node.type) + if ( + isinstance(typ, mypy.types.FunctionLike) and not typ.is_type_obj() + ) or ( # explicit `@member` is required + isinstance(typ, mypy.types.Instance) + and typ.type.fullname == "enum.nonmember" + ): + continue # name is not a member + + members.append(name) + return members + + def __getitem__(self, name: str) -> SymbolTableNode: + n = self.get(name) + if n: + return n + else: + raise KeyError(name) + + def __repr__(self) -> str: + return f"" + + def __bool__(self) -> bool: + # We defined this here instead of just overriding it in + # FakeInfo so that mypyc can generate a direct call instead of + # using the generic bool handling. + return not isinstance(self, FakeInfo) + + def has_readable_member(self, name: str) -> bool: + return self.get(name) is not None + + def get_method(self, name: str) -> FuncBase | Decorator | None: + for cls in self.mro: + if name in cls.names: + node = cls.names[name].node + elif possible_redefinitions := sorted( + [n for n in cls.names.keys() if n.startswith(f"{name}-redefinition")] + ): + node = cls.names[possible_redefinitions[-1]].node + else: + continue + if isinstance(node, SYMBOL_FUNCBASE_TYPES): + return node + elif isinstance(node, Decorator): # Two `if`s make `mypyc` happy + return node + else: + return None + return None + + def calculate_metaclass_type(self) -> mypy.types.Instance | None: + declared = self.declared_metaclass + if declared is not None and not declared.type.has_base("builtins.type"): + return declared + if self._fullname == "builtins.type": + return mypy.types.Instance(self, []) + + winner = declared + for super_class in self.mro[1:]: + super_meta = super_class.declared_metaclass + if super_meta is None or super_meta.type is None: + continue + if winner is None: + winner = super_meta + continue + if winner.type.has_base(super_meta.type.fullname): + continue + if super_meta.type.has_base(winner.type.fullname): + winner = super_meta + continue + # metaclass conflict + winner = None + break + + return winner + + def explain_metaclass_conflict(self) -> str | None: + # Compare to logic in calculate_metaclass_type + declared = self.declared_metaclass + if declared is not None and not declared.type.has_base("builtins.type"): + return None + if self._fullname == "builtins.type": + return None + + winner = declared + if declared is None: + resolution_steps = [] + else: + resolution_steps = [f'"{declared.type.fullname}" (metaclass of "{self.fullname}")'] + for super_class in self.mro[1:]: + super_meta = super_class.declared_metaclass + if super_meta is None or super_meta.type is None: + continue + if winner is None: + winner = super_meta + resolution_steps.append( + f'"{winner.type.fullname}" (metaclass of "{super_class.fullname}")' + ) + continue + if winner.type.has_base(super_meta.type.fullname): + continue + if super_meta.type.has_base(winner.type.fullname): + winner = super_meta + resolution_steps.append( + f'"{winner.type.fullname}" (metaclass of "{super_class.fullname}")' + ) + continue + # metaclass conflict + conflict = f'"{super_meta.type.fullname}" (metaclass of "{super_class.fullname}")' + return f"{' > '.join(resolution_steps)} conflicts with {conflict}" + + return None + + def is_metaclass(self, *, precise: bool = False) -> bool: + return ( + self.has_base("builtins.type") + or self.fullname == "abc.ABCMeta" + or (self.fallback_to_any and not precise) + ) + + def has_base(self, fullname: str) -> bool: + """Return True if type has a base type with the specified name. + + This can be either via extension or via implementation. + """ + for cls in self.mro: + if cls.fullname == fullname: + return True + return False + + def direct_base_classes(self) -> list[TypeInfo]: + """Return a direct base classes. + + Omit base classes of other base classes. + """ + return [base.type for base in self.bases] + + def update_tuple_type(self, typ: mypy.types.TupleType) -> None: + """Update tuple_type and special_alias as needed.""" + self.tuple_type = typ + alias = TypeAlias.from_tuple_type(self) + if not self.special_alias: + self.special_alias = alias + else: + self.special_alias.target = alias.target + # Invalidate recursive status cache in case it was previously set. + self.special_alias._is_recursive = None + + def update_typeddict_type(self, typ: mypy.types.TypedDictType) -> None: + """Update typeddict_type and special_alias as needed.""" + self.typeddict_type = typ + alias = TypeAlias.from_typeddict_type(self) + if not self.special_alias: + self.special_alias = alias + else: + self.special_alias.target = alias.target + # Invalidate recursive status cache in case it was previously set. + self.special_alias._is_recursive = None + + def __str__(self) -> str: + """Return a string representation of the type. + + This includes the most important information about the type. + """ + options = Options() + return self.dump( + str_conv=mypy.strconv.StrConv(options=options), + type_str_conv=mypy.types.TypeStrVisitor(options=options), + ) + + def dump( + self, str_conv: mypy.strconv.StrConv, type_str_conv: mypy.types.TypeStrVisitor + ) -> str: + """Return a string dump of the contents of the TypeInfo.""" + + base: str = "" + + def type_str(typ: mypy.types.Type) -> str: + return typ.accept(type_str_conv) + + head = "TypeInfo" + str_conv.format_id(self) + if self.bases: + base = f"Bases({', '.join(type_str(base) for base in self.bases)})" + mro = "Mro({})".format( + ", ".join(item.fullname + str_conv.format_id(item) for item in self.mro) + ) + names = [] + for name in sorted(self.names): + description = name + str_conv.format_id(self.names[name].node) + node = self.names[name].node + if isinstance(node, Var) and node.type: + description += f" ({type_str(node.type)})" + names.append(description) + items = [f"Name({self.fullname})", base, mro, ("Names", names)] + if self.declared_metaclass: + items.append(f"DeclaredMetaclass({type_str(self.declared_metaclass)})") + if self.metaclass_type: + items.append(f"MetaclassType({type_str(self.metaclass_type)})") + return mypy.strconv.dump_tagged(items, head, str_conv=str_conv) + + def serialize(self) -> JsonDict: + # NOTE: This is where all ClassDefs originate, so there shouldn't be duplicates. + data = { + ".class": "TypeInfo", + "module_name": self.module_name, + "fullname": self.fullname, + "names": self.names.serialize(self.fullname), + "defn": self.defn.serialize(), + "abstract_attributes": self.abstract_attributes, + "type_vars": self.type_vars, + "has_param_spec_type": self.has_param_spec_type, + "bases": [b.serialize() for b in self.bases], + "mro": [c.fullname for c in self.mro], + "_promote": [p.serialize() for p in self._promote], + "alt_promote": None if self.alt_promote is None else self.alt_promote.serialize(), + "declared_metaclass": ( + None if self.declared_metaclass is None else self.declared_metaclass.serialize() + ), + "metaclass_type": ( + None if self.metaclass_type is None else self.metaclass_type.serialize() + ), + "tuple_type": None if self.tuple_type is None else self.tuple_type.serialize(), + "typeddict_type": ( + None if self.typeddict_type is None else self.typeddict_type.serialize() + ), + "flags": get_flags(self, TypeInfo.FLAGS), + "metadata": self.metadata, + "slots": sorted(self.slots) if self.slots is not None else None, + "deletable_attributes": self.deletable_attributes, + "self_type": self.self_type.serialize() if self.self_type is not None else None, + "dataclass_transform_spec": ( + self.dataclass_transform_spec.serialize() + if self.dataclass_transform_spec is not None + else None + ), + "deprecated": self.deprecated, + } + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeInfo: + names = SymbolTable.deserialize(data["names"]) + defn = ClassDef.deserialize(data["defn"]) + module_name = data["module_name"] + ti = TypeInfo(names, defn, module_name) + ti._fullname = data["fullname"] + ti.abstract_attributes = [(attr[0], attr[1]) for attr in data["abstract_attributes"]] + ti.type_vars = data["type_vars"] + ti.has_param_spec_type = data["has_param_spec_type"] + ti.bases = [mypy.types.Instance.deserialize(b) for b in data["bases"]] + _promote = [] + for p in data["_promote"]: + t = mypy.types.deserialize_type(p) + assert isinstance(t, mypy.types.ProperType) + _promote.append(t) + ti._promote = _promote + ti.alt_promote = ( + None + if data["alt_promote"] is None + else mypy.types.Instance.deserialize(data["alt_promote"]) + ) + ti.declared_metaclass = ( + None + if data["declared_metaclass"] is None + else mypy.types.Instance.deserialize(data["declared_metaclass"]) + ) + ti.metaclass_type = ( + None + if data["metaclass_type"] is None + else mypy.types.Instance.deserialize(data["metaclass_type"]) + ) + # NOTE: ti.mro will be set in the fixup phase based on these + # names. The reason we need to store the mro instead of just + # recomputing it from base classes has to do with a subtle + # point about fine-grained incremental: the cache files might + # not be loaded until after a class in the mro has changed its + # bases, which causes the mro to change. If we recomputed our + # mro, we would compute the *new* mro, which leaves us with no + # way to detect that the mro has changed! Thus we need to make + # sure to load the original mro so that once the class is + # rechecked, it can tell that the mro has changed. + ti._mro_refs = data["mro"] + ti.tuple_type = ( + None + if data["tuple_type"] is None + else mypy.types.TupleType.deserialize(data["tuple_type"]) + ) + ti.typeddict_type = ( + None + if data["typeddict_type"] is None + else mypy.types.TypedDictType.deserialize(data["typeddict_type"]) + ) + ti.metadata = data["metadata"] + ti.slots = set(data["slots"]) if data["slots"] is not None else None + ti.deletable_attributes = data["deletable_attributes"] + set_flags(ti, data["flags"]) + st = data["self_type"] + ti.self_type = mypy.types.TypeVarType.deserialize(st) if st is not None else None + if data.get("dataclass_transform_spec") is not None: + ti.dataclass_transform_spec = DataclassTransformSpec.deserialize( + data["dataclass_transform_spec"] + ) + ti.deprecated = data.get("deprecated") + return ti + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_INFO) + self.names.write(data, self.fullname) + self.defn.write(data) + write_str(data, self.module_name) + write_str(data, self.fullname) + write_str_list(data, [a for a, _ in self.abstract_attributes]) + write_int_list(data, [s for _, s in self.abstract_attributes]) + write_str_list(data, self.type_vars) + write_bool(data, self.has_param_spec_type) + mypy.types.write_type_list(data, self.bases) + write_str_list(data, [c.fullname for c in self.mro]) + mypy.types.write_type_list(data, self._promote) + mypy.types.write_type_opt(data, self.alt_promote) + mypy.types.write_type_opt(data, self.declared_metaclass) + mypy.types.write_type_opt(data, self.metaclass_type) + mypy.types.write_type_opt(data, self.tuple_type) + mypy.types.write_type_opt(data, self.typeddict_type) + write_flags( + data, + [ + self.is_abstract, + self.is_enum, + self.fallback_to_any, + self.meta_fallback_to_any, + self.is_named_tuple, + self.is_newtype, + self.is_protocol, + self.runtime_protocol, + self.is_final, + self.is_disjoint_base, + self.is_intersection, + ], + ) + write_json(data, self.metadata) + if self.slots is None: + write_tag(data, LITERAL_NONE) + else: + write_str_list(data, sorted(self.slots)) + write_str_list(data, self.deletable_attributes) + mypy.types.write_type_opt(data, self.self_type) + if self.dataclass_transform_spec is None: + write_tag(data, LITERAL_NONE) + else: + self.dataclass_transform_spec.write(data) + write_str_opt(data, self.deprecated) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeInfo: + names = SymbolTable.read(data) + assert read_tag(data) == CLASS_DEF + defn = ClassDef.read(data) + module_name = read_str(data) + ti = TypeInfo(names, defn, module_name) + ti._fullname = read_str(data) + attrs = read_str_list(data) + statuses = read_int_list(data) + ti.abstract_attributes = list(zip(attrs, statuses)) + ti.type_vars = read_str_list(data) + ti.has_param_spec_type = read_bool(data) + ti.bases = [] + assert read_tag(data) == LIST_GEN + for _ in range(read_int_bare(data)): + assert read_tag(data) == mypy.types.INSTANCE + ti.bases.append(mypy.types.Instance.read(data)) + # NOTE: ti.mro will be set in the fixup phase based on these + # names. The reason we need to store the mro instead of just + # recomputing it from base classes has to do with a subtle + # point about fine-grained incremental: the cache files might + # not be loaded until after a class in the mro has changed its + # bases, which causes the mro to change. If we recomputed our + # mro, we would compute the *new* mro, which leaves us with no + # way to detect that the mro has changed! Thus, we need to make + # sure to load the original mro so that once the class is + # rechecked, it can tell that the mro has changed. + ti._mro_refs = read_str_list(data) + ti._promote = cast(list[mypy.types.ProperType], mypy.types.read_type_list(data)) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.INSTANCE + ti.alt_promote = mypy.types.Instance.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.INSTANCE + ti.declared_metaclass = mypy.types.Instance.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.INSTANCE + ti.metaclass_type = mypy.types.Instance.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.TUPLE_TYPE + ti.tuple_type = mypy.types.TupleType.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.TYPED_DICT_TYPE + ti.typeddict_type = mypy.types.TypedDictType.read(data) + ( + ti.is_abstract, + ti.is_enum, + ti.fallback_to_any, + ti.meta_fallback_to_any, + ti.is_named_tuple, + ti.is_newtype, + ti.is_protocol, + ti.runtime_protocol, + ti.is_final, + ti.is_disjoint_base, + ti.is_intersection, + ) = read_flags(data, num_flags=11) + ti.metadata = read_json(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == LIST_STR + ti.slots = {read_str_bare(data) for _ in range(read_int_bare(data))} + ti.deletable_attributes = read_str_list(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.TYPE_VAR_TYPE + ti.self_type = mypy.types.TypeVarType.read(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == DT_SPEC + ti.dataclass_transform_spec = DataclassTransformSpec.read(data) + ti.deprecated = read_str_opt(data) + assert read_tag(data) == END_TAG + return ti + + +class FakeInfo(TypeInfo): + __slots__ = ("msg",) + + # types.py defines a single instance of this class, called types.NOT_READY. + # This instance is used as a temporary placeholder in the process of de-serialization + # of 'Instance' types. The de-serialization happens in two steps: In the first step, + # Instance.type is set to NOT_READY. In the second step (in fixup.py) it is replaced by + # an actual TypeInfo. If you see the assertion error below, then most probably something + # went wrong during the second step and an 'Instance' that raised this error was not fixed. + # Note: + # 'None' is not used as a dummy value for two reasons: + # 1. This will require around 80-100 asserts to make 'mypy --strict-optional mypy' + # pass cleanly. + # 2. If NOT_READY value is accidentally used somewhere, it will be obvious where the value + # is from, whereas a 'None' value could come from anywhere. + # + # Additionally, this serves as a more general-purpose placeholder + # for missing TypeInfos in a number of places where the excuses + # for not being Optional are a little weaker. + # + # TypeInfo defines a __bool__ method that returns False for FakeInfo + # so that it can be conveniently tested against in the same way that it + # would be if things were properly optional. + def __init__(self, msg: str) -> None: + self.msg = msg + + def __getattribute__(self, attr: str) -> type: + # Handle __class__ so that isinstance still works... + if attr == "__class__": + return object.__getattribute__(self, attr) # type: ignore[no-any-return] + raise AssertionError(object.__getattribute__(self, "msg")) + + +VAR_NO_INFO: Final[TypeInfo] = FakeInfo("Var is lacking info") +CLASSDEF_NO_INFO: Final[TypeInfo] = FakeInfo("ClassDef is lacking info") +FUNC_NO_INFO: Final[TypeInfo] = FakeInfo("FuncBase for non-methods lack info") +MISSING_FALLBACK: Final = FakeInfo("fallback can't be filled out until semanal") + + +class TypeAlias(SymbolNode): + """ + A symbol node representing a type alias. + + Type alias is a static concept, in contrast to variables with types + like Type[...]. Namely: + * type aliases + - can be used in type context (annotations) + - cannot be re-assigned + * variables with type Type[...] + - cannot be used in type context + - but can be re-assigned + + An alias can be defined only by an assignment to a name (not any other lvalues). + + Such assignment defines an alias by default. To define a variable, + an explicit Type[...] annotation is required. As an exception, + at non-global scope non-subscripted rvalue creates a variable even without + an annotation. This exception exists to accommodate the common use case of + class-valued attributes. See SemanticAnalyzerPass2.check_and_set_up_type_alias + for details. + + Aliases can be generic. We use bound type variables for generic aliases, similar + to classes. Essentially, type aliases work as macros that expand textually. + The definition and expansion rules are following: + + 1. An alias targeting a generic class without explicit variables act as + the given class (this doesn't apply to TypedDict, Tuple and Callable, which + are not proper classes but special type constructors): + + A = List + AA = List[Any] + + x: A # same as List[Any] + x: A[int] # same as List[int] + + x: AA # same as List[Any] + x: AA[int] # Error! + + C = Callable # Same as Callable[..., Any] + T = Tuple # Same as Tuple[Any, ...] + + 2. An alias using explicit type variables in its rvalue expects + replacements (type arguments) for these variables. If missing, they + are treated as Any, like for other generics: + + B = List[Tuple[T, T]] + + x: B # same as List[Tuple[Any, Any]] + x: B[int] # same as List[Tuple[int, int]] + + def f(x: B[T]) -> T: ... # without T, Any would be used here + + 3. An alias can be defined using another aliases. In the definition + rvalue the Any substitution doesn't happen for top level unsubscripted + generic classes: + + A = List + B = A # here A is expanded to List, _not_ List[Any], + # to match the Python runtime behaviour + x: B[int] # same as List[int] + C = List[A] # this expands to List[List[Any]] + + AA = List[T] + D = AA # here AA expands to List[Any] + x: D[int] # Error! + + Note: the fact that we support aliases like `A = List` means that the target + type will be initially an instance type with wrong number of type arguments. + Such instances are all fixed either during or after main semantic analysis passes. + We therefore store the difference between `List` and `List[Any]` rvalues (targets) + using the `no_args` flag. + + Meaning of other fields: + + target: The target type. For generic aliases contains bound type variables + as nested types (currently TypeVar and ParamSpec are supported). + _fullname: Qualified name of this type alias. This is used in particular + to track fine-grained dependencies from aliases. + module: Module where the alias was defined. + alias_tvars: Type variables used to define this alias. + normalized: Used to distinguish between `A = List`, and `A = list`. Both + are internally stored using `builtins.list` (because `typing.List` is + itself an alias), while the second cannot be subscripted because of + Python runtime limitation. + line and column: Line and column on the original alias definition. + eager: If True, immediately expand alias when referred to (useful for aliases + within functions that can't be looked up from the symbol table) + """ + + __slots__ = ( + "target", + "_fullname", + "module", + "alias_tvars", + "no_args", + "normalized", + "_is_recursive", + "eager", + "tvar_tuple_index", + "python_3_12_type_alias", + ) + + __match_args__ = ("name", "target", "alias_tvars", "no_args") + + def __init__( + self, + target: mypy.types.Type, + fullname: str, + module: str, + line: int, + column: int, + *, + alias_tvars: list[mypy.types.TypeVarLikeType] | None = None, + no_args: bool = False, + normalized: bool = False, + eager: bool = False, + python_3_12_type_alias: bool = False, + ) -> None: + self._fullname = fullname + self.module = module + self.target = target + if alias_tvars is None: + alias_tvars = [] + self.alias_tvars = alias_tvars + self.no_args = no_args + self.normalized = normalized + # This attribute is manipulated by TypeAliasType. If non-None, + # it is the cached value. + self._is_recursive: bool | None = None + self.eager = eager + self.python_3_12_type_alias = python_3_12_type_alias + self.tvar_tuple_index = None + for i, t in enumerate(alias_tvars): + if isinstance(t, mypy.types.TypeVarTupleType): + self.tvar_tuple_index = i + super().__init__(line, column) + + @classmethod + def from_tuple_type(cls, info: TypeInfo) -> TypeAlias: + """Generate an alias to the tuple type described by a given TypeInfo. + + NOTE: this doesn't set type alias type variables (for generic tuple types), + they must be set by the caller (when fully analyzed). + """ + assert info.tuple_type + # TODO: is it possible to refactor this to set the correct type vars here? + return TypeAlias( + info.tuple_type.copy_modified( + # Create an Instance similar to fill_typevars(). + fallback=mypy.types.Instance( + info, mypy.types.type_vars_as_args(info.defn.type_vars) + ) + ), + info.fullname, + info.module_name, + info.line, + info.column, + ) + + @classmethod + def from_typeddict_type(cls, info: TypeInfo) -> TypeAlias: + """Generate an alias to the TypedDict type described by a given TypeInfo. + + NOTE: this doesn't set type alias type variables (for generic TypedDicts), + they must be set by the caller (when fully analyzed). + """ + assert info.typeddict_type + # TODO: is it possible to refactor this to set the correct type vars here? + return TypeAlias( + info.typeddict_type.copy_modified( + # Create an Instance similar to fill_typevars(). + fallback=mypy.types.Instance( + info, mypy.types.type_vars_as_args(info.defn.type_vars) + ) + ), + info.fullname, + info.module_name, + info.line, + info.column, + ) + + @property + def name(self) -> str: + return self._fullname.split(".")[-1] + + @property + def fullname(self) -> str: + return self._fullname + + @property + def has_param_spec_type(self) -> bool: + return any(isinstance(v, mypy.types.ParamSpecType) for v in self.alias_tvars) + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_type_alias(self) + + def serialize(self) -> JsonDict: + data: JsonDict = { + ".class": "TypeAlias", + "fullname": self._fullname, + "module": self.module, + "target": self.target.serialize(), + "alias_tvars": [v.serialize() for v in self.alias_tvars], + "no_args": self.no_args, + "normalized": self.normalized, + "python_3_12_type_alias": self.python_3_12_type_alias, + } + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeAlias: + assert data[".class"] == "TypeAlias" + fullname = data["fullname"] + module = data["module"] + alias_tvars = [mypy.types.deserialize_type(v) for v in data["alias_tvars"]] + assert all(isinstance(t, mypy.types.TypeVarLikeType) for t in alias_tvars) + target = mypy.types.deserialize_type(data["target"]) + no_args = data["no_args"] + normalized = data["normalized"] + python_3_12_type_alias = data["python_3_12_type_alias"] + return cls( + target, + fullname, + module, + -1, + -1, + alias_tvars=cast(list[mypy.types.TypeVarLikeType], alias_tvars), + no_args=no_args, + normalized=normalized, + python_3_12_type_alias=python_3_12_type_alias, + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_ALIAS) + write_str(data, self._fullname) + write_str(data, self.module) + self.target.write(data) + mypy.types.write_type_list(data, self.alias_tvars) + write_bool(data, self.no_args) + write_bool(data, self.normalized) + write_bool(data, self.python_3_12_type_alias) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeAlias: + fullname = read_str(data) + module = read_str(data) + target = mypy.types.read_type(data) + alias_tvars = mypy.types.read_type_var_likes(data) + ret = TypeAlias( + target, + fullname, + module, + -1, + -1, + alias_tvars=alias_tvars, + no_args=read_bool(data), + normalized=read_bool(data), + python_3_12_type_alias=read_bool(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class PlaceholderNode(SymbolNode): + """Temporary symbol node that will later become a real SymbolNode. + + These are only present during semantic analysis when using the new + semantic analyzer. These are created if some essential dependencies + of a definition are not yet complete. + + A typical use is for names imported from a module which is still + incomplete (within an import cycle): + + from m import f # Initially may create PlaceholderNode + + This is particularly important if the imported shadows a name from + an enclosing scope or builtins: + + from m import int # Placeholder avoids mixups with builtins.int + + Another case where this is useful is when there is another definition + or assignment: + + from m import f + def f() -> None: ... + + In the above example, the presence of PlaceholderNode allows us to + handle the second definition as a redefinition. + + They are also used to create PlaceholderType instances for types + that refer to incomplete types. Example: + + class C(Sequence[C]): ... + + We create a PlaceholderNode (with becomes_typeinfo=True) for C so + that the type C in Sequence[C] can be bound. + + Attributes: + + fullname: Full name of the PlaceholderNode. + node: AST node that contains the definition that caused this to + be created. This is useful for tracking order of incomplete definitions + and for debugging. + becomes_typeinfo: If True, this refers something that could later + become a TypeInfo. It can't be used with type variables, in + particular, as this would cause issues with class type variable + detection. + + The long-term purpose of placeholder nodes/types is to evolve into + something that can support general recursive types. + """ + + __slots__ = ("_fullname", "node", "becomes_typeinfo") + + def __init__( + self, fullname: str, node: Node, line: int, *, becomes_typeinfo: bool = False + ) -> None: + self._fullname = fullname + self.node = node + self.becomes_typeinfo = becomes_typeinfo + self.line = line + + @property + def name(self) -> str: + return self._fullname.split(".")[-1] + + @property + def fullname(self) -> str: + return self._fullname + + def serialize(self) -> JsonDict: + assert False, "PlaceholderNode can't be serialized" + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_placeholder_node(self) + + +class SymbolTableNode: + """Description of a name binding in a symbol table. + + These are only used as values in module (global), function (local) + and class symbol tables (see SymbolTable). The name that is bound is + the key in SymbolTable. + + Symbol tables don't contain direct references to AST nodes primarily + because there can be multiple symbol table references to a single + AST node (due to imports and aliases), and different references can + behave differently. This class describes the unique properties of + each reference. + + The most fundamental attribute is 'node', which is the AST node that + the name refers to. + + The kind is usually one of LDEF, GDEF or MDEF, depending on the scope + of the definition. These three kinds can usually be used + interchangeably and the difference between local, global and class + scopes is mostly descriptive, with no semantic significance. + However, some tools that consume mypy ASTs may care about these so + they should be correct. + + Attributes: + node: AST node of definition. Among others, this can be one of + FuncDef, Var, TypeInfo, TypeVarExpr or MypyFile -- or None + for cross_ref that hasn't been fixed up yet. + kind: Kind of node. Possible values: + - LDEF: local definition + - GDEF: global (module-level) definition + - MDEF: class member definition + - UNBOUND_IMPORTED: temporary kind for imported names (we + don't know the final kind yet) + module_public: If False, this name won't be imported via + 'from import *'. This has no effect on names within + classes. + module_hidden: If True, the name will be never exported (needed for + stub files) + cross_ref: For deserialized MypyFile nodes, the referenced module + name; for other nodes, optionally the name of the referenced object. + implicit: Was this defined by assignment to self attribute? + plugin_generated: Was this symbol generated by a plugin? + (And therefore needs to be removed in aststrip.) + no_serialize: Do not serialize this node if True. This is used to prevent + keys in the cache that refer to modules on which this file does not + depend. Currently this can happen if there is a module not in build + used e.g. like this: + import a.b.c # type: ignore + This will add a submodule symbol to parent module `a` symbol table, + but `a.b` is _not_ added as its dependency. Therefore, we should + not serialize these symbols as they may not be found during fixup + phase, instead they will be re-added during subsequent patch parents + phase. + TODO: Refactor build.py to make dependency tracking more transparent + and/or refactor look-up functions to not require parent patching. + + NOTE: No other attributes should be added to this class unless they + are shared by all node kinds. + """ + + __slots__ = ( + "kind", + "node", + "module_public", + "module_hidden", + "cross_ref", + "implicit", + "plugin_generated", + "no_serialize", + ) + + def __init__( + self, + kind: int, + node: SymbolNode | None, + module_public: bool = True, + implicit: bool = False, + module_hidden: bool = False, + *, + plugin_generated: bool = False, + no_serialize: bool = False, + ) -> None: + self.kind = kind + self.node = node + self.module_public = module_public + self.implicit = implicit + self.module_hidden = module_hidden + self.cross_ref: str | None = None + self.plugin_generated = plugin_generated + self.no_serialize = no_serialize + + @property + def fullname(self) -> str | None: + if self.node is not None: + return self.node.fullname + else: + return None + + @property + def type(self) -> mypy.types.Type | None: + node = self.node + if isinstance(node, (Var, SYMBOL_FUNCBASE_TYPES)) and node.type is not None: + return node.type + elif isinstance(node, Decorator): + return node.var.type + else: + return None + + def copy(self) -> SymbolTableNode: + new = SymbolTableNode( + self.kind, self.node, self.module_public, self.implicit, self.module_hidden + ) + new.cross_ref = self.cross_ref + return new + + def __str__(self) -> str: + s = f"{node_kinds[self.kind]}/{short_type(self.node)}" + if isinstance(self.node, SymbolNode): + s += f" ({self.node.fullname})" + # Include declared type of variables and functions. + if self.type is not None: + s += f" : {self.type}" + if self.cross_ref: + s += f" cross_ref:{self.cross_ref}" + return s + + def serialize(self, prefix: str, name: str) -> JsonDict: + """Serialize a SymbolTableNode. + + Args: + prefix: full name of the containing module or class; or None + name: name of this object relative to the containing object + """ + data: JsonDict = {".class": "SymbolTableNode", "kind": node_kinds[self.kind]} + if self.module_hidden: + data["module_hidden"] = True + if not self.module_public: + data["module_public"] = False + if self.implicit: + data["implicit"] = True + if self.plugin_generated: + data["plugin_generated"] = True + if isinstance(self.node, MypyFile): + data["cross_ref"] = self.node.fullname + else: + assert self.node is not None, f"{prefix}:{name}" + if prefix is not None: + fullname = self.node.fullname + if ( + "." in fullname + and fullname != prefix + "." + name + and not (isinstance(self.node, Var) and self.node.from_module_getattr) + ): + assert not isinstance( + self.node, PlaceholderNode + ), f"Definition of {fullname} is unexpectedly incomplete" + data["cross_ref"] = fullname + return data + data["node"] = self.node.serialize() + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> SymbolTableNode: + assert data[".class"] == "SymbolTableNode" + kind = inverse_node_kinds[data["kind"]] + if "cross_ref" in data: + # This will be fixed up later. + stnode = SymbolTableNode(kind, None) + stnode.cross_ref = data["cross_ref"] + else: + assert "node" in data, data + node = SymbolNode.deserialize(data["node"]) + stnode = SymbolTableNode(kind, node) + if "module_hidden" in data: + stnode.module_hidden = data["module_hidden"] + if "module_public" in data: + stnode.module_public = data["module_public"] + if "implicit" in data: + stnode.implicit = data["implicit"] + if "plugin_generated" in data: + stnode.plugin_generated = data["plugin_generated"] + return stnode + + def write(self, data: WriteBuffer, prefix: str, name: str) -> None: + write_tag(data, SYMBOL_TABLE_NODE) + write_int(data, self.kind) + write_bool(data, self.module_hidden) + write_bool(data, self.module_public) + write_bool(data, self.implicit) + write_bool(data, self.plugin_generated) + + cross_ref = None + if isinstance(self.node, MypyFile): + cross_ref = self.node.fullname + else: + assert self.node is not None, f"{prefix}:{name}" + if prefix is not None: + fullname = self.node.fullname + if ( + "." in fullname + and fullname != prefix + "." + name + and not (isinstance(self.node, Var) and self.node.from_module_getattr) + ): + assert not isinstance( + self.node, PlaceholderNode + ), f"Definition of {fullname} is unexpectedly incomplete" + cross_ref = fullname + + write_str_opt(data, cross_ref) + if cross_ref is None: + assert self.node is not None + self.node.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> SymbolTableNode: + assert read_tag(data) == SYMBOL_TABLE_NODE + sym = SymbolTableNode(read_int(data), None) + sym.module_hidden = read_bool(data) + sym.module_public = read_bool(data) + sym.implicit = read_bool(data) + sym.plugin_generated = read_bool(data) + cross_ref = read_str_opt(data) + if cross_ref is None: + sym.node = read_symbol(data) + else: + sym.cross_ref = cross_ref + assert read_tag(data) == END_TAG + return sym + + +class SymbolTable(dict[str, SymbolTableNode]): + """Static representation of a namespace dictionary. + + This is used for module, class and function namespaces. + """ + + __slots__ = () + + def __str__(self) -> str: + a: list[str] = [] + for key, value in self.items(): + # Filter out the implicit import of builtins. + if isinstance(value, SymbolTableNode): + if ( + value.fullname != "builtins" + and (value.fullname or "").split(".")[-1] not in implicit_module_attrs + ): + a.append(" " + str(key) + " : " + str(value)) + else: + # Used in debugging: + a.append(" ") # type: ignore[unreachable] + a = sorted(a) + a.insert(0, "SymbolTable(") + a[-1] += ")" + return "\n".join(a) + + def copy(self) -> SymbolTable: + return SymbolTable([(key, node.copy()) for key, node in self.items()]) + + def serialize(self, fullname: str) -> JsonDict: + data: JsonDict = {".class": "SymbolTable"} + for key, value in self.items(): + # Skip __builtins__: it's a reference to the builtins + # module that gets added to every module by + # SemanticAnalyzerPass2.visit_file(), but it shouldn't be + # accessed by users of the module. + if key == "__builtins__" or value.no_serialize: + continue + data[key] = value.serialize(fullname, key) + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> SymbolTable: + assert data[".class"] == "SymbolTable" + st = SymbolTable() + for key, value in data.items(): + if key != ".class": + st[key] = SymbolTableNode.deserialize(value) + return st + + def write(self, data: WriteBuffer, fullname: str) -> None: + size = 0 + for key, value in self.items(): + # Skip __builtins__: it's a reference to the builtins + # module that gets added to every module by + # SemanticAnalyzerPass2.visit_file(), but it shouldn't be + # accessed by users of the module. + if key == "__builtins__" or value.no_serialize: + continue + size += 1 + # We intentionally tag SymbolTable as a simple dictionary str -> SymbolTableNode. + write_tag(data, DICT_STR_GEN) + write_int_bare(data, size) + for key in sorted(self): + value = self[key] + if key == "__builtins__" or value.no_serialize: + continue + write_str_bare(data, key) + value.write(data, fullname, key) + + @classmethod + def read(cls, data: ReadBuffer) -> SymbolTable: + assert read_tag(data) == DICT_STR_GEN + size = read_int_bare(data) + return SymbolTable( + [(read_str_bare(data), SymbolTableNode.read(data)) for _ in range(size)] + ) + + +class DataclassTransformSpec: + """Specifies how a dataclass-like transform should be applied. The fields here are based on the + parameters accepted by `typing.dataclass_transform`.""" + + __slots__ = ( + "eq_default", + "order_default", + "kw_only_default", + "frozen_default", + "field_specifiers", + ) + + def __init__( + self, + *, + eq_default: bool | None = None, + order_default: bool | None = None, + kw_only_default: bool | None = None, + field_specifiers: tuple[str, ...] | None = None, + # Specified outside of PEP 681: + # frozen_default was added to CPythonin https://github.com/python/cpython/pull/99958 citing + # positive discussion in typing-sig + frozen_default: bool | None = None, + ) -> None: + self.eq_default = eq_default if eq_default is not None else True + self.order_default = order_default if order_default is not None else False + self.kw_only_default = kw_only_default if kw_only_default is not None else False + self.frozen_default = frozen_default if frozen_default is not None else False + self.field_specifiers = field_specifiers if field_specifiers is not None else () + + def serialize(self) -> JsonDict: + return { + "eq_default": self.eq_default, + "order_default": self.order_default, + "kw_only_default": self.kw_only_default, + "frozen_default": self.frozen_default, + "field_specifiers": list(self.field_specifiers), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> DataclassTransformSpec: + return DataclassTransformSpec( + eq_default=data.get("eq_default"), + order_default=data.get("order_default"), + kw_only_default=data.get("kw_only_default"), + frozen_default=data.get("frozen_default"), + field_specifiers=tuple(data.get("field_specifiers", [])), + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, DT_SPEC) + write_bool(data, self.eq_default) + write_bool(data, self.order_default) + write_bool(data, self.kw_only_default) + write_bool(data, self.frozen_default) + write_str_list(data, self.field_specifiers) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> DataclassTransformSpec: + ret = DataclassTransformSpec( + eq_default=read_bool(data), + order_default=read_bool(data), + kw_only_default=read_bool(data), + frozen_default=read_bool(data), + field_specifiers=tuple(read_str_list(data)), + ) + assert read_tag(data) == END_TAG + return ret + + +@trait +class SplittingVisitor: + # If True, process function definitions. If False, don't. This is used + # for processing module top levels in fine-grained incremental mode. + recurse_into_functions: bool + + @contextmanager + def set_recurse_into_functions(self) -> Iterator[None]: + """Temporarily set recurse_into_functions to True. + + This is used to process top-level functions/methods as a whole. + """ + old_recurse_into_functions = self.recurse_into_functions + self.recurse_into_functions = True + try: + yield + finally: + self.recurse_into_functions = old_recurse_into_functions + + +def get_flags(node: Node, names: list[str]) -> list[str]: + return [name for name in names if getattr(node, name)] + + +def set_flags(node: Node, flags: list[str]) -> None: + for name in flags: + setattr(node, name, True) + + +def write_flags(data: WriteBuffer, flags: list[bool]) -> None: + assert len(flags) <= 26, "This many flags not supported yet" + packed = 0 + for i, flag in enumerate(flags): + if flag: + packed |= 1 << i + write_int(data, packed) + + +def read_flags(data: ReadBuffer, num_flags: int) -> list[bool]: + packed = read_int(data) + return [(packed & (1 << i)) != 0 for i in range(num_flags)] + + +def get_member_expr_fullname(expr: MemberExpr) -> str | None: + """Return the qualified name representation of a member expression. + + Return a string of form foo.bar, foo.bar.baz, or similar, or None if the + argument cannot be represented in this form. + """ + initial: str | None = None + if isinstance(expr.expr, NameExpr): + initial = expr.expr.name + elif isinstance(expr.expr, MemberExpr): + initial = get_member_expr_fullname(expr.expr) + if initial is None: + return None + return f"{initial}.{expr.name}" + + +deserialize_map: Final = { + key: obj.deserialize + for key, obj in globals().items() + if type(obj) is not FakeInfo + and isinstance(obj, type) + and issubclass(obj, SymbolNode) + and obj is not SymbolNode +} + + +def check_arg_kinds( + arg_kinds: list[ArgKind], nodes: list[T], fail: Callable[[str, T], None] +) -> None: + is_var_arg = False + is_kw_arg = False + seen_named = False + seen_opt = False + for kind, node in zip(arg_kinds, nodes): + if kind == ARG_POS: + if is_var_arg or is_kw_arg or seen_named or seen_opt: + fail( + "Required positional args may not appear after default, named or var args", + node, + ) + break + elif kind == ARG_OPT: + if is_var_arg or is_kw_arg or seen_named: + fail("Positional default args may not appear after named or var args", node) + break + seen_opt = True + elif kind == ARG_STAR: + if is_var_arg or is_kw_arg or seen_named: + fail("Var args may not appear after named or var args", node) + break + is_var_arg = True + elif kind == ARG_NAMED or kind == ARG_NAMED_OPT: + seen_named = True + if is_kw_arg: + fail("A **kwargs argument must be the last argument", node) + break + elif kind == ARG_STAR2: + if is_kw_arg: + fail("You may only have one **kwargs argument", node) + break + is_kw_arg = True + + +def check_param_names( + names: Sequence[str | None], + nodes: list[T], + fail: Callable[[str, T], None], + description: str = "function definition", +) -> None: + seen_names: set[str | None] = set() + for name, node in zip(names, nodes): + if name is not None and name in seen_names: + fail(f'Duplicate parameter "{name}" in {description}', node) + break + seen_names.add(name) + + +def is_class_var(expr: NameExpr) -> bool: + """Return whether the expression is ClassVar[...]""" + if isinstance(expr.node, Var): + return expr.node.is_classvar + return False + + +def is_final_node(node: SymbolNode | None) -> bool: + """Check whether `node` corresponds to a final attribute.""" + return isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)) and node.is_final + + +def get_func_def(typ: mypy.types.CallableType) -> SymbolNode | None: + definition = typ.definition + if isinstance(definition, Decorator): + definition = definition.func + return definition + + +def local_definitions( + names: SymbolTable, name_prefix: str, info: TypeInfo | None = None +) -> Iterator[Definition]: + """Iterate over local definitions (not imported) in a symbol table. + + Recursively iterate over class members and nested classes. + """ + # TODO: What should the name be? Or maybe remove it? + for name, symnode in names.items(): + shortname = name + if "-redef" in name: + # Restore original name from mangled name of multiply defined function + shortname = name.split("-redef")[0] + fullname = name_prefix + "." + shortname + node = symnode.node + if node and node.fullname == fullname: + yield fullname, symnode, info + if isinstance(node, TypeInfo): + yield from local_definitions(node.names, fullname, node) + + +# See docstring for mypy/cache.py for reserved tag ranges. +MYPY_FILE: Final[Tag] = 50 +OVERLOADED_FUNC_DEF: Final[Tag] = 51 +FUNC_DEF: Final[Tag] = 52 +DECORATOR: Final[Tag] = 53 +VAR: Final[Tag] = 54 +TYPE_VAR_EXPR: Final[Tag] = 55 +PARAM_SPEC_EXPR: Final[Tag] = 56 +TYPE_VAR_TUPLE_EXPR: Final[Tag] = 57 +TYPE_INFO: Final[Tag] = 58 +TYPE_ALIAS: Final[Tag] = 59 +CLASS_DEF: Final[Tag] = 60 +SYMBOL_TABLE_NODE: Final[Tag] = 61 + +EXPR_STMT: Final[Tag] = 160 +CALL_EXPR: Final[Tag] = 161 +NAME_EXPR: Final[Tag] = 162 +STR_EXPR: Final[Tag] = 163 +IMPORT: Final[Tag] = 164 +MEMBER_EXPR: Final[Tag] = 165 +OP_EXPR: Final[Tag] = 166 +INT_EXPR: Final[Tag] = 167 +IF_STMT: Final[Tag] = 168 +ASSIGNMENT_STMT: Final[Tag] = 169 +TUPLE_EXPR: Final[Tag] = 170 +BLOCK: Final[Tag] = 171 +INDEX_EXPR: Final[Tag] = 172 +LIST_EXPR: Final[Tag] = 173 +SET_EXPR: Final[Tag] = 174 +RETURN_STMT: Final[Tag] = 175 +WHILE_STMT: Final[Tag] = 176 +COMPARISON_EXPR: Final[Tag] = 177 +BOOL_OP_EXPR: Final[Tag] = 178 +FUNC_DEF_STMT: Final[Tag] = 179 +PASS_STMT: Final[Tag] = 180 +FLOAT_EXPR: Final[Tag] = 181 +UNARY_EXPR: Final[Tag] = 182 +DICT_EXPR: Final[Tag] = 183 +COMPLEX_EXPR: Final[Tag] = 184 +SLICE_EXPR: Final[Tag] = 185 +TEMP_NODE: Final[Tag] = 186 +RAISE_STMT: Final[Tag] = 187 +BREAK_STMT: Final[Tag] = 188 +CONTINUE_STMT: Final[Tag] = 189 +GENERATOR_EXPR: Final[Tag] = 190 +YIELD_EXPR: Final[Tag] = 191 +YIELD_FROM_EXPR: Final[Tag] = 192 +LIST_COMPREHENSION: Final[Tag] = 193 +SET_COMPREHENSION: Final[Tag] = 194 +DICT_COMPREHENSION: Final[Tag] = 195 +IMPORT_FROM: Final[Tag] = 196 +ASSERT_STMT: Final[Tag] = 197 +FOR_STMT: Final[Tag] = 198 +WITH_STMT: Final[Tag] = 199 +OPERATOR_ASSIGNMENT_STMT: Final[Tag] = 200 +TRY_STMT: Final[Tag] = 201 +ELLIPSIS_EXPR: Final[Tag] = 202 +CONDITIONAL_EXPR: Final[Tag] = 203 +DEL_STMT: Final[Tag] = 204 +FSTRING_EXPR: Final[Tag] = 205 +FSTRING_INTERPOLATION: Final[Tag] = 206 +LAMBDA_EXPR: Final[Tag] = 207 +NAMED_EXPR: Final[Tag] = 208 +STAR_EXPR: Final[Tag] = 209 +BYTES_EXPR: Final[Tag] = 210 +GLOBAL_DECL: Final[Tag] = 211 +NONLOCAL_DECL: Final[Tag] = 212 +AWAIT_EXPR: Final[Tag] = 213 +BIG_INT_EXPR: Final[Tag] = 214 +IMPORT_ALL: Final[Tag] = 215 +MATCH_STMT: Final[Tag] = 216 +AS_PATTERN: Final[Tag] = 217 +OR_PATTERN: Final[Tag] = 218 +VALUE_PATTERN: Final[Tag] = 219 +SINGLETON_PATTERN: Final[Tag] = 220 +SEQUENCE_PATTERN: Final[Tag] = 221 +STARRED_PATTERN: Final[Tag] = 222 +MAPPING_PATTERN: Final[Tag] = 223 +CLASS_PATTERN: Final[Tag] = 224 +TYPE_ALIAS_STMT: Final[Tag] = 225 +IMPORT_METADATA: Final[Tag] = 226 +IMPORTFROM_METADATA: Final[Tag] = 227 +IMPORTALL_METADATA: Final[Tag] = 228 +TSTRING_EXPR: Final[Tag] = 229 + + +def read_symbol(data: ReadBuffer) -> SymbolNode: + tag = read_tag(data) + # The branches here are ordered manually by type "popularity". + if tag == VAR: + return Var.read(data) + if tag == FUNC_DEF: + return FuncDef.read(data) + if tag == DECORATOR: + return Decorator.read(data) + if tag == TYPE_INFO: + return TypeInfo.read(data) + if tag == OVERLOADED_FUNC_DEF: + return OverloadedFuncDef.read(data) + if tag == TYPE_VAR_EXPR: + return TypeVarExpr.read(data) + if tag == TYPE_ALIAS: + return TypeAlias.read(data) + if tag == PARAM_SPEC_EXPR: + return ParamSpecExpr.read(data) + if tag == TYPE_VAR_TUPLE_EXPR: + return TypeVarTupleExpr.read(data) + assert False, f"Unknown symbol tag {tag}" + + +def read_overload_part(data: ReadBuffer, tag: Tag | None = None) -> OverloadPart: + if tag is None: + tag = read_tag(data) + if tag == DECORATOR: + return Decorator.read(data) + if tag == FUNC_DEF: + return FuncDef.read(data) + assert False, f"Invalid tag for an OverloadPart {tag}" diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/operators.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/operators.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f74a8cbd3256b9ecae37bdd983e71a3dc13892ae Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/operators.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/operators.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/operators.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f050b58faeb5171c54b7de8b4cf5fc97b9bf6e --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/operators.py @@ -0,0 +1,126 @@ +"""Information about Python operators""" + +from __future__ import annotations + +from typing import Final + +# Map from binary operator id to related method name (in Python 3). +op_methods: Final = { + "+": "__add__", + "-": "__sub__", + "*": "__mul__", + "/": "__truediv__", + "%": "__mod__", + "divmod": "__divmod__", + "//": "__floordiv__", + "**": "__pow__", + "@": "__matmul__", + "&": "__and__", + "|": "__or__", + "^": "__xor__", + "<<": "__lshift__", + ">>": "__rshift__", + "==": "__eq__", + "!=": "__ne__", + "<": "__lt__", + ">=": "__ge__", + ">": "__gt__", + "<=": "__le__", + "in": "__contains__", +} + +op_methods_to_symbols: Final = {v: k for (k, v) in op_methods.items()} + +ops_falling_back_to_cmp: Final = {"__ne__", "__eq__", "__lt__", "__le__", "__gt__", "__ge__"} + + +ops_with_inplace_method: Final = { + "+", + "-", + "*", + "/", + "%", + "//", + "**", + "@", + "&", + "|", + "^", + "<<", + ">>", +} + +inplace_operator_methods: Final = {"__i" + op_methods[op][2:] for op in ops_with_inplace_method} + +reverse_op_methods: Final = { + "__add__": "__radd__", + "__sub__": "__rsub__", + "__mul__": "__rmul__", + "__truediv__": "__rtruediv__", + "__mod__": "__rmod__", + "__divmod__": "__rdivmod__", + "__floordiv__": "__rfloordiv__", + "__pow__": "__rpow__", + "__matmul__": "__rmatmul__", + "__and__": "__rand__", + "__or__": "__ror__", + "__xor__": "__rxor__", + "__lshift__": "__rlshift__", + "__rshift__": "__rrshift__", + "__eq__": "__eq__", + "__ne__": "__ne__", + "__lt__": "__gt__", + "__ge__": "__le__", + "__gt__": "__lt__", + "__le__": "__ge__", +} + +reverse_op_method_names: Final = set(reverse_op_methods.values()) + +# Suppose we have some class A. When we do A() + A(), Python will only check +# the output of A().__add__(A()) and skip calling the __radd__ method entirely. +# This shortcut is used only for the following methods: +op_methods_that_shortcut: Final = { + "__add__", + "__sub__", + "__mul__", + "__truediv__", + "__mod__", + "__divmod__", + "__floordiv__", + "__pow__", + "__matmul__", + "__and__", + "__or__", + "__xor__", + "__lshift__", + "__rshift__", +} + +normal_from_reverse_op: Final = {m: n for n, m in reverse_op_methods.items()} +reverse_op_method_set: Final = set(reverse_op_methods.values()) + +unary_op_methods: Final = {"-": "__neg__", "+": "__pos__", "~": "__invert__"} + +int_op_to_method: Final = { + "==": int.__eq__, + "is": int.__eq__, + "<": int.__lt__, + "<=": int.__le__, + "!=": int.__ne__, + "is not": int.__ne__, + ">": int.__gt__, + ">=": int.__ge__, +} + +flip_ops: Final = {"<": ">", "<=": ">=", ">": "<", ">=": "<="} +neg_ops: Final = { + "==": "!=", + "!=": "==", + "is": "is not", + "is not": "is", + "<": ">=", + "<=": ">", + ">": "<=", + ">=": "<", +} diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/options.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/options.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..32dfc376a27860c144c76715b525c25d2434156d Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/options.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/options.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/options.py new file mode 100644 index 0000000000000000000000000000000000000000..79ca75c58be6fb3440038278292db37f26bc370d --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/options.py @@ -0,0 +1,651 @@ +from __future__ import annotations + +import pprint +import re +import sys +import sysconfig +from collections.abc import Callable +from re import Pattern +from typing import Any, Final + +from librt.internal import WriteBuffer, write_bool, write_str + +from mypy import defaults +from mypy.errorcodes import ErrorCode, error_codes +from mypy.util import get_class_descriptors, replace_object_state + + +class BuildType: + STANDARD: Final = 0 + MODULE: Final = 1 + PROGRAM_TEXT: Final = 2 + + +PER_MODULE_OPTIONS: Final = { + # Please keep this list sorted + "allow_redefinition_old", + "allow_redefinition_new", + "allow_untyped_globals", + "always_false", + "always_true", + "check_untyped_defs", + "debug_cache", + "disable_error_code", + "disabled_error_codes", + "disallow_any_decorated", + "disallow_any_explicit", + "disallow_any_expr", + "disallow_any_generics", + "disallow_any_unimported", + "disallow_incomplete_defs", + "disallow_subclassing_any", + "disallow_untyped_calls", + "disallow_untyped_decorators", + "disallow_untyped_defs", + "enable_error_code", + "enabled_error_codes", + "extra_checks", + "follow_imports_for_stubs", + "follow_imports", + "follow_untyped_imports", + "ignore_errors", + "ignore_missing_imports", + "implicit_optional", + "implicit_reexport", + "local_partial_types", + "mypyc", + "strict_concatenate", + "strict_equality", + "strict_equality_for_none", + "strict_optional", + "warn_no_return", + "warn_return_any", + "warn_unreachable", + "warn_unused_ignores", +} + +OPTIONS_AFFECTING_CACHE: Final = ( + PER_MODULE_OPTIONS + | { + "platform", + "bazel", + "native_parser", + "old_type_inference", + "plugins", + "disable_bytearray_promotion", + "disable_memoryview_promotion", + "strict_bytes", + "fixed_format_cache", + "untyped_calls_exclude", + "enable_incomplete_feature", + } +) - {"debug_cache"} + +# OPTIONS_AFFECTING_CACHE without "platform", as a sorted tuple for fast iteration. +# "platform" is handled separately in options_snapshot(). +OPTIONS_AFFECTING_CACHE_NO_PLATFORM: Final = tuple(sorted(OPTIONS_AFFECTING_CACHE - {"platform"})) + +# Features that are currently (or were recently) incomplete/experimental +TYPE_VAR_TUPLE: Final = "TypeVarTuple" +UNPACK: Final = "Unpack" +PRECISE_TUPLE_TYPES: Final = "PreciseTupleTypes" +NEW_GENERIC_SYNTAX: Final = "NewGenericSyntax" +INLINE_TYPEDDICT: Final = "InlineTypedDict" +TYPE_FORM: Final = "TypeForm" +INCOMPLETE_FEATURES: Final = frozenset((PRECISE_TUPLE_TYPES, INLINE_TYPEDDICT, TYPE_FORM)) +COMPLETE_FEATURES: Final = frozenset((TYPE_VAR_TUPLE, UNPACK, NEW_GENERIC_SYNTAX)) + + +class Options: + """Options collected from flags.""" + + def __init__(self) -> None: + # Cache for clone_for_module() + self._per_module_cache: dict[str, Options] | None = None + + # -- build options -- + self.build_type = BuildType.STANDARD + self.python_version: tuple[int, int] = sys.version_info[:2] + # The executable used to search for PEP 561 packages. If this is None, + # then mypy does not search for PEP 561 packages. + self.python_executable: str | None = sys.executable + + # When cross compiling to emscripten, we need to rely on MACHDEP because + # sys.platform is the host build platform, not emscripten. + MACHDEP = sysconfig.get_config_var("MACHDEP") + if MACHDEP == "emscripten": + self.platform = MACHDEP + else: + self.platform = sys.platform + + self.custom_typing_module: str | None = None + self.custom_typeshed_dir: str | None = None + # The abspath() version of the above, we compute it once as an optimization. + self.abs_custom_typeshed_dir: str | None = None + self.mypy_path: list[str] = [] + self.report_dirs: dict[str, str] = {} + # Show errors in PEP 561 packages/site-packages modules + self.no_silence_site_packages = False + self.no_site_packages = False + self.ignore_missing_imports = False + # Is ignore_missing_imports set in a per-module section + self.ignore_missing_imports_per_module = False + # Typecheck modules without stubs or py.typed marker + self.follow_untyped_imports = False + self.follow_imports = "normal" # normal|silent|skip|error + # Whether to respect the follow_imports setting even for stub files. + # Intended to be used for disabling specific stubs. + self.follow_imports_for_stubs = False + # PEP 420 namespace packages + # This allows definitions of packages without __init__.py and allows packages to span + # multiple directories. This flag affects both import discovery and the association of + # input files/modules/packages to the relevant file and fully qualified module name. + self.namespace_packages = True + # Use current directory and MYPYPATH to determine fully qualified module names of files + # passed by automatically considering their subdirectories as packages. This is only + # relevant if namespace packages are enabled, since otherwise examining __init__.py's is + # sufficient to determine module names for files. As a possible alternative, add a single + # top-level __init__.py to your packages. + self.explicit_package_bases = False + # File names, directory names or subpaths to avoid checking + self.exclude: list[str] = [] + self.exclude_gitignore: bool = False + + # disallow_any options + self.disallow_any_generics = False + self.disallow_any_unimported = False + self.disallow_any_expr = False + self.disallow_any_decorated = False + self.disallow_any_explicit = False + + # Disallow calling untyped functions from typed ones + self.disallow_untyped_calls = False + + # Always allow untyped calls for function coming from modules/packages + # in this list (each item effectively acts as a prefix match) + self.untyped_calls_exclude: list[str] = [] + + # Disallow defining untyped (or incompletely typed) functions + self.disallow_untyped_defs = False + + # Disallow defining incompletely typed functions + self.disallow_incomplete_defs = False + + # Type check unannotated functions + self.check_untyped_defs = False + + # Disallow decorating typed functions with untyped decorators + self.disallow_untyped_decorators = False + + # Disallow subclassing values of type 'Any' + self.disallow_subclassing_any = False + + # Also check typeshed for missing annotations + self.warn_incomplete_stub = False + + # Warn about casting an expression to its inferred type + self.warn_redundant_casts = False + + # Warn about falling off the end of a function returning non-None + self.warn_no_return = True + + # Warn about returning objects of type Any when the function is + # declared with a precise type + self.warn_return_any = False + + # Report importing or using deprecated features as errors instead of notes. + self.report_deprecated_as_note = False + + # Allow deprecated calls from function coming from modules/packages + # in this list (each item effectively acts as a prefix match) + self.deprecated_calls_exclude: list[str] = [] + + # Warn about unused '# type: ignore' comments + self.warn_unused_ignores = False + + # Warn about unused '[mypy-]' or '[[tool.mypy.overrides]]' config sections + self.warn_unused_configs = False + + # Files in which to ignore all non-fatal errors + self.ignore_errors = False + + # Apply strict None checking + self.strict_optional = True + + # Show "note: In function "foo":" messages. + self.show_error_context = False + + # Use nicer output (when possible). + self.color_output = True + self.error_summary = True + + # Assume arguments with default values of None are Optional + self.implicit_optional = False + + # Don't re-export names unless they are imported with `from ... as ...` + self.implicit_reexport = True + + # Suppress toplevel errors caused by missing annotations + self.allow_untyped_globals = False + + # Allow variable to be redefined with an arbitrary type in the same block + # and the same nesting level as the initialization + self.allow_redefinition_old = False + + # Allow flexible variable redefinition with an arbitrary type, in different + # blocks and at different nesting levels + self.allow_redefinition_new = False + + # Prohibit equality, identity, and container checks for non-overlapping types. + # This makes 1 == '1', 1 in ['1'], and 1 is '1' errors. + self.strict_equality = False + + # Extend the logic of `strict_equality` to comparisons with `None`. + self.strict_equality_for_none = False + + # Disable treating bytearray and memoryview as subtypes of bytes + self.strict_bytes = False + + # Deprecated, use extra_checks instead. + self.strict_concatenate = False + + # Enable additional checks that are technically correct but impractical. + self.extra_checks = False + + # Report an error for any branches inferred to be unreachable as a result of + # type analysis. + self.warn_unreachable = False + + # Variable names considered True + self.always_true: list[str] = [] + + # Variable names considered False + self.always_false: list[str] = [] + + # Error codes to disable + self.disable_error_code: list[str] = [] + self.disabled_error_codes: set[ErrorCode] = set() + + # Error codes to enable + self.enable_error_code: list[str] = [] + self.enabled_error_codes: set[ErrorCode] = set() + + # Use script name instead of __main__ + self.scripts_are_modules = False + + # Config file name + self.config_file: str | None = None + + # A filename containing a JSON mapping from filenames to + # mtime/size/hash arrays, used to avoid having to recalculate + # source hashes as often. + self.quickstart_file: str | None = None + + # A comma-separated list of files/directories for mypy to type check; + # supports globbing + self.files: list[str] | None = None + + # A list of packages for mypy to type check + self.packages: list[str] | None = None + + # A list of modules for mypy to type check + self.modules: list[str] | None = None + + # Write junit.xml to given file + self.junit_xml: str | None = None + + self.junit_format: str = "global" # global|per_file + + # Caching and incremental checking options + self.incremental = True + self.cache_dir = defaults.CACHE_DIR + self.sqlite_cache = True + self.fixed_format_cache = True + self.debug_cache = False + self.skip_version_check = False + self.skip_cache_mtime_checks = False + self.fine_grained_incremental = False + # Include fine-grained dependencies in written cache files + self.cache_fine_grained = False + # Read cache files in fine-grained incremental mode (cache must include dependencies) + self.use_fine_grained_cache = False + + # Run tree.serialize() even if cache generation is disabled + self.debug_serialize = False + + # Tune certain behaviors when being used as a front-end to mypyc. Set per-module + # in modules being compiled. Not in the config file or command line. + self.mypyc = False + + # An internal flag to modify some type-checking logic while + # running inspections (e.g. don't expand function definitions). + # Not in the config file or command line. + self.inspections = False + + # Disable the memory optimization of freeing ASTs when + # possible. This isn't exposed as a command line option + # because it is intended for software integrating with + # mypy. (Like mypyc.) + self.preserve_asts = False + + # If True, function and class docstrings will be extracted and retained. + # This isn't exposed as a command line option + # because it is intended for software integrating with + # mypy. (Like stubgen.) + self.include_docstrings = False + + # Paths of user plugins + self.plugins: list[str] = [] + + # Per-module options (raw) + self.per_module_options: dict[str, dict[str, object]] = {} + self._glob_options: list[tuple[str, Pattern[str]]] = [] + self.unused_configs: set[str] = set() + + # -- development options -- + self.verbosity = 0 # More verbose messages (for troubleshooting) + self.pdb = False + self.show_traceback = False + self.raise_exceptions = False + self.dump_type_stats = False + self.dump_inference_stats = False + self.dump_build_stats = False + self.enable_incomplete_feature: list[str] = [] + self.timing_stats: str | None = None + self.line_checking_stats: str | None = None + + # -- test options -- + # Stop after the semantic analysis phase + self.semantic_analysis_only = False + + # Use stub builtins fixtures to speed up tests + self.use_builtins_fixtures = False + + # This should only be set when running certain mypy tests. + # Use this sparingly to avoid tests diverging from non-test behavior. + self.test_env = False + + # -- experimental options -- + self.num_workers: int = 0 + self.shadow_file: list[list[str]] | None = None + self.show_column_numbers: bool = False + self.show_error_end: bool = False + self.hide_error_codes = False + self.show_error_code_links = False + # This is an internal-only flag to simplify migrating test output. + self.reveal_verbose_types = False + # Use soft word wrap and show trimmed source snippets with error location markers. + self.pretty = False + self.dump_graph = False + self.dump_deps = False + self.logical_deps = False + # If True, partial types can't span a module top level and a function + self.local_partial_types = False + # If True, use the native parser (experimental) + self.native_parser = False + # Some behaviors are changed when using Bazel (https://bazel.build). + self.bazel = False + # If True, export inferred types for all expressions as BuildResult.types + self.export_types = False + # List of package roots -- directories under these are packages even + # if they don't have __init__.py. + self.package_root: list[str] = [] + self.cache_map: dict[str, tuple[str, str]] = {} + # Don't properly free objects on exit, just kill the current process. + self.fast_exit = True + # fast path for finding modules from source set + self.fast_module_lookup = False + # Allow empty function bodies even if it is not safe, used for testing only. + self.allow_empty_bodies = False + # Used to transform source code before parsing if not None + # TODO: Make the type precise (AnyStr -> AnyStr) + self.transform_source: Callable[[Any], Any] | None = None + # Print full path to each file in the report. + self.show_absolute_path: bool = False + # Install missing stub packages if True + self.install_types = False + # Install missing stub packages in non-interactive mode (don't prompt for + # confirmation, and don't show any errors) + self.non_interactive = False + # When we encounter errors that may cause many additional errors, + # skip most errors after this many messages have been reported. + # -1 means unlimited. + self.many_errors_threshold = defaults.MANY_ERRORS_THRESHOLD + # Disable new type inference algorithm. + self.old_type_inference = False + # Disable expression cache (for debugging). + self.disable_expression_cache = False + # Export line-level, limited, fine-grained dependency information in cache data + # (undocumented feature). + self.export_ref_info = False + # Treat special methods as being implicitly positional-only. + # Set to False when running stubtest. + self.pos_only_special_methods = True + + self.disable_bytearray_promotion = False + self.disable_memoryview_promotion = False + + # Sets custom output format + self.output: str | None = None + + # Output html file for mypyc -a + self.mypyc_annotation_file: str | None = None + # Skip writing C output files, but perform all other steps of a build (allows + # preserving manual tweaks to generated C file) + self.mypyc_skip_c_generation = False + + def use_star_unpack(self) -> bool: + return self.python_version >= (3, 11) or not self.reveal_verbose_types + + def snapshot(self) -> dict[str, object]: + """Produce a comparable snapshot of this Option""" + # Under mypyc, we don't have a __dict__, so we need to do worse things. + d = dict(getattr(self, "__dict__", ())) + for k in get_class_descriptors(Options): + if hasattr(self, k): + d[k] = getattr(self, k) + # Remove private attributes from snapshot + d = {k: v for k, v in d.items() if not k.startswith("_")} + return d + + def __repr__(self) -> str: + return f"Options({pprint.pformat(self.snapshot())})" + + def process_error_codes(self, *, error_callback: Callable[[str], Any]) -> None: + """Process `--enable-error-code` and `--disable-error-code` flags.""" + disabled_code_names = set(self.disable_error_code) + enabled_code_names = set(self.enable_error_code) + + valid_error_code_names = set(error_codes.keys()) + + invalid_code_names_here = ( + enabled_code_names | disabled_code_names + ) - valid_error_code_names + if invalid_code_names_here: + error_callback(f"Invalid error code(s): {', '.join(sorted(invalid_code_names_here))}") + + self.disabled_error_codes |= {error_codes[code] for code in disabled_code_names} + self.enabled_error_codes |= {error_codes[code] for code in enabled_code_names} + + # Enabling an error code always overrides disabling + self.disabled_error_codes -= self.enabled_error_codes + + def process_incomplete_features( + self, *, error_callback: Callable[[str], Any], warning_callback: Callable[[str], Any] + ) -> None: + # Validate incomplete features. + for feature in self.enable_incomplete_feature: + if feature not in INCOMPLETE_FEATURES | COMPLETE_FEATURES: + error_callback(f"Unknown incomplete feature: {feature}") + if feature in COMPLETE_FEATURES: + warning_callback(f"Warning: {feature} is already enabled by default") + + def process_strict_bytes(self) -> None: + # Sync `--strict-bytes` and `--disable-{bytearray,memoryview}-promotion` + if self.strict_bytes: + # backwards compatibility + self.disable_bytearray_promotion = True + self.disable_memoryview_promotion = True + elif self.disable_bytearray_promotion and self.disable_memoryview_promotion: + # forwards compatibility + self.strict_bytes = True + + def apply_changes(self, changes: dict[str, object]) -> Options: + # Note: effects of this method *must* be idempotent. + new_options = Options() + # Under mypyc, we don't have a __dict__, so we need to do worse things. + replace_object_state(new_options, self, copy_dict=True) + for key, value in changes.items(): + setattr(new_options, key, value) + if changes.get("ignore_missing_imports"): + # This is the only option for which a per-module and a global + # option sometimes beheave differently. + new_options.ignore_missing_imports_per_module = True + + # These two act as overrides, so apply them when cloning. + # Similar to global codes enabling overrides disabling, so we start from latter. + new_options.disabled_error_codes = self.disabled_error_codes.copy() + new_options.enabled_error_codes = self.enabled_error_codes.copy() + for code_str in new_options.disable_error_code: + code = error_codes[code_str] + new_options.disabled_error_codes.add(code) + new_options.enabled_error_codes.discard(code) + for code_str in new_options.enable_error_code: + code = error_codes[code_str] + new_options.enabled_error_codes.add(code) + new_options.disabled_error_codes.discard(code) + return new_options + + def compare_stable(self, other_snapshot: dict[str, object]) -> bool: + """Compare options in a way that is stable for snapshot() -> apply_changes() roundtrip. + + This is needed because apply_changes() has non-trivial effects for some flags, so + Options().apply_changes(options.snapshot()) may result in a (slightly) different object. + """ + return ( + Options().apply_changes(self.snapshot()).snapshot() + == Options().apply_changes(other_snapshot).snapshot() + ) + + def build_per_module_cache(self) -> None: + self._per_module_cache = {} + + # Config precedence is as follows: + # 1. Concrete section names: foo.bar.baz + # 2. "Unstructured" glob patterns: foo.*.baz, in the order + # they appear in the file (last wins) + # 3. "Well-structured" wildcard patterns: foo.bar.*, in specificity order. + + # Since structured configs inherit from structured configs above them in the hierarchy, + # we need to process per-module configs in a careful order. + # We have to process foo.* before foo.bar.* before foo.bar, + # and we need to apply *.bar to foo.bar but not to foo.bar.*. + # To do this, process all well-structured glob configs before non-glob configs and + # exploit the fact that foo.* sorts earlier ASCIIbetically (unicodebetically?) + # than foo.bar.*. + # (A section being "processed last" results in its config "winning".) + # Unstructured glob configs are stored and are all checked for each module. + unstructured_glob_keys = [k for k in self.per_module_options.keys() if "*" in k[:-1]] + structured_keys = [k for k in self.per_module_options.keys() if "*" not in k[:-1]] + wildcards = sorted(k for k in structured_keys if k.endswith(".*")) + concrete = [k for k in structured_keys if not k.endswith(".*")] + + for glob in unstructured_glob_keys: + self._glob_options.append((glob, self.compile_glob(glob))) + + # We (for ease of implementation) treat unstructured glob + # sections as used if any real modules use them or if any + # concrete config sections use them. This means we need to + # track which get used while constructing. + self.unused_configs = set(unstructured_glob_keys) + + for key in wildcards + concrete: + # Find what the options for this key would be, just based + # on inheriting from parent configs. + options = self.clone_for_module(key) + # And then update it with its per-module options. + self._per_module_cache[key] = options.apply_changes(self.per_module_options[key]) + + # Add the more structured sections into unused configs, since + # they only count as used if actually used by a real module. + self.unused_configs.update(structured_keys) + + def clone_for_module(self, module: str) -> Options: + """Create an Options object that incorporates per-module options. + + NOTE: Once this method is called all Options objects should be + considered read-only, else the caching might be incorrect. + """ + if self._per_module_cache is None: + self.build_per_module_cache() + assert self._per_module_cache is not None + + # If the module just directly has a config entry, use it. + if module in self._per_module_cache: + self.unused_configs.discard(module) + return self._per_module_cache[module] + + # If not, search for glob paths at all the parents. So if we are looking for + # options for foo.bar.baz, we search foo.bar.baz.*, foo.bar.*, foo.*, + # in that order, looking for an entry. + # This is technically quadratic in the length of the path, but module paths + # don't actually get all that long. + options = self + path = module.split(".") + for i in range(len(path), 0, -1): + key = ".".join(path[:i] + ["*"]) + if key in self._per_module_cache: + self.unused_configs.discard(key) + options = self._per_module_cache[key] + break + + # OK and *now* we need to look for unstructured glob matches. + # We only do this for concrete modules, not structured wildcards. + if not module.endswith(".*"): + for key, pattern in self._glob_options: + if pattern.match(module): + self.unused_configs.discard(key) + options = options.apply_changes(self.per_module_options[key]) + + # We could update the cache to directly point to modules once + # they have been looked up, but in testing this made things + # slower and not faster, so we don't bother. + + return options + + def compile_glob(self, s: str) -> Pattern[str]: + # Compile one of the glob patterns to a regex so that '.*' can + # match *zero or more* module sections. This means we compile + # '.*' into '(\..*)?'. + parts = s.split(".") + expr = re.escape(parts[0]) if parts[0] != "*" else ".*" + for part in parts[1:]: + expr += re.escape("." + part) if part != "*" else r"(\..*)?" + return re.compile(expr + "\\Z") + + def select_options_affecting_cache(self) -> tuple[str, list[object]]: + """Return (platform, [values...]) for options that affect the cache. + + The list contains values for OPTIONS_AFFECTING_CACHE_NO_PLATFORM + in sorted attribute name order. Keys are omitted since the cache + is invalidated when the mypy version changes, and keys are constant + on any specific mypy version. + """ + result: list[object] = [] + for opt in OPTIONS_AFFECTING_CACHE_NO_PLATFORM: + val = getattr(self, opt) + if opt in ("disabled_error_codes", "enabled_error_codes"): + val = sorted([code.code for code in val]) + result.append(val) + return self.platform, result + + def dep_import_options(self) -> bytes: + """Return opaque bytes with options that can affect dependent modules as well. + + The value can be compared for equality to detect changed options. + """ + buf = WriteBuffer() + write_bool(buf, self.ignore_missing_imports) + write_str(buf, self.follow_imports) + write_bool(buf, self.follow_imports_for_stubs) + return buf.getvalue() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/parse.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/parse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..718249e1b815d0e930065e816565b81f8e4ae8c2 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/parse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/parse.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..093653553137fb315250b1450916b8413d305555 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/parse.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import os +import re + +from librt.internal import ReadBuffer + +from mypy import errorcodes as codes +from mypy.cache import read_int +from mypy.errors import Errors +from mypy.nodes import FileRawData, MypyFile +from mypy.options import Options + + +def parse( + source: str | bytes, + fnam: str, + module: str | None, + errors: Errors, + options: Options, + raise_on_error: bool = False, + imports_only: bool = False, +) -> MypyFile: + """Parse a source file, without doing any semantic analysis. + + Return the parse tree. If errors is not provided, raise ParseError + on failure. Otherwise, use the errors object to report parse errors. + + The python_version (major, minor) option determines the Python syntax variant. + """ + if options.native_parser: + # Native parser only works with actual files on disk + # Fall back to fastparse for in-memory source or non-existent files + if os.path.exists(fnam): + import mypy.nativeparse + + ignore_errors = options.ignore_errors or fnam in errors.ignored_files + # If errors are ignored, we can drop many function bodies to speed up type checking. + strip_function_bodies = ignore_errors and not options.preserve_asts + + errors.set_file(fnam, module, options=options) + tree, parse_errors, type_ignores = mypy.nativeparse.native_parse( + fnam, + options, + skip_function_bodies=strip_function_bodies, + imports_only=imports_only, + ) + # Convert type ignores list to dict + tree.ignored_lines = dict(type_ignores) + # Set is_stub based on file extension + tree.is_stub = fnam.endswith(".pyi") + # Note: tree.imports is populated directly by native_parse with deserialized + # import metadata, so we don't need to collect imports via AST traversal + + # Report parse errors + for error in parse_errors: + message = error["message"] + # Standardize error message by capitalizing the first word + message = re.sub(r"^(\s*\w)", lambda m: m.group(1).upper(), message) + # Respect blocker status from error, default to True for syntax errors + is_blocker = error.get("blocker", True) + error_code = error.get("code") + if error_code is None: + error_code = codes.SYNTAX + else: + # Fallback to [syntax] for backwards compatibility. + error_code = codes.error_codes.get(error_code) or codes.SYNTAX + errors.report( + error["line"], error["column"], message, blocker=is_blocker, code=error_code + ) + if raise_on_error and errors.is_errors(): + errors.raise_error() + return tree + # Fall through to fastparse for non-existent files + + assert not imports_only + if options.transform_source is not None: + source = options.transform_source(source) + import mypy.fastparse + + tree = mypy.fastparse.parse(source, fnam=fnam, module=module, errors=errors, options=options) + if raise_on_error and errors.is_errors(): + errors.raise_error() + return tree + + +def load_from_raw( + fnam: str, module: str | None, raw_data: FileRawData, errors: Errors, options: Options +) -> MypyFile: + """Load AST from parsed binary data. + + This essentially replicates parse() above but expects FileRawData instead of actually + parsing the source code in the file. + """ + from mypy.nativeparse import State, deserialize_imports, read_statements + + # This part mimics the logic in native_parse(). + data = ReadBuffer(raw_data.defs) + n = read_int(data) + state = State(options) + defs = read_statements(state, data, n) + imports = deserialize_imports(raw_data.imports) + + tree = MypyFile(defs, imports) + tree.path = fnam + tree.ignored_lines = raw_data.ignored_lines + tree.is_partial_stub_package = raw_data.is_partial_stub_package + tree.uses_template_strings = raw_data.uses_template_strings + tree.is_stub = fnam.endswith(".pyi") + + # Report parse errors, this replicates the logic in parse(). + all_errors = raw_data.raw_errors + state.errors + errors.set_file(fnam, module, options=options) + for error in all_errors: + message = error["message"] + message = re.sub(r"^(\s*\w)", lambda m: m.group(1).upper(), message) + is_blocker = error.get("blocker", True) + error_code = error.get("code") + if error_code is None: + error_code = codes.SYNTAX + else: + error_code = codes.error_codes.get(error_code) or codes.SYNTAX + # Note we never raise in this function, so it should not be called in coordinator. + errors.report(error["line"], error["column"], message, blocker=is_blocker, code=error_code) + return tree diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/partially_defined.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/partially_defined.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..26a7e601ed5d3e220d830deafc9325e96e68bbbc Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/partially_defined.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/partially_defined.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/partially_defined.py new file mode 100644 index 0000000000000000000000000000000000000000..2bff1669becbb5928efe70cf4cb9f7ef5c6ba4a5 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/partially_defined.py @@ -0,0 +1,703 @@ +from __future__ import annotations + +from enum import Enum + +from mypy import checker, errorcodes +from mypy.messages import MessageBuilder +from mypy.nodes import ( + AssertStmt, + AssignmentExpr, + AssignmentStmt, + BreakStmt, + ClassDef, + Context, + ContinueStmt, + DictionaryComprehension, + Expression, + ExpressionStmt, + ForStmt, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportFrom, + LambdaExpr, + ListExpr, + Lvalue, + MatchStmt, + MypyFile, + NameExpr, + NonlocalDecl, + RaiseStmt, + ReturnStmt, + StarExpr, + SymbolTable, + TryStmt, + TupleExpr, + TypeAliasStmt, + WhileStmt, + WithStmt, + implicit_module_attrs, +) +from mypy.options import Options +from mypy.patterns import AsPattern, StarredPattern +from mypy.reachability import ALWAYS_TRUE, infer_pattern_value +from mypy.traverser import ExtendedTraverserVisitor +from mypy.types import Type, UninhabitedType, get_proper_type + + +class BranchState: + """BranchState contains information about variable definition at the end of a branching statement. + `if` and `match` are examples of branching statements. + + `may_be_defined` contains variables that were defined in only some branches. + `must_be_defined` contains variables that were defined in all branches. + """ + + def __init__( + self, + must_be_defined: set[str] | None = None, + may_be_defined: set[str] | None = None, + skipped: bool = False, + ) -> None: + if may_be_defined is None: + may_be_defined = set() + if must_be_defined is None: + must_be_defined = set() + + self.may_be_defined = set(may_be_defined) + self.must_be_defined = set(must_be_defined) + self.skipped = skipped + + def copy(self) -> BranchState: + return BranchState( + must_be_defined=set(self.must_be_defined), + may_be_defined=set(self.may_be_defined), + skipped=self.skipped, + ) + + +class BranchStatement: + def __init__(self, initial_state: BranchState | None = None) -> None: + if initial_state is None: + initial_state = BranchState() + self.initial_state = initial_state + self.branches: list[BranchState] = [ + BranchState( + must_be_defined=self.initial_state.must_be_defined, + may_be_defined=self.initial_state.may_be_defined, + ) + ] + + def copy(self) -> BranchStatement: + result = BranchStatement(self.initial_state) + result.branches = [b.copy() for b in self.branches] + return result + + def next_branch(self) -> None: + self.branches.append( + BranchState( + must_be_defined=self.initial_state.must_be_defined, + may_be_defined=self.initial_state.may_be_defined, + ) + ) + + def record_definition(self, name: str) -> None: + assert len(self.branches) > 0 + self.branches[-1].must_be_defined.add(name) + self.branches[-1].may_be_defined.discard(name) + + def delete_var(self, name: str) -> None: + assert len(self.branches) > 0 + self.branches[-1].must_be_defined.discard(name) + self.branches[-1].may_be_defined.discard(name) + + def record_nested_branch(self, state: BranchState) -> None: + assert len(self.branches) > 0 + current_branch = self.branches[-1] + if state.skipped: + current_branch.skipped = True + return + current_branch.must_be_defined.update(state.must_be_defined) + current_branch.may_be_defined.update(state.may_be_defined) + current_branch.may_be_defined.difference_update(current_branch.must_be_defined) + + def skip_branch(self) -> None: + assert len(self.branches) > 0 + self.branches[-1].skipped = True + + def is_possibly_undefined(self, name: str) -> bool: + assert len(self.branches) > 0 + return name in self.branches[-1].may_be_defined + + def is_undefined(self, name: str) -> bool: + assert len(self.branches) > 0 + branch = self.branches[-1] + return name not in branch.may_be_defined and name not in branch.must_be_defined + + def is_defined_in_a_branch(self, name: str) -> bool: + assert len(self.branches) > 0 + for b in self.branches: + if name in b.must_be_defined or name in b.may_be_defined: + return True + return False + + def done(self) -> BranchState: + # First, compute all vars, including skipped branches. We include skipped branches + # because our goal is to capture all variables that semantic analyzer would + # consider defined. + all_vars = set() + for b in self.branches: + all_vars.update(b.may_be_defined) + all_vars.update(b.must_be_defined) + # For the rest of the things, we only care about branches that weren't skipped. + non_skipped_branches = [b for b in self.branches if not b.skipped] + if non_skipped_branches: + must_be_defined = non_skipped_branches[0].must_be_defined + for b in non_skipped_branches[1:]: + must_be_defined.intersection_update(b.must_be_defined) + else: + must_be_defined = set() + # Everything that wasn't defined in all branches but was defined + # in at least one branch should be in `may_be_defined`! + may_be_defined = all_vars.difference(must_be_defined) + return BranchState( + must_be_defined=must_be_defined, + may_be_defined=may_be_defined, + skipped=len(non_skipped_branches) == 0, + ) + + +class ScopeType(Enum): + Global = 1 + Class = 2 + Func = 3 + Generator = 4 + + +class Scope: + def __init__(self, stmts: list[BranchStatement], scope_type: ScopeType) -> None: + self.branch_stmts: list[BranchStatement] = stmts + self.scope_type = scope_type + self.undefined_refs: dict[str, set[NameExpr]] = {} + + def copy(self) -> Scope: + result = Scope([s.copy() for s in self.branch_stmts], self.scope_type) + result.undefined_refs = self.undefined_refs.copy() + return result + + def record_undefined_ref(self, o: NameExpr) -> None: + if o.name not in self.undefined_refs: + self.undefined_refs[o.name] = set() + self.undefined_refs[o.name].add(o) + + def pop_undefined_ref(self, name: str) -> set[NameExpr]: + return self.undefined_refs.pop(name, set()) + + +class DefinedVariableTracker: + """DefinedVariableTracker manages the state and scope for the UndefinedVariablesVisitor.""" + + def __init__(self) -> None: + # There's always at least one scope. Within each scope, there's at least one "global" BranchingStatement. + self.scopes: list[Scope] = [Scope([BranchStatement()], ScopeType.Global)] + # disable_branch_skip is used to disable skipping a branch due to a return/raise/etc. This is useful + # in things like try/except/finally statements. + self.disable_branch_skip = False + self.in_finally = False + + def copy(self) -> DefinedVariableTracker: + result = DefinedVariableTracker() + result.scopes = [s.copy() for s in self.scopes] + result.disable_branch_skip = self.disable_branch_skip + result.in_finally = self.in_finally + return result + + def _scope(self) -> Scope: + assert len(self.scopes) > 0 + return self.scopes[-1] + + def enter_scope(self, scope_type: ScopeType) -> None: + assert len(self._scope().branch_stmts) > 0 + initial_state = None + if scope_type == ScopeType.Generator: + # Generators are special because they inherit the outer scope. + initial_state = self._scope().branch_stmts[-1].branches[-1] + self.scopes.append(Scope([BranchStatement(initial_state)], scope_type)) + + def exit_scope(self) -> None: + self.scopes.pop() + + def in_scope(self, scope_type: ScopeType) -> bool: + return self._scope().scope_type == scope_type + + def start_branch_statement(self) -> None: + assert len(self._scope().branch_stmts) > 0 + self._scope().branch_stmts.append( + BranchStatement(self._scope().branch_stmts[-1].branches[-1]) + ) + + def next_branch(self) -> None: + assert len(self._scope().branch_stmts) > 1 + self._scope().branch_stmts[-1].next_branch() + + def end_branch_statement(self) -> None: + assert len(self._scope().branch_stmts) > 1 + result = self._scope().branch_stmts.pop().done() + self._scope().branch_stmts[-1].record_nested_branch(result) + + def skip_branch(self) -> None: + # Only skip branch if we're outside of "root" branch statement. + if len(self._scope().branch_stmts) > 1 and not self.disable_branch_skip: + self._scope().branch_stmts[-1].skip_branch() + + def record_definition(self, name: str) -> None: + assert len(self.scopes) > 0 + assert len(self.scopes[-1].branch_stmts) > 0 + self._scope().branch_stmts[-1].record_definition(name) + + def delete_var(self, name: str) -> None: + assert len(self.scopes) > 0 + assert len(self.scopes[-1].branch_stmts) > 0 + self._scope().branch_stmts[-1].delete_var(name) + + def record_undefined_ref(self, o: NameExpr) -> None: + """Records an undefined reference. These can later be retrieved via `pop_undefined_ref`.""" + assert len(self.scopes) > 0 + self._scope().record_undefined_ref(o) + + def pop_undefined_ref(self, name: str) -> set[NameExpr]: + """If name has previously been reported as undefined, the NameExpr that was called will be returned.""" + assert len(self.scopes) > 0 + return self._scope().pop_undefined_ref(name) + + def is_possibly_undefined(self, name: str) -> bool: + assert len(self._scope().branch_stmts) > 0 + # A variable is undefined if it's in a set of `may_be_defined` but not in `must_be_defined`. + return self._scope().branch_stmts[-1].is_possibly_undefined(name) + + def is_defined_in_different_branch(self, name: str) -> bool: + """This will return true if a variable is defined in a branch that's not the current branch.""" + assert len(self._scope().branch_stmts) > 0 + stmt = self._scope().branch_stmts[-1] + if not stmt.is_undefined(name): + return False + for stmt in self._scope().branch_stmts: + if stmt.is_defined_in_a_branch(name): + return True + return False + + def is_undefined(self, name: str) -> bool: + assert len(self._scope().branch_stmts) > 0 + return self._scope().branch_stmts[-1].is_undefined(name) + + +class Loop: + def __init__(self) -> None: + self.has_break = False + # variables defined in every loop branch with `break` + self.break_vars: set[str] | None = None + + +class PossiblyUndefinedVariableVisitor(ExtendedTraverserVisitor): + """Detects the following cases: + - A variable that's defined only part of the time. + - If a variable is used before definition + + An example of a partial definition: + if foo(): + x = 1 + print(x) # Error: "x" may be undefined. + + Example of a used before definition: + x = y + y: int = 2 + + Note that this code does not detect variables not defined in any of the branches -- that is + handled by the semantic analyzer. + """ + + def __init__( + self, + msg: MessageBuilder, + type_map: dict[Expression, Type], + options: Options, + names: SymbolTable, + ) -> None: + self.msg = msg + self.type_map = type_map + self.options = options + self.builtins = SymbolTable() + builtins_mod = names.get("__builtins__", None) + if builtins_mod: + assert isinstance(builtins_mod.node, MypyFile) + self.builtins = builtins_mod.node.names + self.loops: list[Loop] = [] + self.try_depth = 0 + self.tracker = DefinedVariableTracker() + for name in implicit_module_attrs: + self.tracker.record_definition(name) + + def var_used_before_def(self, name: str, context: Context) -> None: + if self.msg.errors.is_error_code_enabled(errorcodes.USED_BEFORE_DEF): + self.msg.var_used_before_def(name, context) + + def variable_may_be_undefined(self, name: str, context: Context) -> None: + if self.msg.errors.is_error_code_enabled(errorcodes.POSSIBLY_UNDEFINED): + self.msg.variable_may_be_undefined(name, context) + + def process_definition(self, name: str) -> None: + # Was this name previously used? If yes, it's a used-before-definition error. + if not self.tracker.in_scope(ScopeType.Class): + refs = self.tracker.pop_undefined_ref(name) + for ref in refs: + if self.loops: + self.variable_may_be_undefined(name, ref) + else: + self.var_used_before_def(name, ref) + else: + # Errors in class scopes are caught by the semantic analyzer. + pass + self.tracker.record_definition(name) + + def visit_global_decl(self, o: GlobalDecl) -> None: + for name in o.names: + self.process_definition(name) + super().visit_global_decl(o) + + def visit_nonlocal_decl(self, o: NonlocalDecl) -> None: + for name in o.names: + self.process_definition(name) + super().visit_nonlocal_decl(o) + + def process_lvalue(self, lvalue: Lvalue | None) -> None: + if isinstance(lvalue, NameExpr): + self.process_definition(lvalue.name) + elif isinstance(lvalue, StarExpr): + self.process_lvalue(lvalue.expr) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + for item in lvalue.items: + self.process_lvalue(item) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + for lvalue in o.lvalues: + self.process_lvalue(lvalue) + super().visit_assignment_stmt(o) + + def visit_assignment_expr(self, o: AssignmentExpr) -> None: + o.value.accept(self) + self.process_lvalue(o.target) + + def visit_if_stmt(self, o: IfStmt) -> None: + for e in o.expr: + e.accept(self) + self.tracker.start_branch_statement() + for b in o.body: + if b.is_unreachable: + continue + b.accept(self) + self.tracker.next_branch() + if o.unreachable_else: + self.tracker.skip_branch() + elif o.else_body: + if o.else_body.is_unreachable: + self.tracker.skip_branch() + else: + o.else_body.accept(self) + self.tracker.end_branch_statement() + + def visit_match_stmt(self, o: MatchStmt) -> None: + o.subject.accept(self) + self.tracker.start_branch_statement() + for i in range(len(o.patterns)): + pattern = o.patterns[i] + pattern.accept(self) + guard = o.guards[i] + if guard is not None: + guard.accept(self) + if not o.bodies[i].is_unreachable: + o.bodies[i].accept(self) + else: + self.tracker.skip_branch() + is_catchall = infer_pattern_value(pattern) == ALWAYS_TRUE + if not is_catchall: + self.tracker.next_branch() + self.tracker.end_branch_statement() + + def visit_func_def(self, o: FuncDef) -> None: + self.process_definition(o.name) + super().visit_func_def(o) + + def visit_func(self, o: FuncItem) -> None: + if o.is_dynamic() and not self.options.check_untyped_defs: + return + + args = o.arguments or [] + # Process initializers (defaults) outside the function scope. + for arg in args: + if arg.initializer is not None: + arg.initializer.accept(self) + + self.tracker.enter_scope(ScopeType.Func) + for arg in args: + self.process_definition(arg.variable.name) + super().visit_var(arg.variable) + o.body.accept(self) + self.tracker.exit_scope() + + def visit_generator_expr(self, o: GeneratorExpr) -> None: + self.tracker.enter_scope(ScopeType.Generator) + for idx in o.indices: + self.process_lvalue(idx) + super().visit_generator_expr(o) + self.tracker.exit_scope() + + def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> None: + self.tracker.enter_scope(ScopeType.Generator) + for idx in o.indices: + self.process_lvalue(idx) + super().visit_dictionary_comprehension(o) + self.tracker.exit_scope() + + def visit_for_stmt(self, o: ForStmt) -> None: + o.expr.accept(self) + self.process_lvalue(o.index) + o.index.accept(self) + self.tracker.start_branch_statement() + loop = Loop() + self.loops.append(loop) + o.body.accept(self) + self.tracker.next_branch() + self.tracker.end_branch_statement() + if o.else_body is not None: + # If the loop has a `break` inside, `else` is executed conditionally. + # If the loop doesn't have a `break` either the function will return or + # execute the `else`. + has_break = loop.has_break + if has_break: + self.tracker.start_branch_statement() + if loop.break_vars is not None: + for bv in loop.break_vars: + self.tracker.record_definition(bv) + self.tracker.next_branch() + o.else_body.accept(self) + if has_break: + self.tracker.end_branch_statement() + self.loops.pop() + + def visit_return_stmt(self, o: ReturnStmt) -> None: + super().visit_return_stmt(o) + self.tracker.skip_branch() + + def visit_lambda_expr(self, o: LambdaExpr) -> None: + self.tracker.enter_scope(ScopeType.Func) + super().visit_lambda_expr(o) + self.tracker.exit_scope() + + def visit_assert_stmt(self, o: AssertStmt) -> None: + super().visit_assert_stmt(o) + if checker.is_false_literal(o.expr): + self.tracker.skip_branch() + + def visit_raise_stmt(self, o: RaiseStmt) -> None: + super().visit_raise_stmt(o) + self.tracker.skip_branch() + + def visit_continue_stmt(self, o: ContinueStmt) -> None: + super().visit_continue_stmt(o) + self.tracker.skip_branch() + + def visit_break_stmt(self, o: BreakStmt) -> None: + super().visit_break_stmt(o) + if self.loops: + self.loops[-1].has_break = True + # Track variables that are definitely defined at the point of break + if len(self.tracker._scope().branch_stmts) > 0: + branch = self.tracker._scope().branch_stmts[-1].branches[-1] + if self.loops[-1].break_vars is None: + self.loops[-1].break_vars = set(branch.must_be_defined) + else: + # we only want variables that have been defined in each branch + self.loops[-1].break_vars.intersection_update(branch.must_be_defined) + self.tracker.skip_branch() + + def visit_expression_stmt(self, o: ExpressionStmt) -> None: + typ = self.type_map.get(o.expr) + if typ is None or isinstance(get_proper_type(typ), UninhabitedType): + self.tracker.skip_branch() + super().visit_expression_stmt(o) + + def visit_try_stmt(self, o: TryStmt) -> None: + """ + Note that finding undefined vars in `finally` requires different handling from + the rest of the code. In particular, we want to disallow skipping branches due to jump + statements in except/else clauses for finally but not for other cases. Imagine a case like: + def f() -> int: + try: + x = 1 + except: + # This jump statement needs to be handled differently depending on whether or + # not we're trying to process `finally` or not. + return 0 + finally: + # `x` may be undefined here. + pass + # `x` is always defined here. + return x + """ + self.try_depth += 1 + if o.finally_body is not None: + # In order to find undefined vars in `finally`, we need to + # process try/except with branch skipping disabled. However, for the rest of the code + # after finally, we need to process try/except with branch skipping enabled. + # Therefore, we need to process try/finally twice. + # Because processing is not idempotent, we should make a copy of the tracker. + old_tracker = self.tracker.copy() + self.tracker.disable_branch_skip = True + self.process_try_stmt(o) + self.tracker = old_tracker + self.process_try_stmt(o) + self.try_depth -= 1 + + def process_try_stmt(self, o: TryStmt) -> None: + """ + Processes try statement decomposing it into the following: + if ...: + body + else_body + elif ...: + except 1 + elif ...: + except 2 + else: + except n + finally + """ + self.tracker.start_branch_statement() + o.body.accept(self) + if o.else_body is not None: + o.else_body.accept(self) + if len(o.handlers) > 0: + assert len(o.handlers) == len(o.vars) == len(o.types) + for i in range(len(o.handlers)): + self.tracker.next_branch() + exc_type = o.types[i] + if exc_type is not None: + exc_type.accept(self) + var = o.vars[i] + if var is not None: + self.process_definition(var.name) + var.accept(self) + o.handlers[i].accept(self) + if var is not None: + self.tracker.delete_var(var.name) + self.tracker.end_branch_statement() + + if o.finally_body is not None: + self.tracker.in_finally = True + o.finally_body.accept(self) + self.tracker.in_finally = False + + def visit_while_stmt(self, o: WhileStmt) -> None: + o.expr.accept(self) + self.tracker.start_branch_statement() + loop = Loop() + self.loops.append(loop) + o.body.accept(self) + has_break = loop.has_break + if not checker.is_true_literal(o.expr): + # If this is a loop like `while True`, we can consider the body to be + # a single branch statement (we're guaranteed that the body is executed at least once). + # If not, call next_branch() to make all variables defined there conditional. + self.tracker.next_branch() + self.tracker.end_branch_statement() + if o.else_body is not None: + # If the loop has a `break` inside, `else` is executed conditionally. + # If the loop doesn't have a `break` either the function will return or + # execute the `else`. + if has_break: + self.tracker.start_branch_statement() + self.tracker.next_branch() + if o.else_body: + o.else_body.accept(self) + if has_break: + self.tracker.end_branch_statement() + self.loops.pop() + + def visit_as_pattern(self, o: AsPattern) -> None: + if o.name is not None: + self.process_lvalue(o.name) + super().visit_as_pattern(o) + + def visit_starred_pattern(self, o: StarredPattern) -> None: + if o.capture is not None: + self.process_lvalue(o.capture) + super().visit_starred_pattern(o) + + def visit_name_expr(self, o: NameExpr) -> None: + if o.name in self.builtins and self.tracker.in_scope(ScopeType.Global): + return + if ( + self.tracker.is_possibly_undefined(o.name) + and self.tracker.in_finally == self.tracker.disable_branch_skip + ): + # A variable is only defined in some branches. + self.variable_may_be_undefined(o.name, o) + # We don't want to report the error on the same variable multiple times. + self.tracker.record_definition(o.name) + elif self.tracker.is_defined_in_different_branch(o.name): + # A variable is defined in one branch but used in a different branch. + if self.loops or self.try_depth > 0: + # If we're in a loop or in a try, we can't be sure that this variable + # is undefined. Report it as "may be undefined". + self.variable_may_be_undefined(o.name, o) + else: + self.var_used_before_def(o.name, o) + elif self.tracker.is_undefined(o.name): + # A variable is undefined. It could be due to two things: + # 1. A variable is just totally undefined + # 2. The variable is defined later in the code. + # Case (1) will be caught by semantic analyzer. Case (2) is a forward ref that should + # be caught by this visitor. Save the ref for later, so that if we see a definition, + # we know it's a used-before-definition scenario. + self.tracker.record_undefined_ref(o) + super().visit_name_expr(o) + + def visit_with_stmt(self, o: WithStmt) -> None: + for expr, idx in zip(o.expr, o.target): + expr.accept(self) + self.process_lvalue(idx) + o.body.accept(self) + + def visit_class_def(self, o: ClassDef) -> None: + self.process_definition(o.name) + self.tracker.enter_scope(ScopeType.Class) + super().visit_class_def(o) + self.tracker.exit_scope() + + def visit_import(self, o: Import) -> None: + for mod, alias in o.ids: + if alias is not None: + self.tracker.record_definition(alias) + else: + # When you do `import x.y`, only `x` becomes defined. + names = mod.split(".") + if names: + # `names` should always be nonempty, but we don't want mypy + # to crash on invalid code. + self.tracker.record_definition(names[0]) + super().visit_import(o) + + def visit_import_from(self, o: ImportFrom) -> None: + for mod, alias in o.names: + name = alias + if name is None: + name = mod + self.tracker.record_definition(name) + super().visit_import_from(o) + + def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: + # Type alias target may contain forward references + self.tracker.record_definition(o.name.name) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/patterns.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/patterns.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0c7fa1a4e9bf5b43f3a0221908b384676e109052 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/patterns.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/patterns.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..a01bf6acc87669fb1c9a990437c8209f193d2eae --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/patterns.py @@ -0,0 +1,150 @@ +"""Classes for representing match statement patterns.""" + +from __future__ import annotations + +from typing import TypeVar + +from mypy_extensions import trait + +from mypy.nodes import Expression, NameExpr, Node, RefExpr +from mypy.visitor import PatternVisitor + +T = TypeVar("T") + + +@trait +class Pattern(Node): + """A pattern node.""" + + __slots__ = () + + def accept(self, visitor: PatternVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +class AsPattern(Pattern): + """The pattern as """ + + # The python ast, and therefore also our ast merges capture, wildcard and as patterns into one + # for easier handling. + # If pattern is None this is a capture pattern. If name and pattern are both none this is a + # wildcard pattern. + # Only name being None should not happen but also won't break anything. + pattern: Pattern | None + name: NameExpr | None + + def __init__(self, pattern: Pattern | None, name: NameExpr | None) -> None: + super().__init__() + self.pattern = pattern + self.name = name + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_as_pattern(self) + + +class OrPattern(Pattern): + """The pattern | | ...""" + + patterns: list[Pattern] + + def __init__(self, patterns: list[Pattern]) -> None: + super().__init__() + self.patterns = patterns + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_or_pattern(self) + + +class ValuePattern(Pattern): + """The pattern x.y (or x.y.z, ...)""" + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_value_pattern(self) + + +class SingletonPattern(Pattern): + # This can be exactly True, False or None + value: bool | None + + def __init__(self, value: bool | None) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_singleton_pattern(self) + + +class SequencePattern(Pattern): + """The pattern [, ...]""" + + patterns: list[Pattern] + + def __init__(self, patterns: list[Pattern]) -> None: + super().__init__() + self.patterns = patterns + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_sequence_pattern(self) + + +class StarredPattern(Pattern): + # None corresponds to *_ in a list pattern. It will match multiple items but won't bind them to + # a name. + capture: NameExpr | None + + def __init__(self, capture: NameExpr | None) -> None: + super().__init__() + self.capture = capture + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_starred_pattern(self) + + +class MappingPattern(Pattern): + keys: list[Expression] + values: list[Pattern] + rest: NameExpr | None + + def __init__( + self, keys: list[Expression], values: list[Pattern], rest: NameExpr | None + ) -> None: + super().__init__() + assert len(keys) == len(values) + self.keys = keys + self.values = values + self.rest = rest + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_mapping_pattern(self) + + +class ClassPattern(Pattern): + """The pattern Cls(...)""" + + class_ref: RefExpr + positionals: list[Pattern] + keyword_keys: list[str] + keyword_values: list[Pattern] + + def __init__( + self, + class_ref: RefExpr, + positionals: list[Pattern], + keyword_keys: list[str], + keyword_values: list[Pattern], + ) -> None: + super().__init__() + assert len(keyword_keys) == len(keyword_values) + self.class_ref = class_ref + self.positionals = positionals + self.keyword_keys = keyword_keys + self.keyword_values = keyword_values + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_class_pattern(self) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/plugin.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/plugin.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..de9839bafd04786d9509294791c0ddabce73ae83 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/plugin.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/plugin.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..383b07af87c0dbb313caf55efcb76c443318d290 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/plugin.py @@ -0,0 +1,928 @@ +"""Plugin system for extending mypy. + +At large scale the plugin system works as following: + +* Plugins are collected from the corresponding mypy config file option + (either via paths to Python files, or installed Python modules) + and imported using importlib. + +* Every module should get an entry point function (called 'plugin' by default, + but may be overridden in the config file) that should accept a single string + argument that is a full mypy version (includes git commit hash for dev + versions) and return a subclass of mypy.plugins.Plugin. + +* All plugin class constructors should match the signature of mypy.plugin.Plugin + (i.e. should accept an mypy.options.Options object), and *must* call + super().__init__(). + +* At several steps during semantic analysis and type checking mypy calls + special `get_xxx` methods on user plugins with a single string argument that + is a fully qualified name (full name) of a relevant definition + (see mypy.plugin.Plugin method docstrings for details). + +* The plugins are called in the order they are passed in the config option. + Every plugin must decide whether to act on a given full name. The first + plugin that returns non-None object will be used. + +* The above decision should be made using the limited common API specified by + mypy.plugin.CommonPluginApi. + +* The callback returned by the plugin will be called with a larger context that + includes relevant current state (e.g. a default return type, or a default + attribute type) and a wider relevant API provider (e.g. + SemanticAnalyzerPluginInterface or CheckerPluginInterface). + +* The result of this is used for further processing. See various `XxxContext` + named tuples for details about which information is given to each hook. + +Plugin developers should ensure that their plugins work well in incremental and +daemon modes. In particular, plugins should not hold global state, and should +always call add_plugin_dependency() in plugin hooks called during semantic +analysis. See the method docstring for more details. + +There is no dedicated cache storage for plugins, but plugins can store +per-TypeInfo data in a special .metadata attribute that is serialized to the +mypy caches between incremental runs. To avoid collisions between plugins, they +are encouraged to store their state under a dedicated key coinciding with +plugin name in the metadata dictionary. Every value stored there must be +JSON-serializable. + +## Notes about the semantic analyzer + +Mypy 0.710 introduced a new semantic analyzer that changed how plugins are +expected to work in several notable ways (from mypy 0.730 the old semantic +analyzer is no longer available): + +1. The order of processing AST nodes in modules is different. The old semantic + analyzer processed modules in textual order, one module at a time. The new + semantic analyzer first processes the module top levels, including bodies of + any top-level classes and classes nested within classes. ("Top-level" here + means "not nested within a function/method".) Functions and methods are + processed only after module top levels have been finished. If there is an + import cycle, all module top levels in the cycle are processed before + processing any functions or methods. Each unit of processing (a module top + level or a function/method) is called a *target*. + + This also means that function signatures in the same module have not been + analyzed yet when analyzing the module top level. If you need access to + a function signature, you'll need to explicitly analyze the signature first + using `anal_type()`. + +2. Each target can be processed multiple times. This may happen if some forward + references are not ready yet, for example. This means that semantic analyzer + related plugin hooks can be called multiple times for the same full name. + These plugin methods must thus be idempotent. + +3. The `anal_type` API function returns None if some part of the type is not + available yet. If this happens, the current target being analyzed will be + *deferred*, which means that it will be processed again soon, in the hope + that additional dependencies will be available. This may happen if there are + forward references to types or inter-module references to types within an + import cycle. + + Note that if there is a circular definition, mypy may decide to stop + processing to avoid an infinite number of iterations. When this happens, + `anal_type` will generate an error and return an `AnyType` type object + during the final iteration (instead of None). + +4. There is a new API method `defer()`. This can be used to explicitly request + the current target to be reprocessed one more time. You don't need this + to call this if `anal_type` returns None, however. + +5. There is a new API property `final_iteration`, which is true once mypy + detected no progress during the previous iteration or if the maximum + semantic analysis iteration count has been reached. You must never + defer during the final iteration, as it will cause a crash. + +6. The `node` attribute of SymbolTableNode objects may contain a reference to + a PlaceholderNode object. This object means that this definition has not + been fully processed yet. If you encounter a PlaceholderNode, you should + defer unless it's the final iteration. If it's the final iteration, you + should generate an error message. It usually means that there's a cyclic + definition that cannot be resolved by mypy. PlaceholderNodes can only refer + to references inside an import cycle. If you are looking up things from + another module, such as the builtins, that is outside the current module or + import cycle, you can safely assume that you won't receive a placeholder. + +When testing your plugin, you should have a test case that forces a module top +level to be processed multiple times. The easiest way to do this is to include +a forward reference to a class in a top-level annotation. Example: + + c: C # Forward reference causes second analysis pass + class C: pass + +Note that a forward reference in a function signature won't trigger another +pass, since all functions are processed only after the top level has been fully +analyzed. +""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar + +from mypy_extensions import mypyc_attr, trait + +from mypy.errorcodes import ErrorCode +from mypy.errors import ErrorInfo +from mypy.lookup import lookup_fully_qualified +from mypy.message_registry import ErrorMessage +from mypy.nodes import ( + ArgKind, + CallExpr, + ClassDef, + Context, + Expression, + MypyFile, + SymbolTableNode, + TypeInfo, +) +from mypy.options import Options +from mypy.types import ( + CallableType, + FunctionLike, + Instance, + ProperType, + Type, + TypeList, + UnboundType, +) + +if TYPE_CHECKING: + from mypy.messages import MessageBuilder + from mypy.tvar_scope import TypeVarLikeScope + + +@trait +class TypeAnalyzerPluginInterface: + """Interface for accessing semantic analyzer functionality in plugins. + + Methods docstrings contain only basic info. Look for corresponding implementation + docstrings in typeanal.py for more details. + """ + + # An options object. Note: these are the cloned options for the current file. + # This might be different from Plugin.options (that contains default/global options) + # if there are per-file options in the config. This applies to all other interfaces + # in this file. + options: Options + + @abstractmethod + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + """Emit an error message at given location.""" + raise NotImplementedError + + @abstractmethod + def named_type(self, fullname: str, args: list[Type], /) -> Instance: + """Construct an instance of a builtin type with given name.""" + raise NotImplementedError + + @abstractmethod + def analyze_type(self, typ: Type, /) -> Type: + """Analyze an unbound type using the default mypy logic.""" + raise NotImplementedError + + @abstractmethod + def analyze_callable_args( + self, arglist: TypeList + ) -> tuple[list[Type], list[ArgKind], list[str | None]] | None: + """Find types, kinds, and names of arguments from extended callable syntax.""" + raise NotImplementedError + + +# A context for a hook that semantically analyzes an unbound type. +class AnalyzeTypeContext(NamedTuple): + type: UnboundType # Type to analyze + context: Context # Relevant location context (e.g. for error messages) + api: TypeAnalyzerPluginInterface + + +@mypyc_attr(allow_interpreted_subclasses=True) +class CommonPluginApi: + """ + A common plugin API (shared between semantic analysis and type checking phases) + that all plugin hooks get independently of the context. + """ + + # Global mypy options. + # Per-file options can be only accessed on various + # XxxPluginInterface classes. + options: Options + + @abstractmethod + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode | None: + """Lookup a symbol by its full name (including module). + + This lookup function available for all plugins. Return None if a name + is not found. This function doesn't support lookup from current scope. + Use SemanticAnalyzerPluginInterface.lookup_qualified() for this.""" + raise NotImplementedError + + +@trait +class CheckerPluginInterface: + """Interface for accessing type checker functionality in plugins. + + Methods docstrings contain only basic info. Look for corresponding implementation + docstrings in checker.py for more details. + """ + + msg: MessageBuilder + options: Options + path: str + + # Type context for type inference + @property + @abstractmethod + def type_context(self) -> list[Type | None]: + """Return the type context of the plugin""" + raise NotImplementedError + + @abstractmethod + def fail( + self, msg: str | ErrorMessage, ctx: Context, /, *, code: ErrorCode | None = None + ) -> ErrorInfo | None: + """Emit an error message at given location.""" + raise NotImplementedError + + @abstractmethod + def named_generic_type(self, name: str, args: list[Type]) -> Instance: + """Construct an instance of a generic type with given type arguments.""" + raise NotImplementedError + + @abstractmethod + def get_expression_type(self, node: Expression, type_context: Type | None = None) -> Type: + """Checks the type of the given expression.""" + raise NotImplementedError + + +@trait +class SemanticAnalyzerPluginInterface: + """Interface for accessing semantic analyzer functionality in plugins. + + Methods docstrings contain only basic info. Look for corresponding implementation + docstrings in semanal.py for more details. + + # TODO: clean-up lookup functions. + """ + + modules: dict[str, MypyFile] + # Options for current file. + options: Options + cur_mod_id: str + msg: MessageBuilder + + @abstractmethod + def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance: + """Construct an instance of a builtin type with given type arguments.""" + raise NotImplementedError + + @abstractmethod + def builtin_type(self, fully_qualified_name: str) -> Instance: + """Legacy function -- use named_type() instead.""" + # NOTE: Do not delete this since many plugins may still use it. + raise NotImplementedError + + @abstractmethod + def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None: + """Construct an instance of a type with given type arguments. + + Return None if a type could not be constructed for the qualified + type name. This is possible when the qualified name includes a + module name and the module has not been imported. + """ + raise NotImplementedError + + @abstractmethod + def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: + raise NotImplementedError + + @abstractmethod + def parse_bool(self, expr: Expression) -> bool | None: + """Parse True/False literals.""" + raise NotImplementedError + + @abstractmethod + def parse_str_literal(self, expr: Expression) -> str | None: + """Parse string literals.""" + + @abstractmethod + def fail( + self, + msg: str, + ctx: Context, + serious: bool = False, + *, + blocker: bool = False, + code: ErrorCode | None = None, + ) -> None: + """Emit an error message at given location.""" + raise NotImplementedError + + @abstractmethod + def anal_type( + self, + typ: Type, + /, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + report_invalid_types: bool = True, + ) -> Type | None: + """Analyze an unbound type. + + Return None if some part of the type is not ready yet. In this + case the current target being analyzed will be deferred and + analyzed again. + """ + raise NotImplementedError + + @abstractmethod + def class_type(self, self_type: Type) -> Type: + """Generate type of first argument of class methods from type of self.""" + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode: + """Lookup a symbol by its fully qualified name. + + Raise an error if not found. + """ + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None: + """Lookup a symbol by its fully qualified name. + + Return None if not found. + """ + raise NotImplementedError + + @abstractmethod + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + """Lookup symbol using a name in current scope. + + This follows Python local->non-local->global->builtins rules. + """ + raise NotImplementedError + + @abstractmethod + def add_plugin_dependency(self, trigger: str, target: str | None = None) -> None: + """Specify semantic dependencies for generated methods/variables. + + If the symbol with full name given by trigger is found to be stale by mypy, + then the body of node with full name given by target will be re-checked. + By default, this is the node that is currently analyzed. + + For example, the dataclass plugin adds a generated __init__ method with + a signature that depends on types of attributes in ancestor classes. If any + attribute in an ancestor class gets stale (modified), we need to reprocess + the subclasses (and thus regenerate __init__ methods). + + This is used by fine-grained incremental mode (mypy daemon). See mypy/server/deps.py + for more details. + """ + raise NotImplementedError + + @abstractmethod + def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> Any: + """Add node to global symbol table (or to nearest class if there is one).""" + raise NotImplementedError + + @abstractmethod + def qualified_name(self, name: str) -> str: + """Make qualified name using current module and enclosing class (if any).""" + raise NotImplementedError + + @abstractmethod + def defer(self) -> None: + """Call this to defer the processing of the current node. + + This will request an additional iteration of semantic analysis. + """ + raise NotImplementedError + + @property + @abstractmethod + def final_iteration(self) -> bool: + """Is this the final iteration of semantic analysis?""" + raise NotImplementedError + + @property + @abstractmethod + def is_stub_file(self) -> bool: + raise NotImplementedError + + @abstractmethod + def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type | None: + raise NotImplementedError + + +# A context for querying for configuration data about a module for +# cache invalidation purposes. +class ReportConfigContext(NamedTuple): + id: str # Module name + path: str # Module file path + is_check: bool # Is this invocation for checking whether the config matches + + +# A context for a function signature hook that infers a better signature for a +# function. Note that argument types aren't available yet. If you need them, +# you have to use a method hook instead. +class FunctionSigContext(NamedTuple): + args: list[list[Expression]] # Actual expressions for each formal argument + default_signature: CallableType # Original signature of the method + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a function hook that infers the return type of a function with +# a special signature. +# +# A no-op callback would just return the inferred return type, but a useful +# callback at least sometimes can infer a more precise type. +class FunctionContext(NamedTuple): + arg_types: list[list[Type]] # List of actual caller types for each formal argument + arg_kinds: list[list[ArgKind]] # Ditto for argument kinds, see nodes.ARG_* constants + # Names of formal parameters from the callee definition, + # these will be sufficient in most cases. + callee_arg_names: list[str | None] + # Names of actual arguments in the call expression. For example, + # in a situation like this: + # def func(**kwargs) -> None: + # pass + # func(kw1=1, kw2=2) + # callee_arg_names will be ['kwargs'] and arg_names will be [['kw1', 'kw2']]. + arg_names: list[list[str | None]] + default_return_type: Type # Return type inferred from signature + args: list[list[Expression]] # Actual expressions for each formal argument + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a method signature hook that infers a better signature for a +# method. Note that argument types aren't available yet. If you need them, +# you have to use a method hook instead. +# TODO: document ProperType in the plugin changelog/update issue. +class MethodSigContext(NamedTuple): + type: ProperType # Base object type for method call + args: list[list[Expression]] # Actual expressions for each formal argument + default_signature: CallableType # Original signature of the method + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a method hook that infers the return type of a method with a +# special signature. +# +# This is very similar to FunctionContext (only differences are documented). +class MethodContext(NamedTuple): + type: ProperType # Base object type for method call + arg_types: list[list[Type]] # List of actual caller types for each formal argument + # see FunctionContext for details about names and kinds + arg_kinds: list[list[ArgKind]] + callee_arg_names: list[str | None] + arg_names: list[list[str | None]] + default_return_type: Type # Return type inferred by mypy + args: list[list[Expression]] # Lists of actual expressions for every formal argument + context: Context + api: CheckerPluginInterface + + +# A context for an attribute type hook that infers the type of an attribute. +class AttributeContext(NamedTuple): + type: ProperType # Type of object with attribute + default_attr_type: Type # Original attribute type + is_lvalue: bool # Whether the attribute is the target of an assignment + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a class hook that modifies the class definition. +class ClassDefContext(NamedTuple): + cls: ClassDef # The class definition + reason: Expression # The expression being applied (decorator, metaclass, base class) + api: SemanticAnalyzerPluginInterface + + +# A context for dynamic class definitions like +# Base = declarative_base() +class DynamicClassDefContext(NamedTuple): + call: CallExpr # The r.h.s. of dynamic class definition + name: str # The name this class is being assigned to + api: SemanticAnalyzerPluginInterface + + +@mypyc_attr(allow_interpreted_subclasses=True) +class Plugin(CommonPluginApi): + """Base class of all type checker plugins. + + This defines a no-op plugin. Subclasses can override some methods to + provide some actual functionality. + + All get_ methods are treated as pure functions (you should assume that + results might be cached). A plugin should return None from a get_ method + to give way to other plugins. + + Look at the comments of various *Context objects for additional information on + various hooks. + """ + + def __init__(self, options: Options) -> None: + self.options = options + self.python_version = options.python_version + # This can't be set in __init__ because it is executed too soon in build.py. + # Therefore, build.py *must* set it later before graph processing starts + # by calling set_modules(). + self._modules: dict[str, MypyFile] | None = None + + def set_modules(self, modules: dict[str, MypyFile]) -> None: + self._modules = modules + + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode | None: + assert self._modules is not None + return lookup_fully_qualified(fullname, self._modules) + + def report_config_data(self, ctx: ReportConfigContext) -> Any: + """Get representation of configuration data for a module. + + The data must be encodable as JSON and will be stored in the + cache metadata for the module. A mismatch between the cached + values and the returned will result in that module's cache + being invalidated and the module being rechecked. + + This can be called twice for each module, once after loading + the cache to check if it is valid and once while writing new + cache information. + + If is_check in the context is true, then the return of this + call will be checked against the cached version. Otherwise the + call is being made to determine what to put in the cache. This + can be used to allow consulting extra cache files in certain + complex situations. + + This can be used to incorporate external configuration information + that might require changes to typechecking. + """ + return None + + def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: + """Customize dependencies for a module. + + This hook allows adding in new dependencies for a module. It + is called after parsing a file but before analysis. This can + be useful if a library has dependencies that are dynamic based + on configuration information, for example. + + Returns a list of (priority, module name, line number) tuples. + + The line number can be -1 when there is not a known real line number. + + Priorities are defined in mypy.build (but maybe shouldn't be). + 10 is a good choice for priority. + """ + return [] + + def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None: + """Customize behaviour of the type analyzer for given full names. + + This method is called during the semantic analysis pass whenever mypy sees an + unbound type. For example, while analysing this code: + + from lib import Special, Other + + var: Special + def func(x: Other[int]) -> None: + ... + + this method will be called with 'lib.Special', and then with 'lib.Other'. + The callback returned by plugin must return an analyzed type, + i.e. an instance of `mypy.types.Type`. + """ + return None + + def get_function_signature_hook( + self, fullname: str + ) -> Callable[[FunctionSigContext], FunctionLike] | None: + """Adjust the signature of a function. + + This method is called before type checking a function call. Plugin + may infer a better type for the function. + + from lib import Class, do_stuff + + do_stuff(42) + Class() + + This method will be called with 'lib.do_stuff' and then with 'lib.Class'. + """ + return None + + def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: + """Adjust the return type of a function call. + + This method is called after type checking a call. Plugin may adjust the return + type inferred by mypy, and/or emit some error messages. Note, this hook is also + called for class instantiation calls, so that in this example: + + from lib import Class, do_stuff + + do_stuff(42) + Class() + + This method will be called with 'lib.do_stuff' and then with 'lib.Class'. + """ + return None + + def get_method_signature_hook( + self, fullname: str + ) -> Callable[[MethodSigContext], FunctionLike] | None: + """Adjust the signature of a method. + + This method is called before type checking a method call. Plugin + may infer a better type for the method. The hook is also called for special + Python dunder methods except __init__ and __new__ (use get_function_hook to customize + class instantiation). This function is called with the method full name using + the class where it was _defined_. For example, in this code: + + from lib import Special + + class Base: + def method(self, arg: Any) -> Any: + ... + class Derived(Base): + ... + + var: Derived + var.method(42) + + x: Special + y = x[0] + + this method is called with '__main__.Base.method', and then with + 'lib.Special.__getitem__'. + """ + return None + + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: + """Adjust return type of a method call. + + This is the same as get_function_hook(), but is called with the + method full name (again, using the class where the method is defined). + """ + return None + + def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + """Adjust type of an instance attribute. + + This method is called with attribute full name using the class of the instance where + the attribute was defined (or Var.info.fullname for generated attributes). + + For classes without __getattr__ or __getattribute__, this hook is only called for + names of fields/properties (but not methods) that exist in the instance MRO. + + For classes that implement __getattr__ or __getattribute__, this hook is called + for all fields/properties, including nonexistent ones (but still not methods). + + For example: + + class Base: + x: Any + def __getattr__(self, attr: str) -> Any: ... + + class Derived(Base): + ... + + var: Derived + var.x + var.y + + get_attribute_hook is called with '__main__.Base.x' and '__main__.Base.y'. + However, if we had not implemented __getattr__ on Base, you would only get + the callback for 'var.x'; 'var.y' would produce an error without calling the hook. + """ + return None + + def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + """ + Adjust type of a class attribute. + + This method is called with attribute full name using the class where the attribute was + defined (or Var.info.fullname for generated attributes). + + For example: + + class Cls: + x: Any + + Cls.x + + get_class_attribute_hook is called with '__main__.Cls.x' as fullname. + """ + return None + + def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Update class definition for given class decorators. + + The plugin can modify a TypeInfo _in place_ (for example add some generated + methods to the symbol table). This hook is called after the class body was + semantically analyzed, but *there may still be placeholders* (typically + caused by forward references). + + NOTE: Usually get_class_decorator_hook_2 is the better option, since it + guarantees that there are no placeholders. + + The hook is called with full names of all class decorators. + + The hook can be called multiple times per class, so it must be + idempotent. + """ + return None + + def get_class_decorator_hook_2( + self, fullname: str + ) -> Callable[[ClassDefContext], bool] | None: + """Update class definition for given class decorators. + + Similar to get_class_decorator_hook, but this runs in a later pass when + placeholders have been resolved. + + The hook can return False if some base class hasn't been + processed yet using class hooks. It causes all class hooks + (that are run in this same pass) to be invoked another time for + the file(s) currently being processed. + + The hook can be called multiple times per class, so it must be + idempotent. + """ + return None + + def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Update class definition for given declared metaclasses. + + Same as get_class_decorator_hook() but for metaclasses. Note: + this hook will be only called for explicit metaclasses, not for + inherited ones. + + TODO: probably it should also be called on inherited metaclasses. + """ + return None + + def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Update class definition for given base classes. + + Same as get_class_decorator_hook() but for base classes. Base classes + don't need to refer to TypeInfos, if a base class refers to a variable with + Any type, this hook will still be called. + """ + return None + + def get_customize_class_mro_hook( + self, fullname: str + ) -> Callable[[ClassDefContext], None] | None: + """Customize MRO for given classes. + + The plugin can modify the class MRO _in place_. This method is called + with the class full name before its body was semantically analyzed. + """ + return None + + def get_dynamic_class_hook( + self, fullname: str + ) -> Callable[[DynamicClassDefContext], None] | None: + """Semantically analyze a dynamic class definition. + + This plugin hook allows one to semantically analyze dynamic class definitions like: + + from lib import dynamic_class + + X = dynamic_class('X', []) + + For such definition, this hook will be called with 'lib.dynamic_class'. + The plugin should create the corresponding TypeInfo, and place it into a relevant + symbol table, e.g. using ctx.api.add_symbol_table_node(). + """ + return None + + +T = TypeVar("T") + + +class ChainedPlugin(Plugin): + """A plugin that represents a sequence of chained plugins. + + Each lookup method returns the hook for the first plugin that + reports a match. + + This class should not be subclassed -- use Plugin as the base class + for all plugins. + """ + + # TODO: Support caching of lookup results (through a LRU cache, for example). + + def __init__(self, options: Options, plugins: list[Plugin]) -> None: + """Initialize chained plugin. + + Assume that the child plugins aren't mutated (results may be cached). + """ + super().__init__(options) + self._plugins = plugins + + def set_modules(self, modules: dict[str, MypyFile]) -> None: + for plugin in self._plugins: + plugin.set_modules(modules) + + def report_config_data(self, ctx: ReportConfigContext) -> Any: + config_data = [plugin.report_config_data(ctx) for plugin in self._plugins] + return config_data if any(x is not None for x in config_data) else None + + def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: + deps = [] + for plugin in self._plugins: + deps.extend(plugin.get_additional_deps(file)) + return deps + + def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_type_analyze_hook(fullname) + if hook is not None: + return hook + return None + + def get_function_signature_hook( + self, fullname: str + ) -> Callable[[FunctionSigContext], FunctionLike] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_function_signature_hook(fullname) + if hook is not None: + return hook + return None + + def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: + return self._find_hook(lambda plugin: plugin.get_function_hook(fullname)) + + def get_method_signature_hook( + self, fullname: str + ) -> Callable[[MethodSigContext], FunctionLike] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_method_signature_hook(fullname) + if hook is not None: + return hook + return None + + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_method_hook(fullname) + if hook is not None: + return hook + return None + + def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_attribute_hook(fullname) + if hook is not None: + return hook + return None + + def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + return self._find_hook(lambda plugin: plugin.get_class_attribute_hook(fullname)) + + def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_class_decorator_hook(fullname)) + + def get_class_decorator_hook_2( + self, fullname: str + ) -> Callable[[ClassDefContext], bool] | None: + return self._find_hook(lambda plugin: plugin.get_class_decorator_hook_2(fullname)) + + def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_metaclass_hook(fullname)) + + def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_base_class_hook(fullname)) + + def get_customize_class_mro_hook( + self, fullname: str + ) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_customize_class_mro_hook(fullname)) + + def get_dynamic_class_hook( + self, fullname: str + ) -> Callable[[DynamicClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_dynamic_class_hook(fullname)) + + def _find_hook(self, lookup: Callable[[Plugin], T]) -> T | None: + for plugin in self._plugins: + hook = lookup(plugin) + if hook is not None: + return hook + return None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/py.typed b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..9724ed562890af1d6c28c46865a752566e14f932 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The mypy package uses inline types. diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/pyinfo.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/pyinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..98350f46363ca87905da28becf81220d46865e34 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/pyinfo.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +"""Utilities to find the site and prefix information of a Python executable. + +This file MUST remain compatible with all Python 3.9+ versions. Since we cannot make any +assumptions about the Python being executed, this module should not use *any* dependencies outside +of the standard library found in Python 3.9. This file is run each mypy run, so it should be kept +as fast as possible. +""" +import sys + +if __name__ == "__main__": + # HACK: We don't want to pick up mypy.types as the top-level types + # module. This could happen if this file is run as a script. + # This workaround fixes this for Python versions before 3.11. + if sys.version_info < (3, 11): + old_sys_path = sys.path + sys.path = sys.path[1:] + import types # noqa: F401 + + sys.path = old_sys_path + +import os +import site +import sysconfig + + +def getsitepackages() -> list[str]: + res = [] + if hasattr(site, "getsitepackages"): + res.extend(site.getsitepackages()) + + if hasattr(site, "getusersitepackages") and site.ENABLE_USER_SITE: + res.insert(0, site.getusersitepackages()) + else: + res = [sysconfig.get_paths()["purelib"]] + return res + + +def getsyspath() -> list[str]: + # Do not include things from the standard library + # because those should come from typeshed. + stdlib_zip = os.path.join( + sys.base_exec_prefix, + getattr(sys, "platlibdir", "lib"), + f"python{sys.version_info.major}{sys.version_info.minor}.zip", + ) + stdlib = sysconfig.get_path("stdlib") + stdlib_ext = os.path.join(stdlib, "lib-dynload") + excludes = {stdlib_zip, stdlib, stdlib_ext} + + # Drop the first entry of sys.path + # - If pyinfo.py is executed as a script (in a subprocess), this is the directory + # containing pyinfo.py + # - Otherwise, if mypy launched via console script, this is the directory of the script + # - Otherwise, if mypy launched via python -m mypy, this is the current directory + # In all these cases, it is desirable to drop the first entry + # Note that mypy adds the cwd to SearchPaths.python_path, so we still find things on the + # cwd consistently (the return value here sets SearchPaths.package_path) + + # Python 3.11 adds a "safe_path" flag wherein Python won't automatically prepend + # anything to sys.path. In this case, the first entry of sys.path is no longer special. + offset = 0 if sys.version_info >= (3, 11) and sys.flags.safe_path else 1 + + abs_sys_path = (os.path.abspath(p) for p in sys.path[offset:]) + return [p for p in abs_sys_path if p not in excludes] + + +def getsearchdirs() -> tuple[list[str], list[str]]: + return (getsyspath(), getsitepackages()) + + +if __name__ == "__main__": + sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr] + if sys.argv[-1] == "getsearchdirs": + print(repr(getsearchdirs())) + else: + print("ERROR: incorrect argument to pyinfo.py.", file=sys.stderr) + sys.exit(1) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/reachability.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/reachability.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0587dce373b9df621c713cf4bd476d71deeec186 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/reachability.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/reachability.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/reachability.py new file mode 100644 index 0000000000000000000000000000000000000000..37c7a9715600af82889cdc864aa4680bc8641a05 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/reachability.py @@ -0,0 +1,370 @@ +"""Utilities related to determining the reachability of code (in semantic analysis).""" + +from __future__ import annotations + +from typing import Final, TypeVar + +from mypy.literals import literal +from mypy.nodes import ( + LITERAL_YES, + AssertStmt, + Block, + CallExpr, + ComparisonExpr, + Expression, + FuncDef, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + MatchStmt, + MemberExpr, + NameExpr, + OpExpr, + SliceExpr, + StrExpr, + TupleExpr, + UnaryExpr, +) +from mypy.options import Options +from mypy.patterns import AsPattern, OrPattern, Pattern +from mypy.traverser import TraverserVisitor + +# Inferred truth value of an expression. +ALWAYS_TRUE: Final = 1 +MYPY_TRUE: Final = 2 # True in mypy, False at runtime +ALWAYS_FALSE: Final = 3 +MYPY_FALSE: Final = 4 # False in mypy, True at runtime +TRUTH_VALUE_UNKNOWN: Final = 5 + +inverted_truth_mapping: Final = { + ALWAYS_TRUE: ALWAYS_FALSE, + ALWAYS_FALSE: ALWAYS_TRUE, + TRUTH_VALUE_UNKNOWN: TRUTH_VALUE_UNKNOWN, + MYPY_TRUE: MYPY_FALSE, + MYPY_FALSE: MYPY_TRUE, +} + +reverse_op: Final = {"==": "==", "!=": "!=", "<": ">", ">": "<", "<=": ">=", ">=": "<="} + + +def infer_reachability_of_if_statement(s: IfStmt, options: Options) -> None: + for i in range(len(s.expr)): + result = infer_condition_value(s.expr[i], options) + if result in (ALWAYS_FALSE, MYPY_FALSE): + # The condition is considered always false, so we skip the if/elif body. + mark_block_unreachable(s.body[i]) + elif result in (ALWAYS_TRUE, MYPY_TRUE): + # This condition is considered always true, so all of the remaining + # elif/else bodies should not be checked. + if result == MYPY_TRUE: + # This condition is false at runtime; this will affect + # import priorities. + mark_block_mypy_only(s.body[i]) + for body in s.body[i + 1 :]: + mark_block_unreachable(body) + + # Make sure else body always exists and is marked as + # unreachable so the type checker always knows that + # all control flow paths will flow through the if + # statement body. + if not s.else_body: + s.else_body = Block([]) + mark_block_unreachable(s.else_body) + break + + +def infer_reachability_of_match_statement(s: MatchStmt, options: Options) -> None: + for i, guard in enumerate(s.guards): + pattern_value = infer_pattern_value(s.patterns[i]) + + if guard is not None: + guard_value = infer_condition_value(guard, options) + else: + guard_value = ALWAYS_TRUE + + if pattern_value in (ALWAYS_FALSE, MYPY_FALSE) or guard_value in ( + ALWAYS_FALSE, + MYPY_FALSE, + ): + # The case is considered always false, so we skip the case body. + mark_block_unreachable(s.bodies[i]) + elif pattern_value in (ALWAYS_TRUE, MYPY_TRUE) and guard_value in (ALWAYS_TRUE, MYPY_TRUE): + for body in s.bodies[i + 1 :]: + mark_block_unreachable(body) + + if guard_value == MYPY_TRUE: + # This condition is false at runtime; this will affect + # import priorities. + mark_block_mypy_only(s.bodies[i]) + + +def assert_will_always_fail(s: AssertStmt, options: Options) -> bool: + return infer_condition_value(s.expr, options) in (ALWAYS_FALSE, MYPY_FALSE) + + +def infer_condition_value(expr: Expression, options: Options) -> int: + """Infer whether the given condition is always true/false. + + Return ALWAYS_TRUE if always true, ALWAYS_FALSE if always false, + MYPY_TRUE if true under mypy and false at runtime, MYPY_FALSE if + false under mypy and true at runtime, else TRUTH_VALUE_UNKNOWN. + """ + if isinstance(expr, UnaryExpr) and expr.op == "not": + positive = infer_condition_value(expr.expr, options) + return inverted_truth_mapping[positive] + + pyversion = options.python_version + name = "" + + result = TRUTH_VALUE_UNKNOWN + if isinstance(expr, NameExpr): + name = expr.name + elif isinstance(expr, MemberExpr): + name = expr.name + elif isinstance(expr, OpExpr): + if expr.op not in ("or", "and"): + return TRUTH_VALUE_UNKNOWN + + left = infer_condition_value(expr.left, options) + right = infer_condition_value(expr.right, options) + results = {left, right} + if expr.op == "or": + if ALWAYS_TRUE in results: + return ALWAYS_TRUE + elif MYPY_TRUE in results: + return MYPY_TRUE + elif left == right == MYPY_FALSE: + return MYPY_FALSE + elif results <= {ALWAYS_FALSE, MYPY_FALSE}: + return ALWAYS_FALSE + elif expr.op == "and": + if ALWAYS_FALSE in results: + return ALWAYS_FALSE + elif MYPY_FALSE in results: + return MYPY_FALSE + elif left == right == ALWAYS_TRUE: + return ALWAYS_TRUE + elif results <= {ALWAYS_TRUE, MYPY_TRUE}: + return MYPY_TRUE + return TRUTH_VALUE_UNKNOWN + else: + result = consider_sys_version_info(expr, pyversion) + if result == TRUTH_VALUE_UNKNOWN: + result = consider_sys_platform(expr, options.platform) + if result == TRUTH_VALUE_UNKNOWN: + if name == "PY2": + result = ALWAYS_FALSE + elif name == "PY3": + result = ALWAYS_TRUE + elif name == "MYPY" or name == "TYPE_CHECKING": + result = MYPY_TRUE + elif name in options.always_true: + result = ALWAYS_TRUE + elif name in options.always_false: + result = ALWAYS_FALSE + return result + + +def infer_pattern_value(pattern: Pattern) -> int: + if isinstance(pattern, AsPattern) and pattern.pattern is None: + return ALWAYS_TRUE + elif isinstance(pattern, OrPattern) and any( + infer_pattern_value(p) == ALWAYS_TRUE for p in pattern.patterns + ): + return ALWAYS_TRUE + else: + return TRUTH_VALUE_UNKNOWN + + +def consider_sys_version_info(expr: Expression, pyversion: tuple[int, ...]) -> int: + """Consider whether expr is a comparison involving sys.version_info. + + Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN. + """ + # Cases supported: + # - sys.version_info[] + # - sys.version_info[:] + # - sys.version_info + # (in this case must be >, >=, <, <=, but cannot be ==, !=) + if not isinstance(expr, ComparisonExpr): + return TRUTH_VALUE_UNKNOWN + # Let's not yet support chained comparisons. + if len(expr.operators) > 1: + return TRUTH_VALUE_UNKNOWN + op = expr.operators[0] + if op not in ("==", "!=", "<=", ">=", "<", ">"): + return TRUTH_VALUE_UNKNOWN + + index = contains_sys_version_info(expr.operands[0]) + thing = contains_int_or_tuple_of_ints(expr.operands[1]) + if index is None or thing is None: + index = contains_sys_version_info(expr.operands[1]) + thing = contains_int_or_tuple_of_ints(expr.operands[0]) + op = reverse_op[op] + if isinstance(index, int) and isinstance(thing, int): + # sys.version_info[i] k + if 0 <= index <= 1: + return fixed_comparison(pyversion[index], op, thing) + else: + return TRUTH_VALUE_UNKNOWN + elif isinstance(index, tuple) and isinstance(thing, tuple): + lo, hi = index + if lo is None: + lo = 0 + if hi is None: + hi = 2 + if 0 <= lo < hi <= 2: + val = pyversion[lo:hi] + if len(val) == len(thing) or len(val) > len(thing) and op not in ("==", "!="): + return fixed_comparison(val, op, thing) + return TRUTH_VALUE_UNKNOWN + + +def consider_sys_platform(expr: Expression, platform: str) -> int: + """Consider whether expr is a comparison involving sys.platform. + + Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN. + """ + # Cases supported: + # - sys.platform == 'linux' + # - sys.platform != 'win32' + # - sys.platform.startswith('win') + if isinstance(expr, ComparisonExpr): + # Let's not yet support chained comparisons. + if len(expr.operators) > 1: + return TRUTH_VALUE_UNKNOWN + op = expr.operators[0] + if op not in ("==", "!="): + return TRUTH_VALUE_UNKNOWN + if not is_sys_attr(expr.operands[0], "platform"): + return TRUTH_VALUE_UNKNOWN + right = expr.operands[1] + if not isinstance(right, StrExpr): + return TRUTH_VALUE_UNKNOWN + return fixed_comparison(platform, op, right.value) + elif isinstance(expr, CallExpr): + if not isinstance(expr.callee, MemberExpr): + return TRUTH_VALUE_UNKNOWN + if len(expr.args) != 1 or not isinstance(expr.args[0], StrExpr): + return TRUTH_VALUE_UNKNOWN + if not is_sys_attr(expr.callee.expr, "platform"): + return TRUTH_VALUE_UNKNOWN + if expr.callee.name != "startswith": + return TRUTH_VALUE_UNKNOWN + if platform.startswith(expr.args[0].value): + return ALWAYS_TRUE + else: + return ALWAYS_FALSE + else: + return TRUTH_VALUE_UNKNOWN + + +Targ = TypeVar("Targ", int, str, tuple[int, ...]) + + +def fixed_comparison(left: Targ, op: str, right: Targ) -> int: + rmap = {False: ALWAYS_FALSE, True: ALWAYS_TRUE} + if op == "==": + return rmap[left == right] + if op == "!=": + return rmap[left != right] + if op == "<=": + return rmap[left <= right] + if op == ">=": + return rmap[left >= right] + if op == "<": + return rmap[left < right] + if op == ">": + return rmap[left > right] + return TRUTH_VALUE_UNKNOWN + + +def contains_int_or_tuple_of_ints(expr: Expression) -> None | int | tuple[int, ...]: + if isinstance(expr, IntExpr): + return expr.value + if isinstance(expr, TupleExpr): + if literal(expr) == LITERAL_YES: + thing = [] + for x in expr.items: + if not isinstance(x, IntExpr): + return None + thing.append(x.value) + return tuple(thing) + return None + + +def contains_sys_version_info(expr: Expression) -> None | int | tuple[int | None, int | None]: + if is_sys_attr(expr, "version_info"): + return (None, None) # Same as sys.version_info[:] + if isinstance(expr, IndexExpr) and is_sys_attr(expr.base, "version_info"): + index = expr.index + if isinstance(index, IntExpr): + return index.value + if isinstance(index, SliceExpr): + if index.stride is not None: + if not isinstance(index.stride, IntExpr) or index.stride.value != 1: + return None + begin = end = None + if index.begin_index is not None: + if not isinstance(index.begin_index, IntExpr): + return None + begin = index.begin_index.value + if index.end_index is not None: + if not isinstance(index.end_index, IntExpr): + return None + end = index.end_index.value + return (begin, end) + return None + + +def is_sys_attr(expr: Expression, name: str) -> bool: + # TODO: This currently doesn't work with code like this: + # - import sys as _sys + # - from sys import version_info + if isinstance(expr, MemberExpr) and expr.name == name: + if isinstance(expr.expr, NameExpr) and expr.expr.name == "sys": + # TODO: Guard against a local named sys, etc. + # (Though later passes will still do most checking.) + return True + return False + + +def mark_block_unreachable(block: Block) -> None: + block.is_unreachable = True + block.accept(MarkImportsUnreachableVisitor()) + + +class MarkImportsUnreachableVisitor(TraverserVisitor): + """Visitor that flags all imports nested within a node as unreachable.""" + + def visit_import(self, node: Import) -> None: + node.is_unreachable = True + + def visit_import_from(self, node: ImportFrom) -> None: + node.is_unreachable = True + + def visit_import_all(self, node: ImportAll) -> None: + node.is_unreachable = True + + +def mark_block_mypy_only(block: Block) -> None: + block.accept(MarkImportsMypyOnlyVisitor()) + + +class MarkImportsMypyOnlyVisitor(TraverserVisitor): + """Visitor that sets is_mypy_only (which affects priority).""" + + def visit_import(self, node: Import) -> None: + node.is_mypy_only = True + + def visit_import_from(self, node: ImportFrom) -> None: + node.is_mypy_only = True + + def visit_import_all(self, node: ImportAll) -> None: + node.is_mypy_only = True + + def visit_func_def(self, node: FuncDef) -> None: + node.is_mypy_only = True diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/refinfo.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/refinfo.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5d8dba5cb94758f2da162ea9358c8b400a699622 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/refinfo.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/refinfo.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/refinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b92832bb7ee7e08bc4d4a9c9a1a01419323810 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/refinfo.py @@ -0,0 +1,92 @@ +"""Find line-level reference information from a mypy AST (undocumented feature)""" + +from __future__ import annotations + +from mypy.nodes import ( + LDEF, + Expression, + FuncDef, + MemberExpr, + MypyFile, + NameExpr, + RefExpr, + SymbolNode, + TypeInfo, +) +from mypy.traverser import TraverserVisitor +from mypy.typeops import tuple_fallback +from mypy.types import ( + FunctionLike, + Instance, + TupleType, + Type, + TypeType, + TypeVarLikeType, + get_proper_type, +) + + +class RefInfoVisitor(TraverserVisitor): + def __init__(self, type_map: dict[Expression, Type]) -> None: + super().__init__() + self.type_map = type_map + self.data: list[dict[str, object]] = [] + + def visit_name_expr(self, expr: NameExpr) -> None: + super().visit_name_expr(expr) + self.record_ref_expr(expr) + + def visit_member_expr(self, expr: MemberExpr) -> None: + super().visit_member_expr(expr) + self.record_ref_expr(expr) + + def visit_func_def(self, func: FuncDef) -> None: + if func.expanded: + for item in func.expanded: + if isinstance(item, FuncDef): + super().visit_func_def(item) + else: + super().visit_func_def(func) + + def record_ref_expr(self, expr: RefExpr) -> None: + fullname = None + if expr.kind != LDEF and "." in expr.fullname: + fullname = expr.fullname + elif isinstance(expr, MemberExpr): + typ = self.type_map.get(expr.expr) + sym = None + if isinstance(expr.expr, RefExpr): + sym = expr.expr.node + if typ: + tfn = type_fullname(typ, sym) + if tfn: + fullname = f"{tfn}.{expr.name}" + if not fullname: + fullname = f"*.{expr.name}" + if fullname is not None: + self.data.append({"line": expr.line, "column": expr.column, "target": fullname}) + + +def type_fullname(typ: Type, node: SymbolNode | None = None) -> str | None: + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return typ.type.fullname + elif isinstance(typ, TypeType): + return type_fullname(typ.item) + elif isinstance(typ, FunctionLike) and typ.is_type_obj(): + if isinstance(node, TypeInfo): + return node.fullname + return type_fullname(typ.fallback) + elif isinstance(typ, TupleType): + return type_fullname(tuple_fallback(typ)) + elif isinstance(typ, TypeVarLikeType): + return type_fullname(typ.upper_bound) + return None + + +def get_undocumented_ref_info_json( + tree: MypyFile, type_map: dict[Expression, Type] +) -> list[dict[str, object]]: + visitor = RefInfoVisitor(type_map) + tree.accept(visitor) + return visitor.data diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/renaming.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/renaming.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..1be39aa804ef598706f016f939f8e5b1ce84b54b Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/renaming.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/renaming.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/renaming.py new file mode 100644 index 0000000000000000000000000000000000000000..dff76b157acc079d22103eb11a69bd5a3ed0f0fd --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/renaming.py @@ -0,0 +1,583 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Final + +from mypy.nodes import ( + AssignmentStmt, + Block, + BreakStmt, + ClassDef, + ContinueStmt, + ForStmt, + FuncDef, + Import, + ImportAll, + ImportFrom, + IndexExpr, + ListExpr, + Lvalue, + MatchStmt, + MemberExpr, + MypyFile, + NameExpr, + StarExpr, + TryStmt, + TupleExpr, + WhileStmt, + WithStmt, +) +from mypy.patterns import AsPattern +from mypy.traverser import TraverserVisitor + +# Scope kinds +FILE: Final = 0 +FUNCTION: Final = 1 +CLASS: Final = 2 + + +class VariableRenameVisitor(TraverserVisitor): + """Rename variables to allow redefinition of variables. + + For example, consider this code: + + x = 0 + f(x) + + x = "a" + g(x) + + It will be transformed like this: + + x' = 0 + f(x') + + x = "a" + g(x) + + There will be two independent variables (x' and x) that will have separate + inferred types. The publicly exposed variant will get the non-suffixed name. + This is the last definition at module top level and the first definition + (argument) within a function. + + Renaming only happens for assignments within the same block. Renaming is + performed before semantic analysis, immediately after parsing. + + The implementation performs a rudimentary static analysis. The analysis is + overly conservative to keep things simple. + """ + + def __init__(self) -> None: + # Counter for labeling new blocks + self.block_id = 0 + # Number of surrounding try statements that disallow variable redefinition + self.disallow_redef_depth = 0 + # Number of surrounding loop statements + self.loop_depth = 0 + # Map block id to loop depth. + self.block_loop_depth: dict[int, int] = {} + # Stack of block ids being processed. + self.blocks: list[int] = [] + # List of scopes; each scope maps short (unqualified) name to block id. + self.var_blocks: list[dict[str, int]] = [] + + # References to variables that we may need to rename. List of + # scopes; each scope is a mapping from name to list of collections + # of names that refer to the same logical variable. + self.refs: list[dict[str, list[list[NameExpr]]]] = [] + # Number of reads of the most recent definition of a variable (per scope) + self.num_reads: list[dict[str, int]] = [] + # Kinds of nested scopes (FILE, FUNCTION or CLASS) + self.scope_kinds: list[int] = [] + + def visit_mypy_file(self, file_node: MypyFile) -> None: + """Rename variables within a file. + + This is the main entry point to this class. + """ + self.clear() + with self.enter_scope(FILE), self.enter_block(): + for d in file_node.defs: + d.accept(self) + + def visit_func_def(self, fdef: FuncDef) -> None: + # Conservatively do not allow variable defined before a function to + # be redefined later, since function could refer to either definition. + self.reject_redefinition_of_vars_in_scope() + + with self.enter_scope(FUNCTION), self.enter_block(): + for arg in fdef.arguments: + name = arg.variable.name + # 'self' can't be redefined since it's special as it allows definition of + # attributes. 'cls' can't be used to define attributes so we can ignore it. + can_be_redefined = name != "self" # TODO: Proper check + self.record_assignment(arg.variable.name, can_be_redefined) + self.handle_arg(name) + + for stmt in fdef.body.body: + stmt.accept(self) + + def visit_class_def(self, cdef: ClassDef) -> None: + self.reject_redefinition_of_vars_in_scope() + with self.enter_scope(CLASS): + super().visit_class_def(cdef) + + def visit_block(self, block: Block) -> None: + with self.enter_block(): + super().visit_block(block) + + def visit_while_stmt(self, stmt: WhileStmt) -> None: + with self.enter_loop(): + super().visit_while_stmt(stmt) + + def visit_for_stmt(self, stmt: ForStmt) -> None: + stmt.expr.accept(self) + self.analyze_lvalue(stmt.index, True) + # Also analyze as non-lvalue so that every for loop index variable is assumed to be read. + stmt.index.accept(self) + with self.enter_loop(): + stmt.body.accept(self) + if stmt.else_body: + stmt.else_body.accept(self) + + def visit_break_stmt(self, stmt: BreakStmt) -> None: + self.reject_redefinition_of_vars_in_loop() + + def visit_continue_stmt(self, stmt: ContinueStmt) -> None: + self.reject_redefinition_of_vars_in_loop() + + def visit_try_stmt(self, stmt: TryStmt) -> None: + # Variables defined by a try statement get special treatment in the + # type checker which allows them to be always redefined, so no need to + # do renaming here. + with self.enter_try(): + stmt.body.accept(self) + + for var, tp, handler in zip(stmt.vars, stmt.types, stmt.handlers): + with self.enter_block(): + # Handle except variable together with its body + if tp is not None: + tp.accept(self) + if var is not None: + self.handle_def(var) + for s in handler.body: + s.accept(self) + if stmt.else_body is not None: + stmt.else_body.accept(self) + if stmt.finally_body is not None: + stmt.finally_body.accept(self) + + def visit_with_stmt(self, stmt: WithStmt) -> None: + for expr in stmt.expr: + expr.accept(self) + for target in stmt.target: + if target is not None: + self.analyze_lvalue(target) + # We allow redefinitions in the body of a with statement for + # convenience. This is unsafe since with statements can affect control + # flow by catching exceptions, but this is rare except for + # assertRaises() and other similar functions, where the exception is + # raised by the last statement in the body, which usually isn't a + # problem. + stmt.body.accept(self) + + def visit_import(self, imp: Import) -> None: + for id, as_id in imp.ids: + self.record_assignment(as_id or id, False) + + def visit_import_from(self, imp: ImportFrom) -> None: + for id, as_id in imp.names: + self.record_assignment(as_id or id, False) + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + s.rvalue.accept(self) + for lvalue in s.lvalues: + self.analyze_lvalue(lvalue) + + def visit_match_stmt(self, s: MatchStmt) -> None: + s.subject.accept(self) + for i in range(len(s.patterns)): + with self.enter_block(): + s.patterns[i].accept(self) + guard = s.guards[i] + if guard is not None: + guard.accept(self) + # We already entered a block, so visit this block's statements directly + for stmt in s.bodies[i].body: + stmt.accept(self) + + def visit_capture_pattern(self, p: AsPattern) -> None: + if p.name is not None: + self.analyze_lvalue(p.name) + + def analyze_lvalue(self, lvalue: Lvalue, is_nested: bool = False) -> None: + """Process assignment; in particular, keep track of (re)defined names. + + Args: + is_nested: True for non-outermost Lvalue in a multiple assignment such as + "x, y = ..." + """ + if isinstance(lvalue, NameExpr): + name = lvalue.name + is_new = self.record_assignment(name, True) + if is_new: + self.handle_def(lvalue) + else: + self.handle_refine(lvalue) + if is_nested: + # This allows these to be redefined freely even if never read. Multiple + # assignment like "x, _ _ = y" defines dummy variables that are never read. + self.handle_ref(lvalue) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + for item in lvalue.items: + self.analyze_lvalue(item, is_nested=True) + elif isinstance(lvalue, MemberExpr): + lvalue.expr.accept(self) + elif isinstance(lvalue, IndexExpr): + lvalue.base.accept(self) + lvalue.index.accept(self) + elif isinstance(lvalue, StarExpr): + # Propagate is_nested since in a typical use case like "x, *rest = ..." 'rest' may + # be freely reused. + self.analyze_lvalue(lvalue.expr, is_nested=is_nested) + + def visit_name_expr(self, expr: NameExpr) -> None: + self.handle_ref(expr) + + # Helpers for renaming references + + def handle_arg(self, name: str) -> None: + """Store function argument.""" + self.refs[-1][name] = [[]] + self.num_reads[-1][name] = 0 + + def handle_def(self, expr: NameExpr) -> None: + """Store new name definition.""" + name = expr.name + names = self.refs[-1].setdefault(name, []) + names.append([expr]) + self.num_reads[-1][name] = 0 + + def handle_refine(self, expr: NameExpr) -> None: + """Store assignment to an existing name (that replaces previous value, if any).""" + name = expr.name + if name in self.refs[-1]: + names = self.refs[-1][name] + if not names: + names.append([]) + names[-1].append(expr) + + def handle_ref(self, expr: NameExpr) -> None: + """Store reference to defined name.""" + name = expr.name + if name in self.refs[-1]: + names = self.refs[-1][name] + if not names: + names.append([]) + names[-1].append(expr) + num_reads = self.num_reads[-1] + num_reads[name] = num_reads.get(name, 0) + 1 + + def flush_refs(self) -> None: + """Rename all references within the current scope. + + This will be called at the end of a scope. + """ + is_func = self.scope_kinds[-1] == FUNCTION + for refs in self.refs[-1].values(): + if len(refs) == 1: + # Only one definition -- no renaming needed. + continue + if is_func: + # In a function, don't rename the first definition, as it + # may be an argument that must preserve the name. + to_rename = refs[1:] + else: + # At module top level, don't rename the final definition, + # as it will be publicly visible outside the module. + to_rename = refs[:-1] + for i, item in enumerate(to_rename): + rename_refs(item, i) + self.refs.pop() + + # Helpers for determining which assignments define new variables + + def clear(self) -> None: + self.blocks = [] + self.var_blocks = [] + + @contextmanager + def enter_block(self) -> Iterator[None]: + self.block_id += 1 + self.blocks.append(self.block_id) + self.block_loop_depth[self.block_id] = self.loop_depth + try: + yield + finally: + self.blocks.pop() + + @contextmanager + def enter_try(self) -> Iterator[None]: + self.disallow_redef_depth += 1 + try: + yield + finally: + self.disallow_redef_depth -= 1 + + @contextmanager + def enter_loop(self) -> Iterator[None]: + self.loop_depth += 1 + try: + yield + finally: + self.loop_depth -= 1 + + def current_block(self) -> int: + return self.blocks[-1] + + @contextmanager + def enter_scope(self, kind: int) -> Iterator[None]: + self.var_blocks.append({}) + self.refs.append({}) + self.num_reads.append({}) + self.scope_kinds.append(kind) + try: + yield + finally: + self.flush_refs() + self.var_blocks.pop() + self.num_reads.pop() + self.scope_kinds.pop() + + def is_nested(self) -> int: + return len(self.var_blocks) > 1 + + def reject_redefinition_of_vars_in_scope(self) -> None: + """Make it impossible to redefine defined variables in the current scope. + + This is used if we encounter a function definition that + can make it ambiguous which definition is live. Example: + + x = 0 + + def f() -> int: + return x + + x = '' # Error -- cannot redefine x across function definition + """ + var_blocks = self.var_blocks[-1] + for key in var_blocks: + var_blocks[key] = -1 + + def reject_redefinition_of_vars_in_loop(self) -> None: + """Reject redefinition of variables in the innermost loop. + + If there is an early exit from a loop, there may be ambiguity about which + value may escape the loop. Example where this matters: + + while f(): + x = 0 + if g(): + break + x = '' # Error -- not a redefinition + reveal_type(x) # int + + This method ensures that the second assignment to 'x' doesn't introduce a new + variable. + """ + var_blocks = self.var_blocks[-1] + for key, block in var_blocks.items(): + if self.block_loop_depth.get(block) == self.loop_depth: + var_blocks[key] = -1 + + def record_assignment(self, name: str, can_be_redefined: bool) -> bool: + """Record assignment to given name and return True if it defines a new variable. + + Args: + can_be_redefined: If True, allows assignment in the same block to redefine + this name (if this is a new definition) + """ + if self.num_reads[-1].get(name, -1) == 0: + # Only set, not read, so no reason to redefine + return False + if self.disallow_redef_depth > 0: + # Can't redefine within try/with a block. + can_be_redefined = False + block = self.current_block() + var_blocks = self.var_blocks[-1] + if name not in var_blocks: + # New definition in this scope. + if can_be_redefined: + # Store the block where this was defined to allow redefinition in + # the same block only. + var_blocks[name] = block + else: + # This doesn't support arbitrary redefinition. + var_blocks[name] = -1 + return True + elif var_blocks[name] == block: + # Redefinition -- defines a new variable with the same name. + return True + else: + # Assigns to an existing variable. + return False + + +class LimitedVariableRenameVisitor(TraverserVisitor): + """Perform some limited variable renaming in with statements. + + This allows reusing a variable in multiple with statements with + different types. For example, the two instances of 'x' can have + incompatible types: + + with C() as x: + f(x) + with D() as x: + g(x) + + The above code gets renamed conceptually into this (not valid Python!): + + with C() as x': + f(x') + with D() as x: + g(x) + + If there's a reference to a variable defined in 'with' outside the + statement, or if there's any trickiness around variable visibility + (e.g. function definitions), we give up and won't perform renaming. + + The main use case is to allow binding both readable and writable + binary files into the same variable. These have different types: + + with open(fnam, 'rb') as f: ... + with open(fnam, 'wb') as f: ... + """ + + def __init__(self) -> None: + # Short names of variables bound in with statements using "as" + # in a surrounding scope + self.bound_vars: list[str] = [] + # Stack of names that can't be safely renamed, per scope ('*' means that + # no names can be renamed) + self.skipped: list[set[str]] = [] + # References to variables that we may need to rename. Stack of + # scopes; each scope is a mapping from name to list of collections + # of names that refer to the same logical variable. + self.refs: list[dict[str, list[list[NameExpr]]]] = [] + + def visit_mypy_file(self, file_node: MypyFile) -> None: + """Rename variables within a file. + + This is the main entry point to this class. + """ + with self.enter_scope(): + for d in file_node.defs: + d.accept(self) + + def visit_func_def(self, fdef: FuncDef) -> None: + self.reject_redefinition_of_vars_in_scope() + with self.enter_scope(): + for arg in fdef.arguments: + self.record_skipped(arg.variable.name) + super().visit_func_def(fdef) + + def visit_class_def(self, cdef: ClassDef) -> None: + self.reject_redefinition_of_vars_in_scope() + with self.enter_scope(): + super().visit_class_def(cdef) + + def visit_with_stmt(self, stmt: WithStmt) -> None: + for expr in stmt.expr: + expr.accept(self) + old_len = len(self.bound_vars) + for target in stmt.target: + if target is not None: + self.analyze_lvalue(target) + for target in stmt.target: + if target: + target.accept(self) + stmt.body.accept(self) + + while len(self.bound_vars) > old_len: + self.bound_vars.pop() + + def analyze_lvalue(self, lvalue: Lvalue) -> None: + if isinstance(lvalue, NameExpr): + name = lvalue.name + if name in self.bound_vars: + # Name bound in a surrounding with statement, so it can be renamed + self.visit_name_expr(lvalue) + else: + var_info = self.refs[-1] + if name not in var_info: + var_info[name] = [] + var_info[name].append([]) + self.bound_vars.append(name) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + for item in lvalue.items: + self.analyze_lvalue(item) + elif isinstance(lvalue, MemberExpr): + lvalue.expr.accept(self) + elif isinstance(lvalue, IndexExpr): + lvalue.base.accept(self) + lvalue.index.accept(self) + elif isinstance(lvalue, StarExpr): + self.analyze_lvalue(lvalue.expr) + + def visit_import(self, imp: Import) -> None: + # We don't support renaming imports + for id, as_id in imp.ids: + self.record_skipped(as_id or id) + + def visit_import_from(self, imp: ImportFrom) -> None: + # We don't support renaming imports + for id, as_id in imp.names: + self.record_skipped(as_id or id) + + def visit_import_all(self, imp: ImportAll) -> None: + # Give up, since we don't know all imported names yet + self.reject_redefinition_of_vars_in_scope() + + def visit_name_expr(self, expr: NameExpr) -> None: + name = expr.name + if name in self.bound_vars: + # Record reference so that it can be renamed later + for scope in reversed(self.refs): + if name in scope: + scope[name][-1].append(expr) + else: + self.record_skipped(name) + + @contextmanager + def enter_scope(self) -> Iterator[None]: + self.skipped.append(set()) + self.refs.append({}) + yield None + self.flush_refs() + + def reject_redefinition_of_vars_in_scope(self) -> None: + self.record_skipped("*") + + def record_skipped(self, name: str) -> None: + self.skipped[-1].add(name) + + def flush_refs(self) -> None: + ref_dict = self.refs.pop() + skipped = self.skipped.pop() + if "*" not in skipped: + for name, refs in ref_dict.items(): + if len(refs) <= 1 or name in skipped: + continue + # At module top level we must not rename the final definition, + # as it may be publicly visible + to_rename = refs[:-1] + for i, item in enumerate(to_rename): + rename_refs(item, i) + + +def rename_refs(names: list[NameExpr], index: int) -> None: + name = names[0].name + new_name = name + "'" * (index + 1) + for expr in names: + expr.name = new_name diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/report.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/report.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..be8bf5f2a885d05d9bb0be66c07432b50498a025 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/report.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/report.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/report.py new file mode 100644 index 0000000000000000000000000000000000000000..885d077d259e54ef6bc3edaba193df7e03bc51a5 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/report.py @@ -0,0 +1,930 @@ +"""Classes for producing HTML reports about imprecision.""" + +from __future__ import annotations + +import collections +import itertools +import json +import os +import shutil +import sys +import sysconfig +import time +import tokenize +from abc import ABCMeta, abstractmethod +from collections.abc import Callable, Iterator +from operator import attrgetter +from typing import Any, Final, TypeAlias as _TypeAlias +from urllib.request import pathname2url + +from mypy import stats +from mypy.defaults import REPORTER_NAMES +from mypy.nodes import Expression, FuncDef, MypyFile +from mypy.options import Options +from mypy.traverser import TraverserVisitor +from mypy.types import Type, TypeOfAny +from mypy.version import __version__ + +try: + if sys.version_info >= (3, 14) and bool(sysconfig.get_config_var("Py_GIL_DISABLED")): + # lxml doesn't support free-threading yet + LXML_INSTALLED = False + else: + from lxml import etree # type: ignore[import-untyped] + + LXML_INSTALLED = True +except ImportError: + LXML_INSTALLED = False + +type_of_any_name_map: Final[collections.OrderedDict[int, str]] = collections.OrderedDict( + [ + (TypeOfAny.unannotated, "Unannotated"), + (TypeOfAny.explicit, "Explicit"), + (TypeOfAny.from_unimported_type, "Unimported"), + (TypeOfAny.from_omitted_generics, "Omitted Generics"), + (TypeOfAny.from_error, "Error"), + (TypeOfAny.special_form, "Special Form"), + (TypeOfAny.implementation_artifact, "Implementation Artifact"), + ] +) + +ReporterClasses: _TypeAlias = dict[ + str, tuple[Callable[["Reports", str], "AbstractReporter"], bool] +] + +reporter_classes: Final[ReporterClasses] = {} + + +class Reports: + def __init__(self, data_dir: str, report_dirs: dict[str, str]) -> None: + self.data_dir = data_dir + self.reporters: list[AbstractReporter] = [] + self.named_reporters: dict[str, AbstractReporter] = {} + + for report_type, report_dir in sorted(report_dirs.items()): + self.add_report(report_type, report_dir) + + def add_report(self, report_type: str, report_dir: str) -> AbstractReporter: + try: + return self.named_reporters[report_type] + except KeyError: + pass + reporter_cls, needs_lxml = reporter_classes[report_type] + if needs_lxml and not LXML_INSTALLED: + print( + ( + "You must install the lxml package before you can run mypy" + " with `--{}-report`.\n" + "You can do this with `python3 -m pip install lxml`." + ).format(report_type), + file=sys.stderr, + ) + raise ImportError + reporter = reporter_cls(self, report_dir) + self.reporters.append(reporter) + self.named_reporters[report_type] = reporter + return reporter + + def file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + for reporter in self.reporters: + reporter.on_file(tree, modules, type_map, options) + + def finish(self) -> None: + for reporter in self.reporters: + reporter.on_finish() + + +class AbstractReporter(metaclass=ABCMeta): + def __init__(self, reports: Reports, output_dir: str) -> None: + self.output_dir = output_dir + if output_dir != "": + os.makedirs(output_dir, exist_ok=True) + + @abstractmethod + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + pass + + @abstractmethod + def on_finish(self) -> None: + pass + + +def register_reporter( + report_name: str, + reporter: Callable[[Reports, str], AbstractReporter], + needs_lxml: bool = False, +) -> None: + reporter_classes[report_name] = (reporter, needs_lxml) + + +def alias_reporter(source_reporter: str, target_reporter: str) -> None: + reporter_classes[target_reporter] = reporter_classes[source_reporter] + + +def should_skip_path(path: str) -> bool: + if stats.is_special_module(path): + return True + if path.startswith(".."): + return True + if "stubs" in path.split("/") or "stubs" in path.split(os.sep): + return True + return False + + +def iterate_python_lines(path: str) -> Iterator[tuple[int, str]]: + """Return an iterator over (line number, line text) from a Python file.""" + if not os.path.isdir(path): # can happen with namespace packages + with tokenize.open(path) as input_file: + yield from enumerate(input_file, 1) + + +class FuncCounterVisitor(TraverserVisitor): + def __init__(self) -> None: + super().__init__() + self.counts = [0, 0] + + def visit_func_def(self, defn: FuncDef) -> None: + self.counts[defn.type is not None] += 1 + + +class LineCountReporter(AbstractReporter): + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.counts: dict[str, tuple[int, int, int, int]] = {} + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + # Count physical lines. This assumes the file's encoding is a + # superset of ASCII (or at least uses \n in its line endings). + if not os.path.isdir(tree.path): # can happen with namespace packages + with open(tree.path, "rb") as f: + physical_lines = len(f.readlines()) + else: + physical_lines = 0 + + func_counter = FuncCounterVisitor() + tree.accept(func_counter) + unannotated_funcs, annotated_funcs = func_counter.counts + total_funcs = annotated_funcs + unannotated_funcs + + # Don't count lines or functions as annotated if they have their errors ignored. + if options.ignore_errors: + annotated_funcs = 0 + + imputed_annotated_lines = ( + physical_lines * annotated_funcs // total_funcs if total_funcs else physical_lines + ) + + self.counts[tree._fullname] = ( + imputed_annotated_lines, + physical_lines, + annotated_funcs, + total_funcs, + ) + + def on_finish(self) -> None: + counts: list[tuple[tuple[int, int, int, int], str]] = sorted( + ((c, p) for p, c in self.counts.items()), reverse=True + ) + total_counts = tuple(sum(c[i] for c, p in counts) for i in range(4)) + with open(os.path.join(self.output_dir, "linecount.txt"), "w") as f: + f.write("{:7} {:7} {:6} {:6} total\n".format(*total_counts)) + for c, p in counts: + f.write(f"{c[0]:7} {c[1]:7} {c[2]:6} {c[3]:6} {p}\n") + + +register_reporter("linecount", LineCountReporter) + + +class AnyExpressionsReporter(AbstractReporter): + """Report frequencies of different kinds of Any types.""" + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.counts: dict[str, tuple[int, int]] = {} + self.any_types_counter: dict[str, collections.Counter[int]] = {} + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + visit_untyped_defs=False, + ) + tree.accept(visitor) + self.any_types_counter[tree.fullname] = visitor.type_of_any_counter + num_unanalyzed_lines = list(visitor.line_map.values()).count(stats.TYPE_UNANALYZED) + # count each line of dead code as one expression of type "Any" + num_any = visitor.num_any_exprs + num_unanalyzed_lines + num_total = visitor.num_imprecise_exprs + visitor.num_precise_exprs + num_any + if num_total > 0: + self.counts[tree.fullname] = (num_any, num_total) + + def on_finish(self) -> None: + self._report_any_exprs() + self._report_types_of_anys() + + def _write_out_report( + self, filename: str, header: list[str], rows: list[list[str]], footer: list[str] + ) -> None: + row_len = len(header) + assert all(len(row) == row_len for row in rows + [header, footer]) + min_column_distance = 3 # minimum distance between numbers in two columns + widths = [-1] * row_len + for row in rows + [header, footer]: + for i, value in enumerate(row): + widths[i] = max(widths[i], len(value)) + for i, w in enumerate(widths): + # Do not add min_column_distance to the first column. + if i > 0: + widths[i] = w + min_column_distance + with open(os.path.join(self.output_dir, filename), "w") as f: + header_str = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(header, widths))) + separator = "-" * len(header_str) + f.write(header_str + "\n") + f.write(separator + "\n") + for row_values in rows: + r = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(row_values, widths))) + f.write(r + "\n") + f.write(separator + "\n") + footer_str = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(footer, widths))) + f.write(footer_str + "\n") + + def _report_any_exprs(self) -> None: + total_any = sum(num_any for num_any, _ in self.counts.values()) + total_expr = sum(total for _, total in self.counts.values()) + total_coverage = 100.0 + if total_expr > 0: + total_coverage = (float(total_expr - total_any) / float(total_expr)) * 100 + + column_names = ["Name", "Anys", "Exprs", "Coverage"] + rows: list[list[str]] = [] + for filename in sorted(self.counts): + num_any, num_total = self.counts[filename] + coverage = (float(num_total - num_any) / float(num_total)) * 100 + coverage_str = f"{coverage:.2f}%" + rows.append([filename, str(num_any), str(num_total), coverage_str]) + rows.sort(key=lambda x: x[0]) + total_row = ["Total", str(total_any), str(total_expr), f"{total_coverage:.2f}%"] + self._write_out_report("any-exprs.txt", column_names, rows, total_row) + + def _report_types_of_anys(self) -> None: + total_counter: collections.Counter[int] = collections.Counter() + for counter in self.any_types_counter.values(): + for any_type, value in counter.items(): + total_counter[any_type] += value + file_column_name = "Name" + total_row_name = "Total" + column_names = [file_column_name] + list(type_of_any_name_map.values()) + rows: list[list[str]] = [] + for filename, counter in self.any_types_counter.items(): + rows.append([filename] + [str(counter[typ]) for typ in type_of_any_name_map]) + rows.sort(key=lambda x: x[0]) + total_row = [total_row_name] + [str(total_counter[typ]) for typ in type_of_any_name_map] + self._write_out_report("types-of-anys.txt", column_names, rows, total_row) + + +register_reporter("any-exprs", AnyExpressionsReporter) + + +class LineCoverageVisitor(TraverserVisitor): + def __init__(self, source: list[str]) -> None: + self.source = source + + # For each line of source, we maintain a pair of + # * the indentation level of the surrounding function + # (-1 if not inside a function), and + # * whether the surrounding function is typed. + # Initially, everything is covered at indentation level -1. + self.lines_covered = [(-1, True) for l in source] + + # The Python AST has position information for the starts of + # elements, but not for their ends. Fortunately the + # indentation-based syntax makes it pretty easy to find where a + # block ends without doing any real parsing. + + # TODO: Handle line continuations (explicit and implicit) and + # multi-line string literals. (But at least line continuations + # are normally more indented than their surrounding block anyways, + # by PEP 8.) + + def indentation_level(self, line_number: int) -> int | None: + """Return the indentation of a line of the source (specified by + zero-indexed line number). Returns None for blank lines or comments.""" + line = self.source[line_number] + indent = 0 + for char in list(line): + if char == " ": + indent += 1 + elif char == "\t": + indent = 8 * ((indent + 8) // 8) + elif char == "#": + # Line is a comment; ignore it + return None + elif char == "\n": + # Line is entirely whitespace; ignore it + return None + # TODO line continuation (\) + else: + # Found a non-whitespace character + return indent + # Line is entirely whitespace, and at end of file + # with no trailing newline; ignore it + return None + + def visit_func_def(self, defn: FuncDef) -> None: + start_line = defn.line - 1 + start_indent = None + # When a function is decorated, sometimes the start line will point to + # whitespace or comments between the decorator and the function, so + # we have to look for the start. + while start_line < len(self.source): + start_indent = self.indentation_level(start_line) + if start_indent is not None: + break + start_line += 1 + # If we can't find the function give up and don't annotate anything. + # Our line numbers are not reliable enough to be asserting on. + if start_indent is None: + return + + cur_line = start_line + 1 + end_line = cur_line + # After this loop, function body will be lines [start_line, end_line) + while cur_line < len(self.source): + cur_indent = self.indentation_level(cur_line) + if cur_indent is None: + # Consume the line, but don't mark it as belonging to the function yet. + cur_line += 1 + elif cur_indent > start_indent: + # A non-blank line that belongs to the function. + cur_line += 1 + end_line = cur_line + else: + # We reached a line outside the function definition. + break + + is_typed = defn.type is not None + for line in range(start_line, end_line): + old_indent, _ = self.lines_covered[line] + # If there was an old indent level for this line, and the new + # level isn't increasing the indentation, ignore it. + # This is to be defensive against funniness in our line numbers, + # which are not always reliable. + if old_indent <= start_indent: + self.lines_covered[line] = (start_indent, is_typed) + + # Visit the body, in case there are nested functions + super().visit_func_def(defn) + + +class LineCoverageReporter(AbstractReporter): + """Exact line coverage reporter. + + This reporter writes a JSON dictionary with one field 'lines' to + the file 'coverage.json' in the specified report directory. The + value of that field is a dictionary which associates to each + source file's absolute pathname the list of line numbers that + belong to typed functions in that file. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.lines_covered: dict[str, list[int]] = {} + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + if os.path.isdir(tree.path): # can happen with namespace packages + return + + with open(tree.path) as f: + tree_source = f.readlines() + + coverage_visitor = LineCoverageVisitor(tree_source) + tree.accept(coverage_visitor) + + covered_lines = [] + for line_number, (_, typed) in enumerate(coverage_visitor.lines_covered): + if typed: + covered_lines.append(line_number + 1) + + self.lines_covered[os.path.abspath(tree.path)] = covered_lines + + def on_finish(self) -> None: + with open(os.path.join(self.output_dir, "coverage.json"), "w") as f: + json.dump({"lines": self.lines_covered}, f) + + +register_reporter("linecoverage", LineCoverageReporter) + + +class FileInfo: + def __init__(self, name: str, module: str) -> None: + self.name = name + self.module = module + self.counts = [0] * len(stats.precision_names) + + def total(self) -> int: + return sum(self.counts) + + def attrib(self) -> dict[str, str]: + return {name: str(val) for name, val in sorted(zip(stats.precision_names, self.counts))} + + +class MemoryXmlReporter(AbstractReporter): + """Internal reporter that generates XML in memory. + + This is used by all other XML-based reporters to avoid duplication. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.xslt_html_path = os.path.join(reports.data_dir, "xml", "mypy-html.xslt") + self.xslt_txt_path = os.path.join(reports.data_dir, "xml", "mypy-txt.xslt") + self.css_html_path = os.path.join(reports.data_dir, "xml", "mypy-html.css") + xsd_path = os.path.join(reports.data_dir, "xml", "mypy.xsd") + self.schema = etree.XMLSchema(etree.parse(xsd_path)) + self.last_xml: Any | None = None + self.files: list[FileInfo] = [] + + # XML doesn't like control characters, but they are sometimes + # legal in source code (e.g. comments, string literals). + # Tabs (#x09) are allowed in XML content. + control_fixer: Final = str.maketrans("".join(chr(i) for i in range(32) if i != 9), "?" * 31) + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + self.last_xml = None + + try: + path = os.path.relpath(tree.path) + except ValueError: + return + + if should_skip_path(path) or os.path.isdir(path): + return # `path` can sometimes be a directory, see #11334 + + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + ) + tree.accept(visitor) + + root = etree.Element("mypy-report-file", name=path, module=tree._fullname) + doc = etree.ElementTree(root) + file_info = FileInfo(path, tree._fullname) + + for lineno, line_text in iterate_python_lines(path): + status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) + file_info.counts[status] += 1 + etree.SubElement( + root, + "line", + any_info=self._get_any_info_for_line(visitor, lineno), + content=line_text.rstrip("\n").translate(self.control_fixer), + number=str(lineno), + precision=stats.precision_names[status], + ) + # Assumes a layout similar to what XmlReporter uses. + xslt_path = os.path.relpath("mypy-html.xslt", path) + transform_pi = etree.ProcessingInstruction( + "xml-stylesheet", f'type="text/xsl" href="{pathname2url(xslt_path)}"' + ) + root.addprevious(transform_pi) + self.schema.assertValid(doc) + + self.last_xml = doc + self.files.append(file_info) + + @staticmethod + def _get_any_info_for_line(visitor: stats.StatisticsVisitor, lineno: int) -> str: + if lineno in visitor.any_line_map: + result = "Any Types on this line: " + counter: collections.Counter[int] = collections.Counter() + for typ in visitor.any_line_map[lineno]: + counter[typ.type_of_any] += 1 + for any_type, occurrences in counter.items(): + result += f"\n{type_of_any_name_map[any_type]} (x{occurrences})" + return result + else: + return "No Anys on this line!" + + def on_finish(self) -> None: + self.last_xml = None + # index_path = os.path.join(self.output_dir, 'index.xml') + output_files = sorted(self.files, key=lambda x: x.module) + + root = etree.Element("mypy-report-index", name="index") + doc = etree.ElementTree(root) + + for file_info in output_files: + etree.SubElement( + root, + "file", + file_info.attrib(), + module=file_info.module, + name=pathname2url(file_info.name), + total=str(file_info.total()), + ) + xslt_path = os.path.relpath("mypy-html.xslt", ".") + transform_pi = etree.ProcessingInstruction( + "xml-stylesheet", f'type="text/xsl" href="{pathname2url(xslt_path)}"' + ) + root.addprevious(transform_pi) + self.schema.assertValid(doc) + + self.last_xml = doc + + +register_reporter("memory-xml", MemoryXmlReporter, needs_lxml=True) + + +def get_line_rate(covered_lines: int, total_lines: int) -> str: + if total_lines == 0: + return str(1.0) + else: + return f"{covered_lines / total_lines:.4f}" + + +class CoberturaPackage: + """Container for XML and statistics mapping python modules to Cobertura package.""" + + def __init__(self, name: str) -> None: + self.name = name + self.classes: dict[str, Any] = {} + self.packages: dict[str, CoberturaPackage] = {} + self.total_lines = 0 + self.covered_lines = 0 + + def as_xml(self) -> Any: + package_element = etree.Element("package", complexity="1.0", name=self.name) + package_element.attrib["branch-rate"] = "0" + package_element.attrib["line-rate"] = get_line_rate(self.covered_lines, self.total_lines) + classes_element = etree.SubElement(package_element, "classes") + for class_name in sorted(self.classes): + classes_element.append(self.classes[class_name]) + self.add_packages(package_element) + return package_element + + def add_packages(self, parent_element: Any) -> None: + if self.packages: + packages_element = etree.SubElement(parent_element, "packages") + for package in sorted(self.packages.values(), key=attrgetter("name")): + packages_element.append(package.as_xml()) + + +class CoberturaXmlReporter(AbstractReporter): + """Reporter for generating Cobertura compliant XML.""" + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.root = etree.Element("coverage", timestamp=str(int(time.time())), version=__version__) + self.doc = etree.ElementTree(self.root) + self.root_package = CoberturaPackage(".") + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + path = os.path.relpath(tree.path) + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + ) + tree.accept(visitor) + + class_name = os.path.basename(path) + file_info = FileInfo(path, tree._fullname) + class_element = etree.Element("class", complexity="1.0", filename=path, name=class_name) + etree.SubElement(class_element, "methods") + lines_element = etree.SubElement(class_element, "lines") + + class_lines_covered = 0 + class_total_lines = 0 + for lineno, _ in iterate_python_lines(path): + status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) + hits = 0 + branch = False + if status == stats.TYPE_EMPTY: + continue + class_total_lines += 1 + if status != stats.TYPE_ANY: + class_lines_covered += 1 + hits = 1 + if status == stats.TYPE_IMPRECISE: + branch = True + file_info.counts[status] += 1 + line_element = etree.SubElement( + lines_element, + "line", + branch=str(branch).lower(), + hits=str(hits), + number=str(lineno), + precision=stats.precision_names[status], + ) + if branch: + line_element.attrib["condition-coverage"] = "50% (1/2)" + class_element.attrib["branch-rate"] = "0" + class_element.attrib["line-rate"] = get_line_rate(class_lines_covered, class_total_lines) + # parent_module is set to whichever module contains this file. For most files, we want + # to simply strip the last element off of the module. But for __init__.py files, + # the module == the parent module. + parent_module = file_info.module.rsplit(".", 1)[0] + if file_info.name.endswith("__init__.py"): + parent_module = file_info.module + + if parent_module not in self.root_package.packages: + self.root_package.packages[parent_module] = CoberturaPackage(parent_module) + current_package = self.root_package.packages[parent_module] + packages_to_update = [self.root_package, current_package] + for package in packages_to_update: + package.total_lines += class_total_lines + package.covered_lines += class_lines_covered + current_package.classes[class_name] = class_element + + def on_finish(self) -> None: + self.root.attrib["line-rate"] = get_line_rate( + self.root_package.covered_lines, self.root_package.total_lines + ) + self.root.attrib["branch-rate"] = "0" + self.root.attrib["lines-covered"] = str(self.root_package.covered_lines) + self.root.attrib["lines-valid"] = str(self.root_package.total_lines) + sources = etree.SubElement(self.root, "sources") + source_element = etree.SubElement(sources, "source") + source_element.text = os.getcwd() + self.root_package.add_packages(self.root) + out_path = os.path.join(self.output_dir, "cobertura.xml") + self.doc.write(out_path, encoding="utf-8", pretty_print=True) + print("Generated Cobertura report:", os.path.abspath(out_path)) + + +register_reporter("cobertura-xml", CoberturaXmlReporter, needs_lxml=True) + + +class AbstractXmlReporter(AbstractReporter): + """Internal abstract class for reporters that work via XML.""" + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + memory_reporter = reports.add_report("memory-xml", "") + assert isinstance(memory_reporter, MemoryXmlReporter) + # The dependency will be called first. + self.memory_xml = memory_reporter + + +class XmlReporter(AbstractXmlReporter): + """Public reporter that exports XML. + + The produced XML files contain a reference to the absolute path + of the html transform, so they will be locally viewable in a browser. + + However, there is a bug in Chrome and all other WebKit-based browsers + that makes it fail from file:// URLs but work on http:// URLs. + """ + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + last_xml = self.memory_xml.last_xml + if last_xml is None: + return + path = os.path.relpath(tree.path) + if path.startswith(".."): + return + out_path = os.path.join(self.output_dir, "xml", path + ".xml") + os.makedirs(os.path.dirname(out_path), exist_ok=True) + last_xml.write(out_path, encoding="utf-8") + + def on_finish(self) -> None: + last_xml = self.memory_xml.last_xml + assert last_xml is not None + out_path = os.path.join(self.output_dir, "index.xml") + out_xslt = os.path.join(self.output_dir, "mypy-html.xslt") + out_css = os.path.join(self.output_dir, "mypy-html.css") + last_xml.write(out_path, encoding="utf-8") + shutil.copyfile(self.memory_xml.xslt_html_path, out_xslt) + shutil.copyfile(self.memory_xml.css_html_path, out_css) + print("Generated XML report:", os.path.abspath(out_path)) + + +register_reporter("xml", XmlReporter, needs_lxml=True) + + +class XsltHtmlReporter(AbstractXmlReporter): + """Public reporter that exports HTML via XSLT. + + This is slightly different than running `xsltproc` on the .xml files, + because it passes a parameter to rewrite the links. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.xslt_html = etree.XSLT(etree.parse(self.memory_xml.xslt_html_path)) + self.param_html = etree.XSLT.strparam("html") + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + last_xml = self.memory_xml.last_xml + if last_xml is None: + return + path = os.path.relpath(tree.path) + if path.startswith(".."): + return + out_path = os.path.join(self.output_dir, "html", path + ".html") + os.makedirs(os.path.dirname(out_path), exist_ok=True) + transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html)) + with open(out_path, "wb") as out_file: + out_file.write(transformed_html) + + def on_finish(self) -> None: + last_xml = self.memory_xml.last_xml + assert last_xml is not None + out_path = os.path.join(self.output_dir, "index.html") + out_css = os.path.join(self.output_dir, "mypy-html.css") + transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html)) + with open(out_path, "wb") as out_file: + out_file.write(transformed_html) + shutil.copyfile(self.memory_xml.css_html_path, out_css) + print("Generated HTML report (via XSLT):", os.path.abspath(out_path)) + + +register_reporter("xslt-html", XsltHtmlReporter, needs_lxml=True) + + +class XsltTxtReporter(AbstractXmlReporter): + """Public reporter that exports TXT via XSLT. + + Currently this only does the summary, not the individual reports. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.xslt_txt = etree.XSLT(etree.parse(self.memory_xml.xslt_txt_path)) + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + pass + + def on_finish(self) -> None: + last_xml = self.memory_xml.last_xml + assert last_xml is not None + out_path = os.path.join(self.output_dir, "index.txt") + transformed_txt = bytes(self.xslt_txt(last_xml)) + with open(out_path, "wb") as out_file: + out_file.write(transformed_txt) + print("Generated TXT report (via XSLT):", os.path.abspath(out_path)) + + +register_reporter("xslt-txt", XsltTxtReporter, needs_lxml=True) + +alias_reporter("xslt-html", "html") +alias_reporter("xslt-txt", "txt") + + +class LinePrecisionReporter(AbstractReporter): + """Report per-module line counts for typing precision. + + Each line is classified into one of these categories: + + * precise (fully type checked) + * imprecise (Any types in a type component, such as List[Any]) + * any (something with an Any type, implicit or explicit) + * empty (empty line, comment or docstring) + * unanalyzed (mypy considers line unreachable) + + The meaning of these categories varies slightly depending on + context. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.files: list[FileInfo] = [] + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + try: + path = os.path.relpath(tree.path) + except ValueError: + return + + if should_skip_path(path): + return + + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + ) + tree.accept(visitor) + + file_info = FileInfo(path, tree._fullname) + for lineno, _ in iterate_python_lines(path): + status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) + file_info.counts[status] += 1 + + self.files.append(file_info) + + def on_finish(self) -> None: + if not self.files: + # Nothing to do. + return + output_files = sorted(self.files, key=lambda x: x.module) + report_file = os.path.join(self.output_dir, "lineprecision.txt") + width = max(4, max(len(info.module) for info in output_files)) + titles = ("Lines", "Precise", "Imprecise", "Any", "Empty", "Unanalyzed") + widths = (width,) + tuple(len(t) for t in titles) + fmt = "{:%d} {:%d} {:%d} {:%d} {:%d} {:%d} {:%d}\n" % widths + with open(report_file, "w") as f: + f.write(fmt.format("Name", *titles)) + f.write("-" * (width + 51) + "\n") + for file_info in output_files: + counts = file_info.counts + f.write( + fmt.format( + file_info.module.ljust(width), + file_info.total(), + counts[stats.TYPE_PRECISE], + counts[stats.TYPE_IMPRECISE], + counts[stats.TYPE_ANY], + counts[stats.TYPE_EMPTY], + counts[stats.TYPE_UNANALYZED], + ) + ) + + +register_reporter("lineprecision", LinePrecisionReporter) + + +# Reporter class names are defined twice to speed up mypy startup, as this +# module is slow to import. Ensure that the two definitions match. +assert set(reporter_classes) == set(REPORTER_NAMES) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/scope.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/scope.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e4cc93418abb0955dc9b92192e0eb739d701007a Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/scope.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/scope.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..7c234a3c7bc5640b22e5b07774b487e96edcf815 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/scope.py @@ -0,0 +1,125 @@ +"""Track current scope to easily calculate the corresponding fine-grained target. + +TODO: Use everywhere where we track targets, including in mypy.errors. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager, nullcontext +from typing import TypeAlias as _TypeAlias + +from mypy.nodes import FuncBase, TypeInfo + +SavedScope: _TypeAlias = tuple[str, TypeInfo | None, FuncBase | None] + + +class Scope: + """Track which target we are processing at any given time.""" + + def __init__(self) -> None: + self.module: str | None = None + self.classes: list[TypeInfo] = [] + self.function: FuncBase | None = None + self.functions: list[FuncBase] = [] + # Number of nested scopes ignored (that don't get their own separate targets) + self.ignored = 0 + + def current_module_id(self) -> str: + assert self.module + return self.module + + def current_target(self) -> str: + """Return the current target (non-class; for a class return enclosing module).""" + assert self.module + if self.function: + fullname = self.function.fullname + return fullname or "" + return self.module + + def current_full_target(self) -> str: + """Return the current target (may be a class).""" + assert self.module + if self.function: + return self.function.fullname + if self.classes: + return self.classes[-1].fullname + return self.module + + def current_type_name(self) -> str | None: + """Return the current type's short name if it exists""" + return self.classes[-1].name if self.classes else None + + def current_function_name(self) -> str | None: + """Return the current function's short name if it exists""" + return self.function.name if self.function else None + + @contextmanager + def module_scope(self, prefix: str) -> Iterator[None]: + self.module = prefix + self.classes = [] + self.function = None + self.ignored = 0 + yield + assert self.module + self.module = None + + @contextmanager + def function_scope(self, fdef: FuncBase) -> Iterator[None]: + self.functions.append(fdef) + if not self.function: + self.function = fdef + else: + # Nested functions are part of the topmost function target. + self.ignored += 1 + yield + self.functions.pop() + if self.ignored: + # Leave a scope that's included in the enclosing target. + self.ignored -= 1 + else: + assert self.function + self.function = None + + def outer_functions(self) -> list[FuncBase]: + return self.functions[:-1] + + def enter_class(self, info: TypeInfo) -> None: + """Enter a class target scope.""" + if not self.function: + self.classes.append(info) + else: + # Classes within functions are part of the enclosing function target. + self.ignored += 1 + + def leave_class(self) -> None: + """Leave a class target scope.""" + if self.ignored: + # Leave a scope that's included in the enclosing target. + self.ignored -= 1 + else: + assert self.classes + # Leave the innermost class. + self.classes.pop() + + @contextmanager + def class_scope(self, info: TypeInfo) -> Iterator[None]: + self.enter_class(info) + yield + self.leave_class() + + def save(self) -> SavedScope: + """Produce a saved scope that can be entered with saved_scope()""" + assert self.module + # We only save the innermost class, which is sufficient since + # the rest are only needed for when classes are left. + cls = self.classes[-1] if self.classes else None + return self.module, cls, self.function + + @contextmanager + def saved_scope(self, saved: SavedScope) -> Iterator[None]: + module, info, function = saved + with self.module_scope(module): + with self.class_scope(info) if info else nullcontext(): + with self.function_scope(function) if function else nullcontext(): + yield diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c146e1e72aa794e80e04a649c406f8b715943153 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal.py new file mode 100644 index 0000000000000000000000000000000000000000..d944c60cd16e4aa68d9c9d5011d32e516144d319 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal.py @@ -0,0 +1,8390 @@ +"""The semantic analyzer. + +Bind names to definitions and do various other simple consistency +checks. Populate symbol tables. The semantic analyzer also detects +special forms which reuse generic syntax such as NamedTuple and +cast(). Multiple analysis iterations may be needed to analyze forward +references and import cycles. Each iteration "fills in" additional +bindings and references until everything has been bound. + +For example, consider this program: + + x = 1 + y = x + +Here semantic analysis would detect that the assignment 'x = 1' +defines a new variable, the type of which is to be inferred (in a +later pass; type inference or type checking is not part of semantic +analysis). Also, it would bind both references to 'x' to the same +module-level variable (Var) node. The second assignment would also +be analyzed, and the type of 'y' marked as being inferred. + +Semantic analysis of types is implemented in typeanal.py. + +See semanal_main.py for the top-level logic. + +Some important properties: + +* After semantic analysis is complete, no PlaceholderNode and + PlaceholderType instances should remain. During semantic analysis, + if we encounter one of these, the current target should be deferred. + +* A TypeInfo is only created once we know certain basic information about + a type, such as the MRO, existence of a Tuple base class (e.g., for named + tuples), and whether we have a TypedDict. We use a temporary + PlaceholderNode node in the symbol table if some such information is + missing. + +* For assignments, we only add a non-placeholder symbol table entry once + we know the sort of thing being defined (variable, NamedTuple, type alias, + etc.). + +* Every part of the analysis step must support multiple iterations over + the same AST nodes, and each iteration must be able to fill in arbitrary + things that were missing or incomplete in previous iterations. + +* Changes performed by the analysis need to be reversible, since mypy + daemon strips and reuses existing ASTs (to improve performance and/or + reduce memory use). +""" + +from __future__ import annotations + +import re +from collections.abc import Callable, Collection, Iterable, Iterator +from contextlib import contextmanager +from typing import Any, Final, TypeAlias as _TypeAlias, TypeGuard, TypeVar, cast +from typing_extensions import assert_never + +from mypy import errorcodes as codes, message_registry +from mypy.constant_fold import constant_fold_expr +from mypy.errorcodes import PROPERTY_DECORATOR, ErrorCode +from mypy.errors import Errors, report_internal_error +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.message_registry import ErrorMessage +from mypy.messages import ( + SUGGESTED_TEST_FIXTURES, + TYPES_FOR_UNIMPORTED_HINTS, + MessageBuilder, + best_matches, + pretty_seq, +) +from mypy.mro import MroError, calculate_mro +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + ARG_STAR2, + CONTRAVARIANT, + COVARIANT, + GDEF, + IMPLICITLY_ABSTRACT, + INVARIANT, + IS_ABSTRACT, + LDEF, + MDEF, + NOT_ABSTRACT, + PARAM_SPEC_KIND, + REVEAL_LOCALS, + REVEAL_TYPE, + RUNTIME_PROTOCOL_DECOS, + SYMBOL_FUNCBASE_TYPES, + TYPE_VAR_KIND, + TYPE_VAR_TUPLE_KIND, + VARIANCE_NOT_READY, + ArgKind, + AssertStmt, + AssertTypeExpr, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + Context, + ContinueStmt, + DataclassTransformSpec, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + ExpressionStmt, + FakeExpression, + FloatExpr, + ForStmt, + FuncBase, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportBase, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + Lvalue, + MatchStmt, + MaybeTypeExpression, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + ParamSpecExpr, + PassStmt, + PlaceholderNode, + PromoteExpr, + RaiseStmt, + RefExpr, + ReturnStmt, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + SplittingVisitor, + StarExpr, + Statement, + StrExpr, + SuperExpr, + SymbolNode, + SymbolTable, + SymbolTableNode, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAlias, + TypeAliasExpr, + TypeAliasStmt, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeInfo, + TypeParam, + TypeVarExpr, + TypeVarLikeExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, + get_member_expr_fullname, + implicit_module_attrs, + is_final_node, + type_aliases, + type_aliases_source_versions, + typing_extensions_aliases, +) +from mypy.options import TYPE_FORM, Options +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.plugin import ( + ClassDefContext, + DynamicClassDefContext, + Plugin, + SemanticAnalyzerPluginInterface, +) +from mypy.plugins import dataclasses as dataclasses_plugin +from mypy.reachability import ( + ALWAYS_FALSE, + ALWAYS_TRUE, + MYPY_FALSE, + MYPY_TRUE, + infer_condition_value, + infer_reachability_of_if_statement, + infer_reachability_of_match_statement, +) +from mypy.scope import Scope +from mypy.semanal_enum import EnumCallAnalyzer +from mypy.semanal_namedtuple import NamedTupleAnalyzer +from mypy.semanal_newtype import NewTypeAnalyzer +from mypy.semanal_shared import ( + ALLOW_INCOMPATIBLE_OVERRIDE, + PRIORITY_FALLBACKS, + SemanticAnalyzerInterface, + calculate_tuple_fallback, + find_dataclass_transform_spec, + has_placeholder, + parse_bool, + require_bool_literal_argument, + set_callable_name as set_callable_name, +) +from mypy.semanal_typeddict import TypedDictAnalyzer +from mypy.tvar_scope import TypeVarLikeScope +from mypy.typeanal import ( + SELF_TYPE_NAMES, + FindTypeVarVisitor, + TypeAnalyser, + TypeVarDefaultTranslator, + TypeVarLikeList, + analyze_type_alias, + check_for_explicit_any, + check_vec_type_args, + detect_diverging_alias, + find_self_type, + fix_instance, + has_any_from_unimported_type, + type_constructors, + validate_instance, +) +from mypy.typeops import function_type, get_type_vars, try_getting_str_literals_from_type +from mypy.types import ( + ASSERT_TYPE_NAMES, + DATACLASS_TRANSFORM_NAMES, + DEPRECATED_TYPE_NAMES, + DISJOINT_BASE_DECORATOR_NAMES, + FINAL_DECORATOR_NAMES, + FINAL_TYPE_NAMES, + IMPORTED_REVEAL_TYPE_NAMES, + NEVER_NAMES, + OVERLOAD_NAMES, + OVERRIDE_DECORATOR_NAMES, + PROTOCOL_NAMES, + REVEAL_TYPE_NAMES, + TPDICT_NAMES, + TYPE_ALIAS_NAMES, + TYPE_CHECK_ONLY_NAMES, + TYPE_NAMES, + TYPE_VAR_LIKE_NAMES, + TYPED_NAMEDTUPLE_NAMES, + UNPACK_TYPE_NAMES, + AnyType, + CallableType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PlaceholderType, + ProperType, + TrivialSyntheticTypeTranslator, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeStrVisitor, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UnionType, + UnpackType, + flatten_nested_tuples, + get_proper_type, + get_proper_types, + has_type_vars, + is_named_instance, + remove_dups, + type_vars_as_args, +) +from mypy.types_utils import is_invalid_recursive_alias, store_argument_type +from mypy.typevars import fill_typevars +from mypy.util import correct_relative_import, is_dunder, module_prefix, unmangle, unnamed_function +from mypy.visitor import NodeVisitor + +T = TypeVar("T") + + +# Whether to print diagnostic information for failed full parses +# in SemanticAnalyzer.try_parse_as_type_expression(). +# +# See also: misc/analyze_typeform_stats.py +DEBUG_TYPE_EXPRESSION_FULL_PARSE_FAILURES: Final = False + + +FUTURE_IMPORTS: Final = { + "__future__.nested_scopes": "nested_scopes", + "__future__.generators": "generators", + "__future__.division": "division", + "__future__.absolute_import": "absolute_import", + "__future__.with_statement": "with_statement", + "__future__.print_function": "print_function", + "__future__.unicode_literals": "unicode_literals", + "__future__.barry_as_FLUFL": "barry_as_FLUFL", + "__future__.generator_stop": "generator_stop", + "__future__.annotations": "annotations", +} + + +# Special cased built-in classes that are needed for basic functionality and need to be +# available very early on. +CORE_BUILTIN_CLASSES: Final = ["object", "bool", "function"] + + +# Python has several different scope/namespace kinds with subtly different semantics. +SCOPE_GLOBAL: Final = 0 # Module top level +SCOPE_CLASS: Final = 1 # Class body +SCOPE_FUNC: Final = 2 # Function or lambda +SCOPE_COMPREHENSION: Final = 3 # Comprehension or generator expression +SCOPE_ANNOTATION: Final = 4 # Annotation scopes for type parameters and aliases (PEP 695) + + +# Used for tracking incomplete references +Tag: _TypeAlias = int + + +# Matches two words separated by whitespace, where each word lacks +# any symbols which have special meaning in a type expression. +# +# Any string literal matching this common pattern cannot be a valid +# type expression and can be ignored quickly when attempting to parse a +# string literal as a type expression. +_MULTIPLE_WORDS_NONTYPE_RE = re.compile(r'\s*[^\s.\'"|\[]+\s+[^\s.\'"|\[]') + +# Matches any valid Python identifier, including identifiers with Unicode characters. +# +# [^\d\W] = word character that is not a digit +# \w = word character +# \Z = match end of string; does not allow a trailing \n, unlike $ +_IDENTIFIER_RE = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE) + + +class SemanticAnalyzer( + NodeVisitor[None], SemanticAnalyzerInterface, SemanticAnalyzerPluginInterface, SplittingVisitor +): + """Semantically analyze parsed mypy files. + + The analyzer binds names and does various consistency checks for an + AST. Note that type checking is performed as a separate pass. + """ + + __deletable__ = ["patches", "options", "cur_mod_node"] + + # Module name space + modules: dict[str, MypyFile] + # Global name space for current module + globals: SymbolTable + # Names declared using "global" (separate set for each scope) + global_decls: list[set[str]] + # Names declared using "nonlocal" (separate set for each scope) + nonlocal_decls: list[set[str]] + # Local names of function scopes; None for non-function scopes. + locals: list[SymbolTable | None] + # Type of each scope (SCOPE_*, indexes match locals) + scope_stack: list[int] + # Nested block depths of scopes + block_depth: list[int] + # TypeInfo of directly enclosing class (or None) + _type: TypeInfo | None = None + # Stack of outer classes (the second tuple item contains tvars). + type_stack: list[TypeInfo | None] + # Type variables bound by the current scope, be it class or function + tvar_scope: TypeVarLikeScope + # Per-module options + options: Options + + # Stack of functions being analyzed + function_stack: list[FuncItem] + + # Set to True if semantic analysis defines a name, or replaces a + # placeholder definition. If some iteration makes no progress, + # there can be at most one additional final iteration (see below). + progress = False + deferred = False # Set to true if another analysis pass is needed + incomplete = False # Set to true if current module namespace is missing things + # Is this the final iteration of semantic analysis (where we report + # unbound names due to cyclic definitions and should not defer)? + _final_iteration = False + # These names couldn't be added to the symbol table due to incomplete deps. + # Note that missing names are per module, _not_ per namespace. This means that e.g. + # a missing name at global scope will block adding same name at a class scope. + # This should not affect correctness and is purely a performance issue, + # since it can cause unnecessary deferrals. These are represented as + # PlaceholderNodes in the symbol table. We use this to ensure that the first + # definition takes precedence even if it's incomplete. + # + # Note that a star import adds a special name '*' to the set, this blocks + # adding _any_ names in the current file. + missing_names: list[set[str]] + # Callbacks that will be called after semantic analysis to tweak things. + patches: list[tuple[int, Callable[[], None]]] + loop_depth: list[int] # Depth of breakable loops + cur_mod_id = "" # Current module id (or None) (phase 2) + _is_stub_file = False # Are we analyzing a stub file? + _is_typeshed_stub_file = False # Are we analyzing a typeshed stub file? + imports: set[str] # Imported modules (during phase 2 analysis) + # Note: some imports (and therefore dependencies) might + # not be found in phase 1, for example due to * imports. + errors: Errors # Keeps track of generated errors + plugin: Plugin # Mypy plugin for special casing of library features + statement: Statement | None = None # Statement/definition being analyzed + + # Mapping from 'async def' function definitions to their return type wrapped as a + # 'Coroutine[Any, Any, T]'. Used to keep track of whether a function definition's + # return type has already been wrapped, by checking if the function definition's + # type is stored in this mapping and that it still matches. + wrapped_coro_return_types: dict[FuncDef, Type] = {} + + def __init__( + self, + modules: dict[str, MypyFile], + missing_modules: dict[str, int], + incomplete_namespaces: set[str], + errors: Errors, + plugin: Plugin, + import_map: dict[str, set[str]], + ) -> None: + """Construct semantic analyzer. + + We reuse the same semantic analyzer instance across multiple modules. + + Args: + modules: Global modules dictionary + missing_modules: Modules that could not be imported encountered so far + incomplete_namespaces: Namespaces that are being populated during semantic analysis + (can contain modules and classes within the current SCC; mutated by the caller) + errors: Report analysis errors using this instance + """ + self.locals = [None] + self.scope_stack = [SCOPE_GLOBAL] + # Saved namespaces from previous iteration. Every top-level function/method body is + # analyzed in several iterations until all names are resolved. We need to save + # the local namespaces for the top level function and all nested functions between + # these iterations. See also semanal_main.process_top_level_function(). + self.saved_locals: dict[ + FuncItem | GeneratorExpr | DictionaryComprehension, SymbolTable + ] = {} + self.imports = set() + self._type = None + self.type_stack = [] + # Are the namespaces of classes being processed complete? + self.incomplete_type_stack: list[bool] = [] + self.tvar_scope = TypeVarLikeScope() + self.function_stack = [] + self.block_depth = [0] + self.loop_depth = [0] + self.errors = errors + self.modules = modules + self.import_map = import_map + self.msg = MessageBuilder(errors, modules) + self.missing_modules = missing_modules + self.missing_names = [set()] + # These namespaces are still in process of being populated. If we encounter a + # missing name in these namespaces, we need to defer the current analysis target, + # since it's possible that the name will be there once the namespace is complete. + self.incomplete_namespaces = incomplete_namespaces + self.all_exports: list[str] = [] + self.plugin = plugin + self.recurse_into_functions = True + self.scope = Scope() + + # Trace line numbers for every file where deferral happened during analysis of + # current SCC or top-level function. + self.deferral_debug_context: list[tuple[str, int]] = [] + + # This is needed to properly support recursive type aliases. The problem is that + # Foo[Bar] could mean three things depending on context: a target for type alias, + # a normal index expression (including enum index), or a type application. + # The latter is particularly problematic as it can falsely create incomplete + # refs while analysing rvalues of type aliases. To avoid this we first analyse + # rvalues while temporarily setting this to True. + self.basic_type_applications = False + + # Used to temporarily enable unbound type variables in some contexts. Namely, + # in base class expressions, and in right hand sides of type aliases. Do not add + # new uses of this, as this may cause leaking `UnboundType`s to type checking. + self.allow_unbound_tvars = False + + # Used to pass information about current overload index to visit_func_def(). + self.current_overload_item: int | None = None + + # Used to track whether currently inside an except* block. This helps + # to invoke errors when continue/break/return is used inside except* block. + self.inside_except_star_block: bool = False + # Used to track edge case when return is still inside except* if it enters a loop + self.return_stmt_inside_except_star_block: bool = False + + self._str_type: Instance | None = None + self._function_type: Instance | None = None + self._object_type: Instance | None = None + + # TypeForm profiling counters + self.type_expression_parse_count: int = 0 # Total try_parse_as_type_expression calls + self.type_expression_full_parse_success_count: int = 0 # Successful full parses + self.type_expression_full_parse_failure_count: int = 0 # Failed full parses + + # Imports of submodules transitively visible from given module. + # This is needed to support patterns like this + # [a.py] + # import b + # import foo + # foo.bar # <- this should work even if bar is not re-exported in foo + # [b.py] + # import foo.bar + self.transitive_submodule_imports: dict[str, set[str]] = {} + + # mypyc doesn't properly handle implementing an abstractproperty + # with a regular attribute so we make them properties + @property + def type(self) -> TypeInfo | None: + return self._type + + @property + def is_stub_file(self) -> bool: + return self._is_stub_file + + @property + def is_typeshed_stub_file(self) -> bool: + return self._is_typeshed_stub_file + + @property + def final_iteration(self) -> bool: + return self._final_iteration + + @contextmanager + def allow_unbound_tvars_set(self) -> Iterator[None]: + old = self.allow_unbound_tvars + self.allow_unbound_tvars = True + try: + yield + finally: + self.allow_unbound_tvars = old + + @contextmanager + def inside_except_star_block_set( + self, value: bool, entering_loop: bool = False + ) -> Iterator[None]: + old = self.inside_except_star_block + self.inside_except_star_block = value + + # Return statement would still be in except* scope if entering loops + if not entering_loop: + old_return_stmt_flag = self.return_stmt_inside_except_star_block + self.return_stmt_inside_except_star_block = value + + try: + yield + finally: + self.inside_except_star_block = old + if not entering_loop: + self.return_stmt_inside_except_star_block = old_return_stmt_flag + + # + # Preparing module (performed before semantic analysis) + # + + def prepare_file(self, file_node: MypyFile) -> None: + """Prepare a freshly parsed file for semantic analysis.""" + if "builtins" in self.modules: + file_node.names["__builtins__"] = SymbolTableNode(GDEF, self.modules["builtins"]) + if file_node.fullname == "builtins": + self.prepare_builtins_namespace(file_node) + if file_node.fullname == "typing": + self.prepare_typing_namespace(file_node, type_aliases) + if file_node.fullname == "typing_extensions": + self.prepare_typing_namespace(file_node, typing_extensions_aliases) + + def prepare_typing_namespace(self, file_node: MypyFile, aliases: dict[str, str]) -> None: + """Remove dummy alias definitions such as List = TypeAlias(object) from typing. + + They will be replaced with real aliases when corresponding targets are ready. + """ + + # This is all pretty unfortunate. typeshed now has a + # sys.version_info check for OrderedDict, and we shouldn't + # take it out, because it is correct and a typechecker should + # use that as a source of truth. But instead we rummage + # through IfStmts to remove the info first. (I tried to + # remove this whole machinery and ran into issues with the + # builtins/typing import cycle.) + def helper(defs: list[Statement]) -> None: + for stmt in defs.copy(): + if isinstance(stmt, IfStmt): + for body in stmt.body: + helper(body.body) + if stmt.else_body: + helper(stmt.else_body.body) + if ( + isinstance(stmt, AssignmentStmt) + and len(stmt.lvalues) == 1 + and isinstance(stmt.lvalues[0], NameExpr) + ): + # Assignment to a simple name, remove it if it is a dummy alias. + if f"{file_node.fullname}.{stmt.lvalues[0].name}" in aliases: + defs.remove(stmt) + + helper(file_node.defs) + + def prepare_builtins_namespace(self, file_node: MypyFile) -> None: + """Add certain special-cased definitions to the builtins module. + + Some definitions are too special or fundamental to be processed + normally from the AST. + """ + names = file_node.names + + # Add empty definition for core built-in classes, since they are required for basic + # operation. These will be completed later on. + for name in CORE_BUILTIN_CLASSES: + cdef = ClassDef(name, Block([])) # Dummy ClassDef, will be replaced later + info = TypeInfo(SymbolTable(), cdef, "builtins") + info._fullname = f"builtins.{name}" + names[name] = SymbolTableNode(GDEF, info) + + bool_info = names["bool"].node + assert isinstance(bool_info, TypeInfo) + bool_type = Instance(bool_info, []) + + special_var_types: list[tuple[str, Type]] = [ + ("None", NoneType()), + # reveal_type is a mypy-only function that gives an error with + # the type of its arg. + ("reveal_type", AnyType(TypeOfAny.special_form)), + # reveal_locals is a mypy-only function that gives an error with the types of + # locals + ("reveal_locals", AnyType(TypeOfAny.special_form)), + ("True", bool_type), + ("False", bool_type), + ("__debug__", bool_type), + ] + + for name, typ in special_var_types: + v = Var(name, typ) + v._fullname = f"builtins.{name}" + file_node.names[name] = SymbolTableNode(GDEF, v) + + # + # Analyzing a target + # + + def refresh_partial( + self, + node: MypyFile | FuncDef | OverloadedFuncDef, + patches: list[tuple[int, Callable[[], None]]], + final_iteration: bool, + file_node: MypyFile, + options: Options, + active_type: TypeInfo | None = None, + ) -> None: + """Refresh a stale target in fine-grained incremental mode.""" + self.patches = patches + self.deferred = False + self.incomplete = False + self._final_iteration = final_iteration + self.missing_names[-1] = set() + + with self.file_context(file_node, options, active_type): + if isinstance(node, MypyFile): + self.refresh_top_level(node) + else: + self.recurse_into_functions = True + self.accept(node) + del self.patches + + def refresh_top_level(self, file_node: MypyFile) -> None: + """Reanalyze a stale module top-level in fine-grained incremental mode.""" + if self.options.allow_redefinition_new and not self.options.local_partial_types: + n = TempNode(AnyType(TypeOfAny.special_form)) + n.line = 1 + n.column = 0 + n.end_line = 1 + n.end_column = 0 + self.fail("--local-partial-types must be enabled if using --allow-redefinition-new", n) + if self.options.allow_redefinition_new and self.options.allow_redefinition_old: + n = TempNode(AnyType(TypeOfAny.special_form)) + n.line = 1 + n.column = 0 + n.end_line = 1 + n.end_column = 0 + self.fail( + "--allow-redefinition-old and --allow-redefinition-new" + " should not be used together", + n, + ) + self.recurse_into_functions = False + self.add_implicit_module_attrs(file_node) + for d in file_node.defs: + self.accept(d) + if file_node.fullname == "typing": + self.add_builtin_aliases(file_node) + if file_node.fullname == "typing_extensions": + self.add_typing_extension_aliases(file_node) + self.adjust_public_exports() + self.all_exports = [] + + def add_implicit_module_attrs(self, file_node: MypyFile) -> None: + """Manually add implicit definitions of module '__name__' etc.""" + str_type: Type | None = self.named_type_or_none("builtins.str") + if str_type is None: + str_type = UnboundType("builtins.str") + inst: Type | None + for name, t in implicit_module_attrs.items(): + if name == "__doc__": + typ: Type = str_type + elif name == "__path__": + if not file_node.is_package_init_file(): + continue + # Need to construct the type ourselves, to avoid issues with __builtins__.list + # not being subscriptable or typing.List not getting bound + inst = self.named_type_or_none("builtins.list", [str_type]) + if inst is None: + assert not self.final_iteration, "Cannot find builtins.list to add __path__" + self.defer() + return + typ = inst + elif name == "__annotations__": + inst = self.named_type_or_none( + "builtins.dict", [str_type, AnyType(TypeOfAny.special_form)] + ) + if inst is None: + assert ( + not self.final_iteration + ), "Cannot find builtins.dict to add __annotations__" + self.defer() + return + typ = inst + elif name == "__spec__": + if self.options.use_builtins_fixtures: + inst = self.named_type_or_none("builtins.object") + else: + inst = self.named_type_or_none("importlib.machinery.ModuleSpec") + if inst is None: + if ( + self.final_iteration + or self.options.clone_for_module("importlib.machinery").follow_imports + == "skip" + ): + # If we are not allowed to resolve imports from `importlib.machinery`, + # ModuleSpec will not be available at any iteration. + # Use the fallback earlier. + # (see https://github.com/python/mypy/issues/18237) + inst = self.named_type_or_none("builtins.object") + assert inst is not None, "Cannot find builtins.object" + else: + self.defer() + return + if file_node.name == "__main__": + # https://docs.python.org/3/reference/import.html#main-spec + inst = UnionType.make_union([inst, NoneType()]) + typ = inst + else: + assert t is not None, f"type should be specified for {name}" + typ = UnboundType(t) + + existing = file_node.names.get(name) + if existing is not None and not isinstance(existing.node, PlaceholderNode): + # Already exists. + continue + + an_type = self.anal_type(typ) + if an_type: + var = Var(name, an_type) + var._fullname = self.qualified_name(name) + var.is_ready = True + self.add_symbol(name, var, dummy_context()) + else: + self.add_symbol( + name, + PlaceholderNode(self.qualified_name(name), file_node, -1), + dummy_context(), + ) + + def add_builtin_aliases(self, tree: MypyFile) -> None: + """Add builtin type aliases to typing module. + + For historical reasons, the aliases like `List = list` are not defined + in typeshed stubs for typing module. Instead we need to manually add the + corresponding nodes on the fly. We explicitly mark these aliases as normalized, + so that a user can write `typing.List[int]`. + """ + assert tree.fullname == "typing" + for alias, target_name in type_aliases.items(): + if ( + alias in type_aliases_source_versions + and type_aliases_source_versions[alias] > self.options.python_version + ): + # This alias is not available on this Python version. + continue + name = alias.split(".")[-1] + if name in tree.names and not isinstance(tree.names[name].node, PlaceholderNode): + continue + self.create_alias(tree, target_name, alias, name) + + def add_typing_extension_aliases(self, tree: MypyFile) -> None: + """Typing extensions module does contain some type aliases. + + We need to analyze them as such, because in typeshed + they are just defined as `_Alias()` call. + Which is not supported natively. + """ + assert tree.fullname == "typing_extensions" + + for alias, target_name in typing_extensions_aliases.items(): + name = alias.split(".")[-1] + if name in tree.names and isinstance(tree.names[name].node, TypeAlias): + continue # Do not reset TypeAliases on the second pass. + + # We need to remove any node that is there at the moment. It is invalid. + tree.names.pop(name, None) + + # Now, create a new alias. + self.create_alias(tree, target_name, alias, name) + + def create_alias(self, tree: MypyFile, target_name: str, alias: str, name: str) -> None: + tag = self.track_incomplete_refs() + n = self.lookup_fully_qualified_or_none(target_name) + if n: + if isinstance(n.node, PlaceholderNode): + self.mark_incomplete(name, tree) + else: + # Found built-in class target. Create alias. + target = self.named_type_or_none(target_name, []) + assert target is not None + # Transform List to List[Any], etc. + fix_instance( + target, self.fail, self.note, disallow_any=False, options=self.options + ) + alias_node = TypeAlias( + target, + alias, + tree.fullname, + line=-1, + column=-1, # there is no context + no_args=True, + normalized=True, + ) + self.add_symbol(name, alias_node, tree) + elif self.found_incomplete_ref(tag): + # Built-in class target may not ready yet -- defer. + self.mark_incomplete(name, tree) + else: + # Test fixtures may be missing some builtin classes, which is okay. + # Kill the placeholder if there is one. + if name in tree.names: + assert isinstance(tree.names[name].node, PlaceholderNode) + del tree.names[name] + + def adjust_public_exports(self) -> None: + """Adjust the module visibility of globals due to __all__.""" + if "__all__" in self.globals: + for name, g in self.globals.items(): + # Being included in __all__ explicitly exports and makes public. + if name in self.all_exports: + g.module_public = True + g.module_hidden = False + # But when __all__ is defined, and a symbol is not included in it, + # it cannot be public. + else: + g.module_public = False + + @contextmanager + def file_context( + self, file_node: MypyFile, options: Options, active_type: TypeInfo | None = None + ) -> Iterator[None]: + """Configure analyzer for analyzing targets within a file/class. + + Args: + file_node: target file + options: options specific to the file + active_type: must be the surrounding class to analyze method targets + """ + scope = self.scope + self.options = options + self.errors.set_file(file_node.path, file_node.fullname, scope=scope, options=options) + self.cur_mod_node = file_node + self.cur_mod_id = file_node.fullname + with scope.module_scope(self.cur_mod_id): + self._is_stub_file = file_node.path.lower().endswith(".pyi") + self._is_typeshed_stub_file = file_node.is_typeshed_file(options) + self.globals = file_node.names + self.tvar_scope = TypeVarLikeScope() + + self.named_tuple_analyzer = NamedTupleAnalyzer(options, self, self.msg) + self.typed_dict_analyzer = TypedDictAnalyzer(options, self, self.msg) + self.enum_call_analyzer = EnumCallAnalyzer(options, self) + self.newtype_analyzer = NewTypeAnalyzer(options, self, self.msg) + + # Counter that keeps track of references to undefined things potentially caused by + # incomplete namespaces. + self.num_incomplete_refs = 0 + + if active_type: + enclosing_fullname = active_type.fullname.rsplit(".", 1)[0] + if "." in enclosing_fullname: + enclosing_node = self.lookup_fully_qualified_or_none(enclosing_fullname) + if enclosing_node and isinstance(enclosing_node.node, TypeInfo): + self._type = enclosing_node.node + self.push_type_args(active_type.defn.type_args, active_type.defn) + self.incomplete_type_stack.append(False) + scope.enter_class(active_type) + self.enter_class(active_type.defn.info) + for tvar in active_type.defn.type_vars: + self.tvar_scope.bind_existing(tvar) + + yield + + if active_type: + scope.leave_class() + self.leave_class() + self._type = None + self.incomplete_type_stack.pop() + self.pop_type_args(active_type.defn.type_args) + del self.options + + # + # Functions + # + + def visit_func_def(self, defn: FuncDef) -> None: + self.statement = defn + + # Visit default values because they may contain assignment expressions. + for arg in defn.arguments: + if arg.initializer: + arg.initializer.accept(self) + + defn.is_conditional = self.block_depth[-1] > 0 + + # Set full names even for those definitions that aren't added + # to a symbol table. For example, for overload items. + defn._fullname = self.qualified_name(defn.name) + + # We don't add module top-level functions to symbol tables + # when we analyze their bodies in the second phase on analysis, + # since they were added in the first phase. Nested functions + # get always added, since they aren't separate targets. + if not self.recurse_into_functions or len(self.function_stack) > 0: + if not defn.is_decorated and not defn.is_overload: + self.add_function_to_symbol_table(defn) + + if not self.recurse_into_functions and not defn.def_or_infer_vars: + return + + with self.scope.function_scope(defn), self.set_recurse_into_functions(): + with self.inside_except_star_block_set(value=False): + self.analyze_func_def(defn) + + def function_fullname(self, fullname: str) -> str: + if self.current_overload_item is None: + return fullname + return f"{fullname}#{self.current_overload_item}" + + def analyze_func_def(self, defn: FuncDef) -> None: + if self.push_type_args(defn.type_args, defn) is None: + self.defer(defn) + return + + self.function_stack.append(defn) + + if defn.type: + assert isinstance(defn.type, CallableType) + has_self_type = self.update_function_type_variables(defn.type, defn) + else: + has_self_type = False + + self.function_stack.pop() + + if self.is_class_scope(): + # Method definition + assert self.type is not None + defn.info = self.type + if defn.type is not None and defn.name in ("__init__", "__init_subclass__"): + assert isinstance(defn.type, CallableType) + if isinstance(get_proper_type(defn.type.ret_type), AnyType): + defn.type = defn.type.copy_modified(ret_type=NoneType()) + self.prepare_method_signature(defn, self.type, has_self_type) + + # Analyze function signature + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + if defn.type: + self.check_classvar_in_signature(defn.type) + assert isinstance(defn.type, CallableType) + # Signature must be analyzed in the surrounding scope so that + # class-level imported names and type variables are in scope. + analyzer = self.type_analyzer() + tag = self.track_incomplete_refs() + result = analyzer.visit_callable_type(defn.type, nested=False, namespace=fullname) + # Don't store not ready types (including placeholders). + if self.found_incomplete_ref(tag) or has_placeholder(result): + self.defer(defn) + self.pop_type_args(defn.type_args) + return + assert isinstance(result, ProperType) + if isinstance(result, CallableType): + # type guards need to have a positional argument, to spec + skip_self = self.is_class_scope() and not defn.is_static + if result.type_guard and ARG_POS not in result.arg_kinds[skip_self:]: + self.fail( + "TypeGuard functions must have a positional argument", + result, + code=codes.VALID_TYPE, + ) + # in this case, we just kind of just ... remove the type guard. + result = result.copy_modified(type_guard=None) + if result.type_is and ARG_POS not in result.arg_kinds[skip_self:]: + self.fail( + '"TypeIs" functions must have a positional argument', + result, + code=codes.VALID_TYPE, + ) + result = result.copy_modified(type_is=None) + + result = self.remove_unpack_kwargs(defn, result) + if has_self_type and self.type is not None: + info = self.type + if info.self_type is not None: + result.variables = (info.self_type,) + result.variables + defn.type = result + self.add_type_alias_deps(analyzer.aliases_used) + self.check_function_signature(defn) + if isinstance(defn, FuncDef): + assert isinstance(defn.type, CallableType) + defn.type = set_callable_name(defn.type, defn) + + self.analyze_arg_initializers(defn) + self.analyze_function_body(defn) + + if self.is_class_scope(): + assert self.type is not None + # Mark protocol methods with empty bodies as implicitly abstract. + # This makes explicit protocol subclassing type-safe. + if ( + self.type.is_protocol + and not self.is_stub_file # Bodies in stub files are always empty. + and (not isinstance(self.scope.function, OverloadedFuncDef) or defn.is_property) + and defn.abstract_status != IS_ABSTRACT + and is_trivial_body(defn.body) + ): + defn.abstract_status = IMPLICITLY_ABSTRACT + if ( + is_trivial_body(defn.body) + and not self.is_stub_file + and defn.abstract_status != NOT_ABSTRACT + ): + defn.is_trivial_body = True + + if ( + defn.is_coroutine + and isinstance(defn.type, CallableType) + and self.wrapped_coro_return_types.get(defn) != defn.type + ): + if defn.is_async_generator: + # Async generator types are handled elsewhere + pass + else: + # A coroutine defined as `async def foo(...) -> T: ...` + # has external return type `Coroutine[Any, Any, T]`. + any_type = AnyType(TypeOfAny.special_form) + ret_type = self.named_type_or_none( + "typing.Coroutine", [any_type, any_type, defn.type.ret_type] + ) + assert ret_type is not None, "Internal error: typing.Coroutine not found" + defn.type = defn.type.copy_modified(ret_type=ret_type) + self.wrapped_coro_return_types[defn] = defn.type + + self.pop_type_args(defn.type_args) + + def remove_unpack_kwargs(self, defn: FuncDef, typ: CallableType) -> CallableType: + if not typ.arg_kinds or typ.arg_kinds[-1] is not ArgKind.ARG_STAR2: + return typ + last_type = typ.arg_types[-1] + if not isinstance(last_type, UnpackType): + return typ + p_last_type = get_proper_type(last_type.type) + if not isinstance(p_last_type, TypedDictType): + self.fail("Unpack item in ** parameter must be a TypedDict", last_type) + new_arg_types = typ.arg_types[:-1] + [AnyType(TypeOfAny.from_error)] + return typ.copy_modified(arg_types=new_arg_types) + overlap = set(typ.arg_names) & set(p_last_type.items) + # It is OK for TypedDict to have a key named 'kwargs'. + overlap.discard(typ.arg_names[-1]) + if overlap: + overlapped = ", ".join([f'"{name}"' for name in sorted(filter(None, overlap))]) + self.fail( + f"Overlap between parameter names and ** TypedDict items: {overlapped}", defn + ) + new_arg_types = typ.arg_types[:-1] + [AnyType(TypeOfAny.from_error)] + return typ.copy_modified(arg_types=new_arg_types) + # OK, everything looks right now, mark the callable type as using unpack. + new_arg_types = typ.arg_types[:-1] + [p_last_type] + return typ.copy_modified(arg_types=new_arg_types, unpack_kwargs=True) + + def prepare_method_signature(self, func: FuncDef, info: TypeInfo, has_self_type: bool) -> None: + """Check basic signature validity and tweak annotation of self/cls argument.""" + # Only non-static methods are special, as well as __new__. + functype = func.type + if func.name == "__new__": + func.is_static = True + if func.has_self_or_cls_argument: + if func.name in ["__init_subclass__", "__class_getitem__"]: + func.is_class = True + if func.arguments and isinstance(functype, CallableType): + self_type = get_proper_type(functype.arg_types[0]) + if isinstance(self_type, AnyType): + if has_self_type: + assert self.type is not None and self.type.self_type is not None + leading_type: Type = self.type.self_type + else: + func.is_trivial_self = True + leading_type = fill_typevars(info) + if func.is_class or func.name == "__new__": + leading_type = self.class_type(leading_type) + func.type = replace_implicit_first_type(functype, leading_type) + elif has_self_type and isinstance(func.unanalyzed_type, CallableType): + if not isinstance(get_proper_type(func.unanalyzed_type.arg_types[0]), AnyType): + if self.is_expected_self_type( + self_type, func.is_class or func.name == "__new__" + ): + # This error is off by default, since it is explicitly allowed + # by the PEP 673. + self.fail( + 'Redundant "Self" annotation for the first method argument', + func, + code=codes.REDUNDANT_SELF_TYPE, + ) + else: + self.fail( + "Method cannot have explicit self annotation and Self type", func + ) + elif has_self_type: + self.fail("Static methods cannot use Self type", func) + + def is_expected_self_type(self, typ: Type, is_classmethod: bool) -> bool: + """Does this (analyzed or not) type represent the expected Self type for a method?""" + assert self.type is not None + typ = get_proper_type(typ) + if is_classmethod: + if isinstance(typ, TypeType): + return self.is_expected_self_type(typ.item, is_classmethod=False) + if isinstance(typ, UnboundType): + sym = self.lookup_qualified(typ.name, typ, suppress_errors=True) + if sym is not None and sym.fullname in TYPE_NAMES and typ.args: + return self.is_expected_self_type(typ.args[0], is_classmethod=False) + return False + if isinstance(typ, TypeVarType): + return typ == self.type.self_type + if isinstance(typ, UnboundType): + sym = self.lookup_qualified(typ.name, typ, suppress_errors=True) + return sym is not None and sym.fullname in SELF_TYPE_NAMES + return False + + def set_original_def(self, previous: Node | None, new: FuncDef | Decorator) -> bool: + """If 'new' conditionally redefine 'previous', set 'previous' as original + + We reject straight redefinitions of functions, as they are usually + a programming error. For example: + + def f(): ... + def f(): ... # Error: 'f' redefined + """ + if isinstance(new, Decorator): + new = new.func + if ( + isinstance(previous, (FuncDef, Decorator)) + and unnamed_function(new.name) + and unnamed_function(previous.name) + ): + return True + if isinstance(previous, (FuncDef, Var, Decorator)) and new.is_conditional: + new.original_def = previous + return True + else: + return False + + def update_function_type_variables(self, fun_type: CallableType, defn: FuncItem) -> bool: + """Make any type variables in the signature of defn explicit. + + Update the signature of defn to contain type variable definitions + if defn is generic. Return True, if the signature contains typing.Self + type, or False otherwise. + """ + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + a = self.type_analyzer() + fun_type.variables, has_self_type = a.bind_function_type_variables(fun_type, defn) + if has_self_type and self.type is not None: + self.setup_self_type() + if defn.type_args: + bound_fullnames = {v.fullname for v in fun_type.variables} + declared_fullnames = {self.qualified_name(p.name) for p in defn.type_args} + extra = sorted(bound_fullnames - declared_fullnames) + if extra: + self.msg.type_parameters_should_be_declared( + [n.split(".")[-1] for n in extra], defn + ) + return has_self_type + + def setup_self_type(self) -> None: + """Setup a (shared) Self type variable for current class. + + We intentionally don't add it to the class symbol table, + so it can be accessed only by mypy and will not cause + clashes with user defined names. + """ + assert self.type is not None + info = self.type + if info.self_type is not None: + if has_placeholder(info.self_type.upper_bound): + # Similar to regular (user defined) type variables. + self.process_placeholder( + None, + "Self upper bound", + info, + force_progress=info.self_type.upper_bound != fill_typevars(info), + ) + else: + return + info.self_type = TypeVarType( + "Self", + f"{info.fullname}.Self", + id=TypeVarId(0), # 0 is a special value for self-types. + values=[], + upper_bound=fill_typevars(info), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + + def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: + self.statement = defn + self.add_function_to_symbol_table(defn) + + if not self.recurse_into_functions and not defn.def_or_infer_vars: + return + + # NB: Since _visit_overloaded_func_def will call accept on the + # underlying FuncDefs, the function might get entered twice. + # This is fine, though, because only the outermost function is + # used to compute targets. + with self.scope.function_scope(defn), self.set_recurse_into_functions(): + self.analyze_overloaded_func_def(defn) + + @contextmanager + def overload_item_set(self, item: int | None) -> Iterator[None]: + self.current_overload_item = item + try: + yield + finally: + self.current_overload_item = None + + def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: + # OverloadedFuncDef refers to any legitimate situation where you have + # more than one declaration for the same function in a row. This occurs + # with a @property with a setter or a deleter, and for a classic + # @overload. + + defn._fullname = self.qualified_name(defn.name) + # TODO: avoid modifying items. + defn.items = defn.unanalyzed_items.copy() + + first_item = defn.items[0] + first_item.is_overload = True + with self.overload_item_set(0): + first_item.accept(self) + + bare_setter_type = None + is_property = False + if isinstance(first_item, Decorator) and first_item.func.is_property: + is_property = True + # This is a property. + first_item.func.is_overload = True + bare_setter_type = self.analyze_property_with_multi_part_definition(defn) + typ = function_type(first_item.func, self.function_type()) + assert isinstance(typ, CallableType) + typ.definition = first_item + types = [typ] + else: + # This is a normal overload. Find the item signatures, the + # implementation (if outside a stub), and any missing @overload + # decorators. + types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn) + defn.impl = impl + if non_overload_indexes: + self.handle_missing_overload_decorators( + defn, non_overload_indexes, some_overload_decorators=len(types) > 0 + ) + # If we found an implementation, remove it from the overload item list, + # as it's special. + if impl is not None: + assert impl is defn.items[-1] + defn.items = defn.items[:-1] + elif not non_overload_indexes: + self.handle_missing_overload_implementation(defn) + + if types and not any( + # If some overload items are decorated with other decorators, then + # the overload type will be determined during type checking. + # Note: bare @property is removed in visit_decorator(). + isinstance(it, Decorator) + and len(it.decorators) > (1 if i > 0 or not is_property else 0) + for i, it in enumerate(defn.items) + ): + # TODO: should we enforce decorated overloads consistency somehow? + # Some existing code uses both styles: + # * Put decorator only on implementation, use "effective" types in overloads + # * Put decorator everywhere, use "bare" types in overloads. + defn.type = Overloaded(types) + defn.type.line = defn.line + # In addition, we can set the getter/setter type for valid properties as some + # code paths may either use the above type, or var.type etc. of the first item. + if isinstance(first_item, Decorator) and bare_setter_type: + first_item.var.type = types[0] + first_item.var.setter_type = bare_setter_type + + if not defn.items: + # It was not a real overload after all, but function redefinition. We've + # visited the redefinition(s) already. + if not defn.impl: + # For really broken overloads with no items and no implementation we need to keep + # at least one item to hold basic information like function name. + defn.impl = defn.unanalyzed_items[-1] + return + + # We know this is an overload def. Infer properties and perform some checks. + self.process_deprecated_overload(defn) + self.process_final_in_overload(defn) + self.process_static_or_class_method_in_overload(defn) + self.process_overload_impl(defn) + + def process_deprecated_overload(self, defn: OverloadedFuncDef) -> None: + if defn.is_property: + return + + if isinstance(impl := defn.impl, Decorator) and ( + (deprecated := impl.func.deprecated) is not None + ): + defn.deprecated = deprecated + for item in defn.items: + if isinstance(item, Decorator): + item.func.deprecated = deprecated + + for item in defn.items: + deprecation = False + if isinstance(item, Decorator): + for d in item.decorators: + if deprecation and refers_to_fullname(d, OVERLOAD_NAMES): + self.msg.note("@overload should be placed before @deprecated", d) + elif (deprecated := self.get_deprecated(d)) is not None: + deprecation = True + if isinstance(typ := item.func.type, CallableType): + typestr = f" {typ.accept(TypeStrVisitor(options=self.options))} " + else: + typestr = " " + item.func.deprecated = ( + f"overload{typestr}of function {defn.fullname} is deprecated: " + f"{deprecated}" + ) + + @staticmethod + def get_deprecated(expression: Expression) -> str | None: + if ( + isinstance(expression, CallExpr) + and refers_to_fullname(expression.callee, DEPRECATED_TYPE_NAMES) + and (len(args := expression.args) >= 1) + and isinstance(deprecated := args[0], StrExpr) + ): + return deprecated.value + return None + + def process_overload_impl(self, defn: OverloadedFuncDef) -> None: + """Set flags for an overload implementation. + + Currently, this checks for a trivial body in protocols classes, + where it makes the method implicitly abstract. + """ + if defn.impl is None: + return + impl = defn.impl if isinstance(defn.impl, FuncDef) else defn.impl.func + if is_trivial_body(impl.body) and self.is_class_scope() and not self.is_stub_file: + assert self.type is not None + if self.type.is_protocol: + impl.abstract_status = IMPLICITLY_ABSTRACT + if impl.abstract_status != NOT_ABSTRACT: + impl.is_trivial_body = True + + def analyze_overload_sigs_and_impl( + self, defn: OverloadedFuncDef + ) -> tuple[list[CallableType], OverloadPart | None, list[int]]: + """Find overload signatures, the implementation, and items with missing @overload. + + Assume that the first was already analyzed. As a side effect: + analyzes remaining items and updates 'is_overload' flags. + """ + types = [] + non_overload_indexes = [] + impl: OverloadPart | None = None + for i, item in enumerate(defn.items): + if i != 0: + # Assume that the first item was already visited + item.is_overload = True + with self.overload_item_set(i if i < len(defn.items) - 1 else None): + item.accept(self) + # TODO: support decorated overloaded functions properly + if isinstance(item, Decorator): + callable = function_type(item.func, self.function_type()) + assert isinstance(callable, CallableType) + callable.definition = item + if not any(refers_to_fullname(dec, OVERLOAD_NAMES) for dec in item.decorators): + if i == len(defn.items) - 1 and not self.is_stub_file: + # Last item outside a stub is impl + impl = item + else: + # Oops it wasn't an overload after all. A clear error + # will vary based on where in the list it is, record + # that. + non_overload_indexes.append(i) + else: + item.func.is_overload = True + types.append(callable) + if item.var.is_property: + self.fail("An overload can not be a property", item) + # If any item was decorated with `@override`, the whole overload + # becomes an explicit override. + defn.is_explicit_override |= item.func.is_explicit_override + elif isinstance(item, FuncDef): + if i == len(defn.items) - 1 and not self.is_stub_file: + impl = item + else: + non_overload_indexes.append(i) + return types, impl, non_overload_indexes + + def handle_missing_overload_decorators( + self, + defn: OverloadedFuncDef, + non_overload_indexes: list[int], + some_overload_decorators: bool, + ) -> None: + """Generate errors for overload items without @overload. + + Side effect: remote non-overload items. + """ + if some_overload_decorators: + # Some of them were overloads, but not all. + for idx in non_overload_indexes: + if self.is_stub_file: + self.fail( + "An implementation for an overloaded function " + "is not allowed in a stub file", + defn.items[idx], + ) + else: + self.fail( + "The implementation for an overloaded function must come last", + defn.items[idx], + ) + else: + for idx in non_overload_indexes[1:]: + self.name_already_defined(defn.name, defn.items[idx], defn.items[0]) + if defn.impl: + self.name_already_defined(defn.name, defn.impl, defn.items[0]) + # Remove the non-overloads + for idx in reversed(non_overload_indexes): + del defn.items[idx] + + def handle_missing_overload_implementation(self, defn: OverloadedFuncDef) -> None: + """Generate error about missing overload implementation (only if needed).""" + if not self.is_stub_file: + if self.type and self.type.is_protocol and not self.is_func_scope(): + # An overloaded protocol method doesn't need an implementation, + # but if it doesn't have one, then it is considered abstract. + for item in defn.items: + if isinstance(item, Decorator): + item.func.abstract_status = IS_ABSTRACT + else: + item.abstract_status = IS_ABSTRACT + elif all( + isinstance(item, Decorator) and item.func.abstract_status == IS_ABSTRACT + for item in defn.items + ): + # Since there is no implementation, it can't be called via super(). + if defn.items: + assert isinstance(defn.items[0], Decorator) + defn.items[0].func.is_trivial_body = True + else: + self.fail( + "An overloaded function outside a stub file must have an implementation", + defn, + code=codes.NO_OVERLOAD_IMPL, + ) + + def process_final_in_overload(self, defn: OverloadedFuncDef) -> None: + """Detect the @final status of an overloaded function (and perform checks).""" + # If the implementation is marked as @final (or the first overload in + # stubs), then the whole overloaded definition if @final. + if any(item.is_final for item in defn.items): + # We anyway mark it as final because it was probably the intention. + defn.is_final = True + # Only show the error once per overload + bad_final = next(ov for ov in defn.items if ov.is_final) + if not self.is_stub_file: + self.fail("@final should be applied only to overload implementation", bad_final) + elif any(item.is_final for item in defn.items[1:]): + bad_final = next(ov for ov in defn.items[1:] if ov.is_final) + self.fail( + "In a stub file @final must be applied only to the first overload", bad_final + ) + if defn.impl is not None and defn.impl.is_final: + defn.is_final = True + + def process_static_or_class_method_in_overload(self, defn: OverloadedFuncDef) -> None: + class_status = [] + static_status = [] + for item in defn.items: + if isinstance(item, Decorator): + inner = item.func + elif isinstance(item, FuncDef): + inner = item + else: + assert False, f"The 'item' variable is an unexpected type: {type(item)}" + class_status.append(inner.is_class) + static_status.append(inner.is_static) + + if defn.impl is not None: + if isinstance(defn.impl, Decorator): + inner = defn.impl.func + elif isinstance(defn.impl, FuncDef): + inner = defn.impl + else: + assert False, f"Unexpected impl type: {type(defn.impl)}" + class_status.append(inner.is_class) + static_status.append(inner.is_static) + + if len(set(class_status)) != 1: + self.msg.overload_inconsistently_applies_decorator("classmethod", defn) + elif len(set(static_status)) != 1: + self.msg.overload_inconsistently_applies_decorator("staticmethod", defn) + else: + defn.is_class = class_status[0] + defn.is_static = static_status[0] + + def analyze_property_with_multi_part_definition( + self, defn: OverloadedFuncDef + ) -> CallableType | None: + """Analyze a property defined using multiple methods (e.g., using @x.setter). + + Assume that the first method (@property) has already been analyzed. + Return bare setter type (without any other decorators applied), this may be used + by the caller for performance optimizations. + """ + defn.is_property = True + items = defn.items + first_item = defn.items[0] + assert isinstance(first_item, Decorator) + deleted_items = [] + bare_setter_type = None + func_name = first_item.func.name + for i, item in enumerate(items[1:]): + if isinstance(item, Decorator): + item.func.accept(self) + if item.decorators: + first_node = item.decorators[0] + if self._is_valid_property_decorator(first_node, func_name): + # Get abstractness from the original definition. + item.func.abstract_status = first_item.func.abstract_status + if first_node.name == "setter": + # The first item represents the entire property. + first_item.var.is_settable_property = True + setter_func_type = function_type(item.func, self.function_type()) + assert isinstance(setter_func_type, CallableType) + bare_setter_type = setter_func_type + defn.setter_index = i + 1 + for other_node in item.decorators[1:]: + other_node.accept(self) + else: + self.fail( + f'Only supported top decorators are "@{func_name}.setter" and "@{func_name}.deleter"', + first_node, + ) + else: + self.fail(f'Unexpected definition for property "{func_name}"', item) + deleted_items.append(i + 1) + for i in reversed(deleted_items): + del items[i] + + for item in items[1:]: + if isinstance(item, Decorator): + for d in item.decorators: + if (deprecated := self.get_deprecated(d)) is not None: + item.func.deprecated = ( + f"function {item.fullname} is deprecated: {deprecated}" + ) + return bare_setter_type + + def _is_valid_property_decorator( + self, deco: Expression, property_name: str + ) -> TypeGuard[MemberExpr]: + if not isinstance(deco, MemberExpr): + return False + if not isinstance(deco.expr, NameExpr) or deco.expr.name != property_name: + return False + if deco.name not in {"setter", "deleter"}: + # This intentionally excludes getter. While `@prop.getter` is valid at + # runtime, that would mean replacing the already processed getter type. + # Such usage is almost definitely a mistake (except for overrides in + # subclasses but we don't support them anyway) and might be a typo + # (only one letter away from `setter`), it's likely almost never used, + # so supporting it properly won't pay off. + return False + return True + + def add_function_to_symbol_table(self, func: FuncDef | OverloadedFuncDef) -> None: + if self.is_class_scope(): + assert self.type is not None + func.info = self.type + func._fullname = self.qualified_name(func.name) + self.add_symbol(func.name, func, func) + + def analyze_arg_initializers(self, defn: FuncItem) -> None: + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + # Analyze default arguments + for arg in defn.arguments: + if arg.initializer: + arg.initializer.accept(self) + + def analyze_function_body(self, defn: FuncItem) -> None: + is_method = self.is_class_scope() + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + # Bind the type variables again to visit the body. + if defn.type: + a = self.type_analyzer() + typ = defn.type + assert isinstance(typ, CallableType) + a.bind_function_type_variables(typ, defn) + for i in range(len(typ.arg_types)): + store_argument_type(defn, i, typ, self.named_type) + self.function_stack.append(defn) + with self.enter(defn): + for arg in defn.arguments: + self.add_local(arg.variable, defn) + + # The first argument of a non-static, non-class method is like 'self' + # (though the name could be different), having the enclosing class's + # instance type. + if is_method and defn.has_self_or_cls_argument and defn.arguments: + if not defn.is_class: + defn.arguments[0].variable.is_self = True + else: + defn.arguments[0].variable.is_cls = True + + defn.body.accept(self) + self.function_stack.pop() + + def check_classvar_in_signature(self, typ: ProperType) -> None: + t: ProperType + if isinstance(typ, Overloaded): + for t in typ.items: + self.check_classvar_in_signature(t) + return + if not isinstance(typ, CallableType): + return + for t in get_proper_types(typ.arg_types) + [get_proper_type(typ.ret_type)]: + if self.is_classvar(t): + self.fail_invalid_classvar(t) + # Show only one error per signature + break + + def check_function_signature(self, fdef: FuncItem) -> None: + sig = fdef.type + assert isinstance(sig, CallableType) + if len(sig.arg_types) < len(fdef.arguments): + self.fail("Type signature has too few arguments", fdef) + # Add dummy Any arguments to prevent crashes later. + num_extra_anys = len(fdef.arguments) - len(sig.arg_types) + extra_anys = [AnyType(TypeOfAny.from_error)] * num_extra_anys + sig.arg_types.extend(extra_anys) + elif len(sig.arg_types) > len(fdef.arguments): + self.fail("Type signature has too many arguments", fdef, blocker=True) + + def visit_decorator(self, dec: Decorator) -> None: + self.statement = dec + # TODO: better don't modify them at all. + dec.decorators = dec.original_decorators.copy() + dec.func.is_conditional = self.block_depth[-1] > 0 + if not dec.is_overload: + self.add_symbol(dec.name, dec, dec) + dec.func._fullname = self.qualified_name(dec.name) + dec.var._fullname = self.qualified_name(dec.name) + for d in dec.decorators: + d.accept(self) + removed: list[int] = [] + no_type_check = False + could_be_decorated_property = False + for i, d in enumerate(dec.decorators): + # A bunch of decorators are special cased here. + if refers_to_fullname(d, "abc.abstractmethod"): + removed.append(i) + dec.func.abstract_status = IS_ABSTRACT + self.check_decorated_function_is_method("abstractmethod", dec) + elif refers_to_fullname(d, ("asyncio.coroutines.coroutine", "types.coroutine")): + removed.append(i) + dec.func.is_awaitable_coroutine = True + elif refers_to_fullname(d, "builtins.staticmethod"): + removed.append(i) + dec.func.is_static = True + dec.var.is_staticmethod = True + self.check_decorated_function_is_method("staticmethod", dec) + elif refers_to_fullname(d, "builtins.classmethod"): + removed.append(i) + dec.func.is_class = True + dec.var.is_classmethod = True + self.check_decorated_function_is_method("classmethod", dec) + elif refers_to_fullname(d, OVERRIDE_DECORATOR_NAMES): + removed.append(i) + dec.func.is_explicit_override = True + self.check_decorated_function_is_method("override", dec) + elif refers_to_fullname( + d, + ( + "builtins.property", + "abc.abstractproperty", + "functools.cached_property", + "enum.property", + "types.DynamicClassAttribute", + ), + ): + removed.append(i) + dec.func.is_property = True + dec.var.is_property = True + if refers_to_fullname(d, "abc.abstractproperty"): + dec.func.abstract_status = IS_ABSTRACT + elif refers_to_fullname(d, "functools.cached_property"): + dec.var.is_settable_property = True + self.check_decorated_function_is_method("property", dec) + elif refers_to_fullname(d, "typing.no_type_check"): + dec.var.type = AnyType(TypeOfAny.special_form) + no_type_check = True + elif refers_to_fullname(d, FINAL_DECORATOR_NAMES): + if self.is_class_scope(): + assert self.type is not None, "No type set at class scope" + if self.type.is_protocol: + self.msg.protocol_members_cant_be_final(d) + else: + dec.func.is_final = True + dec.var.is_final = True + removed.append(i) + else: + self.fail("@final cannot be used with non-method functions", d) + elif refers_to_fullname(d, TYPE_CHECK_ONLY_NAMES): + # TODO: support `@overload` funcs. + dec.func.is_type_check_only = True + elif isinstance(d, CallExpr) and refers_to_fullname( + d.callee, DATACLASS_TRANSFORM_NAMES + ): + dec.func.dataclass_transform_spec = self.parse_dataclass_transform_spec(d) + elif (deprecated := self.get_deprecated(d)) is not None: + dec.func.deprecated = f"function {dec.fullname} is deprecated: {deprecated}" + elif not dec.var.is_property: + # We have seen a "non-trivial" decorator before seeing @property, if + # we will see a @property later, give an error, as we don't support this. + could_be_decorated_property = True + for i in reversed(removed): + del dec.decorators[i] + if (not dec.is_overload or dec.var.is_property) and self.type: + dec.var.info = self.type + dec.var.is_initialized_in_class = True + if no_type_check: + erase_func_annotations(dec.func) + if not no_type_check and (self.recurse_into_functions or dec.func.def_or_infer_vars): + with self.set_recurse_into_functions(): + dec.func.accept(self) + if could_be_decorated_property and dec.decorators and dec.var.is_property: + self.fail( + "Decorators on top of @property are not supported", dec, code=PROPERTY_DECORATOR + ) + if (dec.func.is_static or dec.func.is_class) and dec.var.is_property: + self.fail("Only instance methods can be decorated with @property", dec) + if dec.func.abstract_status == IS_ABSTRACT and dec.func.is_final: + self.fail(f"Method {dec.func.name} is both abstract and final", dec) + if dec.func.is_static and dec.func.is_class: + self.fail(message_registry.CLASS_PATTERN_CLASS_OR_STATIC_METHOD, dec) + + def check_decorated_function_is_method(self, decorator: str, context: Context) -> None: + if not self.type or self.is_func_scope(): + self.fail(f'"{decorator}" used with a non-method', context) + + # + # Classes + # + + def visit_class_def(self, defn: ClassDef) -> None: + self.statement = defn + self.incomplete_type_stack.append(not defn.info) + namespace = self.qualified_name(defn.name) + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + if self.push_type_args(defn.type_args, defn) is None: + self.mark_incomplete(defn.name, defn) + return + + self.analyze_class(defn) + self.pop_type_args(defn.type_args) + self.incomplete_type_stack.pop() + + def push_type_args( + self, type_args: list[TypeParam] | None, context: Context + ) -> list[tuple[str, TypeVarLikeExpr]] | None: + if not type_args: + return [] + self.locals.append(SymbolTable()) + self.scope_stack.append(SCOPE_ANNOTATION) + tvs: list[tuple[str, TypeVarLikeExpr]] = [] + for p in type_args: + tv = self.analyze_type_param(p, context) + if tv is None: + return None + tvs.append((p.name, tv)) + + if self.is_defined_type_param(p.name): + self.fail(f'"{p.name}" already defined as a type parameter', context) + else: + assert self.add_symbol( + p.name, tv, context, no_progress=True, type_param=True + ), "Type parameter should not be discarded" + + return tvs + + def is_defined_type_param(self, name: str) -> bool: + for names in self.locals: + if names is None: + continue + if name in names: + node = names[name].node + if isinstance(node, TypeVarLikeExpr): + return True + return False + + def analyze_type_param( + self, type_param: TypeParam, context: Context + ) -> TypeVarLikeExpr | None: + fullname = self.qualified_name(type_param.name) + if type_param.upper_bound: + upper_bound = self.anal_type(type_param.upper_bound, allow_placeholder=True) + # TODO: we should validate the upper bound is valid for a given kind. + if upper_bound is None: + # This and below copies special-casing for old-style type variables, that + # is equally necessary for new-style classes to break a vicious circle. + upper_bound = PlaceholderType(None, [], context.line) + else: + if type_param.kind == TYPE_VAR_TUPLE_KIND: + upper_bound = self.named_type("builtins.tuple", [self.object_type()]) + else: + upper_bound = self.object_type() + if type_param.default: + default = self.anal_type( + type_param.default, + allow_placeholder=True, + allow_unbound_tvars=True, + report_invalid_types=False, + allow_param_spec_literals=type_param.kind == PARAM_SPEC_KIND, + allow_tuple_literal=type_param.kind == PARAM_SPEC_KIND, + allow_unpack=type_param.kind == TYPE_VAR_TUPLE_KIND, + ) + if default is None: + default = PlaceholderType(None, [], context.line) + elif type_param.kind == TYPE_VAR_KIND: + default = self.check_typevar_default(default, type_param.default) + elif type_param.kind == PARAM_SPEC_KIND: + default = self.check_paramspec_default(default, type_param.default) + elif type_param.kind == TYPE_VAR_TUPLE_KIND: + default = self.check_typevartuple_default(default, type_param.default) + else: + default = AnyType(TypeOfAny.from_omitted_generics) + if type_param.kind == TYPE_VAR_KIND: + values: list[Type] = [] + if type_param.values: + for value in type_param.values: + analyzed = self.anal_type(value, allow_placeholder=True) + if analyzed is None: + analyzed = PlaceholderType(None, [], context.line) + if has_type_vars(analyzed): + self.fail(message_registry.TYPE_VAR_GENERIC_CONSTRAINT_TYPE, context) + values.append(AnyType(TypeOfAny.from_error)) + else: + values.append(analyzed) + return TypeVarExpr( + name=type_param.name, + fullname=fullname, + values=values, + upper_bound=upper_bound, + default=default, + variance=VARIANCE_NOT_READY, + is_new_style=True, + line=context.line, + ) + elif type_param.kind == PARAM_SPEC_KIND: + return ParamSpecExpr( + name=type_param.name, + fullname=fullname, + upper_bound=upper_bound, + default=default, + is_new_style=True, + line=context.line, + ) + else: + assert type_param.kind == TYPE_VAR_TUPLE_KIND + tuple_fallback = self.named_type("builtins.tuple", [self.object_type()]) + return TypeVarTupleExpr( + name=type_param.name, + fullname=fullname, + upper_bound=upper_bound, + tuple_fallback=tuple_fallback, + default=default, + is_new_style=True, + line=context.line, + ) + + def pop_type_args(self, type_args: list[TypeParam] | None) -> None: + if not type_args: + return + self.locals.pop() + self.scope_stack.pop() + + def analyze_class(self, defn: ClassDef) -> None: + fullname = self.qualified_name(defn.name) + if not defn.info and not self.is_core_builtin_class(defn): + # Add placeholder so that self-references in base classes can be + # resolved. We don't want this to cause a deferral, since if there + # are no incomplete references, we'll replace this with a TypeInfo + # before returning. + placeholder = PlaceholderNode(fullname, defn, defn.line, becomes_typeinfo=True) + self.add_symbol(defn.name, placeholder, defn, can_defer=False) + + tag = self.track_incomplete_refs() + + # Restore base classes after previous iteration (things like Generic[T] might be removed). + defn.base_type_exprs.extend(defn.removed_base_type_exprs) + defn.removed_base_type_exprs.clear() + + self.infer_metaclass_and_bases_from_compat_helpers(defn) + + bases = defn.base_type_exprs + bases, tvar_defs, is_protocol = self.clean_up_bases_and_infer_type_variables( + defn, bases, context=defn + ) + + self.check_type_alias_bases(bases) + + for tvd in tvar_defs: + if isinstance(tvd, TypeVarType) and any( + has_placeholder(t) for t in [tvd.upper_bound] + tvd.values + ): + # Some type variable bounds or values are not ready, we need + # to re-analyze this class. + self.defer() + if has_placeholder(tvd.default): + # Placeholder values in TypeVarLikeTypes may get substituted in. + # Defer current target until they are ready. + self.mark_incomplete(defn.name, defn) + return + + self.analyze_class_keywords(defn) + bases_result = self.analyze_base_classes(bases) + if bases_result is None or self.found_incomplete_ref(tag): + # Something was incomplete. Defer current target. + self.mark_incomplete(defn.name, defn) + return + + base_types, base_error = bases_result + if any(isinstance(base, PlaceholderType) for base, _ in base_types): + # We need to know the TypeInfo of each base to construct the MRO. Placeholder types + # are okay in nested positions, since they can't affect the MRO. + self.mark_incomplete(defn.name, defn) + return + + declared_metaclass, should_defer, any_meta = self.get_declared_metaclass( + defn.name, defn.metaclass + ) + if should_defer or self.found_incomplete_ref(tag): + # Metaclass was not ready. Defer current target. + self.mark_incomplete(defn.name, defn) + return + + if self.analyze_typeddict_classdef(defn): + if defn.info: + self.setup_type_vars(defn, tvar_defs) + self.setup_alias_type_vars(defn) + return + + if self.analyze_namedtuple_classdef(defn, tvar_defs): + return + + # Create TypeInfo for class now that base classes and the MRO can be calculated. + self.prepare_class_def(defn) + self.setup_type_vars(defn, tvar_defs) + if base_error: + defn.info.fallback_to_any = True + if any_meta: + defn.info.meta_fallback_to_any = True + + with self.scope.class_scope(defn.info): + self.configure_base_classes(defn, base_types) + defn.info.is_protocol = is_protocol + self.recalculate_metaclass(defn, declared_metaclass) + defn.info.runtime_protocol = False + + if defn.type_args: + # PEP 695 type parameters are not in scope in class decorators, so + # temporarily disable type parameter namespace. + type_params_names = self.locals.pop() + self.scope_stack.pop() + for decorator in defn.decorators: + self.analyze_class_decorator(defn, decorator) + if defn.type_args: + self.locals.append(type_params_names) + self.scope_stack.append(SCOPE_ANNOTATION) + + self.analyze_class_body_common(defn) + + def check_type_alias_bases(self, bases: list[Expression]) -> None: + for base in bases: + if isinstance(base, IndexExpr): + base = base.base + if ( + isinstance(base, RefExpr) + and isinstance(base.node, TypeAlias) + and base.node.python_3_12_type_alias + ): + self.fail( + 'Type alias defined using "type" statement not valid as base class', base + ) + + def setup_type_vars(self, defn: ClassDef, tvar_defs: list[TypeVarLikeType]) -> None: + defn.type_vars = tvar_defs + defn.info.type_vars = [] + # we want to make sure any additional logic in add_type_vars gets run + defn.info.add_type_vars() + + def setup_alias_type_vars(self, defn: ClassDef) -> None: + assert defn.info.special_alias is not None + defn.info.special_alias.alias_tvars = list(defn.type_vars) + # It is a bit unfortunate that we need to inline some logic from TypeAlias constructor, + # but it is required, since type variables may change during semantic analyzer passes. + for i, t in enumerate(defn.type_vars): + if isinstance(t, TypeVarTupleType): + defn.info.special_alias.tvar_tuple_index = i + target = defn.info.special_alias.target + assert isinstance(target, ProperType) + if isinstance(target, TypedDictType): + target.fallback.args = type_vars_as_args(defn.type_vars) + elif isinstance(target, TupleType): + target.partial_fallback.args = type_vars_as_args(defn.type_vars) + else: + assert False, f"Unexpected special alias type: {type(target)}" + + def is_core_builtin_class(self, defn: ClassDef) -> bool: + return self.cur_mod_id == "builtins" and defn.name in CORE_BUILTIN_CLASSES + + def analyze_class_body_common(self, defn: ClassDef) -> None: + """Parts of class body analysis that are common to all kinds of class defs.""" + self.enter_class(defn.info) + if any(b.self_type is not None for b in defn.info.mro): + self.setup_self_type() + defn.defs.accept(self) + self.apply_class_plugin_hooks(defn) + self.leave_class() + + def analyze_typeddict_classdef(self, defn: ClassDef) -> bool: + if ( + defn.info + and defn.info.typeddict_type + and not has_placeholder(defn.info.typeddict_type) + ): + # This is a valid TypedDict, and it is fully analyzed. + return True + is_typeddict, info = self.typed_dict_analyzer.analyze_typeddict_classdef(defn) + if is_typeddict: + for decorator in defn.decorators: + decorator.accept(self) + if info is not None: + self.analyze_class_decorator_common(defn, info, decorator) + if info is None: + self.mark_incomplete(defn.name, defn) + else: + self.prepare_class_def(defn, info, custom_names=True) + return True + return False + + def analyze_namedtuple_classdef( + self, defn: ClassDef, tvar_defs: list[TypeVarLikeType] + ) -> bool: + """Check if this class can define a named tuple.""" + if ( + defn.info + and defn.info.is_named_tuple + and defn.info.tuple_type + and not has_placeholder(defn.info.tuple_type) + ): + # Don't reprocess everything. We just need to process methods defined + # in the named tuple class body. + is_named_tuple = True + info: TypeInfo | None = defn.info + else: + is_named_tuple, info = self.named_tuple_analyzer.analyze_namedtuple_classdef( + defn, self.is_stub_file, self.is_func_scope() + ) + if is_named_tuple: + if info is None: + self.mark_incomplete(defn.name, defn) + else: + self.prepare_class_def(defn, info, custom_names=True) + self.setup_type_vars(defn, tvar_defs) + self.setup_alias_type_vars(defn) + with self.scope.class_scope(defn.info): + for deco in defn.decorators: + deco.accept(self) + self.analyze_class_decorator_common(defn, defn.info, deco) + with self.named_tuple_analyzer.save_namedtuple_body(info): + self.analyze_class_body_common(defn) + return True + return False + + def apply_class_plugin_hooks(self, defn: ClassDef) -> None: + """Apply a plugin hook that may infer a more precise definition for a class.""" + + for decorator in defn.decorators: + decorator_name = self.get_fullname_for_hook(decorator) + if decorator_name: + hook = self.plugin.get_class_decorator_hook(decorator_name) + # Special case: if the decorator is itself decorated with + # typing.dataclass_transform, apply the hook for the dataclasses plugin + # TODO: remove special casing here + if hook is None and find_dataclass_transform_spec(decorator): + hook = dataclasses_plugin.dataclass_tag_callback + if hook: + hook(ClassDefContext(defn, decorator, self)) + + if defn.metaclass: + metaclass_name = self.get_fullname_for_hook(defn.metaclass) + if metaclass_name: + hook = self.plugin.get_metaclass_hook(metaclass_name) + if hook: + hook(ClassDefContext(defn, defn.metaclass, self)) + + for base_expr in defn.base_type_exprs: + base_name = self.get_fullname_for_hook(base_expr) + if base_name: + hook = self.plugin.get_base_class_hook(base_name) + if hook: + hook(ClassDefContext(defn, base_expr, self)) + + # Check if the class definition itself triggers a dataclass transform (via a parent class/ + # metaclass) + spec = find_dataclass_transform_spec(defn) + if spec is not None: + dataclasses_plugin.add_dataclass_tag(defn.info) + + def get_fullname_for_hook(self, expr: Expression) -> str | None: + if isinstance(expr, CallExpr): + return self.get_fullname_for_hook(expr.callee) + elif isinstance(expr, IndexExpr): + return self.get_fullname_for_hook(expr.base) + elif isinstance(expr, RefExpr): + if expr.fullname: + return expr.fullname + # If we don't have a fullname look it up. This happens because base classes are + # analyzed in a different manner (see exprtotype.py) and therefore those AST + # nodes will not have full names. + sym = self.lookup_type_node(expr) + if sym: + return sym.fullname + return None + + def analyze_class_keywords(self, defn: ClassDef) -> None: + for value in defn.keywords.values(): + value.accept(self) + + def enter_class(self, info: TypeInfo) -> None: + # Remember previous active class + self.type_stack.append(self.type) + self.locals.append(None) # Add class scope + self.scope_stack.append(SCOPE_CLASS) + self.block_depth.append(-1) # The class body increments this to 0 + self.loop_depth.append(0) + self._type = info + self.missing_names.append(set()) + + def leave_class(self) -> None: + """Restore analyzer state.""" + self.block_depth.pop() + self.loop_depth.pop() + self.locals.pop() + self.scope_stack.pop() + self._type = self.type_stack.pop() + self.missing_names.pop() + + def analyze_class_decorator(self, defn: ClassDef, decorator: Expression) -> None: + decorator.accept(self) + self.analyze_class_decorator_common(defn, defn.info, decorator) + if isinstance(decorator, RefExpr): + if decorator.fullname in RUNTIME_PROTOCOL_DECOS: + if defn.info.is_protocol: + defn.info.runtime_protocol = True + else: + self.fail("@runtime_checkable can only be used with protocol classes", defn) + elif isinstance(decorator, CallExpr) and refers_to_fullname( + decorator.callee, DATACLASS_TRANSFORM_NAMES + ): + defn.info.dataclass_transform_spec = self.parse_dataclass_transform_spec(decorator) + + def analyze_class_decorator_common( + self, defn: ClassDef, info: TypeInfo, decorator: Expression + ) -> None: + """Common method for applying class decorators. + + Called on regular classes, typeddicts, and namedtuples. + """ + if refers_to_fullname(decorator, FINAL_DECORATOR_NAMES): + info.is_final = True + elif refers_to_fullname(decorator, DISJOINT_BASE_DECORATOR_NAMES): + if info.is_protocol: + self.fail("@disjoint_base cannot be used with protocol class", decorator) + elif info.typeddict_type is not None: + self.fail("@disjoint_base cannot be used with TypedDict", decorator) + else: + info.is_disjoint_base = True + elif refers_to_fullname(decorator, TYPE_CHECK_ONLY_NAMES): + info.is_type_check_only = True + elif (deprecated := self.get_deprecated(decorator)) is not None: + info.deprecated = f"class {defn.fullname} is deprecated: {deprecated}" + + def clean_up_bases_and_infer_type_variables( + self, defn: ClassDef, base_type_exprs: list[Expression], context: Context + ) -> tuple[list[Expression], list[TypeVarLikeType], bool]: + """Remove extra base classes such as Generic and infer type vars. + + For example, consider this class: + + class Foo(Bar, Generic[T]): ... + + Now we will remove Generic[T] from bases of Foo and infer that the + type variable 'T' is a type argument of Foo. + + Note that this is performed *before* semantic analysis. + + Returns (remaining base expressions, inferred type variables, is protocol). + """ + removed: list[int] = [] + declared_tvars: TypeVarLikeList = [] + is_protocol = False + has_type_var_tuple = False + if defn.type_args is not None: + for p in defn.type_args: + node = self.lookup(p.name, context) + assert node is not None + assert isinstance(node.node, TypeVarLikeExpr) + if isinstance(node.node, TypeVarTupleExpr): + if has_type_var_tuple: + self.fail("Can only use one type var tuple in a class def", context) + continue + has_type_var_tuple = True + declared_tvars.append((p.name, node.node)) + + for i, base_expr in enumerate(base_type_exprs): + if isinstance(base_expr, StarExpr): + base_expr.valid = True + self.analyze_type_expr(base_expr) + + try: + base = self.expr_to_unanalyzed_type(base_expr) + except TypeTranslationError: + # This error will be caught later. + continue + result = self.analyze_class_typevar_declaration(base, has_type_var_tuple) + if result is not None: + tvars = result[0] + is_protocol |= result[1] + if declared_tvars: + if defn.type_args: + if is_protocol: + self.fail('No arguments expected for "Protocol" base class', context) + else: + self.fail("Generic[...] base class is redundant", context) + else: + self.fail( + "Only single Generic[...] or Protocol[...] can be in bases", context + ) + removed.append(i) + declared_tvars.extend(tvars) + if isinstance(base, UnboundType): + sym = self.lookup_qualified(base.name, base) + if sym is not None and sym.node is not None: + if sym.node.fullname in PROTOCOL_NAMES and i not in removed: + # also remove bare 'Protocol' bases + removed.append(i) + is_protocol = True + + all_tvars = self.get_all_bases_tvars(base_type_exprs, removed) + if declared_tvars: + if len(remove_dups(declared_tvars)) < len(declared_tvars) and not defn.type_args: + self.fail("Duplicate type variables in Generic[...] or Protocol[...]", context) + declared_tvars = remove_dups(declared_tvars) + if not set(all_tvars).issubset(set(declared_tvars)): + if defn.type_args: + undeclared = sorted(set(all_tvars) - set(declared_tvars)) + self.msg.type_parameters_should_be_declared( + [tv[0] for tv in undeclared], context + ) + else: + self.fail( + "If Generic[...] or Protocol[...] is present" + " it should list all type variables", + context, + ) + # In case of error, Generic tvars will go first + declared_tvars = remove_dups(declared_tvars + all_tvars) + else: + declared_tvars = all_tvars + for i in reversed(removed): + # We need to actually remove the base class expressions like Generic[T], + # mostly because otherwise they will create spurious dependencies in fine + # grained incremental mode. + defn.removed_base_type_exprs.append(defn.base_type_exprs[i]) + del base_type_exprs[i] + tvar_defs = self.tvar_defs_from_tvars(declared_tvars, context) + return base_type_exprs, tvar_defs, is_protocol + + def analyze_class_typevar_declaration( + self, base: Type, has_type_var_tuple: bool + ) -> tuple[TypeVarLikeList, bool] | None: + """Analyze type variables declared using Generic[...] or Protocol[...]. + + Args: + base: Non-analyzed base class + + Return None if the base class does not declare type variables. Otherwise, + return the type variables. + """ + if not isinstance(base, UnboundType): + return None + unbound = base + sym = self.lookup_qualified(unbound.name, unbound) + if sym is None or sym.node is None: + return None + if ( + sym.node.fullname == "typing.Generic" + or sym.node.fullname in PROTOCOL_NAMES + and base.args + ): + is_proto = sym.node.fullname != "typing.Generic" + tvars: TypeVarLikeList = [] + for arg in unbound.args: + tag = self.track_incomplete_refs() + tvar = self.analyze_unbound_tvar(arg) + if tvar: + if isinstance(tvar[1], TypeVarTupleExpr): + if has_type_var_tuple: + self.fail("Can only use one type var tuple in a class def", base) + continue + has_type_var_tuple = True + tvars.append(tvar) + elif not self.found_incomplete_ref(tag): + self.fail("Free type variable expected in %s[...]" % sym.node.name, base) + return tvars, is_proto + return None + + def analyze_unbound_tvar(self, t: Type) -> tuple[str, TypeVarLikeExpr] | None: + if isinstance(t, UnpackType) and isinstance(t.type, UnboundType): + return self.analyze_unbound_tvar_impl(t.type, is_unpacked=True) + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym and sym.fullname in UNPACK_TYPE_NAMES: + inner_t = t.args[0] + if isinstance(inner_t, UnboundType): + return self.analyze_unbound_tvar_impl(inner_t, is_unpacked=True) + return None + return self.analyze_unbound_tvar_impl(t) + return None + + def analyze_unbound_tvar_impl( + self, t: UnboundType, is_unpacked: bool = False, is_typealias_param: bool = False + ) -> tuple[str, TypeVarLikeExpr] | None: + assert not is_unpacked or not is_typealias_param, "Mutually exclusive conditions" + sym = self.lookup_qualified(t.name, t) + if sym and isinstance(sym.node, PlaceholderNode): + self.record_incomplete_ref() + if not is_unpacked and sym and isinstance(sym.node, ParamSpecExpr): + if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): + # It's bound by our type variable scope + return None + return t.name, sym.node + if (is_unpacked or is_typealias_param) and sym and isinstance(sym.node, TypeVarTupleExpr): + if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): + # It's bound by our type variable scope + return None + return t.name, sym.node + if sym is None or not isinstance(sym.node, TypeVarExpr) or is_unpacked: + return None + elif sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): + # It's bound by our type variable scope + return None + else: + assert isinstance(sym.node, TypeVarExpr) + return t.name, sym.node + + def find_type_var_likes(self, t: Type) -> TypeVarLikeList: + visitor = FindTypeVarVisitor(self, self.tvar_scope) + t.accept(visitor) + return visitor.type_var_likes + + def get_all_bases_tvars( + self, base_type_exprs: list[Expression], removed: list[int] + ) -> TypeVarLikeList: + """Return all type variable references in bases.""" + tvars: TypeVarLikeList = [] + for i, base_expr in enumerate(base_type_exprs): + if i not in removed: + try: + base = self.expr_to_unanalyzed_type(base_expr) + except TypeTranslationError: + # This error will be caught later. + continue + base_tvars = self.find_type_var_likes(base) + tvars.extend(base_tvars) + return remove_dups(tvars) + + def tvar_defs_from_tvars( + self, tvars: TypeVarLikeList, context: Context + ) -> list[TypeVarLikeType]: + tvar_defs: list[TypeVarLikeType] = [] + last_tvar_name_with_default: str | None = None + for name, tvar_expr in tvars: + tvar_expr.default = tvar_expr.default.accept( + TypeVarDefaultTranslator(self, tvar_expr.name, context) + ) + # PEP-695 type variables that are redeclared in an inner scope are warned + # about elsewhere. + if not tvar_expr.is_new_style and not self.tvar_scope.allow_binding( + tvar_expr.fullname + ): + self.fail( + message_registry.TYPE_VAR_REDECLARED_IN_NESTED_CLASS.format(name), context + ) + tvar_def = self.tvar_scope.bind_new(name, tvar_expr, self.fail, context) + if last_tvar_name_with_default is not None and not tvar_def.has_default(): + self.msg.tvar_without_default_type( + tvar_def.name, last_tvar_name_with_default, context + ) + tvar_def.default = AnyType(TypeOfAny.from_error) + elif tvar_def.has_default(): + last_tvar_name_with_default = tvar_def.name + tvar_defs.append(tvar_def) + return tvar_defs + + def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]: + """Return all type variable references in item type expressions. + + This is a helper for generic TypedDicts and NamedTuples. Essentially it is + a simplified version of the logic we use for ClassDef bases. We duplicate + some amount of code, because it is hard to refactor common pieces. + """ + tvars: dict[str, tuple[TypeVarLikeExpr, Expression]] = {} + for base_expr in type_exprs: + try: + base = self.expr_to_unanalyzed_type(base_expr) + except TypeTranslationError: + # This error will be caught later. + continue + for name, expr in self.find_type_var_likes(base): + tvars.setdefault(name, (expr, base_expr)) + tvar_defs = [] + for name, (tvar_expr, context) in tvars.items(): + tvar_def = self.tvar_scope.bind_new(name, tvar_expr, self.fail, context) + tvar_defs.append(tvar_def) + return tvar_defs + + def prepare_class_def( + self, defn: ClassDef, info: TypeInfo | None = None, custom_names: bool = False + ) -> None: + """Prepare for the analysis of a class definition. + + Create an empty TypeInfo and store it in a symbol table, or if the 'info' + argument is provided, store it instead (used for magic type definitions). + """ + if not defn.info: + defn.fullname = self.qualified_name(defn.name) + # TODO: Nested classes + info = info or self.make_empty_type_info(defn) + defn.info = info + info.defn = defn + if not custom_names: + # Some special classes (in particular NamedTuples) use custom fullname logic. + # Don't override it here (also see comment below, this needs cleanup). + if not self.is_func_scope(): + info._fullname = self.qualified_name(defn.name) + else: + info._fullname = info.name + local_name = defn.name + if "@" in local_name: + local_name = local_name.split("@")[0] + self.add_symbol(local_name, defn.info, defn) + if self.is_nested_within_func_scope(): + # We need to preserve local classes, let's store them + # in globals under mangled unique names + # + # TODO: Putting local classes into globals breaks assumptions in fine-grained + # incremental mode and we should avoid it. In general, this logic is too + # ad-hoc and needs to be removed/refactored. + if "@" not in defn.info._fullname: + global_name = defn.info.name + "@" + str(defn.line) + defn.info._fullname = self.cur_mod_id + "." + global_name + else: + # Preserve name from previous fine-grained incremental run. + global_name = defn.info.name + defn.fullname = defn.info._fullname + if defn.info.is_named_tuple or defn.info.typeddict_type: + # Named tuples and Typed dicts nested within a class are stored + # in the class symbol table. + self.add_symbol_skip_local(global_name, defn.info) + else: + self.globals[global_name] = SymbolTableNode(GDEF, defn.info) + + def make_empty_type_info(self, defn: ClassDef) -> TypeInfo: + if ( + self.is_module_scope() + and self.cur_mod_id == "builtins" + and defn.name in CORE_BUILTIN_CLASSES + ): + # Special case core built-in classes. A TypeInfo was already + # created for it before semantic analysis, but with a dummy + # ClassDef. Patch the real ClassDef object. + info = self.globals[defn.name].node + assert isinstance(info, TypeInfo) + else: + info = TypeInfo(SymbolTable(), defn, self.cur_mod_id) + info.set_line(defn) + return info + + def get_name_repr_of_expr(self, expr: Expression) -> str | None: + """Try finding a short simplified textual representation of a base class expression.""" + if isinstance(expr, NameExpr): + return expr.name + if isinstance(expr, MemberExpr): + return get_member_expr_fullname(expr) + if isinstance(expr, IndexExpr): + return self.get_name_repr_of_expr(expr.base) + if isinstance(expr, CallExpr): + return self.get_name_repr_of_expr(expr.callee) + return None + + def analyze_base_classes( + self, base_type_exprs: list[Expression] + ) -> tuple[list[tuple[ProperType, Expression]], bool] | None: + """Analyze base class types. + + Return None if some definition was incomplete. Otherwise, return a tuple + with these items: + + * List of (analyzed type, original expression) tuples + * Boolean indicating whether one of the bases had a semantic analysis error + """ + is_error = False + bases = [] + for base_expr in base_type_exprs: + if ( + isinstance(base_expr, RefExpr) + and base_expr.fullname in TYPED_NAMEDTUPLE_NAMES + TPDICT_NAMES + ) or ( + isinstance(base_expr, CallExpr) + and isinstance(base_expr.callee, RefExpr) + and base_expr.callee.fullname in TPDICT_NAMES + ): + # Ignore magic bases for now. + # For example: + # class Foo(TypedDict): ... # RefExpr + # class Foo(NamedTuple): ... # RefExpr + # class Foo(TypedDict("Foo", {"a": int})): ... # CallExpr + continue + + try: + base = self.expr_to_analyzed_type( + base_expr, allow_placeholder=True, allow_type_any=True + ) + except TypeTranslationError: + name = self.get_name_repr_of_expr(base_expr) + if isinstance(base_expr, CallExpr): + msg = "Unsupported dynamic base class" + else: + msg = "Invalid base class" + if name: + msg += f' "{name}"' + self.fail(msg, base_expr) + is_error = True + continue + if base is None: + return None + base = get_proper_type(base) + bases.append((base, base_expr)) + return bases, is_error + + def configure_base_classes( + self, defn: ClassDef, bases: list[tuple[ProperType, Expression]] + ) -> None: + """Set up base classes. + + This computes several attributes on the corresponding TypeInfo defn.info + related to the base classes: defn.info.bases, defn.info.mro, and + miscellaneous others (at least tuple_type, fallback_to_any, and is_enum.) + """ + base_types: list[Instance] = [] + info = defn.info + + for base, base_expr in bases: + if isinstance(base, TupleType): + actual_base = self.configure_tuple_base_class(defn, base) + base_types.append(actual_base) + elif isinstance(base, Instance): + if base.type.is_newtype: + self.fail('Cannot subclass "NewType"', defn) + base_types.append(base) + elif isinstance(base, AnyType): + if self.options.disallow_subclassing_any: + if isinstance(base_expr, (NameExpr, MemberExpr)): + msg = f'Class cannot subclass "{base_expr.name}" (has type "Any")' + else: + msg = 'Class cannot subclass value of type "Any"' + self.fail(msg, base_expr) + info.fallback_to_any = True + elif isinstance(base, TypedDictType): + base_types.append(base.fallback) + else: + msg = "Invalid base class" + name = self.get_name_repr_of_expr(base_expr) + if name: + msg += f' "{name}"' + self.fail(msg, base_expr) + info.fallback_to_any = True + if self.options.disallow_any_unimported and has_any_from_unimported_type(base): + if isinstance(base_expr, (NameExpr, MemberExpr)): + prefix = f"Base type {base_expr.name}" + else: + prefix = "Base type" + self.msg.unimported_type_becomes_any(prefix, base, base_expr) + check_for_explicit_any( + base, self.options, self.is_typeshed_stub_file, self.msg, context=base_expr + ) + + # Add 'object' as implicit base if there is no other base class. + if not base_types and defn.fullname != "builtins.object": + base_types.append(self.object_type()) + + info.bases = base_types + + # Calculate the MRO. + if not self.verify_base_classes(defn): + self.set_dummy_mro(defn.info) + return + if not self.verify_duplicate_base_classes(defn): + # We don't want to block the typechecking process, + # so, we just insert `Any` as the base class and show an error. + self.set_any_mro(defn.info) + self.calculate_class_mro(defn, self.object_type) + + def configure_tuple_base_class(self, defn: ClassDef, base: TupleType) -> Instance: + info = defn.info + + # There may be an existing valid tuple type from previous semanal iterations. + # Use equality to check if it is the case. + if info.tuple_type and info.tuple_type != base and not has_placeholder(info.tuple_type): + self.fail("Class has two incompatible bases derived from tuple", defn) + defn.has_incompatible_baseclass = True + if has_placeholder(base): + self.process_placeholder( + None, "tuple base", defn, force_progress=base != info.tuple_type + ) + info.update_tuple_type(base) + self.setup_alias_type_vars(defn) + + if base.partial_fallback.type.fullname == "builtins.tuple" and not has_placeholder(base): + # Fallback can only be safely calculated after semantic analysis, since base + # classes may be incomplete. Postpone the calculation. + self.schedule_patch(PRIORITY_FALLBACKS, lambda: calculate_tuple_fallback(base)) + + return base.partial_fallback + + def set_dummy_mro(self, info: TypeInfo) -> None: + # Give it an MRO consisting of just the class itself and object. + info.mro = [info, self.object_type().type] + info.bad_mro = True + + def set_any_mro(self, info: TypeInfo) -> None: + # Give it an MRO consisting direct `Any` subclass. + info.fallback_to_any = True + info.mro = [info, self.object_type().type] + + def calculate_class_mro( + self, defn: ClassDef, obj_type: Callable[[], Instance] | None = None + ) -> None: + """Calculate method resolution order for a class. + + `obj_type` exists just to fill in empty base class list in case of an error. + """ + try: + calculate_mro(defn.info, obj_type) + except MroError: + self.fail( + f'Cannot determine consistent method resolution order (MRO) for "{defn.name}"', + defn, + ) + self.set_dummy_mro(defn.info) + # Allow plugins to alter the MRO to handle the fact that `def mro()` + # on metaclasses permits MRO rewriting. + if defn.fullname: + hook = self.plugin.get_customize_class_mro_hook(defn.fullname) + if hook: + hook(ClassDefContext(defn, FakeExpression(), self)) + + def infer_metaclass_and_bases_from_compat_helpers(self, defn: ClassDef) -> None: + """Lookup for special metaclass declarations, and update defn fields accordingly. + + * six.with_metaclass(M, B1, B2, ...) + * @six.add_metaclass(M) + * future.utils.with_metaclass(M, B1, B2, ...) + * past.utils.with_metaclass(M, B1, B2, ...) + """ + + # Look for six.with_metaclass(M, B1, B2, ...) + with_meta_expr: Expression | None = None + if len(defn.base_type_exprs) == 1: + base_expr = defn.base_type_exprs[0] + if isinstance(base_expr, CallExpr) and isinstance(base_expr.callee, RefExpr): + self.analyze_type_expr(base_expr) + if ( + base_expr.callee.fullname + in { + "six.with_metaclass", + "future.utils.with_metaclass", + "past.utils.with_metaclass", + } + and len(base_expr.args) >= 1 + and all(kind == ARG_POS for kind in base_expr.arg_kinds) + ): + with_meta_expr = base_expr.args[0] + defn.base_type_exprs = base_expr.args[1:] + + # Look for @six.add_metaclass(M) + add_meta_expr: Expression | None = None + for dec_expr in defn.decorators: + if isinstance(dec_expr, CallExpr) and isinstance(dec_expr.callee, RefExpr): + dec_expr.callee.accept(self) + if ( + dec_expr.callee.fullname == "six.add_metaclass" + and len(dec_expr.args) == 1 + and dec_expr.arg_kinds[0] == ARG_POS + ): + add_meta_expr = dec_expr.args[0] + break + + metas = {defn.metaclass, with_meta_expr, add_meta_expr} - {None} + if len(metas) == 0: + return + if len(metas) > 1: + self.fail("Multiple metaclass definitions", defn, code=codes.METACLASS) + return + defn.metaclass = metas.pop() + + def verify_base_classes(self, defn: ClassDef) -> bool: + info = defn.info + cycle = False + for base in info.bases: + baseinfo = base.type + if self.is_base_class(info, baseinfo): + self.fail("Cycle in inheritance hierarchy", defn) + cycle = True + return not cycle + + def verify_duplicate_base_classes(self, defn: ClassDef) -> bool: + dup = find_duplicate(defn.info.direct_base_classes()) + if dup: + self.fail(f'Duplicate base class "{dup.name}"', defn) + return not dup + + def is_base_class(self, t: TypeInfo, s: TypeInfo) -> bool: + """Determine if t is a base class of s (but do not use mro).""" + # Search the base class graph for t, starting from s. + worklist = [s] + visited = {s} + while worklist: + nxt = worklist.pop() + if nxt == t: + return True + for base in nxt.bases: + if base.type not in visited: + worklist.append(base.type) + visited.add(base.type) + return False + + def get_declared_metaclass( + self, name: str, metaclass_expr: Expression | None + ) -> tuple[Instance | None, bool, bool]: + """Get declared metaclass from metaclass expression. + + Returns a tuple of three values: + * A metaclass instance or None + * A boolean indicating whether we should defer + * A boolean indicating whether we should set metaclass Any fallback + (either for Any metaclass or invalid/dynamic metaclass). + + The two boolean flags can only be True if instance is None. + """ + declared_metaclass = None + if metaclass_expr: + metaclass_name = None + if isinstance(metaclass_expr, NameExpr): + metaclass_name = metaclass_expr.name + elif isinstance(metaclass_expr, MemberExpr): + metaclass_name = get_member_expr_fullname(metaclass_expr) + if metaclass_name is None: + self.fail( + f'Dynamic metaclass not supported for "{name}"', + metaclass_expr, + code=codes.METACLASS, + ) + return None, False, True + sym = self.lookup_qualified(metaclass_name, metaclass_expr) + if sym is None: + # Probably a name error - it is already handled elsewhere + return None, False, True + if isinstance(sym.node, Var) and isinstance(get_proper_type(sym.node.type), AnyType): + if self.options.disallow_subclassing_any: + self.fail( + f'Class cannot use "{sym.node.name}" as a metaclass (has type "Any")', + metaclass_expr, + code=codes.METACLASS, + ) + return None, False, True + if isinstance(sym.node, PlaceholderNode): + return None, True, False # defer later in the caller + + # Support type aliases, like `_Meta: TypeAlias = type` + metaclass_info: Node | None = sym.node + if ( + isinstance(sym.node, TypeAlias) + and not sym.node.python_3_12_type_alias + and not sym.node.alias_tvars + ): + target = get_proper_type(sym.node.target) + if isinstance(target, Instance): + metaclass_info = target.type + + if not isinstance(metaclass_info, TypeInfo) or metaclass_info.tuple_type is not None: + self.fail( + f'Invalid metaclass "{metaclass_name}"', metaclass_expr, code=codes.METACLASS + ) + return None, False, False + if not metaclass_info.is_metaclass(): + self.fail( + 'Metaclasses not inheriting from "type" are not supported', + metaclass_expr, + code=codes.METACLASS, + ) + return None, False, False + inst = fill_typevars(metaclass_info) + assert isinstance(inst, Instance) + declared_metaclass = inst + return declared_metaclass, False, False + + def recalculate_metaclass(self, defn: ClassDef, declared_metaclass: Instance | None) -> None: + defn.info.declared_metaclass = declared_metaclass + defn.info.metaclass_type = defn.info.calculate_metaclass_type() + if any(info.is_protocol for info in defn.info.mro): + if ( + not defn.info.metaclass_type + or defn.info.metaclass_type.type.fullname == "builtins.type" + ): + # All protocols and their subclasses have ABCMeta metaclass by default. + # TODO: add a metaclass conflict check if there is another metaclass. + abc_meta = self.named_type_or_none("abc.ABCMeta", []) + if abc_meta is not None: # May be None in tests with incomplete lib-stub. + defn.info.metaclass_type = abc_meta + if defn.info.metaclass_type and defn.info.metaclass_type.type.has_base("enum.EnumMeta"): + defn.info.is_enum = True + if defn.type_vars: + self.fail("Enum class cannot be generic", defn) + + # + # Imports + # + + def visit_import(self, i: Import) -> None: + self.statement = i + for id, as_id in i.ids: + # Modules imported in a stub file without using 'import X as X' won't get exported + # When implicit re-exporting is disabled, we have the same behavior as stubs. + use_implicit_reexport = not self.is_stub_file and self.options.implicit_reexport + if as_id is not None: + base_id = id + imported_id = as_id + module_public = use_implicit_reexport or id == as_id + else: + base_id = id.split(".")[0] + imported_id = base_id + module_public = use_implicit_reexport + + if base_id in self.modules: + node = self.modules[base_id] + if self.is_func_scope(): + kind = LDEF + elif self.type is not None: + kind = MDEF + else: + kind = GDEF + symbol = SymbolTableNode( + kind, node, module_public=module_public, module_hidden=not module_public + ) + self.add_imported_symbol( + imported_id, + symbol, + context=i, + module_public=module_public, + module_hidden=not module_public, + ) + else: + self.add_unknown_imported_symbol( + imported_id, + context=i, + target_name=base_id, + module_public=module_public, + module_hidden=not module_public, + ) + + def visit_import_from(self, imp: ImportFrom) -> None: + self.statement = imp + module_id = self.correct_relative_import(imp) + module = self.modules.get(module_id) + for id, as_id in imp.names: + fullname = module_id + "." + id + self.set_future_import_flags(fullname) + if module is None: + node = None + elif module_id == self.cur_mod_id and fullname in self.modules: + # Submodule takes precedence over definition in surround package, for + # compatibility with runtime semantics in typical use cases. This + # could more precisely model runtime semantics by taking into account + # the line number beyond which the local definition should take + # precedence, but doesn't seem to be important in most use cases. + node = SymbolTableNode(GDEF, self.modules[fullname]) + else: + if id == as_id == "__all__": + # For modules with __all__ public status of symbols is determined uniquely + # by contents of __all__, so we can recover the latter here, and avoid + # serializing this (redundant) information in MypyFile. + self.all_exports[:] = [ + name for name, sym in module.names.items() if sym.module_public + ] + node = module.names.get(id) + + missing_submodule = False + imported_id = as_id or id + + # Modules imported in a stub file without using 'from Y import X as X' will + # not get exported. + # When implicit re-exporting is disabled, we have the same behavior as stubs. + use_implicit_reexport = not self.is_stub_file and self.options.implicit_reexport + module_public = use_implicit_reexport or (as_id is not None and id == as_id) + + # If the module does not contain a symbol with the name 'id', + # try checking if it's a module instead. + if not node: + mod = self.modules.get(fullname) + if mod is not None: + kind = self.current_symbol_kind() + node = SymbolTableNode(kind, mod) + elif fullname in self.missing_modules: + missing_submodule = True + # If it is still not resolved, check for a module level __getattr__ + if module and not node and "__getattr__" in module.names: + # We store the fullname of the original definition so that we can + # detect whether two imported names refer to the same thing. + fullname = module_id + "." + id + gvar = self.create_getattr_var(module.names["__getattr__"], imported_id, fullname) + if gvar: + self.add_symbol( + imported_id, + gvar, + imp, + module_public=module_public, + module_hidden=not module_public, + ) + continue + + if node: + self.process_imported_symbol( + node, module_id, id, imported_id, fullname, module_public, context=imp + ) + if node.module_hidden: + self.report_missing_module_attribute( + module_id, + id, + imported_id, + module_public=module_public, + module_hidden=not module_public, + context=imp, + add_unknown_imported_symbol=False, + ) + elif module and not missing_submodule: + # Target module exists but the imported name is missing or hidden. + self.report_missing_module_attribute( + module_id, + id, + imported_id, + module_public=module_public, + module_hidden=not module_public, + context=imp, + ) + else: + # Import of a missing (sub)module. + self.add_unknown_imported_symbol( + imported_id, + imp, + target_name=fullname, + module_public=module_public, + module_hidden=not module_public, + ) + + def process_imported_symbol( + self, + node: SymbolTableNode, + module_id: str, + id: str, + imported_id: str, + fullname: str, + module_public: bool, + context: ImportBase, + ) -> None: + module_hidden = not module_public and ( + # `from package import submodule` should work regardless of whether package + # re-exports submodule, so we shouldn't hide it + not isinstance(node.node, MypyFile) + or fullname not in self.modules + # but given `from somewhere import random_unrelated_module` we should hide + # random_unrelated_module + or not fullname.startswith(self.cur_mod_id + ".") + ) + + if isinstance(node.node, PlaceholderNode): + if self.final_iteration: + self.report_missing_module_attribute( + module_id, + id, + imported_id, + module_public=module_public, + module_hidden=module_hidden, + context=context, + ) + return + else: + # This might become a type. + self.mark_incomplete( + imported_id, + node.node, + module_public=module_public, + module_hidden=module_hidden, + becomes_typeinfo=True, + ) + # NOTE: we take the original node even for final `Var`s. This is to support + # a common pattern when constants are re-exported (same applies to import *). + self.add_imported_symbol( + imported_id, node, context, module_public=module_public, module_hidden=module_hidden + ) + + def report_missing_module_attribute( + self, + import_id: str, + source_id: str, + imported_id: str, + module_public: bool, + module_hidden: bool, + context: Node, + add_unknown_imported_symbol: bool = True, + ) -> None: + # Missing attribute. + if self.is_incomplete_namespace(import_id): + # We don't know whether the name will be there, since the namespace + # is incomplete. Defer the current target. + self.mark_incomplete( + imported_id, context, module_public=module_public, module_hidden=module_hidden + ) + return + message = f'Module "{import_id}" has no attribute "{source_id}"' + # Suggest alternatives, if any match is found. + module = self.modules.get(import_id) + if module: + if source_id in module.names.keys() and not module.names[source_id].module_public: + message = ( + f'Module "{import_id}" does not explicitly export attribute "{source_id}"' + ) + elif not ( + self.options.ignore_errors or self.cur_mod_node.path in self.errors.ignored_files + ): + alternatives = set(module.names.keys()).difference({source_id}) + matches = best_matches(source_id, alternatives, n=3) + if matches: + suggestion = f"; maybe {pretty_seq(matches, 'or')}?" + message += f"{suggestion}" + self.fail(message, context, code=codes.ATTR_DEFINED) + if add_unknown_imported_symbol: + self.add_unknown_imported_symbol( + imported_id, + context, + target_name=None, + module_public=module_public, + module_hidden=not module_public, + ) + + if import_id == "typing": + # The user probably has a missing definition in a test fixture. Let's verify. + fullname = f"builtins.{source_id.lower()}" + if ( + self.lookup_fully_qualified_or_none(fullname) is None + and fullname in SUGGESTED_TEST_FIXTURES + ): + # Yes. Generate a helpful note. + self.msg.add_fixture_note(fullname, context) + else: + typing_extensions = self.modules.get("typing_extensions") + if typing_extensions and source_id in typing_extensions.names: + self.msg.note( + f"Use `from typing_extensions import {source_id}` instead", + context, + code=codes.ATTR_DEFINED, + ) + self.msg.note( + "See https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-new-additions-to-the-typing-module", + context, + code=codes.ATTR_DEFINED, + ) + + def process_import_over_existing_name( + self, + imported_id: str, + existing_symbol: SymbolTableNode, + module_symbol: SymbolTableNode, + import_node: ImportBase, + ) -> bool: + if existing_symbol.node is module_symbol.node: + # We added this symbol on previous iteration. + return False + if existing_symbol.kind in (LDEF, GDEF, MDEF) and isinstance( + existing_symbol.node, (Var, FuncDef, TypeInfo, Decorator, TypeAlias) + ): + # This is a valid import over an existing definition in the file. Construct a dummy + # assignment that we'll use to type check the import. + lvalue = NameExpr(imported_id) + lvalue.kind = existing_symbol.kind + lvalue.node = existing_symbol.node + rvalue = NameExpr(imported_id) + rvalue.kind = module_symbol.kind + rvalue.node = module_symbol.node + if isinstance(rvalue.node, TypeAlias): + # Suppress bogus errors from the dummy assignment if rvalue is an alias. + # Otherwise mypy may complain that alias is invalid in runtime context. + rvalue.is_alias_rvalue = True + assignment = AssignmentStmt([lvalue], rvalue) + for node in assignment, lvalue, rvalue: + node.set_line(import_node) + import_node.assignments.append(assignment) + return True + return False + + def correct_relative_import(self, node: ImportFrom | ImportAll) -> str: + import_id, ok = correct_relative_import( + self.cur_mod_id, node.relative, node.id, self.cur_mod_node.is_package_init_file() + ) + if not ok: + self.fail("Relative import climbs too many namespaces", node) + return import_id + + def visit_import_all(self, i: ImportAll) -> None: + i_id = self.correct_relative_import(i) + if i_id in self.modules: + m = self.modules[i_id] + if self.is_incomplete_namespace(i_id): + # Any names could be missing from the current namespace if the target module + # namespace is incomplete. + self.mark_incomplete("*", i) + for name, node in m.names.items(): + if node.no_serialize: + # This is either internal or generated symbol, skip it to avoid problems + # like accidental name conflicts or invalid cross-references. + continue + fullname = i_id + "." + name + self.set_future_import_flags(fullname) + # if '__all__' exists, all nodes not included have had module_public set to + # False, and we can skip checking '_' because it's been explicitly included. + if node.module_public and (not name.startswith("_") or "__all__" in m.names): + if isinstance(node.node, MypyFile): + # Star import of submodule from a package, add it as a dependency. + self.imports.add(node.node.fullname) + # `from x import *` always reexports symbols + self.add_imported_symbol( + name, node, context=i, module_public=True, module_hidden=False + ) + # This is a (minimalist) copy of the logic in visit_import_from(), we need + # to clean-up any remaining placeholders by replacing them with Var(Any). + if isinstance(node.node, PlaceholderNode) and self.final_iteration: + self.add_unknown_imported_symbol( + name, i, target_name=None, module_public=True, module_hidden=False + ) + + else: + # Don't add any dummy symbols for 'from x import *' if 'x' is unknown. + pass + + # + # Assignment + # + + def visit_assignment_expr(self, s: AssignmentExpr) -> None: + s.value.accept(self) + if self.is_func_scope(): + if not self.check_valid_comprehension(s): + return + self.analyze_lvalue(s.target, escape_comprehensions=True, has_explicit_value=True) + + def check_valid_comprehension(self, s: AssignmentExpr) -> bool: + """Check that assignment expression is not nested within comprehension at class scope. + + class C: + [(j := i) for i in [1, 2, 3]] + is a syntax error that is not enforced by Python parser, but at later steps. + """ + for i, scope_type in enumerate(reversed(self.scope_stack)): + if scope_type != SCOPE_COMPREHENSION and i < len(self.locals) - 1: + if self.locals[-1 - i] is None: + self.fail( + "Assignment expression within a comprehension" + " cannot be used in a class body", + s, + code=codes.SYNTAX, + serious=True, + blocker=True, + ) + return False + break + return True + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + self.statement = s + + # Special case assignment like X = X. + if self.analyze_identity_global_assignment(s): + return + + tag = self.track_incomplete_refs() + + # Here we have a chicken and egg problem: at this stage we can't call + # can_be_type_alias(), because we have not enough information about rvalue. + # But we can't use a full visit because it may emit extra incomplete refs (namely + # when analysing any type applications there) thus preventing the further analysis. + # To break the tie, we first analyse rvalue partially, if it can be a type alias. + if self.can_possibly_be_type_form(s): + old_basic_type_applications = self.basic_type_applications + self.basic_type_applications = True + with self.allow_unbound_tvars_set(): + s.rvalue.accept(self) + self.basic_type_applications = old_basic_type_applications + elif self.can_possibly_be_typevarlike_declaration(s): + # Allow unbound tvars inside TypeVarLike defaults to be evaluated later + with self.allow_unbound_tvars_set(): + s.rvalue.accept(self) + else: + s.rvalue.accept(self) + + if self.found_incomplete_ref(tag) or self.should_wait_rhs(s.rvalue): + # Initializer couldn't be fully analyzed. Defer the current node and give up. + # Make sure that if we skip the definition of some local names, they can't be + # added later in this scope, since an earlier definition should take precedence. + for expr in names_modified_by_assignment(s): + self.mark_incomplete(expr.name, expr) + return + if self.can_possibly_be_type_form(s): + # Now re-visit those rvalues that were we skipped type applications above. + # This should be safe as generally semantic analyzer is idempotent. + with self.allow_unbound_tvars_set(): + s.rvalue.accept(self) + + # The r.h.s. is now ready to be classified, first check if it is a special form: + special_form = False + # * type alias + if self.check_and_set_up_type_alias(s): + s.is_alias_def = True + special_form = True + elif isinstance(s.rvalue, CallExpr): + # * type variable definition + if self.process_typevar_declaration(s): + special_form = True + elif self.process_paramspec_declaration(s): + special_form = True + elif self.process_typevartuple_declaration(s): + special_form = True + # * type constructors + elif self.analyze_namedtuple_assign(s): + special_form = True + elif self.analyze_typeddict_assign(s): + special_form = True + elif self.newtype_analyzer.process_newtype_declaration(s): + special_form = True + elif self.analyze_enum_assign(s): + special_form = True + + if special_form: + self.record_special_form_lvalue(s) + return + # Clear the alias flag if assignment turns out not a special form after all. It + # may be set to True while there were still placeholders due to forward refs. + s.is_alias_def = False + + # OK, this is a regular assignment, perform the necessary analysis steps. + s.is_final_def = self.unwrap_final(s) + self.analyze_lvalues(s) + self.check_final_implicit_def(s) + self.store_final_status(s) + self.check_classvar(s) + self.process_type_annotation(s) + self.analyze_rvalue_as_type_form(s) + self.apply_dynamic_class_hook(s) + if not s.type: + self.process_module_assignment(s.lvalues, s.rvalue, s) + self.process__all__(s) + self.process__deletable__(s) + self.process__slots__(s) + + def analyze_identity_global_assignment(self, s: AssignmentStmt) -> bool: + """Special case 'X = X' in global scope. + + This allows supporting some important use cases. + + Return true if special casing was applied. + """ + if not isinstance(s.rvalue, NameExpr) or len(s.lvalues) != 1: + # Not of form 'X = X' + return False + lvalue = s.lvalues[0] + if not isinstance(lvalue, NameExpr) or s.rvalue.name != lvalue.name: + # Not of form 'X = X' + return False + if self.type is not None or self.is_func_scope(): + # Not in global scope + return False + # It's an assignment like 'X = X' in the global scope. + name = lvalue.name + sym = self.lookup(name, s) + if sym is None: + if self.final_iteration: + # Fall back to normal assignment analysis. + return False + else: + self.defer() + return True + else: + if sym.node is None: + # Something special -- fall back to normal assignment analysis. + return False + if name not in self.globals: + # The name is from builtins. Add an alias to the current module. + self.add_symbol(name, sym.node, s) + if not isinstance(sym.node, PlaceholderNode): + for node in s.rvalue, lvalue: + node.node = sym.node + node.kind = GDEF + node.fullname = sym.node.fullname + return True + + def should_wait_rhs(self, rv: Expression) -> bool: + """Can we already classify this r.h.s. of an assignment or should we wait? + + This returns True if we don't have enough information to decide whether + an assignment is just a normal variable definition or a special form. + Always return False if this is a final iteration. This will typically cause + the lvalue to be classified as a variable plus emit an error. + """ + if self.final_iteration: + # No chance, nothing has changed. + return False + if isinstance(rv, NameExpr): + n = self.lookup(rv.name, rv) + if n and isinstance(n.node, PlaceholderNode) and not n.node.becomes_typeinfo: + return True + elif isinstance(rv, MemberExpr): + fname = get_member_expr_fullname(rv) + if fname: + n = self.lookup_qualified(fname, rv, suppress_errors=True) + if n and isinstance(n.node, PlaceholderNode) and not n.node.becomes_typeinfo: + return True + elif isinstance(rv, IndexExpr) and isinstance(rv.base, RefExpr): + return self.should_wait_rhs(rv.base) + elif isinstance(rv, CallExpr) and isinstance(rv.callee, RefExpr): + # This is only relevant for builtin SCC where things like 'TypeVar' + # may be not ready. + return self.should_wait_rhs(rv.callee) + return False + + def can_be_type_alias(self, rv: Expression, allow_none: bool = False) -> bool: + """Is this a valid r.h.s. for an alias definition? + + Note: this function should be only called for expressions where self.should_wait_rhs() + returns False. + """ + if isinstance(rv, RefExpr) and self.is_type_ref(rv, bare=True): + return True + if isinstance(rv, IndexExpr) and self.is_type_ref(rv.base, bare=False): + return True + if self.is_none_alias(rv): + return True + if allow_none and isinstance(rv, NameExpr) and rv.fullname == "builtins.None": + return True + if isinstance(rv, OpExpr) and rv.op == "|": + if self.is_stub_file: + return True + if self.can_be_type_alias(rv.left, allow_none=True) and self.can_be_type_alias( + rv.right, allow_none=True + ): + return True + return False + + def can_possibly_be_type_form(self, s: AssignmentStmt) -> bool: + """Like can_be_type_alias(), but simpler and doesn't require fully analyzed rvalue. + + Instead, use lvalues/annotations structure to figure out whether this can potentially be + a type alias definition, NamedTuple, or TypedDict. Another difference from above function + is that we are only interested IndexExpr, CallExpr and OpExpr rvalues, since only those + can be potentially recursive (things like `A = A` are never valid). + """ + if len(s.lvalues) > 1: + return False + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.callee, RefExpr): + ref = s.rvalue.callee.fullname + return ref in TPDICT_NAMES or ref in TYPED_NAMEDTUPLE_NAMES + if not isinstance(s.lvalues[0], NameExpr): + return False + if s.unanalyzed_type is not None and not self.is_pep_613(s): + return False + if not isinstance(s.rvalue, (IndexExpr, OpExpr)): + return False + # Something that looks like Foo = Bar[Baz, ...] + return True + + def can_possibly_be_typevarlike_declaration(self, s: AssignmentStmt) -> bool: + """Check if r.h.s. can be a TypeVarLike declaration.""" + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr): + return False + if not isinstance(s.rvalue, CallExpr) or not isinstance(s.rvalue.callee, NameExpr): + return False + ref = s.rvalue.callee + ref.accept(self) + return ref.fullname in TYPE_VAR_LIKE_NAMES + + def is_type_ref(self, rv: Expression, bare: bool = False) -> bool: + """Does this expression refer to a type? + + This includes: + * Special forms, like Any or Union + * Classes (except subscripted enums) + * Other type aliases + * PlaceholderNodes with becomes_typeinfo=True (these can be not ready class + definitions, and not ready aliases). + + If bare is True, this is not a base of an index expression, so some special + forms are not valid (like a bare Union). + + Note: This method should be only used in context of a type alias definition. + This method can only return True for RefExprs, to check if C[int] is a valid + target for type alias call this method on expr.base (i.e. on C in C[int]). + See also can_be_type_alias(). + """ + if not isinstance(rv, RefExpr): + return False + if isinstance(rv.node, TypeVarLikeExpr): + self.fail(f'Type variable "{rv.fullname}" is invalid as target for type alias', rv) + return False + + if bare: + # These three are valid even if bare, for example + # A = Tuple is just equivalent to A = Tuple[Any, ...]. + valid_refs = {"typing.Any", "typing.Tuple", "typing.Callable"} + else: + valid_refs = type_constructors + + if isinstance(rv.node, TypeAlias) or rv.fullname in valid_refs: + return True + if isinstance(rv.node, TypeInfo): + if bare: + return True + # Assignment color = Color['RED'] defines a variable, not an alias. + return not rv.node.is_enum + if isinstance(rv.node, Var): + return rv.node.fullname in NEVER_NAMES + + if isinstance(rv, NameExpr): + n = self.lookup(rv.name, rv) + if n and isinstance(n.node, PlaceholderNode) and n.node.becomes_typeinfo: + return True + elif isinstance(rv, MemberExpr): + fname = get_member_expr_fullname(rv) + if fname: + # The r.h.s. for variable definitions may not be a type reference but just + # an instance attribute, so suppress the errors. + n = self.lookup_qualified(fname, rv, suppress_errors=True) + if n and isinstance(n.node, PlaceholderNode) and n.node.becomes_typeinfo: + return True + return False + + def is_none_alias(self, node: Expression) -> bool: + """Is this a r.h.s. for a None alias? + + We special case the assignments like Void = type(None), to allow using + Void in type annotations. + """ + if isinstance(node, CallExpr): + if ( + isinstance(node.callee, NameExpr) + and len(node.args) == 1 + and isinstance(node.args[0], NameExpr) + ): + call = self.lookup_qualified(node.callee.name, node.callee) + arg = self.lookup_qualified(node.args[0].name, node.args[0]) + if ( + call is not None + and call.node + and call.node.fullname == "builtins.type" + and arg is not None + and arg.node + and arg.node.fullname == "builtins.None" + ): + return True + return False + + def record_special_form_lvalue(self, s: AssignmentStmt) -> None: + """Record minimal necessary information about l.h.s. of a special form. + + This exists mostly for compatibility with the old semantic analyzer. + """ + lvalue = s.lvalues[0] + assert isinstance(lvalue, NameExpr) + lvalue.is_special_form = True + if self.current_symbol_kind() == GDEF: + lvalue.fullname = self.qualified_name(lvalue.name) + lvalue.kind = self.current_symbol_kind() + + def analyze_enum_assign(self, s: AssignmentStmt) -> bool: + """Check if s defines an Enum.""" + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, EnumCallExpr): + # This is an analyzed enum definition. + # It is valid iff it can be stored correctly, failures were already reported. + return self._is_single_name_assignment(s) + return self.enum_call_analyzer.process_enum_call(s, self.is_func_scope()) + + def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool: + """Check if s defines a namedtuple.""" + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, NamedTupleExpr): + if s.rvalue.analyzed.info.tuple_type and not has_placeholder( + s.rvalue.analyzed.info.tuple_type + ): + # This is an analyzed named tuple definition. + # It is valid iff it can be stored correctly, failures were already reported. + return self._is_single_name_assignment(s) + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)): + return False + lvalue = s.lvalues[0] + if isinstance(lvalue, MemberExpr): + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.callee, RefExpr): + fullname = s.rvalue.callee.fullname + if fullname == "collections.namedtuple" or fullname in TYPED_NAMEDTUPLE_NAMES: + self.fail("NamedTuple type as an attribute is not supported", lvalue) + return False + name = lvalue.name + namespace = self.qualified_name(name) + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + internal_name, info, tvar_defs = self.named_tuple_analyzer.check_namedtuple( + s.rvalue, name, self.is_func_scope() + ) + if internal_name is None: + return False + if internal_name != name: + self.fail( + 'First argument to namedtuple() should be "{}", not "{}"'.format( + name, internal_name + ), + s.rvalue, + code=codes.NAME_MATCH, + ) + return True + # Yes, it's a valid namedtuple, but defer if it is not ready. + if not info: + self.mark_incomplete(name, lvalue, becomes_typeinfo=True) + else: + self.setup_type_vars(info.defn, tvar_defs) + self.setup_alias_type_vars(info.defn) + return True + + def analyze_typeddict_assign(self, s: AssignmentStmt) -> bool: + """Check if s defines a typed dict.""" + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, TypedDictExpr): + if s.rvalue.analyzed.info.typeddict_type and not has_placeholder( + s.rvalue.analyzed.info.typeddict_type + ): + # This is an analyzed typed dict definition. + # It is valid iff it can be stored correctly, failures were already reported. + return self._is_single_name_assignment(s) + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)): + return False + lvalue = s.lvalues[0] + name = lvalue.name + namespace = self.qualified_name(name) + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + is_typed_dict, info, tvar_defs = self.typed_dict_analyzer.check_typeddict( + s.rvalue, name, self.is_func_scope() + ) + if not is_typed_dict: + return False + if isinstance(lvalue, MemberExpr): + self.fail("TypedDict type as attribute is not supported", lvalue) + return False + # Yes, it's a valid typed dict, but defer if it is not ready. + if not info: + self.mark_incomplete(name, lvalue, becomes_typeinfo=True) + else: + defn = info.defn + self.setup_type_vars(defn, tvar_defs) + self.setup_alias_type_vars(defn) + return True + + def _is_single_name_assignment(self, s: AssignmentStmt) -> bool: + return len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr) + + def analyze_lvalues(self, s: AssignmentStmt) -> None: + # We cannot use s.type, because analyze_simple_literal_type() will set it. + explicit = s.unanalyzed_type is not None + if self.is_final_type(s.unanalyzed_type): + # We need to exclude bare Final. + assert isinstance(s.unanalyzed_type, UnboundType) + if not s.unanalyzed_type.args: + explicit = False + + if s.rvalue: + if isinstance(s.rvalue, TempNode): + has_explicit_value = not s.rvalue.no_rhs + else: + has_explicit_value = True + else: + has_explicit_value = False + + for lval in s.lvalues: + self.analyze_lvalue( + lval, + explicit_type=explicit, + is_final=s.is_final_def, + has_explicit_value=has_explicit_value, + ) + + def analyze_rvalue_as_type_form(self, s: AssignmentStmt) -> None: + if TYPE_FORM in self.options.enable_incomplete_feature: + self.try_parse_as_type_expression(s.rvalue) + + def apply_dynamic_class_hook(self, s: AssignmentStmt) -> None: + if not isinstance(s.rvalue, CallExpr): + return + fname = "" + call = s.rvalue + while True: + if isinstance(call.callee, RefExpr): + fname = call.callee.fullname + # check if method call + if not fname and isinstance(call.callee, MemberExpr): + callee_expr = call.callee.expr + if isinstance(callee_expr, RefExpr) and callee_expr.fullname: + method_name = call.callee.name + fname = callee_expr.fullname + "." + method_name + elif ( + isinstance(callee_expr, IndexExpr) + and isinstance(callee_expr.base, RefExpr) + and isinstance(callee_expr.analyzed, TypeApplication) + ): + method_name = call.callee.name + fname = callee_expr.base.fullname + "." + method_name + elif isinstance(callee_expr, CallExpr): + # check if chain call + call = callee_expr + continue + break + if not fname: + return + hook = self.plugin.get_dynamic_class_hook(fname) + if not hook: + return + for lval in s.lvalues: + if not isinstance(lval, NameExpr): + continue + hook(DynamicClassDefContext(call, lval.name, self)) + + def unwrap_final(self, s: AssignmentStmt) -> bool: + """Strip Final[...] if present in an assignment. + + This is done to invoke type inference during type checking phase for this + assignment. Also, Final[...] doesn't affect type in any way -- it is rather an + access qualifier for given `Var`. + + Also perform various consistency checks. + + Returns True if Final[...] was present. + """ + if not s.unanalyzed_type or not self.is_final_type(s.unanalyzed_type): + return False + assert isinstance(s.unanalyzed_type, UnboundType) + if len(s.unanalyzed_type.args) > 1: + self.fail("Final[...] takes at most one type argument", s.unanalyzed_type) + invalid_bare_final = False + if not s.unanalyzed_type.args: + s.type = None + if ( + isinstance(s.rvalue, TempNode) + and s.rvalue.no_rhs + # Filter duplicate errors, we already reported this: + and not (self.type and self.type.is_named_tuple) + ): + invalid_bare_final = True + self.fail("Type in Final[...] can only be omitted if there is an initializer", s) + else: + s.type = s.unanalyzed_type.args[0] + + if ( + s.type is not None + and self.options.python_version < (3, 13) + and self.is_classvar(s.type) + ): + self.fail("Variable should not be annotated with both ClassVar and Final", s) + return False + + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], RefExpr): + self.fail("Invalid final declaration", s) + return False + lval = s.lvalues[0] + assert isinstance(lval, RefExpr) + + # Reset inferred status if it was set due to simple literal rvalue on previous iteration. + # TODO: this is a best-effort quick fix, we should avoid the need to manually sync this, + # see https://github.com/python/mypy/issues/6458. + if lval.is_new_def: + lval.is_inferred_def = s.type is None + + if self.loop_depth[-1] > 0: + self.fail("Cannot use Final inside a loop", s) + if self.type and self.type.is_protocol: + if self.is_class_scope(): + self.msg.protocol_members_cant_be_final(s) + if ( + isinstance(s.rvalue, TempNode) + and s.rvalue.no_rhs + and not self.is_stub_file + and not self.is_class_scope() + ): + if not invalid_bare_final: # Skip extra error messages. + self.msg.final_without_value(s) + return True + + def check_final_implicit_def(self, s: AssignmentStmt) -> None: + """Do basic checks for final declaration on self in __init__. + + Additional re-definition checks are performed by `analyze_lvalue`. + """ + if not s.is_final_def: + return + lval = s.lvalues[0] + assert isinstance(lval, RefExpr) + if isinstance(lval, MemberExpr): + if not self.is_self_member_ref(lval): + self.fail("Final can be only applied to a name or an attribute on self", s) + s.is_final_def = False + return + else: + assert self.function_stack + if self.function_stack[-1].name != "__init__": + self.fail("Can only declare a final attribute in class body or __init__", s) + s.is_final_def = False + return + + def store_final_status(self, s: AssignmentStmt) -> None: + """If this is a locally valid final declaration, set the corresponding flag on `Var`.""" + if s.is_final_def: + if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr): + node = s.lvalues[0].node + if isinstance(node, Var): + node.is_final = True + if s.type: + node.final_value = constant_fold_expr(s.rvalue, self.cur_mod_id) + if self.is_class_scope() and ( + isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs + ): + node.final_unset_in_class = True + else: + for lval in self.flatten_lvalues(s.lvalues): + # Special case: we are working with an `Enum`: + # + # class MyEnum(Enum): + # key = 'some value' + # + # Here `key` is implicitly final. In runtime, code like + # + # MyEnum.key = 'modified' + # + # will fail with `AttributeError: Cannot reassign members.` + # That's why we need to replicate this. + if ( + isinstance(lval, NameExpr) + and isinstance(self.type, TypeInfo) + and self.type.is_enum + ): + cur_node = self.type.names.get(lval.name, None) + if ( + cur_node + and isinstance(cur_node.node, Var) + and not (isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs) + ): + # Double underscored members are writable on an `Enum`. + # (Except read-only `__members__` but that is handled in type checker) + cur_node.node.is_final = s.is_final_def = not is_dunder(cur_node.node.name) + + # Special case: deferred initialization of a final attribute in __init__. + # In this case we just pretend this is a valid final definition to suppress + # errors about assigning to final attribute. + if isinstance(lval, MemberExpr) and self.is_self_member_ref(lval): + assert self.type, "Self member outside a class" + cur_node = self.type.names.get(lval.name, None) + if cur_node and isinstance(cur_node.node, Var) and cur_node.node.is_final: + assert self.function_stack + current_function = self.function_stack[-1] + if ( + current_function.name == "__init__" + and cur_node.node.final_unset_in_class + and not cur_node.node.final_set_in_init + and not (isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs) + ): + cur_node.node.final_set_in_init = True + s.is_final_def = True + + def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]: + res: list[Expression] = [] + for lv in lvalues: + if isinstance(lv, (TupleExpr, ListExpr)): + res.extend(self.flatten_lvalues(lv.items)) + else: + res.append(lv) + return res + + def process_type_annotation(self, s: AssignmentStmt) -> None: + """Analyze type annotation or infer simple literal type.""" + if s.type: + lvalue = s.lvalues[-1] + allow_tuple_literal = isinstance(lvalue, TupleExpr) + analyzed = self.anal_type(s.type, allow_tuple_literal=allow_tuple_literal) + # Don't store not ready types (including placeholders). + if analyzed is None or has_placeholder(analyzed): + self.defer(s) + return + s.type = analyzed + if ( + self.type + and self.type.is_protocol + and isinstance(lvalue, NameExpr) + and isinstance(s.rvalue, TempNode) + and s.rvalue.no_rhs + ): + if isinstance(lvalue.node, Var): + lvalue.node.is_abstract_var = True + else: + if ( + self.type + and self.type.is_protocol + and self.is_annotated_protocol_member(s) + and not self.is_func_scope() + ): + self.fail("All protocol members must have explicitly declared types", s) + # Set the type if the rvalue is a simple literal (even if the above error occurred). + if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr): + ref_expr = s.lvalues[0] + safe_literal_inference = True + if self.type and isinstance(ref_expr, NameExpr) and len(self.type.mro) > 1: + # Check if there is a definition in supertype. If yes, we can't safely + # decide here what to infer: int or Literal[42]. + safe_literal_inference = self.type.mro[1].get(ref_expr.name) is None + if safe_literal_inference and ref_expr.is_inferred_def: + s.type = self.analyze_simple_literal_type(s.rvalue, s.is_final_def) + if s.type: + # Store type into nodes. + for lvalue in s.lvalues: + self.store_declared_types(lvalue, s.type) + + def is_annotated_protocol_member(self, s: AssignmentStmt) -> bool: + """Check whether a protocol member is annotated. + + There are some exceptions that can be left unannotated, like ``__slots__``.""" + return any( + (isinstance(lv, NameExpr) and lv.name != "__slots__" and lv.is_inferred_def) + for lv in s.lvalues + ) + + def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type | None: + """Return builtins.int if rvalue is an int literal, etc. + + If this is a 'Final' context, we return "Literal[...]" instead. + """ + if self.function_stack: + # Skip inside a function; this is to avoid confusing + # the code that handles dead code due to isinstance() + # inside type variables with value restrictions (like + # AnyStr). + return None + + value = constant_fold_expr(rvalue, self.cur_mod_id) + if value is None or isinstance(value, complex): + return None + + if isinstance(value, bool): + type_name = "builtins.bool" + elif isinstance(value, int): + type_name = "builtins.int" + elif isinstance(value, str): + type_name = "builtins.str" + elif isinstance(value, float): + type_name = "builtins.float" + + typ = self.named_type_or_none(type_name) + if typ and is_final: + return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ)) + return typ + + def analyze_alias( + self, + name: str, + rvalue: Expression, + allow_placeholder: bool = False, + declared_type_vars: TypeVarLikeList | None = None, + all_declared_type_params_names: list[str] | None = None, + python_3_12_type_alias: bool = False, + ) -> tuple[Type | None, list[TypeVarLikeType], set[str], bool]: + """Check if 'rvalue' is a valid type allowed for aliasing (e.g. not a type variable). + + If yes, return the corresponding type, a list of type variables for generic aliases, + a set of names the alias depends on, and True if the original type has empty tuple index. + An example for the dependencies: + A = int + B = str + analyze_alias(dict[A, B])[2] == {'__main__.A', '__main__.B'} + """ + dynamic = bool(self.function_stack and self.function_stack[-1].is_dynamic()) + global_scope = not self.type and not self.function_stack + try: + typ = expr_to_unanalyzed_type( + rvalue, self.options, self.is_stub_file, lookup_qualified=self.lookup_qualified + ) + except TypeTranslationError: + self.fail( + "Invalid type alias: expression is not a valid type", rvalue, code=codes.VALID_TYPE + ) + return None, [], set(), False + + found_type_vars = self.find_type_var_likes(typ) + namespace = self.qualified_name(name) + alias_type_vars = found_type_vars if declared_type_vars is None else declared_type_vars + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + tvar_defs = self.tvar_defs_from_tvars(alias_type_vars, typ) + + if python_3_12_type_alias: + with self.allow_unbound_tvars_set(): + rvalue.accept(self) + + analyzed, depends_on = analyze_type_alias( + typ, + self, + self.tvar_scope, + self.plugin, + self.options, + self.cur_mod_node, + self.is_typeshed_stub_file, + allow_placeholder=allow_placeholder, + in_dynamic_func=dynamic, + global_scope=global_scope, + allowed_alias_tvars=tvar_defs, + alias_type_params_names=all_declared_type_params_names, + python_3_12_type_alias=python_3_12_type_alias, + ) + + # There can be only one variadic variable at most, the error is reported elsewhere. + new_tvar_defs = [] + variadic = False + for td in tvar_defs: + if isinstance(td, TypeVarTupleType): + if variadic: + continue + variadic = True + new_tvar_defs.append(td) + + indexed = bool(isinstance(typ, UnboundType) and (typ.args or typ.empty_tuple_index)) + return analyzed, new_tvar_defs, depends_on, indexed + + def is_pep_613(self, s: AssignmentStmt) -> bool: + if s.unanalyzed_type is not None and isinstance(s.unanalyzed_type, UnboundType): + lookup = self.lookup_qualified(s.unanalyzed_type.name, s, suppress_errors=True) + if lookup and lookup.fullname in TYPE_ALIAS_NAMES: + return True + return False + + def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: + """Check if assignment creates a type alias and set it up as needed. + + Return True if it is a type alias (even if the target is not ready), + or False otherwise. + + Note: the resulting types for subscripted (including generic) aliases + are also stored in rvalue.analyzed. + """ + if s.invalid_recursive_alias: + return True + lvalue = s.lvalues[0] + if len(s.lvalues) > 1 or not isinstance(lvalue, NameExpr): + # First rule: Only simple assignments like Alias = ... create aliases. + return False + + pep_613 = self.is_pep_613(s) + if not pep_613 and s.unanalyzed_type is not None: + # Second rule: Explicit type (cls: Type[A] = A) always creates variable, not alias. + # unless using PEP 613 `cls: TypeAlias = A` + return False + + # It can be `A = TypeAliasType('A', ...)` call, in this case, + # we just take the second argument and analyze it: + type_params: TypeVarLikeList | None + all_type_params_names: list[str] | None + if self.check_type_alias_type_call(s.rvalue, name=lvalue.name): + rvalue = ( + s.rvalue.args[1] + if s.rvalue.arg_kinds[1] == ARG_POS + else s.rvalue.args[s.rvalue.arg_names.index("value")] + ) + pep_695 = True + type_params, all_type_params_names = self.analyze_type_alias_type_params(s.rvalue) + else: + rvalue = s.rvalue + pep_695 = False + type_params = None + all_type_params_names = None + + if isinstance(rvalue, CallExpr) and rvalue.analyzed: + return False + + existing = self.current_symbol_table().get(lvalue.name) + # Third rule: type aliases can't be re-defined. For example: + # A: Type[float] = int + # A = float # OK, but this doesn't define an alias + # B = int + # B = float # Error! + # Don't create an alias in these cases: + if existing and ( + isinstance(existing.node, Var) # existing variable + or (isinstance(existing.node, TypeAlias) and not s.is_alias_def) # existing alias + or (isinstance(existing.node, PlaceholderNode) and existing.node.node.line < s.line) + ): # previous incomplete definition + # TODO: find a more robust way to track the order of definitions. + # Note: if is_alias_def=True, this is just a node from previous iteration. + if isinstance(existing.node, TypeAlias) and not s.is_alias_def: + self.fail( + 'Cannot assign multiple types to name "{}"' + ' without an explicit "type[...]" annotation'.format(lvalue.name), + lvalue, + ) + return False + + non_global_scope = self.type or self.is_func_scope() + if not pep_613 and not pep_695 and isinstance(rvalue, RefExpr) and non_global_scope: + # Fourth rule (special case): Non-subscripted right hand side creates a variable + # at class and function scopes. For example: + # + # class Model: + # ... + # class C: + # model = Model # this is automatically a variable with type 'Type[Model]' + # + # without this rule, this typical use case will require a lot of explicit + # annotations (see the second rule). + return False + if not pep_613 and not pep_695 and not self.can_be_type_alias(rvalue): + return False + + if existing and not isinstance(existing.node, (PlaceholderNode, TypeAlias)): + # Cannot redefine existing node as type alias. + return False + + res: Type | None = None + if self.is_none_alias(rvalue): + res = NoneType() + alias_tvars: list[TypeVarLikeType] = [] + depends_on: set[str] = set() + indexed = False + else: + tag = self.track_incomplete_refs() + res, alias_tvars, depends_on, indexed = self.analyze_alias( + lvalue.name, + rvalue, + allow_placeholder=True, + declared_type_vars=type_params, + all_declared_type_params_names=all_type_params_names, + ) + if not res: + return False + if not self.is_func_scope(): + # Only marking incomplete for top-level placeholders makes recursive aliases like + # `A = Sequence[str | A]` valid here, similar to how we treat base classes in class + # definitions, allowing `class str(Sequence[str]): ...` + incomplete_target = isinstance(res, ProperType) and isinstance( + res, PlaceholderType + ) + else: + incomplete_target = has_placeholder(res) + if self.found_incomplete_ref(tag) or incomplete_target: + # Since we have got here, we know this must be a type alias (incomplete refs + # may appear in nested positions), therefore use becomes_typeinfo=True. + self.mark_incomplete(lvalue.name, rvalue, becomes_typeinfo=True) + return True + self.add_type_alias_deps(depends_on) + check_for_explicit_any(res, self.options, self.is_typeshed_stub_file, self.msg, context=s) + # When this type alias gets "inlined", the Any is not explicit anymore, + # so we need to replace it with non-explicit Anys. + res = make_any_non_explicit(res) + if self.options.disallow_any_unimported and has_any_from_unimported_type(res): + # Only show error message once, when the type is fully analyzed. + if not has_placeholder(res): + self.msg.unimported_type_becomes_any("Type alias target", res, s) + res = make_any_non_unimported(res) + # Note: with the new (lazy) type alias representation we only need to set no_args to True + # if the expected number of arguments is non-zero, so that aliases like `A = List` work + # but not aliases like `A = TypeAliasType("A", List)` as these need explicit type params. + # However, eagerly expanding aliases like Text = str is a nice performance optimization. + no_args = ( + isinstance(res, ProperType) + and isinstance(res, Instance) + and not pep_695 + and not indexed + ) + if isinstance(res, ProperType) and isinstance(res, Instance): + if not validate_instance(res, self.fail, indexed): + fix_instance(res, self.fail, self.note, disallow_any=False, options=self.options) + # Aliases defined within functions can't be accessed outside + # the function, since the symbol table will no longer + # exist. Work around by expanding them eagerly when used. + eager = self.is_func_scope() + alias_node = TypeAlias( + res, + self.qualified_name(lvalue.name), + self.cur_mod_id, + s.line, + s.column, + alias_tvars=alias_tvars, + no_args=no_args, + eager=eager, + python_3_12_type_alias=pep_695, + ) + if isinstance(s.rvalue, (IndexExpr, CallExpr, OpExpr)) and ( + not isinstance(rvalue, OpExpr) + or (self.options.python_version >= (3, 10) or self.is_stub_file) + ): + # Note: CallExpr is for "void = type(None)" and OpExpr is for "X | Y" union syntax. + if not isinstance(s.rvalue.analyzed, TypeAliasExpr): + # Any existing node will be updated in-place below. + s.rvalue.analyzed = TypeAliasExpr(alias_node) + s.rvalue.analyzed.line = s.line + # we use the column from resulting target, to get better location for errors + s.rvalue.analyzed.column = res.column + elif isinstance(s.rvalue, RefExpr): + s.rvalue.is_alias_rvalue = True + + if existing: + # An alias gets updated. + updated = False + if isinstance(existing.node, TypeAlias): + if existing.node.target != res: + # Copy expansion to the existing alias, this matches how we update base classes + # for a TypeInfo _in place_ if there are nested placeholders. + existing.node.target = res + existing.node.alias_tvars = alias_tvars + existing.node.no_args = no_args + updated = True + # Invalidate recursive status cache in case it was previously set. + existing.node._is_recursive = None + else: + # Otherwise just replace existing placeholder with type alias. + existing.node = alias_node + updated = True + if updated: + if self.final_iteration: + self.cannot_resolve_name(lvalue.name, "name", s) + return True + else: + # We need to defer so that this change can get propagated to base classes. + self.defer(s, force_progress=True) + else: + self.add_symbol(lvalue.name, alias_node, s) + if isinstance(rvalue, RefExpr) and isinstance(rvalue.node, TypeAlias): + alias_node.normalized = rvalue.node.normalized + current_node = existing.node if existing else alias_node + assert isinstance(current_node, TypeAlias) + self.disable_invalid_recursive_aliases(s, current_node, s.rvalue) + if self.is_class_scope(): + assert self.type is not None + if self.type.is_protocol: + self.fail("Type aliases are prohibited in protocol bodies", s) + if not lvalue.name[0].isupper(): + self.note("Use variable annotation syntax to define protocol members", s) + return True + + def check_type_alias_type_call(self, rvalue: Expression, *, name: str) -> TypeGuard[CallExpr]: + if not isinstance(rvalue, CallExpr): + return False + + names = ["typing_extensions.TypeAliasType"] + if self.options.python_version >= (3, 12): + names.append("typing.TypeAliasType") + if not refers_to_fullname(rvalue.callee, tuple(names)): + return False + if not self.check_typevarlike_name(rvalue, name, rvalue): + return False + if rvalue.arg_kinds.count(ARG_POS) != ( + 2 - ("value" in rvalue.arg_names) - ("name" in rvalue.arg_names) + ): + return False + + return True + + def analyze_type_alias_type_params( + self, rvalue: CallExpr + ) -> tuple[TypeVarLikeList, list[str]]: + """Analyze type_params of TypeAliasType. + + Returns declared unbound type variable expressions and a list of all declared type + variable names for error reporting. + """ + if "type_params" in rvalue.arg_names: + type_params_arg = rvalue.args[rvalue.arg_names.index("type_params")] + if not isinstance(type_params_arg, TupleExpr): + self.fail( + "Tuple literal expected as the type_params argument to TypeAliasType", + type_params_arg, + ) + return [], [] + type_params = type_params_arg.items + else: + return [], [] + + declared_tvars: TypeVarLikeList = [] + all_declared_tvar_names: list[str] = [] # includes bound type variables + have_type_var_tuple = False + for tp_expr in type_params: + if isinstance(tp_expr, StarExpr): + tp_expr.valid = False + self.analyze_type_expr(tp_expr) + try: + base = self.expr_to_unanalyzed_type(tp_expr) + except TypeTranslationError: + continue + if not isinstance(base, UnboundType): + continue + + tag = self.track_incomplete_refs() + tvar = self.analyze_unbound_tvar_impl(base, is_typealias_param=True) + if tvar: + if isinstance(tvar[1], TypeVarTupleExpr): + if have_type_var_tuple: + self.fail( + "Can only use one TypeVarTuple in type_params argument to TypeAliasType", + base, + code=codes.TYPE_VAR, + ) + have_type_var_tuple = True + continue + have_type_var_tuple = True + elif not self.found_incomplete_ref(tag): + sym = self.lookup_qualified(base.name, base) + if sym and isinstance(sym.node, TypeVarLikeExpr): + all_declared_tvar_names.append(sym.node.name) # Error will be reported later + else: + self.fail( + "Free type variable expected in type_params argument to TypeAliasType", + base, + code=codes.TYPE_VAR, + ) + if sym and sym.fullname in UNPACK_TYPE_NAMES: + self.note( + "Don't Unpack type variables in type_params", base, code=codes.TYPE_VAR + ) + continue + if tvar in declared_tvars: + self.fail( + f'Duplicate type variable "{tvar[0]}" in type_params argument to TypeAliasType', + base, + code=codes.TYPE_VAR, + ) + continue + if tvar: + all_declared_tvar_names.append(tvar[0]) + declared_tvars.append(tvar) + return declared_tvars, all_declared_tvar_names + + def disable_invalid_recursive_aliases( + self, s: AssignmentStmt | TypeAliasStmt, current_node: TypeAlias, ctx: Context + ) -> None: + """Prohibit and fix recursive type aliases that are invalid/unsupported.""" + messages = [] + if ( + isinstance(current_node.target, TypeAliasType) + and current_node.target.alias is current_node + ): + # We want to have consistent error messages, but not calling name_not_defined(), + # since it will do a bunch of unrelated things we don't want here. + messages.append( + f'Cannot resolve name "{current_node.name}" (possible cyclic definition)' + ) + elif is_invalid_recursive_alias({current_node}, current_node.target): + target = ( + "tuple" if isinstance(get_proper_type(current_node.target), TupleType) else "union" + ) + messages.append(f"Invalid recursive alias: a {target} item of itself") + if detect_diverging_alias( + current_node, current_node.target, self.lookup_qualified, self.tvar_scope + ): + messages.append("Invalid recursive alias: type variable nesting on right hand side") + if messages: + current_node.target = AnyType(TypeOfAny.from_error) + s.invalid_recursive_alias = True + for msg in messages: + self.fail(msg, ctx) + + def analyze_lvalue( + self, + lval: Lvalue, + nested: bool = False, + explicit_type: bool = False, + is_final: bool = False, + escape_comprehensions: bool = False, + has_explicit_value: bool = False, + is_index_var: bool = False, + ) -> None: + """Analyze an lvalue or assignment target. + + Args: + lval: The target lvalue + nested: If true, the lvalue is within a tuple or list lvalue expression + explicit_type: Assignment has type annotation + escape_comprehensions: If we are inside a comprehension, set the variable + in the enclosing scope instead. This implements + https://www.python.org/dev/peps/pep-0572/#scope-of-the-target + is_index_var: If lval is the index variable in a for loop + """ + if escape_comprehensions: + assert isinstance(lval, NameExpr), "assignment expression target must be NameExpr" + if isinstance(lval, NameExpr): + self.analyze_name_lvalue( + lval, + explicit_type, + is_final, + escape_comprehensions, + has_explicit_value=has_explicit_value, + is_index_var=is_index_var, + ) + elif isinstance(lval, MemberExpr): + self.analyze_member_lvalue(lval, explicit_type, is_final, has_explicit_value) + if explicit_type and not self.is_self_member_ref(lval): + self.fail("Type cannot be declared in assignment to non-self attribute", lval) + elif isinstance(lval, IndexExpr): + if explicit_type: + self.fail("Unexpected type declaration", lval) + lval.accept(self) + elif isinstance(lval, TupleExpr): + self.analyze_tuple_or_list_lvalue(lval, explicit_type) + elif isinstance(lval, StarExpr): + if nested: + self.analyze_lvalue(lval.expr, nested, explicit_type) + else: + self.fail("Starred assignment target must be in a list or tuple", lval) + else: + self.fail("Invalid assignment target", lval) + + def analyze_name_lvalue( + self, + lvalue: NameExpr, + explicit_type: bool, + is_final: bool, + escape_comprehensions: bool, + has_explicit_value: bool, + is_index_var: bool, + ) -> None: + """Analyze an lvalue that targets a name expression. + + Arguments are similar to "analyze_lvalue". + """ + if lvalue.node: + # This has been bound already in a previous iteration. + return + + name = lvalue.name + if self.is_alias_for_final_name(name): + if is_final: + self.fail("Cannot redefine an existing name as final", lvalue) + else: + self.msg.cant_assign_to_final(name, self.type is not None, lvalue) + + kind = self.current_symbol_kind() + names = self.current_symbol_table(escape_comprehensions=escape_comprehensions) + existing = names.get(name) + + outer = self.is_global_or_nonlocal(name) + if ( + kind == MDEF + and isinstance(self.type, TypeInfo) + and self.type.is_enum + and not name.startswith("__") + ): + # Special case: we need to be sure that `Enum` keys are unique. + if existing is not None and not isinstance(existing.node, PlaceholderNode): + self.fail( + 'Attempted to reuse member name "{}" in Enum definition "{}"'.format( + name, self.type.name + ), + lvalue, + ) + + if explicit_type and has_explicit_value: + self.fail("Enum members must be left unannotated", lvalue) + self.note( + "See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members", + lvalue, + ) + + if (not existing or isinstance(existing.node, PlaceholderNode)) and not outer: + # Define new variable. + var = self.make_name_lvalue_var( + lvalue, kind, not explicit_type, has_explicit_value, is_index_var + ) + added = self.add_symbol(name, var, lvalue, escape_comprehensions=escape_comprehensions) + # Only bind expression if we successfully added name to symbol table. + if added: + lvalue.is_new_def = True + lvalue.is_inferred_def = True + lvalue.kind = kind + lvalue.node = var + if kind == GDEF: + lvalue.fullname = var._fullname + else: + lvalue.fullname = lvalue.name + if self.is_func_scope(): + if unmangle(name) == "_" and not self.options.allow_redefinition_new: + # Special case for assignment to local named '_': always infer 'Any'. + # This isn't needed with --allow-redefinition-new, since arbitrary + # types can be assigned to '_' anyway. + typ = AnyType(TypeOfAny.special_form) + self.store_declared_types(lvalue, typ) + if is_final and self.is_final_redefinition(kind, name): + self.fail("Cannot redefine an existing name as final", lvalue) + else: + self.make_name_lvalue_point_to_existing_def(lvalue, explicit_type, is_final) + + def is_final_redefinition(self, kind: int, name: str) -> bool: + if kind == GDEF: + return self.is_mangled_global(name) and not self.is_initial_mangled_global(name) + elif kind == MDEF and self.type: + return unmangle(name) + "'" in self.type.names + return False + + def is_alias_for_final_name(self, name: str) -> bool: + if self.is_func_scope(): + if not name.endswith("'"): + # Not a mangled name -- can't be an alias + return False + name = unmangle(name) + assert self.locals[-1] is not None, "No locals at function scope" + existing = self.locals[-1].get(name) + return existing is not None and is_final_node(existing.node) + elif self.type is not None: + orig_name = unmangle(name) + "'" + if name == orig_name: + return False + existing = self.type.names.get(orig_name) + return existing is not None and is_final_node(existing.node) + else: + orig_name = unmangle(name) + "'" + if name == orig_name: + return False + existing = self.globals.get(orig_name) + return existing is not None and is_final_node(existing.node) + + def make_name_lvalue_var( + self, + lvalue: NameExpr, + kind: int, + inferred: bool, + has_explicit_value: bool, + is_index_var: bool, + ) -> Var: + """Return a Var node for an lvalue that is a name expression.""" + name = lvalue.name + v = Var(name) + v.set_line(lvalue) + v.is_inferred = inferred + if kind == MDEF: + assert self.type is not None + v.info = self.type + v.is_initialized_in_class = True + v.allow_incompatible_override = name in ALLOW_INCOMPATIBLE_OVERRIDE + if kind != LDEF: + v._fullname = self.qualified_name(name) + else: + # fullname should never stay None + v._fullname = name + v.is_ready = False # Type not inferred yet + v.has_explicit_value = has_explicit_value + v.is_index_var = is_index_var + return v + + def make_name_lvalue_point_to_existing_def( + self, lval: NameExpr, explicit_type: bool, is_final: bool + ) -> None: + """Update an lvalue to point to existing definition in the same scope. + + Arguments are similar to "analyze_lvalue". + + Assume that an existing name exists. + """ + if is_final: + # Redefining an existing name with final is always an error. + self.fail("Cannot redefine an existing name as final", lval) + original_def = self.lookup(lval.name, lval, suppress_errors=True) + if original_def is None and self.type and not self.is_func_scope(): + # Workaround to allow "x, x = ..." in class body. + original_def = self.type.get(lval.name) + if explicit_type: + # Don't re-bind if there is a type annotation. + self.name_already_defined(lval.name, lval, original_def) + else: + # Bind to an existing name. + if original_def: + self.bind_name_expr(lval, original_def) + else: + self.name_not_defined(lval.name, lval) + self.check_lvalue_validity(lval.node, lval) + + if self.scope.functions and lval.name in self.global_decls[-1]: + # Technically, we only need to set this if original r.h.s. would be inferred + # as None, but it is tricky to detect reliably during semantic analysis. + if ( + original_def + and isinstance(original_def.node, Var) + and original_def.node.is_inferred + ): + for func in self.scope.functions: + func.def_or_infer_vars = True + + def analyze_tuple_or_list_lvalue(self, lval: TupleExpr, explicit_type: bool = False) -> None: + """Analyze an lvalue or assignment target that is a list or tuple.""" + items = lval.items + star_exprs = [item for item in items if isinstance(item, StarExpr)] + + if len(star_exprs) > 1: + self.fail("Two starred expressions in assignment", lval) + else: + if len(star_exprs) == 1: + star_exprs[0].valid = True + for i in items: + self.analyze_lvalue( + lval=i, + nested=True, + explicit_type=explicit_type, + # Lists and tuples always have explicit values defined: + # `a, b, c = value` + has_explicit_value=True, + ) + + def analyze_member_lvalue( + self, lval: MemberExpr, explicit_type: bool, is_final: bool, has_explicit_value: bool + ) -> None: + """Analyze lvalue that is a member expression. + + Arguments: + lval: The target lvalue + explicit_type: Assignment has type annotation + is_final: Is the target final + """ + if lval.node: + # This has been bound already in a previous iteration. + return + lval.accept(self) + if self.is_self_member_ref(lval): + assert self.type, "Self member outside a class" + cur_node = self.type.names.get(lval.name) + node = self.type.get(lval.name) + if cur_node and is_final: + # Overrides will be checked in type checker. + self.fail("Cannot redefine an existing name as final", lval) + # On first encounter with this definition, if this attribute was defined before + # with an inferred type and it's marked with an explicit type now, give an error. + if ( + not lval.node + and cur_node + and isinstance(cur_node.node, Var) + and cur_node.node.is_inferred + and explicit_type + ): + self.attribute_already_defined(lval.name, lval, cur_node) + if self.type.is_protocol and has_explicit_value and cur_node is not None: + # Make this variable non-abstract, it would be safer to do this only if we + # are inside __init__, but we do this always to preserve historical behaviour. + if isinstance(cur_node.node, Var): + cur_node.node.is_abstract_var = False + if ( + # If the attribute of self is not defined, create a new Var, ... + node is None + # ... or if it is defined as abstract in a *superclass*. + or (cur_node is None and isinstance(node.node, Var) and node.node.is_abstract_var) + # ... also an explicit declaration on self also creates a new Var. + # Note that `explicit_type` might have been erased for bare `Final`, + # so we also check if `is_final` is passed. + or (cur_node is None and (explicit_type or is_final)) + ): + if self.type.is_protocol and node is None: + self.fail("Protocol members cannot be defined via assignment to self", lval) + else: + # Implicit attribute definition in __init__. + lval.is_new_def = True + lval.is_inferred_def = True + v = Var(lval.name) + v.set_line(lval) + v._fullname = self.qualified_name(lval.name) + v.info = self.type + v.is_ready = False + v.explicit_self_type = explicit_type or is_final + lval.def_var = v + lval.node = v + # TODO: should we also set lval.kind = MDEF? + self.type.names[lval.name] = SymbolTableNode(MDEF, v, implicit=True) + for func in self.scope.functions: + func.def_or_infer_vars = True + if ( + cur_node + and isinstance(cur_node.node, Var) + and cur_node.node.is_inferred + and cur_node.node.is_initialized_in_class + ): + for func in self.scope.functions: + func.def_or_infer_vars = True + self.check_lvalue_validity(lval.node, lval) + + def is_self_member_ref(self, memberexpr: MemberExpr) -> bool: + """Does memberexpr to refer to an attribute of self?""" + if not isinstance(memberexpr.expr, NameExpr): + return False + node = memberexpr.expr.node + return isinstance(node, Var) and node.is_self + + def check_lvalue_validity(self, node: Expression | SymbolNode | None, ctx: Context) -> None: + if isinstance(node, TypeVarExpr): + self.fail("Invalid assignment target", ctx) + elif isinstance(node, TypeInfo): + self.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, ctx) + + def store_declared_types(self, lvalue: Lvalue, typ: Type) -> None: + if isinstance(lvalue, RefExpr): + lvalue.is_inferred_def = False + if isinstance(lvalue.node, Var): + var = lvalue.node + var.type = typ + var.is_ready = True + typ = get_proper_type(typ) + if ( + var.is_final + and isinstance(typ, Instance) + and typ.last_known_value + and (not self.type or not self.type.is_enum) + ): + var.final_value = typ.last_known_value.value + # If node is not a variable, we'll catch it elsewhere. + elif isinstance(lvalue, TupleExpr): + typ = get_proper_type(typ) + if isinstance(typ, TupleType): + if len(lvalue.items) != len(typ.items): + self.fail("Incompatible number of tuple items", lvalue) + return + for item, itemtype in zip(lvalue.items, typ.items): + self.store_declared_types(item, itemtype) + else: + self.fail("Tuple type expected for multiple variables", lvalue) + elif isinstance(lvalue, StarExpr): + # Historical behavior for the old parser + self.store_declared_types(lvalue.expr, typ) + else: + # This has been flagged elsewhere as an error, so just ignore here. + pass + + def process_typevar_declaration(self, s: AssignmentStmt) -> bool: + """Check if s declares a TypeVar; it yes, store it in symbol table. + + Return True if this looks like a type variable declaration (but maybe + with errors), otherwise return False. + """ + call = self.get_typevarlike_declaration(s, ("typing.TypeVar", "typing_extensions.TypeVar")) + if not call: + return False + + name = self.extract_typevarlike_name(s, call) + if name is None: + return False + + # Constraining types + n_values = call.arg_kinds[1:].count(ARG_POS) + values = self.analyze_value_types(call.args[1 : 1 + n_values]) + + res = self.process_typevar_parameters( + call.args[1 + n_values :], + call.arg_names[1 + n_values :], + call.arg_kinds[1 + n_values :], + n_values, + s, + ) + if res is None: + return False + variance, upper_bound, default = res + + existing = self.current_symbol_table().get(name) + if existing and not ( + isinstance(existing.node, PlaceholderNode) + or + # Also give error for another type variable with the same name. + (isinstance(existing.node, TypeVarExpr) and existing.node is call.analyzed) + ): + self.fail(f'Cannot redefine "{name}" as a type variable', s) + return False + + if self.options.disallow_any_unimported: + for idx, constraint in enumerate(values, start=1): + if has_any_from_unimported_type(constraint): + prefix = f"Constraint {idx}" + self.msg.unimported_type_becomes_any(prefix, constraint, s) + + if has_any_from_unimported_type(upper_bound): + prefix = "Upper bound of type variable" + self.msg.unimported_type_becomes_any(prefix, upper_bound, s) + + for t in values + [upper_bound, default]: + check_for_explicit_any( + t, self.options, self.is_typeshed_stub_file, self.msg, context=s + ) + + # mypyc suppresses making copies of a function to check each + # possible type, so set the upper bound to Any to prevent that + # from causing errors. + if values and self.options.mypyc: + upper_bound = AnyType(TypeOfAny.implementation_artifact) + + # Yes, it's a valid type variable definition! Add it to the symbol table. + if not call.analyzed: + type_var = TypeVarExpr( + name, self.qualified_name(name), values, upper_bound, default, variance + ) + type_var.line = call.line + call.analyzed = type_var + updated = True + else: + assert isinstance(call.analyzed, TypeVarExpr) + updated = ( + values != call.analyzed.values + or upper_bound != call.analyzed.upper_bound + or default != call.analyzed.default + ) + call.analyzed.upper_bound = upper_bound + call.analyzed.values = values + call.analyzed.default = default + if any(has_placeholder(v) for v in values): + self.process_placeholder(None, "TypeVar values", s, force_progress=updated) + elif has_placeholder(upper_bound): + self.process_placeholder(None, "TypeVar upper bound", s, force_progress=updated) + elif has_placeholder(default): + self.process_placeholder(None, "TypeVar default", s, force_progress=updated) + + self.add_symbol(name, call.analyzed, s) + return True + + def check_typevar_default(self, default: Type, context: Context) -> Type: + typ = get_proper_type(default) + if isinstance(typ, AnyType) and typ.is_from_error: + self.fail( + message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format("TypeVar", "default"), context + ) + return default + + def check_paramspec_default(self, default: Type, context: Context) -> Type: + typ = get_proper_type(default) + if isinstance(typ, Parameters): + for i, arg_type in enumerate(typ.arg_types): + arg_ptype = get_proper_type(arg_type) + if isinstance(arg_ptype, AnyType) and arg_ptype.is_from_error: + self.fail(f"Argument {i} of ParamSpec default must be a type", context) + elif ( + isinstance(typ, AnyType) + and typ.is_from_error + or not isinstance(typ, (AnyType, UnboundType)) + ): + self.fail( + "The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec", + context, + ) + default = AnyType(TypeOfAny.from_error) + return default + + def check_typevartuple_default(self, default: Type, context: Context) -> Type: + typ = get_proper_type(default) + if not isinstance(typ, UnpackType): + self.fail("The default argument to TypeVarTuple must be an Unpacked tuple", context) + default = AnyType(TypeOfAny.from_error) + return default + + def check_typevarlike_name(self, call: CallExpr, name: str, context: Context) -> bool: + """Checks that the name of a TypeVar or ParamSpec matches its variable.""" + name = unmangle(name) + assert isinstance(call.callee, RefExpr) + typevarlike_type = ( + call.callee.name if isinstance(call.callee, NameExpr) else call.callee.fullname + ) + if len(call.args) < 1: + self.fail(f"Too few arguments for {typevarlike_type}()", context) + return False + if not isinstance(call.args[0], StrExpr) or call.arg_kinds[0] != ARG_POS: + self.fail(f"{typevarlike_type}() expects a string literal as first argument", context) + return False + elif call.args[0].value != name: + msg = 'String argument 1 "{}" to {}(...) does not match variable name "{}"' + self.fail(msg.format(call.args[0].value, typevarlike_type, name), context) + return False + return True + + def get_typevarlike_declaration( + self, s: AssignmentStmt, typevarlike_types: tuple[str, ...] + ) -> CallExpr | None: + """Returns the call expression if `s` is a declaration of `typevarlike_type` + (TypeVar or ParamSpec), or None otherwise. + """ + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr): + return None + if not isinstance(s.rvalue, CallExpr): + return None + call = s.rvalue + callee = call.callee + if not isinstance(callee, RefExpr): + return None + if callee.fullname not in typevarlike_types: + return None + return call + + def process_typevar_parameters( + self, + args: list[Expression], + names: list[str | None], + kinds: list[ArgKind], + num_values: int, + context: Context, + ) -> tuple[int, Type, Type] | None: + has_values = num_values > 0 + covariant = False + contravariant = False + upper_bound: Type = self.object_type() + default: Type = AnyType(TypeOfAny.from_omitted_generics) + for param_value, param_name, param_kind in zip(args, names, kinds): + if not param_kind.is_named(): + self.fail(message_registry.TYPEVAR_UNEXPECTED_ARGUMENT, context) + return None + if param_name == "covariant": + if isinstance(param_value, NameExpr) and param_value.name in ("True", "False"): + covariant = param_value.name == "True" + else: + self.fail(message_registry.TYPEVAR_VARIANCE_DEF.format("covariant"), context) + return None + elif param_name == "contravariant": + if isinstance(param_value, NameExpr) and param_value.name in ("True", "False"): + contravariant = param_value.name == "True" + else: + self.fail( + message_registry.TYPEVAR_VARIANCE_DEF.format("contravariant"), context + ) + return None + elif param_name == "bound": + if has_values: + self.fail("TypeVar cannot have both values and an upper bound", context) + return None + tv_arg = self.get_typevarlike_argument("TypeVar", param_name, param_value, context) + if tv_arg is None: + return None + upper_bound = tv_arg + elif param_name == "default": + tv_arg = self.get_typevarlike_argument( + "TypeVar", param_name, param_value, context, allow_unbound_tvars=True + ) + default = tv_arg or AnyType(TypeOfAny.from_error) + elif param_name == "values": + # Probably using obsolete syntax with values=(...). Explain the current syntax. + self.fail('TypeVar "values" argument not supported', context) + self.fail( + "Use TypeVar('T', t, ...) instead of TypeVar('T', values=(t, ...))", context + ) + return None + else: + self.fail( + f'{message_registry.TYPEVAR_UNEXPECTED_ARGUMENT}: "{param_name}"', context + ) + return None + + if covariant and contravariant: + self.fail("TypeVar cannot be both covariant and contravariant", context) + return None + elif num_values == 1: + self.fail(message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES, context) + return None + elif covariant: + variance = COVARIANT + elif contravariant: + variance = CONTRAVARIANT + else: + variance = INVARIANT + return variance, upper_bound, default + + def get_typevarlike_argument( + self, + typevarlike_name: str, + param_name: str, + param_value: Expression, + context: Context, + *, + allow_unbound_tvars: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_typevar_arg: bool = True, + ) -> ProperType | None: + try: + # We want to use our custom error message below, so we suppress + # the default error message for invalid types here. + analyzed = self.expr_to_analyzed_type( + param_value, + allow_placeholder=True, + report_invalid_types=False, + allow_unbound_tvars=allow_unbound_tvars, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + ) + if analyzed is None: + # Type variables are special: we need to place them in the symbol table + # soon, even if upper bound is not ready yet. Otherwise, avoiding + # a "deadlock" in this common pattern would be tricky: + # T = TypeVar('T', bound=Custom[Any]) + # class Custom(Generic[T]): + # ... + analyzed = PlaceholderType(None, [], context.line) + typ = get_proper_type(analyzed) + if report_invalid_typevar_arg and isinstance(typ, AnyType) and typ.is_from_error: + self.fail( + message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name), + param_value, + ) + # Note: we do not return 'None' here -- we want to continue + # using the AnyType. + return typ + except TypeTranslationError: + if report_invalid_typevar_arg: + self.fail( + message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name), + param_value, + ) + return None + + def extract_typevarlike_name(self, s: AssignmentStmt, call: CallExpr) -> str | None: + if not call: + return None + + lvalue = s.lvalues[0] + assert isinstance(lvalue, NameExpr) + if s.type: + self.fail("Cannot declare the type of a TypeVar or similar construct", s) + return None + + if not self.check_typevarlike_name(call, lvalue.name, s): + return None + return lvalue.name + + def process_paramspec_declaration(self, s: AssignmentStmt) -> bool: + """Checks if s declares a ParamSpec; if yes, store it in symbol table. + + Return True if this looks like a ParamSpec (maybe with errors), otherwise return False. + + In the future, ParamSpec may accept bounds and variance arguments, in which + case more aggressive sharing of code with process_typevar_declaration should be pursued. + """ + call = self.get_typevarlike_declaration( + s, ("typing_extensions.ParamSpec", "typing.ParamSpec") + ) + if not call: + return False + + name = self.extract_typevarlike_name(s, call) + if name is None: + return False + + n_values = call.arg_kinds[1:].count(ARG_POS) + if n_values != 0: + self.fail('Too many positional arguments for "ParamSpec"', s) + + default: Type = AnyType(TypeOfAny.from_omitted_generics) + for param_value, param_name in zip( + call.args[1 + n_values :], call.arg_names[1 + n_values :] + ): + if param_name == "default": + tv_arg = self.get_typevarlike_argument( + "ParamSpec", + param_name, + param_value, + s, + allow_unbound_tvars=True, + allow_param_spec_literals=True, + report_invalid_typevar_arg=False, + ) + default = tv_arg or AnyType(TypeOfAny.from_error) + default = self.check_paramspec_default(default, param_value) + else: + # ParamSpec is different from a regular TypeVar: + # arguments are not semantically valid. But, allowed in runtime. + # So, we need to warn users about possible invalid usage. + self.fail( + "The variance and bound arguments to ParamSpec do not have defined semantics yet", + s, + ) + + # PEP 612 reserves the right to define bound, covariant and contravariant arguments to + # ParamSpec in a later PEP. If and when that happens, we should do something + # on the lines of process_typevar_parameters + + if not call.analyzed: + paramspec_var = ParamSpecExpr( + name, self.qualified_name(name), self.object_type(), default, INVARIANT + ) + paramspec_var.line = call.line + call.analyzed = paramspec_var + updated = True + else: + assert isinstance(call.analyzed, ParamSpecExpr) + updated = default != call.analyzed.default + call.analyzed.default = default + if has_placeholder(default): + self.process_placeholder(None, "ParamSpec default", s, force_progress=updated) + + self.add_symbol(name, call.analyzed, s) + return True + + def process_typevartuple_declaration(self, s: AssignmentStmt) -> bool: + """Checks if s declares a TypeVarTuple; if yes, store it in symbol table. + + Return True if this looks like a TypeVarTuple (maybe with errors), otherwise return False. + """ + call = self.get_typevarlike_declaration( + s, ("typing_extensions.TypeVarTuple", "typing.TypeVarTuple") + ) + if not call: + return False + + n_values = call.arg_kinds[1:].count(ARG_POS) + if n_values != 0: + self.fail('Too many positional arguments for "TypeVarTuple"', s) + + default: Type = AnyType(TypeOfAny.from_omitted_generics) + for param_value, param_name in zip( + call.args[1 + n_values :], call.arg_names[1 + n_values :] + ): + if param_name == "default": + tv_arg = self.get_typevarlike_argument( + "TypeVarTuple", + param_name, + param_value, + s, + allow_unbound_tvars=True, + report_invalid_typevar_arg=False, + allow_unpack=True, + ) + default = tv_arg or AnyType(TypeOfAny.from_error) + default = self.check_typevartuple_default(default, param_value) + else: + self.fail(f'Unexpected keyword argument "{param_name}" for "TypeVarTuple"', s) + + name = self.extract_typevarlike_name(s, call) + if name is None: + return False + + # PEP 646 does not specify the behavior of variance, constraints, or bounds. + if not call.analyzed: + tuple_fallback = self.named_type("builtins.tuple", [self.object_type()]) + typevartuple_var = TypeVarTupleExpr( + name, + self.qualified_name(name), + # Upper bound for *Ts is *tuple[object, ...], it can never be object. + tuple_fallback.copy_modified(), + tuple_fallback, + default, + INVARIANT, + ) + typevartuple_var.line = call.line + call.analyzed = typevartuple_var + updated = True + else: + assert isinstance(call.analyzed, TypeVarTupleExpr) + updated = default != call.analyzed.default + call.analyzed.default = default + if has_placeholder(default): + self.process_placeholder(None, "TypeVarTuple default", s, force_progress=updated) + + self.add_symbol(name, call.analyzed, s) + return True + + def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: + if self.is_func_scope() and not self.type and "@" not in name: + name += "@" + str(line) + class_def = ClassDef(name, Block([])) + if self.is_func_scope() and not self.type: + # Full names of generated classes should always be prefixed with the module names + # even if they are nested in a function, since these classes will be (de-)serialized. + # (Note that the caller should append @line to the name to avoid collisions.) + # TODO: clean this up, see #6422. + class_def.fullname = self.cur_mod_id + "." + self.qualified_name(name) + else: + class_def.fullname = self.qualified_name(name) + + info = TypeInfo(SymbolTable(), class_def, self.cur_mod_id) + class_def.info = info + mro = basetype_or_fallback.type.mro + if not mro: + # Probably an error, we should not crash so generate something meaningful. + mro = [basetype_or_fallback.type, self.object_type().type] + info.mro = [info] + mro + info.bases = [basetype_or_fallback] + return info + + def analyze_value_types(self, items: list[Expression]) -> list[Type]: + """Analyze types from values expressions in type variable definition.""" + result: list[Type] = [] + for node in items: + try: + analyzed = self.anal_type( + self.expr_to_unanalyzed_type(node), allow_placeholder=True + ) + if analyzed is None: + # Type variables are special: we need to place them in the symbol table + # soon, even if some value is not ready yet, see process_typevar_parameters() + # for an example. + analyzed = PlaceholderType(None, [], node.line) + if has_type_vars(analyzed): + self.fail(message_registry.TYPE_VAR_GENERIC_CONSTRAINT_TYPE, node) + result.append(AnyType(TypeOfAny.from_error)) + else: + result.append(analyzed) + except TypeTranslationError: + self.fail("Type expected", node) + result.append(AnyType(TypeOfAny.from_error)) + return result + + def check_classvar(self, s: AssignmentStmt) -> None: + """Check if assignment defines a class variable.""" + lvalue = s.lvalues[0] + if len(s.lvalues) != 1 or not isinstance(lvalue, RefExpr): + return + if not s.type or not self.is_classvar(s.type): + return + assert isinstance(s.type, UnboundType) + if self.is_class_scope() and isinstance(lvalue, NameExpr): + node = lvalue.node + if isinstance(node, Var): + node.is_classvar = True + analyzed = self.anal_type(s.type) + assert self.type is not None + if ( + analyzed is not None + and self.type.self_type in get_type_vars(analyzed) + and self.type.defn.type_vars + ): + self.fail(message_registry.CLASS_VAR_WITH_GENERIC_SELF, s) + elif not isinstance(lvalue, MemberExpr) or self.is_self_member_ref(lvalue): + # In case of member access, report error only when assigning to self + # Other kinds of member assignments should be already reported + self.fail_invalid_classvar(lvalue) + if not s.type.args: + if isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs: + if self.options.disallow_any_generics: + self.fail("ClassVar without type argument becomes Any", s, code=codes.TYPE_ARG) + return + s.type = None + + def is_classvar(self, typ: Type) -> bool: + if not isinstance(typ, UnboundType): + return False + sym = self.lookup_qualified(typ.name, typ) + if not sym or not sym.node: + return False + return sym.node.fullname == "typing.ClassVar" + + def is_final_type(self, typ: Type | None) -> bool: + if not isinstance(typ, UnboundType): + return False + sym = self.lookup_qualified(typ.name, typ) + if not sym or not sym.node: + return False + return sym.node.fullname in FINAL_TYPE_NAMES + + def fail_invalid_classvar(self, context: Context) -> None: + self.fail(message_registry.CLASS_VAR_OUTSIDE_OF_CLASS, context) + + def process_module_assignment( + self, lvals: list[Lvalue], rval: Expression, ctx: AssignmentStmt + ) -> None: + """Propagate module references across assignments. + + Recursively handles the simple form of iterable unpacking; doesn't + handle advanced unpacking with *rest, dictionary unpacking, etc. + + In an expression like x = y = z, z is the rval and lvals will be [x, + y]. + + """ + if isinstance(rval, (TupleExpr, ListExpr)) and all( + isinstance(v, TupleExpr) for v in lvals + ): + # rval and all lvals are either list or tuple, so we are dealing + # with unpacking assignment like `x, y = a, b`. Mypy didn't + # understand our all(isinstance(...)), so cast them as TupleExpr + # so mypy knows it is safe to access their .items attribute. + seq_lvals = cast(list[TupleExpr], lvals) + # given an assignment like: + # (x, y) = (m, n) = (a, b) + # we now have: + # seq_lvals = [(x, y), (m, n)] + # seq_rval = (a, b) + # We now zip this into: + # elementwise_assignments = [(a, x, m), (b, y, n)] + # where each elementwise assignment includes one element of rval and the + # corresponding element of each lval. Basically we unpack + # (x, y) = (m, n) = (a, b) + # into elementwise assignments + # x = m = a + # y = n = b + # and then we recursively call this method for each of those assignments. + # If the rval and all lvals are not all of the same length, zip will just ignore + # extra elements, so no error will be raised here; mypy will later complain + # about the length mismatch in type-checking. + elementwise_assignments = zip(rval.items, *[v.items for v in seq_lvals]) + for rv, *lvs in elementwise_assignments: + self.process_module_assignment(lvs, rv, ctx) + elif isinstance(rval, RefExpr): + rnode = self.lookup_type_node(rval) + if rnode and isinstance(rnode.node, MypyFile): + for lval in lvals: + if not isinstance(lval, RefExpr): + continue + # respect explicitly annotated type + if isinstance(lval.node, Var) and lval.node.type is not None: + continue + + # We can handle these assignments to locals and to self + if isinstance(lval, NameExpr): + lnode = self.current_symbol_table().get(lval.name) + elif isinstance(lval, MemberExpr) and self.is_self_member_ref(lval): + assert self.type is not None + lnode = self.type.names.get(lval.name) + else: + continue + + if lnode: + if isinstance(lnode.node, MypyFile) and lnode.node is not rnode.node: + assert isinstance(lval, (NameExpr, MemberExpr)) + self.fail( + 'Cannot assign multiple modules to name "{}" ' + 'without explicit "types.ModuleType" annotation'.format(lval.name), + ctx, + ) + # never create module alias except on initial var definition + elif lval.is_inferred_def: + assert rnode.node is not None + lnode.node = rnode.node + + def process__all__(self, s: AssignmentStmt) -> None: + """Export names if argument is a __all__ assignment.""" + if ( + len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and s.lvalues[0].name == "__all__" + and s.lvalues[0].kind == GDEF + and isinstance(s.rvalue, (ListExpr, TupleExpr)) + ): + self.add_exports(s.rvalue.items) + + def process__deletable__(self, s: AssignmentStmt) -> None: + if not self.options.mypyc: + return + if ( + len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and s.lvalues[0].name == "__deletable__" + and s.lvalues[0].kind == MDEF + ): + rvalue = s.rvalue + if not isinstance(rvalue, (ListExpr, TupleExpr)): + self.fail('"__deletable__" must be initialized with a list or tuple expression', s) + return + items = rvalue.items + attrs = [] + for item in items: + if not isinstance(item, StrExpr): + self.fail('Invalid "__deletable__" item; string literal expected', item) + else: + attrs.append(item.value) + assert self.type + self.type.deletable_attributes = attrs + + def process__slots__(self, s: AssignmentStmt) -> None: + """ + Processing ``__slots__`` if defined in type. + + See: https://docs.python.org/3/reference/datamodel.html#slots + """ + # Later we can support `__slots__` defined as `__slots__ = other = ('a', 'b')` + if ( + isinstance(self.type, TypeInfo) + and len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and s.lvalues[0].name == "__slots__" + and s.lvalues[0].kind == MDEF + ): + # We understand `__slots__` defined as string, tuple, list, set, and dict: + if not isinstance(s.rvalue, (StrExpr, ListExpr, TupleExpr, SetExpr, DictExpr)): + # For example, `__slots__` can be defined as a variable, + # we don't support it for now. + return + + if any(p.slots is None for p in self.type.mro[1:-1]): + # At least one type in mro (excluding `self` and `object`) + # does not have concrete `__slots__` defined. Ignoring. + return + + concrete_slots = True + rvalue: list[Expression] = [] + if isinstance(s.rvalue, StrExpr): + rvalue.append(s.rvalue) + elif isinstance(s.rvalue, (ListExpr, TupleExpr, SetExpr)): + rvalue.extend(s.rvalue.items) + else: + # We have a special treatment of `dict` with possible `{**kwargs}` usage. + # In this case we consider all `__slots__` to be non-concrete. + for key, _ in s.rvalue.items: + if concrete_slots and key is not None: + rvalue.append(key) + else: + concrete_slots = False + + slots = [] + for item in rvalue: + # Special case for `'__dict__'` value: + # when specified it will still allow any attribute assignment. + if isinstance(item, StrExpr) and item.value != "__dict__": + slots.append(item.value) + else: + concrete_slots = False + if not concrete_slots: + # Some slot items are dynamic, we don't want any false positives, + # so, we just pretend that this type does not have any slots at all. + return + + # We need to copy all slots from super types: + for super_type in self.type.mro[1:-1]: + assert super_type.slots is not None + slots.extend(super_type.slots) + self.type.slots = set(slots) + + # + # Misc statements + # + + def visit_block(self, b: Block) -> None: + if b.is_unreachable: + return + self.block_depth[-1] += 1 + for s in b.body: + self.accept(s) + self.block_depth[-1] -= 1 + + def visit_block_maybe(self, b: Block | None) -> None: + if b: + self.visit_block(b) + + def visit_expression_stmt(self, s: ExpressionStmt) -> None: + self.statement = s + s.expr.accept(self) + + def visit_return_stmt(self, s: ReturnStmt) -> None: + old = self.statement + self.statement = s + if not self.is_func_scope(): + self.fail('"return" outside function', s) + if self.return_stmt_inside_except_star_block: + self.fail('"return" not allowed in except* block', s, serious=True) + if s.expr: + s.expr.accept(self) + if TYPE_FORM in self.options.enable_incomplete_feature: + self.try_parse_as_type_expression(s.expr) + self.statement = old + + def visit_raise_stmt(self, s: RaiseStmt) -> None: + self.statement = s + if s.expr: + s.expr.accept(self) + if s.from_expr: + s.from_expr.accept(self) + + def visit_assert_stmt(self, s: AssertStmt) -> None: + self.statement = s + if s.expr: + s.expr.accept(self) + if s.msg: + s.msg.accept(self) + + def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None: + self.statement = s + s.lvalue.accept(self) + s.rvalue.accept(self) + if ( + isinstance(s.lvalue, NameExpr) + and s.lvalue.name == "__all__" + and s.lvalue.kind == GDEF + and isinstance(s.rvalue, (ListExpr, TupleExpr)) + ): + self.add_exports(s.rvalue.items) + + def visit_while_stmt(self, s: WhileStmt) -> None: + self.statement = s + s.expr.accept(self) + self.loop_depth[-1] += 1 + with self.inside_except_star_block_set(value=False, entering_loop=True): + s.body.accept(self) + self.loop_depth[-1] -= 1 + self.visit_block_maybe(s.else_body) + + def visit_for_stmt(self, s: ForStmt) -> None: + if s.is_async: + if not self.is_func_scope() or not self.function_stack[-1].is_coroutine: + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, s, code=codes.SYNTAX) + + self.statement = s + s.expr.accept(self) + + # Bind index variables and check if they define new names. + self.analyze_lvalue(s.index, explicit_type=s.index_type is not None, is_index_var=True) + if s.index_type: + if self.is_classvar(s.index_type): + self.fail_invalid_classvar(s.index) + allow_tuple_literal = isinstance(s.index, TupleExpr) + analyzed = self.anal_type(s.index_type, allow_tuple_literal=allow_tuple_literal) + if analyzed is not None: + self.store_declared_types(s.index, analyzed) + s.index_type = analyzed + + self.loop_depth[-1] += 1 + with self.inside_except_star_block_set(value=False, entering_loop=True): + self.visit_block(s.body) + self.loop_depth[-1] -= 1 + self.visit_block_maybe(s.else_body) + + def visit_break_stmt(self, s: BreakStmt) -> None: + self.statement = s + if self.loop_depth[-1] == 0: + self.fail('"break" outside loop', s, serious=True, blocker=True) + if self.inside_except_star_block: + self.fail('"break" not allowed in except* block', s, serious=True) + + def visit_continue_stmt(self, s: ContinueStmt) -> None: + self.statement = s + if self.loop_depth[-1] == 0: + self.fail('"continue" outside loop', s, serious=True, blocker=True) + if self.inside_except_star_block: + self.fail('"continue" not allowed in except* block', s, serious=True) + + def visit_if_stmt(self, s: IfStmt) -> None: + self.statement = s + infer_reachability_of_if_statement(s, self.options) + for i in range(len(s.expr)): + s.expr[i].accept(self) + self.visit_block(s.body[i]) + self.visit_block_maybe(s.else_body) + + def visit_try_stmt(self, s: TryStmt) -> None: + self.statement = s + self.analyze_try_stmt(s, self) + + def analyze_try_stmt(self, s: TryStmt, visitor: NodeVisitor[None]) -> None: + s.body.accept(visitor) + for type, var, handler in zip(s.types, s.vars, s.handlers): + if type: + type.accept(visitor) + if var: + self.analyze_lvalue(var) + with self.inside_except_star_block_set(self.inside_except_star_block or s.is_star): + handler.accept(visitor) + if s.else_body: + s.else_body.accept(visitor) + if s.finally_body: + s.finally_body.accept(visitor) + + def visit_with_stmt(self, s: WithStmt) -> None: + self.statement = s + types: list[Type] = [] + + if s.is_async: + if not self.is_func_scope() or not self.function_stack[-1].is_coroutine: + self.fail(message_registry.ASYNC_WITH_OUTSIDE_COROUTINE, s, code=codes.SYNTAX) + + if s.unanalyzed_type: + assert isinstance(s.unanalyzed_type, ProperType) + actual_targets = [t for t in s.target if t is not None] + if len(actual_targets) == 0: + # We have a type for no targets + self.fail('Invalid type comment: "with" statement has no targets', s) + elif len(actual_targets) == 1: + # We have one target and one type + types = [s.unanalyzed_type] + elif isinstance(s.unanalyzed_type, TupleType): + # We have multiple targets and multiple types + if len(actual_targets) == len(s.unanalyzed_type.items): + types = s.unanalyzed_type.items.copy() + else: + # But it's the wrong number of items + self.fail('Incompatible number of types for "with" targets', s) + else: + # We have multiple targets and one type + self.fail('Multiple types expected for multiple "with" targets', s) + + new_types: list[Type] = [] + for e, n in zip(s.expr, s.target): + e.accept(self) + if n: + self.analyze_lvalue(n, explicit_type=s.unanalyzed_type is not None) + + # Since we have a target, pop the next type from types + if types: + t = types.pop(0) + if self.is_classvar(t): + self.fail_invalid_classvar(n) + allow_tuple_literal = isinstance(n, TupleExpr) + analyzed = self.anal_type(t, allow_tuple_literal=allow_tuple_literal) + if analyzed is not None: + # TODO: Deal with this better + new_types.append(analyzed) + self.store_declared_types(n, analyzed) + + s.analyzed_types = new_types + + self.visit_block(s.body) + + def visit_del_stmt(self, s: DelStmt) -> None: + self.statement = s + s.expr.accept(self) + if not self.is_valid_del_target(s.expr): + self.fail("Invalid delete target", s) + + def is_valid_del_target(self, s: Expression) -> bool: + if isinstance(s, (IndexExpr, NameExpr, MemberExpr)): + return True + elif isinstance(s, (TupleExpr, ListExpr)): + return all(self.is_valid_del_target(item) for item in s.items) + else: + return False + + def visit_global_decl(self, g: GlobalDecl) -> None: + self.statement = g + for name in g.names: + if name in self.nonlocal_decls[-1]: + self.fail(f'Name "{name}" is nonlocal and global', g) + self.global_decls[-1].add(name) + + def visit_nonlocal_decl(self, d: NonlocalDecl) -> None: + self.statement = d + if self.is_module_scope(): + self.fail("nonlocal declaration not allowed at module level", d) + else: + for name in d.names: + for table, scope_type in zip( + reversed(self.locals[:-1]), reversed(self.scope_stack[:-1]) + ): + if table is not None and name in table: + if scope_type == SCOPE_ANNOTATION: + self.fail( + f'nonlocal binding not allowed for type parameter "{name}"', d + ) + break + else: + self.fail(f'No binding for nonlocal "{name}" found', d) + + if self.locals[-1] is not None and name in self.locals[-1]: + self.fail( + 'Name "{}" is already defined in local ' + "scope before nonlocal declaration".format(name), + d, + ) + + if name in self.global_decls[-1]: + self.fail(f'Name "{name}" is nonlocal and global', d) + self.nonlocal_decls[-1].add(name) + + def visit_match_stmt(self, s: MatchStmt) -> None: + self.statement = s + infer_reachability_of_match_statement(s, self.options) + s.subject.accept(self) + for i in range(len(s.patterns)): + s.patterns[i].accept(self) + guard = s.guards[i] + if guard is not None: + guard.accept(self) + self.visit_block(s.bodies[i]) + + def visit_type_alias_stmt(self, s: TypeAliasStmt) -> None: + if s.invalid_recursive_alias: + return + self.statement = s + type_params = self.push_type_args(s.type_args, s) + if type_params is None: + self.defer(s) + return + all_type_params_names = [p.name for p in s.type_args] + + try: + existing = self.current_symbol_table().get(s.name.name) + if existing and not ( + isinstance(existing.node, TypeAlias) + or (isinstance(existing.node, PlaceholderNode) and existing.node.line == s.line) + ): + self.already_defined(s.name.name, s, existing, "Name") + return + + tag = self.track_incomplete_refs() + res, alias_tvars, depends_on, indexed = self.analyze_alias( + s.name.name, + s.value.expr(), + allow_placeholder=True, + declared_type_vars=type_params, + all_declared_type_params_names=all_type_params_names, + python_3_12_type_alias=True, + ) + if not res: + res = AnyType(TypeOfAny.from_error) + + if not self.is_func_scope(): + # Only marking incomplete for top-level placeholders makes recursive aliases like + # `A = Sequence[str | A]` valid here, similar to how we treat base classes in class + # definitions, allowing `class str(Sequence[str]): ...` + incomplete_target = isinstance(res, ProperType) and isinstance( + res, PlaceholderType + ) + else: + incomplete_target = has_placeholder(res) + + if self.found_incomplete_ref(tag) or incomplete_target: + # Since we have got here, we know this must be a type alias (incomplete refs + # may appear in nested positions), therefore use becomes_typeinfo=True. + self.mark_incomplete(s.name.name, s.value, becomes_typeinfo=True) + return + + # Now go through all new variables and temporary replace all tvars that still + # refer to some placeholders. We defer the whole alias and will revisit it again, + # as well as all its dependents. + for i, tv in enumerate(alias_tvars): + if has_placeholder(tv): + self.mark_incomplete(s.name.name, s.value, becomes_typeinfo=True) + alias_tvars[i] = self._trivial_typevarlike_like(tv) + + self.add_type_alias_deps(depends_on) + check_for_explicit_any( + res, self.options, self.is_typeshed_stub_file, self.msg, context=s + ) + # When this type alias gets "inlined", the Any is not explicit anymore, + # so we need to replace it with non-explicit Anys. + res = make_any_non_explicit(res) + if self.options.disallow_any_unimported and has_any_from_unimported_type(res): + self.msg.unimported_type_becomes_any("Type alias target", res, s) + res = make_any_non_unimported(res) + eager = self.is_func_scope() + if isinstance(res, ProperType) and isinstance(res, Instance): + fix_instance(res, self.fail, self.note, disallow_any=False, options=self.options) + alias_node = TypeAlias( + res, + self.qualified_name(s.name.name), + self.cur_mod_id, + s.line, + s.column, + alias_tvars=alias_tvars, + no_args=False, + eager=eager, + python_3_12_type_alias=True, + ) + s.alias_node = alias_node + + if ( + existing + and isinstance(existing.node, (PlaceholderNode, TypeAlias)) + and existing.node.line == s.line + ): + updated = False + if isinstance(existing.node, TypeAlias): + if ( + existing.node.target != res + or existing.node.alias_tvars != alias_node.alias_tvars + ): + # Copy expansion to the existing alias, this matches how we update base classes + # for a TypeInfo _in place_ if there are nested placeholders. + existing.node.target = res + existing.node.alias_tvars = alias_tvars + updated = True + # Invalidate recursive status cache in case it was previously set. + existing.node._is_recursive = None + else: + # Otherwise just replace existing placeholder with type alias. + existing.node = alias_node + updated = True + + if updated: + if self.final_iteration: + self.cannot_resolve_name(s.name.name, "name", s) + return + else: + # We need to defer so that this change can get propagated to base classes. + self.defer(s, force_progress=True) + else: + self.add_symbol(s.name.name, alias_node, s) + + current_node = existing.node if existing else alias_node + assert isinstance(current_node, TypeAlias) + self.disable_invalid_recursive_aliases(s, current_node, s.value) + s.name.accept(self) + finally: + self.pop_type_args(s.type_args) + + def _trivial_typevarlike_like(self, tv: TypeVarLikeType) -> TypeVarLikeType: + object_type = self.named_type("builtins.object") + if isinstance(tv, TypeVarType): + return TypeVarType( + tv.name, + tv.fullname, + tv.id, + values=[], + upper_bound=object_type, + default=AnyType(TypeOfAny.from_omitted_generics), + variance=tv.variance, + line=tv.line, + column=tv.column, + ) + elif isinstance(tv, TypeVarTupleType): + tuple_type = self.named_type("builtins.tuple", [object_type]) + return TypeVarTupleType( + tv.name, + tv.fullname, + tv.id, + upper_bound=tuple_type, + tuple_fallback=tuple_type, + default=AnyType(TypeOfAny.from_omitted_generics), + line=tv.line, + column=tv.column, + ) + elif isinstance(tv, ParamSpecType): + return ParamSpecType( + tv.name, + tv.fullname, + tv.id, + flavor=tv.flavor, + upper_bound=object_type, + default=AnyType(TypeOfAny.from_omitted_generics), + line=tv.line, + column=tv.column, + ) + else: + assert False, f"Unknown TypeVarLike: {tv!r}" + + # + # Expressions + # + + def visit_name_expr(self, expr: NameExpr) -> None: + n = self.lookup(expr.name, expr) + if n: + self.bind_name_expr(expr, n) + + def bind_name_expr(self, expr: NameExpr, sym: SymbolTableNode) -> None: + """Bind name expression to a symbol table node.""" + if ( + isinstance(sym.node, TypeVarExpr) + and self.tvar_scope.get_binding(sym) + and not self.allow_unbound_tvars + ): + self.fail(f'"{expr.name}" is a type variable and only valid in type context', expr) + elif isinstance(sym.node, PlaceholderNode): + self.process_placeholder(expr.name, "name", expr) + else: + expr.kind = sym.kind + expr.node = sym.node + expr.fullname = sym.fullname or "" + + def visit_super_expr(self, expr: SuperExpr) -> None: + if not self.type and not expr.call.args: + self.fail('"super" used outside class', expr) + return + expr.info = self.type + for arg in expr.call.args: + arg.accept(self) + + def visit_tuple_expr(self, expr: TupleExpr) -> None: + for item in expr.items: + if isinstance(item, StarExpr): + item.valid = True + item.accept(self) + + def visit_list_expr(self, expr: ListExpr) -> None: + for item in expr.items: + if isinstance(item, StarExpr): + item.valid = True + item.accept(self) + + def visit_set_expr(self, expr: SetExpr) -> None: + for item in expr.items: + if isinstance(item, StarExpr): + item.valid = True + item.accept(self) + + def visit_dict_expr(self, expr: DictExpr) -> None: + for key, value in expr.items: + if key is not None: + key.accept(self) + value.accept(self) + + def visit_template_str_expr(self, expr: TemplateStrExpr) -> None: + for item in expr.items: + if isinstance(item, tuple): + item[0].accept(self) + if item[3] is not None: + item[3].accept(self) + else: + item.accept(self) + + def visit_star_expr(self, expr: StarExpr) -> None: + if not expr.valid: + self.fail("can't use starred expression here", expr, blocker=True) + else: + expr.expr.accept(self) + + def visit_yield_from_expr(self, e: YieldFromExpr) -> None: + if not self.is_func_scope(): + self.fail('"yield from" outside function', e, serious=True, blocker=True) + elif self.scope_stack[-1] == SCOPE_COMPREHENSION: + self.fail( + '"yield from" inside comprehension or generator expression', + e, + serious=True, + blocker=True, + ) + elif self.function_stack[-1].is_coroutine: + self.fail('"yield from" in async function', e, serious=True, blocker=True) + else: + self.function_stack[-1].is_generator = True + if e.expr: + e.expr.accept(self) + + def visit_call_expr(self, expr: CallExpr) -> None: + """Analyze a call expression. + + Some call expressions are recognized as special forms, including + cast(...). + """ + expr.callee.accept(self) + if refers_to_fullname(expr.callee, "typing.cast"): + # Special form cast(...). + if not self.check_fixed_args(expr, 2, "cast"): + return + # Translate first argument to an unanalyzed type. + try: + target = self.expr_to_unanalyzed_type(expr.args[0]) + except TypeTranslationError: + self.fail("Cast target is not a type", expr) + return + # Piggyback CastExpr object to the CallExpr object; it takes + # precedence over the CallExpr semantics. + expr.analyzed = CastExpr(expr.args[1], target) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, ASSERT_TYPE_NAMES): + if not self.check_fixed_args(expr, 2, "assert_type"): + return + # Translate second argument to an unanalyzed type. + try: + target = self.expr_to_unanalyzed_type(expr.args[1]) + except TypeTranslationError: + self.fail("assert_type() type is not a type", expr) + return + expr.analyzed = AssertTypeExpr(expr.args[0], target) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, REVEAL_TYPE_NAMES): + if not self.check_fixed_args(expr, 1, "reveal_type"): + return + reveal_imported = False + reveal_type_node = self.lookup("reveal_type", expr, suppress_errors=True) + if ( + reveal_type_node + and isinstance(reveal_type_node.node, SYMBOL_FUNCBASE_TYPES) + and reveal_type_node.fullname in IMPORTED_REVEAL_TYPE_NAMES + ): + reveal_imported = True + expr.analyzed = RevealExpr( + kind=REVEAL_TYPE, expr=expr.args[0], is_imported=reveal_imported + ) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, "builtins.reveal_locals"): + # Store the local variable names into the RevealExpr for use in the + # type checking pass + local_nodes: list[Var] = [] + if self.is_module_scope(): + # try to determine just the variable declarations in module scope + # self.globals.values() contains SymbolTableNode's + # Each SymbolTableNode has an attribute node that is nodes.Var + # look for variable nodes that marked as is_inferred + # Each symboltable node has a Var node as .node + local_nodes = [ + n.node + for name, n in self.globals.items() + if getattr(n.node, "is_inferred", False) and isinstance(n.node, Var) + ] + elif self.is_class_scope(): + # type = None # type: Optional[TypeInfo] + if self.type is not None: + local_nodes = [ + st.node for st in self.type.names.values() if isinstance(st.node, Var) + ] + elif self.is_func_scope(): + # locals = None # type: List[Optional[SymbolTable]] + if self.locals is not None: + symbol_table = self.locals[-1] + if symbol_table is not None: + local_nodes = [ + st.node for st in symbol_table.values() if isinstance(st.node, Var) + ] + expr.analyzed = RevealExpr(kind=REVEAL_LOCALS, local_nodes=local_nodes) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, "typing.Any"): + # Special form Any(...) no longer supported. + self.fail("Any(...) is no longer supported. Use cast(Any, ...) instead", expr) + elif refers_to_fullname(expr.callee, "typing._promote"): + # Special form _promote(...). + if not self.check_fixed_args(expr, 1, "_promote"): + return + # Translate first argument to an unanalyzed type. + try: + target = self.expr_to_unanalyzed_type(expr.args[0]) + except TypeTranslationError: + self.fail("Argument 1 to _promote is not a type", expr) + return + expr.analyzed = PromoteExpr(target) + expr.analyzed.line = expr.line + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, "builtins.dict") and not ( + isinstance(expr.callee, RefExpr) + and isinstance(expr.callee.node, TypeAlias) + and not expr.callee.node.no_args + ): + expr.analyzed = self.translate_dict_call(expr) + elif refers_to_fullname(expr.callee, "builtins.divmod"): + if not self.check_fixed_args(expr, 2, "divmod"): + return + expr.analyzed = OpExpr("divmod", expr.args[0], expr.args[1]) + expr.analyzed.line = expr.line + expr.analyzed.accept(self) + elif refers_to_fullname( + expr.callee, ("typing.TypeAliasType", "typing_extensions.TypeAliasType") + ): + with self.allow_unbound_tvars_set(): + for a in expr.args: + a.accept(self) + elif refers_to_fullname(expr.callee, ("typing.TypeForm", "typing_extensions.TypeForm")): + # Special form TypeForm(...). + if not self.check_fixed_args(expr, 1, "TypeForm"): + return + # Translate first argument to an unanalyzed type. + try: + typ = self.expr_to_unanalyzed_type(expr.args[0]) + except TypeTranslationError: + self.fail("TypeForm argument is not a type", expr) + # Suppress future error: "" not callable + expr.analyzed = CastExpr(expr.args[0], AnyType(TypeOfAny.from_error)) + return + # Piggyback TypeFormExpr object to the CallExpr object; it takes + # precedence over the CallExpr semantics. + expr.analyzed = TypeFormExpr(typ) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + else: + # Normal call expression. + calculate_type_forms = TYPE_FORM in self.options.enable_incomplete_feature + for a in expr.args: + a.accept(self) + if calculate_type_forms: + self.try_parse_as_type_expression(a) + + if ( + isinstance(expr.callee, MemberExpr) + and isinstance(expr.callee.expr, NameExpr) + and expr.callee.expr.name == "__all__" + and expr.callee.expr.kind == GDEF + and expr.callee.name in ("append", "extend", "remove") + ): + if expr.callee.name == "append" and expr.args: + self.add_exports(expr.args[0]) + elif ( + expr.callee.name == "extend" + and expr.args + and isinstance(expr.args[0], (ListExpr, TupleExpr)) + ): + self.add_exports(expr.args[0].items) + elif ( + expr.callee.name == "remove" + and expr.args + and isinstance(expr.args[0], StrExpr) + ): + self.all_exports = [n for n in self.all_exports if n != expr.args[0].value] + + def translate_dict_call(self, call: CallExpr) -> DictExpr | None: + """Translate 'dict(x=y, ...)' to {'x': y, ...} and 'dict()' to {}. + + For other variants of dict(...), return None. + """ + if not all(kind in (ARG_NAMED, ARG_STAR2) for kind in call.arg_kinds): + # Must still accept those args. + for a in call.args: + a.accept(self) + return None + expr = DictExpr( + [ + (StrExpr(key) if key is not None else None, value) + for key, value in zip(call.arg_names, call.args) + ] + ) + expr.set_line(call) + expr.accept(self) + return expr + + def check_fixed_args(self, expr: CallExpr, numargs: int, name: str) -> bool: + """Verify that expr has specified number of positional args. + + Return True if the arguments are valid. + """ + s = "s" + if numargs == 1: + s = "" + if len(expr.args) != numargs: + self.fail('"%s" expects %d argument%s' % (name, numargs, s), expr) + return False + if expr.arg_kinds != [ARG_POS] * numargs: + self.fail(f'"{name}" must be called with {numargs} positional argument{s}', expr) + return False + return True + + def visit_member_expr(self, expr: MemberExpr) -> None: + base = expr.expr + base.accept(self) + if isinstance(base, RefExpr) and isinstance(base.node, MypyFile): + # Handle module attribute. + sym = self.get_module_symbol(base.node, expr.name) + if sym: + if isinstance(sym.node, PlaceholderNode): + self.process_placeholder(expr.name, "attribute", expr) + return + self.record_imported_symbol(sym) + expr.kind = sym.kind + expr.fullname = sym.fullname or "" + expr.node = sym.node + elif isinstance(base, RefExpr): + # This branch handles the case C.bar (or cls.bar or self.bar inside + # a classmethod/method), where C is a class and bar is a type + # definition or a module resulting from `import bar` (or a module + # assignment) inside class C. We look up bar in the class' TypeInfo + # namespace. This is done only when bar is a module or a type; + # other things (e.g. methods) are handled by other code in + # checkmember. + type_info = None + if isinstance(base.node, TypeInfo): + # C.bar where C is a class + type_info = base.node + elif isinstance(base.node, Var) and self.type and self.function_stack: + # check for self.bar or cls.bar in method/classmethod + func_def = self.function_stack[-1] + if ( + func_def.has_self_or_cls_argument + and func_def.info is self.type + and isinstance(func_def.type, CallableType) + and func_def.arguments + and base.node is func_def.arguments[0].variable + ): + type_info = self.type + elif isinstance(base.node, TypeAlias) and base.node.no_args: + assert isinstance(base.node.target, ProperType) + if isinstance(base.node.target, Instance): + type_info = base.node.target.type + + if type_info: + n = type_info.names.get(expr.name) + if n is not None and isinstance(n.node, (MypyFile, TypeInfo, TypeAlias)): + self.record_imported_symbol(n) + expr.kind = n.kind + expr.fullname = n.fullname or "" + expr.node = n.node + + def visit_op_expr(self, expr: OpExpr) -> None: + expr.left.accept(self) + + if expr.op in ("and", "or"): + inferred = infer_condition_value(expr.left, self.options) + if (inferred in (ALWAYS_FALSE, MYPY_FALSE) and expr.op == "and") or ( + inferred in (ALWAYS_TRUE, MYPY_TRUE) and expr.op == "or" + ): + expr.right_unreachable = True + return + elif (inferred in (ALWAYS_TRUE, MYPY_TRUE) and expr.op == "and") or ( + inferred in (ALWAYS_FALSE, MYPY_FALSE) and expr.op == "or" + ): + expr.right_always = True + + expr.right.accept(self) + + def visit_comparison_expr(self, expr: ComparisonExpr) -> None: + for operand in expr.operands: + operand.accept(self) + + def visit_unary_expr(self, expr: UnaryExpr) -> None: + expr.expr.accept(self) + + def visit_index_expr(self, expr: IndexExpr) -> None: + base = expr.base + base.accept(self) + if ( + isinstance(base, RefExpr) + and isinstance(base.node, TypeInfo) + and not base.node.is_generic() + ): + expr.index.accept(self) + elif ( + isinstance(base, RefExpr) and isinstance(base.node, TypeAlias) + ) or refers_to_class_or_function(base): + # We need to do full processing on every iteration, since some type + # arguments may contain placeholder types. + self.analyze_type_application(expr) + else: + expr.index.accept(self) + + def analyze_type_application(self, expr: IndexExpr) -> None: + """Analyze special form -- type application (either direct or via type aliasing).""" + types = self.analyze_type_application_args(expr) + if types is None: + return + base = expr.base + expr.analyzed = TypeApplication(base, types) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + + if isinstance(base, RefExpr) and base.fullname == "librt.vecs.vec": + # Apply restrictions specific to vec + check_vec_type_args(types, expr, self) + + def analyze_type_application_args(self, expr: IndexExpr) -> list[Type] | None: + """Analyze type arguments (index) in a type application. + + Return None if anything was incomplete. + """ + index = expr.index + tag = self.track_incomplete_refs() + self.analyze_type_expr(index) + if self.found_incomplete_ref(tag): + return None + if self.basic_type_applications: + # Postpone the rest until we have more information (for r.h.s. of an assignment) + return None + types: list[Type] = [] + if isinstance(index, TupleExpr): + items = index.items + is_tuple = isinstance(expr.base, RefExpr) and expr.base.fullname == "builtins.tuple" + if is_tuple and len(items) == 2 and isinstance(items[-1], EllipsisExpr): + items = items[:-1] + else: + items = [index] + + # TODO: this needs a clean-up. + # Probably always allow Parameters literals, and validate in semanal_typeargs.py + base = expr.base + if isinstance(base, RefExpr) and isinstance(base.node, TypeAlias): + allow_unpack = base.node.tvar_tuple_index is not None + alias = base.node + if any(isinstance(t, ParamSpecType) for t in alias.alias_tvars): + has_param_spec = True + num_args = len(alias.alias_tvars) + else: + has_param_spec = False + num_args = -1 + elif isinstance(base, RefExpr) and isinstance(base.node, TypeInfo): + allow_unpack = ( + base.node.has_type_var_tuple_type or base.node.fullname == "builtins.tuple" + ) + has_param_spec = base.node.has_param_spec_type + num_args = len(base.node.type_vars) + else: + allow_unpack = False + has_param_spec = False + num_args = -1 + + for item in items: + try: + typearg = self.expr_to_unanalyzed_type(item, allow_unpack=True) + except TypeTranslationError: + self.fail("Type expected within [...]", expr) + return None + analyzed = self.anal_type( + typearg, + # The type application may appear in base class expression, + # where type variables are not bound yet. Or when accepting + # r.h.s. of type alias before we figured out it is a type alias. + allow_unbound_tvars=self.allow_unbound_tvars, + allow_placeholder=True, + allow_param_spec_literals=has_param_spec, + allow_unpack=allow_unpack, + ) + if analyzed is None: + return None + types.append(analyzed) + + if allow_unpack: + # need to flatten away harmless unpacks like Unpack[tuple[int]] + flattened_items = flatten_nested_tuples(types) + types = self.type_analyzer().check_unpacks_in_list(flattened_items) + if has_param_spec and num_args == 1 and types: + first_arg = get_proper_type(types[0]) + single_any = len(types) == 1 and isinstance(first_arg, AnyType) + if not (single_any or any(isinstance(t, (Parameters, ParamSpecType)) for t in types)): + types = [Parameters(types, [ARG_POS] * len(types), [None] * len(types))] + + return types + + def visit_slice_expr(self, expr: SliceExpr) -> None: + if expr.begin_index: + expr.begin_index.accept(self) + if expr.end_index: + expr.end_index.accept(self) + if expr.stride: + expr.stride.accept(self) + + def visit_cast_expr(self, expr: CastExpr) -> None: + expr.expr.accept(self) + analyzed = self.anal_type(expr.type) + if analyzed is not None: + expr.type = analyzed + + def visit_type_form_expr(self, expr: TypeFormExpr) -> None: + analyzed = self.anal_type(expr.type) + if analyzed is not None: + expr.type = analyzed + + def visit_assert_type_expr(self, expr: AssertTypeExpr) -> None: + expr.expr.accept(self) + analyzed = self.anal_type(expr.type) + if analyzed is not None: + expr.type = analyzed + + def visit_reveal_expr(self, expr: RevealExpr) -> None: + if expr.kind == REVEAL_TYPE: + if expr.expr is not None: + expr.expr.accept(self) + else: + # Reveal locals doesn't have an inner expression, there's no + # need to traverse inside it + pass + + def visit_type_application(self, expr: TypeApplication) -> None: + expr.expr.accept(self) + for i in range(len(expr.types)): + analyzed = self.anal_type(expr.types[i]) + if analyzed is not None: + expr.types[i] = analyzed + + def visit_list_comprehension(self, expr: ListComprehension) -> None: + if any(expr.generator.is_async): + if ( + not self.is_func_scope() + or not self.function_stack + or not self.function_stack[-1].is_coroutine + ): + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX) + + expr.generator.accept(self) + + def visit_set_comprehension(self, expr: SetComprehension) -> None: + if any(expr.generator.is_async): + if ( + not self.is_func_scope() + or not self.function_stack + or not self.function_stack[-1].is_coroutine + ): + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX) + + expr.generator.accept(self) + + def visit_dictionary_comprehension(self, expr: DictionaryComprehension) -> None: + if any(expr.is_async): + if ( + not self.is_func_scope() + or not self.function_stack + or not self.function_stack[-1].is_coroutine + ): + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX) + + with self.enter(expr): + self.analyze_comp_for(expr) + expr.key.accept(self) + expr.value.accept(self) + self.analyze_comp_for_2(expr) + + def visit_generator_expr(self, expr: GeneratorExpr) -> None: + with self.enter(expr): + self.analyze_comp_for(expr) + expr.left_expr.accept(self) + self.analyze_comp_for_2(expr) + + def analyze_comp_for(self, expr: GeneratorExpr | DictionaryComprehension) -> None: + """Analyses the 'comp_for' part of comprehensions (part 1). + + That is the part after 'for' in (x for x in l if p). This analyzes + variables and conditions which are analyzed in a local scope. + """ + for i, (index, sequence, conditions) in enumerate( + zip(expr.indices, expr.sequences, expr.condlists) + ): + if i > 0: + sequence.accept(self) + # Bind index variables. + self.analyze_lvalue(index) + for cond in conditions: + cond.accept(self) + + def analyze_comp_for_2(self, expr: GeneratorExpr | DictionaryComprehension) -> None: + """Analyses the 'comp_for' part of comprehensions (part 2). + + That is the part after 'for' in (x for x in l if p). This analyzes + the 'l' part which is analyzed in the surrounding scope. + """ + expr.sequences[0].accept(self) + + def visit_lambda_expr(self, expr: LambdaExpr) -> None: + self.analyze_arg_initializers(expr) + with self.inside_except_star_block_set(False, entering_loop=False): + self.analyze_function_body(expr) + + def visit_conditional_expr(self, expr: ConditionalExpr) -> None: + expr.if_expr.accept(self) + expr.cond.accept(self) + expr.else_expr.accept(self) + + def visit__promote_expr(self, expr: PromoteExpr) -> None: + analyzed = self.anal_type(expr.type) + if analyzed is not None: + assert isinstance(analyzed, ProperType), "Cannot use type aliases for promotions" + expr.type = analyzed + + def visit_yield_expr(self, e: YieldExpr) -> None: + if not self.is_func_scope(): + self.fail('"yield" outside function', e, serious=True, blocker=True) + elif self.scope_stack[-1] == SCOPE_COMPREHENSION: + self.fail( + '"yield" inside comprehension or generator expression', + e, + serious=True, + blocker=True, + ) + elif self.function_stack[-1].is_coroutine: + self.function_stack[-1].is_generator = True + self.function_stack[-1].is_async_generator = True + else: + self.function_stack[-1].is_generator = True + if e.expr: + e.expr.accept(self) + + def visit_await_expr(self, expr: AwaitExpr) -> None: + if not self.is_func_scope() or not self.function_stack: + # We check both because is_function_scope() returns True inside comprehensions. + # This is not a blocker, because some environments (like ipython) + # support top level awaits. + self.fail('"await" outside function', expr, serious=True, code=codes.TOP_LEVEL_AWAIT) + elif not self.function_stack[-1].is_coroutine: + self.fail( + '"await" outside coroutine ("async def")', + expr, + serious=True, + code=codes.AWAIT_NOT_ASYNC, + ) + expr.expr.accept(self) + + # + # Patterns + # + + def visit_as_pattern(self, p: AsPattern) -> None: + if p.pattern is not None: + p.pattern.accept(self) + if p.name is not None: + self.analyze_lvalue(p.name) + + def visit_or_pattern(self, p: OrPattern) -> None: + for pattern in p.patterns: + pattern.accept(self) + + def visit_value_pattern(self, p: ValuePattern) -> None: + p.expr.accept(self) + + def visit_sequence_pattern(self, p: SequencePattern) -> None: + for pattern in p.patterns: + pattern.accept(self) + + def visit_starred_pattern(self, p: StarredPattern) -> None: + if p.capture is not None: + self.analyze_lvalue(p.capture) + + def visit_mapping_pattern(self, p: MappingPattern) -> None: + for key in p.keys: + key.accept(self) + for value in p.values: + value.accept(self) + if p.rest is not None: + self.analyze_lvalue(p.rest) + + def visit_class_pattern(self, p: ClassPattern) -> None: + p.class_ref.accept(self) + for pos in p.positionals: + pos.accept(self) + for v in p.keyword_values: + v.accept(self) + + # + # Lookup functions + # + + def lookup( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + node = self._lookup(name, ctx, suppress_errors) + if node is not None: + # This call is unfortunate from performance point of view, but + # needed for rare cases like e.g. testIncrementalChangingAlias. + self.record_imported_symbol(node) + return node + + def record_imported_symbol(self, sym: SymbolTableNode) -> None: + """If the symbol was not defined in current module, add its module to module_refs.""" + if sym.kind == LDEF or sym.node is None: + return + node = sym.node + if isinstance(node, PlaceholderNode) or not node.fullname: + # This node is not ready yet. + return + if node.fullname.startswith(("builtins.", "typing.")): + # Skip dependencies on builtins/typing. + return + # Modules, classes, and type aliases store defining module directly. + if isinstance(node, MypyFile): + fullname = node.fullname + elif isinstance(node, TypeInfo): + fullname = node.module_name + elif isinstance(node, TypeAlias): + fullname = node.module + elif isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)): + # For functions/variables infer defining module from enclosing class. + info = node.var.info if isinstance(node, Decorator) else node.info + if info: + fullname = info.module_name + else: + # global function/variable + fullname = node.fullname.rsplit(".", maxsplit=1)[0] + else: + # Some nodes (currently only TypeVarLikeExpr subclasses) don't store + # module fullname explicitly, infer it from the node fullname iteratively. + # TODO: this is not 100% robust for type variables nested within a class + # with a name that matches name of a submodule. + fullname = node.fullname.rsplit(".", maxsplit=1)[0] + if fullname == self.cur_mod_id: + return + while "." in fullname and fullname not in self.modules: + fullname = fullname.rsplit(".", maxsplit=1)[0] + if fullname != self.cur_mod_id: + self.cur_mod_node.module_refs.add(fullname) + + def _lookup( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + """Look up an unqualified (no dots) name in all active namespaces. + + Note that the result may contain a PlaceholderNode. The caller may + want to defer in that case. + + Generate an error if the name is not defined unless suppress_errors + is true or the current namespace is incomplete. In the latter case + defer. + """ + implicit_name = False + # 1a. Name declared using 'global x' takes precedence + if name in self.global_decls[-1]: + if name in self.globals: + return self.globals[name] + if not suppress_errors: + self.name_not_defined(name, ctx) + return None + # 1b. Name declared using 'nonlocal x' takes precedence + if name in self.nonlocal_decls[-1]: + for table in reversed(self.locals[:-1]): + if table is not None and name in table: + return table[name] + if not suppress_errors: + self.name_not_defined(name, ctx) + return None + # 2a. Class attributes (if within class definition) + if self.type and not self.is_func_scope() and name in self.type.names: + node = self.type.names[name] + if not node.implicit: + if self.is_active_symbol_in_class_body(node.node): + return node + else: + # Defined through self.x assignment + implicit_name = True + implicit_node = node + # 2b. Class attributes __qualname__ and __module__ + if self.type and not self.is_func_scope() and name in {"__qualname__", "__module__"}: + v = Var(name, self.str_type()) + v._fullname = self.qualified_name(name) + return SymbolTableNode(MDEF, v) + # 3. Local (function) scopes + for table in reversed(self.locals): + if table is not None and name in table: + return table[name] + + # 4. Current file global scope + if name in self.globals: + return self.globals[name] + # 5. Builtins + b = self.globals.get("__builtins__", None) + if b: + assert isinstance(b.node, MypyFile) + table = b.node.names + if name in table: + if len(name) > 1 and name[0] == "_" and name[1] != "_": + if not suppress_errors: + self.name_not_defined(name, ctx) + return None + node = table[name] + return node + # Give up. + if not implicit_name and not suppress_errors: + self.name_not_defined(name, ctx) + else: + if implicit_name: + return implicit_node + return None + + def is_active_symbol_in_class_body(self, node: SymbolNode | None) -> bool: + """Can a symbol defined in class body accessed at current statement? + + Only allow access to class attributes textually after + the definition, so that it's possible to fall back to the + outer scope. Example: + + class X: ... + + class C: + X = X # Initializer refers to outer scope + + Nested classes are an exception, since we want to support + arbitrary forward references in type annotations. Also, we + allow forward references to type aliases to support recursive + types. + """ + # TODO: Forward reference to name imported in class body is not + # caught. + if self.statement is None: + # Assume it's fine -- don't have enough context to check + return True + if ( + node is None + or self.is_textually_before_statement(node) + or not self.is_defined_in_current_module(node.fullname) + ): + return True + if self.is_type_like(node): + # Allow forward references to classes/type aliases (see docstring), but + # a forward reference should never shadow an existing regular reference. + if node.name not in self.globals: + return True + global_node = self.globals[node.name] + if not self.is_textually_before_class(global_node.node): + return True + return not self.is_type_like(global_node.node) + return False + + def is_type_like(self, node: SymbolNode | None) -> bool: + return isinstance(node, (TypeInfo, TypeAlias)) or ( + isinstance(node, PlaceholderNode) and node.becomes_typeinfo + ) + + def is_textually_before_statement(self, node: SymbolNode) -> bool: + """Check if a node is defined textually before the current statement + + Note that decorated functions' line number are the same as + the top decorator. + """ + assert self.statement + line_diff = self.statement.line - node.line + + # The first branch handles reference an overloaded function variant inside itself, + # this is a corner case where mypy technically deviates from runtime name resolution, + # but it is fine because we want an overloaded function to be treated as a single unit. + if self.is_overloaded_item(node, self.statement): + return False + elif isinstance(node, Decorator) and not node.is_overload: + return line_diff > len(node.original_decorators) + else: + return line_diff > 0 + + def is_textually_before_class(self, node: SymbolNode | None) -> bool: + """Similar to above, but check if a node is defined before current class.""" + assert self.type is not None + if node is None: + return False + return node.line < self.type.defn.line + + def is_overloaded_item(self, node: SymbolNode, statement: Statement) -> bool: + """Check whether the function belongs to the overloaded variants""" + if isinstance(node, OverloadedFuncDef) and isinstance(statement, FuncDef): + in_items = statement in { + item.func if isinstance(item, Decorator) else item for item in node.items + } + in_impl = node.impl is not None and ( + (isinstance(node.impl, Decorator) and statement is node.impl.func) + or statement is node.impl + ) + return in_items or in_impl + return False + + def is_defined_in_current_module(self, fullname: str | None) -> bool: + if not fullname: + return False + return module_prefix(self.modules, fullname) == self.cur_mod_id + + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + """Lookup a qualified name in all activate namespaces. + + Note that the result may contain a PlaceholderNode. The caller may + want to defer in that case. + + Generate an error if the name is not defined unless suppress_errors + is true or the current namespace is incomplete. In the latter case + defer. + """ + if "." not in name: + # Simple case: look up a short name. + return self.lookup(name, ctx, suppress_errors=suppress_errors) + parts = name.split(".") + namespace = self.cur_mod_id + sym = self.lookup(parts[0], ctx, suppress_errors=suppress_errors) + if sym: + for i in range(1, len(parts)): + node = sym.node + part = parts[i] + if isinstance(node, TypeInfo): + nextsym = node.get(part) + elif isinstance(node, MypyFile): + nextsym = self.get_module_symbol(node, part) + namespace = node.fullname + elif isinstance(node, PlaceholderNode): + return sym + elif isinstance(node, TypeAlias) and node.no_args: + assert isinstance(node.target, ProperType) + if isinstance(node.target, Instance): + nextsym = node.target.type.get(part) + else: + nextsym = None + else: + if isinstance(node, Var): + typ = get_proper_type(node.type) + if isinstance(typ, AnyType): + # Allow access through Var with Any type without error. + return self.implicit_symbol(sym, name, parts[i:], typ) + # This might be something like valid `P.args` or invalid `P.__bound__` access. + # Important note that `ParamSpecExpr` is also ignored in other places. + # See https://github.com/python/mypy/pull/13468 + if isinstance(node, ParamSpecExpr) and part in ("args", "kwargs"): + return None + # Lookup through invalid node, such as variable or function + nextsym = None + if not nextsym or nextsym.module_hidden: + if not suppress_errors: + self.name_not_defined(name, ctx, namespace=namespace) + return None + sym = nextsym + if sym is not None: + self.record_imported_symbol(sym) + return sym + + def lookup_type_node(self, expr: Expression) -> SymbolTableNode | None: + try: + t = self.expr_to_unanalyzed_type(expr) + except TypeTranslationError: + return None + if isinstance(t, UnboundType): + n = self.lookup_qualified(t.name, expr, suppress_errors=True) + return n + return None + + def get_module_symbol(self, node: MypyFile, name: str) -> SymbolTableNode | None: + """Look up a symbol from a module. + + Return None if no matching symbol could be bound. + """ + module = node.fullname + names = node.names + sym = names.get(name) + if not sym: + fullname = module + "." + name + if fullname in self.modules and self.is_visible_import(module, fullname): + sym = SymbolTableNode(GDEF, self.modules[fullname]) + elif self.is_incomplete_namespace(module): + self.record_incomplete_ref() + elif "__getattr__" in names: + gvar = self.create_getattr_var(names["__getattr__"], name, fullname) + if gvar: + sym = SymbolTableNode(GDEF, gvar) + elif self.is_missing_module(fullname): + # We use the fullname of the original definition so that we can + # detect whether two names refer to the same thing. + var_type = AnyType(TypeOfAny.from_unimported_type) + v = Var(name, type=var_type) + v._fullname = fullname + sym = SymbolTableNode(GDEF, v) + elif sym.module_hidden: + sym = None + return sym + + def is_visible_import(self, base_id: str, id: str) -> bool: + # TODO: can we reuse SCC-level tracking from build.py instead? + if id in self.import_map[self.cur_mod_id]: + # Fast path: module is imported locally. + return True + if base_id not in self.transitive_submodule_imports: + # This is a performance optimization for a common pattern. If one module + # in a codebase uses import numpy as np; np.foo.bar, then it is likely that + # other modules use similar pattern as well. So we pre-compute transitive + # dependencies for np, to avoid possible duplicate work in the future. + self.add_transitive_submodule_imports(base_id) + if self.cur_mod_id not in self.transitive_submodule_imports: + self.add_transitive_submodule_imports(self.cur_mod_id) + return id in self.transitive_submodule_imports[self.cur_mod_id] + + def add_transitive_submodule_imports(self, mod_id: str) -> None: + if mod_id not in self.import_map: + return + todo = self.import_map[mod_id] + seen = {mod_id} + result = {mod_id} + while todo: + dep = todo.pop() + if dep in seen: + continue + seen.add(dep) + if "." in dep: + result.add(dep) + if dep in self.transitive_submodule_imports: + result |= self.transitive_submodule_imports[dep] + continue + if dep in self.import_map: + todo |= self.import_map[dep] + self.transitive_submodule_imports[mod_id] = result + + def is_missing_module(self, module: str) -> bool: + return module in self.missing_modules + + def implicit_symbol( + self, sym: SymbolTableNode, name: str, parts: list[str], source_type: AnyType + ) -> SymbolTableNode: + """Create symbol for a qualified name reference through Any type.""" + if sym.node is None: + basename = None + else: + basename = sym.node.fullname + if basename is None: + fullname = name + else: + fullname = basename + "." + ".".join(parts) + var_type = AnyType(TypeOfAny.from_another_any, source_type) + var = Var(parts[-1], var_type) + var._fullname = fullname + return SymbolTableNode(GDEF, var) + + def create_getattr_var( + self, getattr_defn: SymbolTableNode, name: str, fullname: str + ) -> Var | None: + """Create a dummy variable using module-level __getattr__ return type. + + If not possible, return None. + + Note that multiple Var nodes can be created for a single name. We + can use the from_module_getattr and the fullname attributes to + check if two dummy Var nodes refer to the same thing. Reusing Var + nodes would require non-local mutable state, which we prefer to + avoid. + """ + if isinstance(getattr_defn.node, (FuncDef, Var)): + node_type = get_proper_type(getattr_defn.node.type) + if isinstance(node_type, CallableType): + typ = node_type.ret_type + else: + typ = AnyType(TypeOfAny.from_error) + v = Var(name, type=typ) + v._fullname = fullname + v.from_module_getattr = True + return v + return None + + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode: + ret = self.lookup_fully_qualified_or_none(fullname) + assert ret is not None, fullname + return ret + + def lookup_fully_qualified_or_none(self, fullname: str) -> SymbolTableNode | None: + """Lookup a fully qualified name that refers to a module-level definition. + + Don't assume that the name is defined. This happens in the global namespace -- + the local module namespace is ignored. This does not dereference indirect + refs. + + Note that this can't be used for names nested in class namespaces. + """ + # TODO: unify/clean-up/simplify lookup methods, see #4157. + module, name = fullname.rsplit(".", maxsplit=1) + + if module in self.modules: + # If the module exists, look up the name in the module. + # This is the common case. + filenode = self.modules[module] + result = filenode.names.get(name) + if result is None and self.is_incomplete_namespace(module): + # TODO: More explicit handling of incomplete refs? + self.record_incomplete_ref() + return result + else: + # Else, try to find the longest prefix of the module name that is in the modules dictionary. + splitted_modules = fullname.split(".") + names = [] + + while splitted_modules and ".".join(splitted_modules) not in self.modules: + names.append(splitted_modules.pop()) + + if not splitted_modules or not names: + # If no module or name is found, return None. + return None + + # Reverse the names list to get the correct order of names. + names.reverse() + + module = ".".join(splitted_modules) + filenode = self.modules[module] + result = filenode.names.get(names[0]) + + if result is None and self.is_incomplete_namespace(module): + # TODO: More explicit handling of incomplete refs? + self.record_incomplete_ref() + + for part in names[1:]: + if result is not None and isinstance(result.node, TypeInfo): + result = result.node.names.get(part) + else: + return None + return result + + def object_type(self) -> Instance: + if self._object_type is None: + self._object_type = self.named_type("builtins.object") + return self._object_type + + def str_type(self) -> Instance: + if self._str_type is None: + self._str_type = self.named_type("builtins.str") + return self._str_type + + def function_type(self) -> Instance: + if self._function_type is None: + self._function_type = self.named_type("builtins.function") + return self._function_type + + def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance: + sym = self.lookup_fully_qualified(fullname) + assert sym, "Internal error: attempted to construct unknown type" + node = sym.node + assert isinstance(node, TypeInfo), node + if args: + # TODO: assert len(args) == len(node.defn.type_vars) + return Instance(node, args) + return Instance(node, [AnyType(TypeOfAny.special_form)] * len(node.defn.type_vars)) + + def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None: + sym = self.lookup_fully_qualified_or_none(fullname) + if not sym or isinstance(sym.node, PlaceholderNode): + return None + node = sym.node + if isinstance(node, TypeAlias): + assert isinstance(node.target, Instance) # type: ignore[misc] + node = node.target.type + assert isinstance(node, TypeInfo), node + if args is not None: + # TODO: assert len(args) == len(node.defn.type_vars) + return Instance(node, args) + return Instance(node, [AnyType(TypeOfAny.unannotated)] * len(node.defn.type_vars)) + + def builtin_type(self, fully_qualified_name: str) -> Instance: + """Legacy function -- use named_type() instead.""" + return self.named_type(fully_qualified_name) + + def lookup_current_scope(self, name: str) -> SymbolTableNode | None: + if self.locals[-1] is not None: + return self.locals[-1].get(name) + elif self.type is not None: + return self.type.names.get(name) + else: + return self.globals.get(name) + + # + # Adding symbols + # + + def add_symbol( + self, + name: str, + node: SymbolNode, + context: Context, + module_public: bool = True, + module_hidden: bool = False, + can_defer: bool = True, + escape_comprehensions: bool = False, + no_progress: bool = False, + type_param: bool = False, + ) -> bool: + """Add symbol to the currently active symbol table. + + Generally additions to symbol table should go through this method or + one of the methods below so that kinds, redefinitions, conditional + definitions, and skipped names are handled consistently. + + Return True if we actually added the symbol, or False if we refused to do so + (because something is not ready). + + If can_defer is True, defer current target if adding a placeholder. + """ + if self.is_func_scope(): + kind = LDEF + elif self.type is not None: + kind = MDEF + else: + kind = GDEF + symbol = SymbolTableNode( + kind, node, module_public=module_public, module_hidden=module_hidden + ) + return self.add_symbol_table_node( + name, symbol, context, can_defer, escape_comprehensions, no_progress, type_param + ) + + def add_symbol_skip_local(self, name: str, node: SymbolNode) -> None: + """Same as above, but skipping the local namespace. + + This doesn't check for previous definition and is only used + for serialization of method-level classes. + + Classes defined within methods can be exposed through an + attribute type, but method-level symbol tables aren't serialized. + This method can be used to add such classes to an enclosing, + serialized symbol table. + """ + # TODO: currently this is only used by named tuples and typed dicts. + # Use this method also by normal classes, see issue #6422. + if self.type is not None: + names = self.type.names + kind = MDEF + else: + names = self.globals + kind = GDEF + symbol = SymbolTableNode(kind, node) + names[name] = symbol + + def add_symbol_table_node( + self, + name: str, + symbol: SymbolTableNode, + context: Context | None = None, + can_defer: bool = True, + escape_comprehensions: bool = False, + no_progress: bool = False, + type_param: bool = False, + ) -> bool: + """Add symbol table node to the currently active symbol table. + + Return True if we actually added the symbol, or False if we refused + to do so (because something is not ready or it was a no-op). + + Generate an error if there is an invalid redefinition. + + If context is None, unconditionally add node, since we can't report + an error. Note that this is used by plugins to forcibly replace nodes! + + TODO: Prevent plugins from replacing nodes, as it could cause problems? + + Args: + name: short name of symbol + symbol: Node to add + can_defer: if True, defer current target if adding a placeholder + context: error context (see above about None value) + """ + names = self.current_symbol_table( + escape_comprehensions=escape_comprehensions, type_param=type_param + ) + existing = names.get(name) + if isinstance(symbol.node, PlaceholderNode) and can_defer: + if context is not None: + self.process_placeholder(name, "name", context) + else: + # see note in docstring describing None contexts + self.defer() + + if ( + existing is not None + and context is not None + and not is_valid_replacement(existing, symbol) + ): + # There is an existing node, so this may be a redefinition. + # If the new node points to the same node as the old one, + # or if both old and new nodes are placeholders, we don't + # need to do anything. + old = existing.node + new = symbol.node + if isinstance(new, PlaceholderNode): + # We don't know whether this is okay. Let's wait until the next iteration. + return False + if not is_same_symbol(old, new): + if isinstance(new, (FuncDef, Decorator, OverloadedFuncDef, TypeInfo)): + self.add_redefinition(names, name, symbol) + if isinstance(old, Var) and is_init_only(old): + if old.has_explicit_value: + self.fail("InitVar with default value cannot be redefined", context) + elif not ( + isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new) + ): + self.name_already_defined(name, context, existing) + elif type_param or ( + name not in self.missing_names[-1] and "*" not in self.missing_names[-1] + ): + names[name] = symbol + if not no_progress: + self.progress = True + return True + return False + + def add_redefinition(self, names: SymbolTable, name: str, symbol: SymbolTableNode) -> None: + """Add a symbol table node that reflects a redefinition as a function or a class. + + Redefinitions need to be added to the symbol table so that they can be found + through AST traversal, but they have dummy names of form 'name-redefinition[N]', + where N ranges over 2, 3, ... (omitted for the first redefinition). + + Note: we always store redefinitions independently of whether they are valid or not + (so they will be semantically analyzed), the caller should give an error for invalid + redefinitions (such as e.g. variable redefined as a class). + """ + i = 1 + # Don't serialize redefined nodes. They are likely to have + # busted internal references which can cause problems with + # serialization and they can't have any external references to + # them. + symbol.no_serialize = True + while True: + if i == 1: + new_name = f"{name}-redefinition" + else: + new_name = f"{name}-redefinition{i}" + existing = names.get(new_name) + if existing is None: + names[new_name] = symbol + return + elif existing.node is symbol.node: + # Already there + return + i += 1 + + def add_local(self, node: Var | FuncDef | OverloadedFuncDef, context: Context) -> None: + """Add local variable or function.""" + assert self.is_func_scope() + name = node.name + node._fullname = name + self.add_symbol(name, node, context) + + def _get_node_for_class_scoped_import( + self, name: str, symbol_node: SymbolNode | None, context: Context + ) -> SymbolNode | None: + if symbol_node is None: + return None + # I promise this type checks; I'm just making mypyc issues go away. + # mypyc is absolutely convinced that `symbol_node` narrows to a Var in the following, + # when it can also be a FuncBase. Once fixed, `f` in the following can be removed. + # See also https://github.com/mypyc/mypyc/issues/892 + f: Callable[[object], Any] = lambda x: x + if isinstance(f(symbol_node), (Decorator, FuncBase, Var)): + # For imports in class scope, we construct a new node to represent the symbol and + # set its `info` attribute to `self.type`. + existing = self.current_symbol_table().get(name) + if ( + # The redefinition checks in `add_symbol_table_node` don't work for our + # constructed Var / FuncBase, so check for possible redefinitions here. + existing is not None + and isinstance(f(existing.node), (Decorator, FuncBase, Var)) + and ( + isinstance(f(existing.type), f(AnyType)) + or f(existing.type) == f(symbol_node).type + ) + ): + return existing.node + + # Construct the new node + if isinstance(f(symbol_node), (FuncBase, Decorator)): + # In theory we could construct a new node here as well, but in practice + # it doesn't work well, see #12197 + typ: Type | None = AnyType(TypeOfAny.from_error) + self.fail("Unsupported class scoped import", context) + else: + typ = f(symbol_node).type + symbol_node = Var(name, typ) + symbol_node._fullname = self.qualified_name(name) + assert self.type is not None # guaranteed by is_class_scope + symbol_node.info = self.type + symbol_node.line = context.line + symbol_node.column = context.column + return symbol_node + + def add_imported_symbol( + self, + name: str, + node: SymbolTableNode, + context: ImportBase, + module_public: bool, + module_hidden: bool, + ) -> None: + """Add an alias to an existing symbol through import.""" + assert not module_hidden or not module_public + + existing_symbol = self.lookup_current_scope(name) + if ( + existing_symbol + and not isinstance(existing_symbol.node, PlaceholderNode) + and not isinstance(node.node, PlaceholderNode) + ): + # Import can redefine a variable. They get special treatment. + if self.process_import_over_existing_name(name, existing_symbol, node, context): + return + + symbol_node: SymbolNode | None = node.node + + if self.is_class_scope(): + symbol_node = self._get_node_for_class_scoped_import(name, symbol_node, context) + + symbol = SymbolTableNode( + node.kind, symbol_node, module_public=module_public, module_hidden=module_hidden + ) + self.add_symbol_table_node(name, symbol, context) + + def add_unknown_imported_symbol( + self, + name: str, + context: Context, + target_name: str | None, + module_public: bool, + module_hidden: bool, + ) -> None: + """Add symbol that we don't know what it points to because resolving an import failed. + + This can happen if a module is missing, or it is present, but doesn't have + the imported attribute. The `target_name` is the name of symbol in the namespace + it is imported from. For example, for 'from mod import x as y' the target_name is + 'mod.x'. This is currently used only to track logical dependencies. + """ + existing = self.current_symbol_table().get(name) + if existing and isinstance(existing.node, Var) and existing.node.is_suppressed_import: + # This missing import was already added -- nothing to do here. + return + var = Var(name) + if self.options.logical_deps and target_name is not None: + # This makes it possible to add logical fine-grained dependencies + # from a missing module. We can't use this by default, since in a + # few places we assume that the full name points to a real + # definition, but this name may point to nothing. + var._fullname = target_name + elif self.type: + var._fullname = self.type.fullname + "." + name + var.info = self.type + else: + var._fullname = self.qualified_name(name) + var.is_ready = True + any_type = AnyType(TypeOfAny.from_unimported_type, missing_import_name=var._fullname) + var.type = any_type + var.is_suppressed_import = True + self.add_symbol( + name, var, context, module_public=module_public, module_hidden=module_hidden + ) + + # + # Other helpers + # + + @contextmanager + def tvar_scope_frame(self, frame: TypeVarLikeScope) -> Iterator[None]: + old_scope = self.tvar_scope + self.tvar_scope = frame + yield + self.tvar_scope = old_scope + + def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None: + """Defer current analysis target to be analyzed again. + + This must be called if something in the current target is + incomplete or has a placeholder node. However, this must *not* + be called during the final analysis iteration! Instead, an error + should be generated. Often 'process_placeholder' is a good + way to either defer or generate an error. + + NOTE: Some methods, such as 'anal_type', 'mark_incomplete' and + 'record_incomplete_ref', call this implicitly, or when needed. + They are usually preferable to a direct defer() call. + """ + assert not self.final_iteration, "Must not defer during final iteration" + if force_progress: + # Usually, we report progress if we have replaced a placeholder node + # with an actual valid node. However, sometimes we need to update an + # existing node *in-place*. For example, this is used by type aliases + # in context of forward references and/or recursive aliases, and in + # similar situations (recursive named tuples etc). + self.progress = True + self.deferred = True + # Store debug info for this deferral. + line = ( + debug_context.line if debug_context else self.statement.line if self.statement else -1 + ) + self.deferral_debug_context.append((self.cur_mod_id, line)) + + def track_incomplete_refs(self) -> Tag: + """Return tag that can be used for tracking references to incomplete names.""" + return self.num_incomplete_refs + + def found_incomplete_ref(self, tag: Tag) -> bool: + """Have we encountered an incomplete reference since starting tracking?""" + return self.num_incomplete_refs != tag + + def record_incomplete_ref(self) -> None: + """Record the encounter of an incomplete reference and defer current analysis target.""" + self.defer() + self.num_incomplete_refs += 1 + + def mark_incomplete( + self, + name: str, + node: Node, + becomes_typeinfo: bool = False, + module_public: bool = True, + module_hidden: bool = False, + ) -> None: + """Mark a definition as incomplete (and defer current analysis target). + + Also potentially mark the current namespace as incomplete. + + Args: + name: The name that we weren't able to define (or '*' if the name is unknown) + node: The node that refers to the name (definition or lvalue) + becomes_typeinfo: Pass this to PlaceholderNode (used by special forms like + named tuples that will create TypeInfos). + """ + self.defer(node) + if name == "*": + self.incomplete = True + elif not self.is_global_or_nonlocal(name): + fullname = self.qualified_name(name) + assert self.statement + placeholder = PlaceholderNode( + fullname, node, self.statement.line, becomes_typeinfo=becomes_typeinfo + ) + self.add_symbol( + name, + placeholder, + module_public=module_public, + module_hidden=module_hidden, + context=dummy_context(), + ) + self.missing_names[-1].add(name) + + def is_incomplete_namespace(self, fullname: str) -> bool: + """Is a module or class namespace potentially missing some definitions? + + If a name is missing from an incomplete namespace, we'll need to defer the + current analysis target. + """ + return fullname in self.incomplete_namespaces + + def process_placeholder( + self, name: str | None, kind: str, ctx: Context, force_progress: bool = False + ) -> None: + """Process a reference targeting placeholder node. + + If this is not a final iteration, defer current node, + otherwise report an error. + + The 'kind' argument indicates if this a name or attribute expression + (used for better error message). + """ + if self.final_iteration: + self.cannot_resolve_name(name, kind, ctx) + else: + self.defer(ctx, force_progress=force_progress) + + def cannot_resolve_name(self, name: str | None, kind: str, ctx: Context) -> None: + name_format = f' "{name}"' if name else "" + self.fail(f"Cannot resolve {kind}{name_format} (possible cyclic definition)", ctx) + if self.is_func_scope(): + self.note("Recursive types are not allowed at function scope", ctx) + + def qualified_name(self, name: str) -> str: + if self.type is not None: + return self.type._fullname + "." + name + elif self.is_func_scope(): + return name + else: + return self.cur_mod_id + "." + name + + @contextmanager + def enter( + self, function: FuncItem | GeneratorExpr | DictionaryComprehension + ) -> Iterator[None]: + """Enter a function, generator or comprehension scope.""" + names = self.saved_locals.setdefault(function, SymbolTable()) + self.locals.append(names) + is_comprehension = isinstance(function, (GeneratorExpr, DictionaryComprehension)) + self.scope_stack.append(SCOPE_FUNC if not is_comprehension else SCOPE_COMPREHENSION) + self.global_decls.append(set()) + self.nonlocal_decls.append(set()) + # -1 since entering block will increment this to 0. + self.block_depth.append(-1) + self.loop_depth.append(0) + self.missing_names.append(set()) + try: + yield + finally: + self.locals.pop() + self.scope_stack.pop() + self.global_decls.pop() + self.nonlocal_decls.pop() + self.block_depth.pop() + self.loop_depth.pop() + self.missing_names.pop() + + def is_func_scope(self) -> bool: + scope_type = self.scope_stack[-1] + if scope_type == SCOPE_ANNOTATION: + scope_type = self.scope_stack[-2] + return scope_type in (SCOPE_FUNC, SCOPE_COMPREHENSION) + + def is_nested_within_func_scope(self) -> bool: + """Are we underneath a function scope, even if we are in a nested class also?""" + return any(s in (SCOPE_FUNC, SCOPE_COMPREHENSION) for s in self.scope_stack) + + def is_class_scope(self) -> bool: + return self.type is not None and not self.is_func_scope() + + def is_module_scope(self) -> bool: + return not (self.is_class_scope() or self.is_func_scope()) + + def current_symbol_kind(self) -> int: + if self.is_class_scope(): + kind = MDEF + elif self.is_func_scope(): + kind = LDEF + else: + kind = GDEF + return kind + + def current_symbol_table( + self, escape_comprehensions: bool = False, type_param: bool = False + ) -> SymbolTable: + if type_param and self.scope_stack[-1] == SCOPE_ANNOTATION: + n = self.locals[-1] + assert n is not None + return n + elif self.is_func_scope(): + if self.scope_stack[-1] == SCOPE_ANNOTATION: + n = self.locals[-2] + else: + n = self.locals[-1] + assert n is not None + if escape_comprehensions: + assert len(self.locals) == len(self.scope_stack) + # Retrieve the symbol table from the enclosing non-comprehension scope. + for i, scope_type in enumerate(reversed(self.scope_stack)): + if scope_type != SCOPE_COMPREHENSION: + if i == len(self.locals) - 1: # The last iteration. + # The caller of the comprehension is in the global space. + names = self.globals + else: + names_candidate = self.locals[-1 - i] + assert ( + names_candidate is not None + ), "Escaping comprehension from invalid scope" + names = names_candidate + break + else: + assert False, "Should have at least one non-comprehension scope" + else: + names = n + assert names is not None + elif self.type is not None: + names = self.type.names + else: + names = self.globals + return names + + def is_global_or_nonlocal(self, name: str) -> bool: + return self.is_func_scope() and ( + name in self.global_decls[-1] or name in self.nonlocal_decls[-1] + ) + + def add_exports(self, exp_or_exps: Iterable[Expression] | Expression) -> None: + exps = [exp_or_exps] if isinstance(exp_or_exps, Expression) else exp_or_exps + for exp in exps: + if isinstance(exp, StrExpr): + self.all_exports.append(exp.value) + + def name_not_defined(self, name: str, ctx: Context, namespace: str | None = None) -> None: + incomplete = self.is_incomplete_namespace(namespace or self.cur_mod_id) + if ( + namespace is None + and self.type + and not self.is_func_scope() + and self.incomplete_type_stack + and self.incomplete_type_stack[-1] + and not self.final_iteration + ): + # We are processing a class body for the first time, so it is incomplete. + incomplete = True + if incomplete: + # Target namespace is incomplete, so it's possible that the name will be defined + # later on. Defer current target. + self.record_incomplete_ref() + return + message = f'Name "{name}" is not defined' + self.fail(message, ctx, code=codes.NAME_DEFINED) + + if f"builtins.{name}" in SUGGESTED_TEST_FIXTURES: + # The user probably has a missing definition in a test fixture. Let's verify. + fullname = f"builtins.{name}" + if self.lookup_fully_qualified_or_none(fullname) is None: + # Yes. Generate a helpful note. + self.msg.add_fixture_note(fullname, ctx) + + modules_with_unimported_hints = { + name.split(".", 1)[0] for name in TYPES_FOR_UNIMPORTED_HINTS + } + lowercased = {name.lower(): name for name in TYPES_FOR_UNIMPORTED_HINTS} + for module in modules_with_unimported_hints: + fullname = f"{module}.{name}".lower() + if fullname not in lowercased: + continue + # User probably forgot to import these types. + hint = ( + 'Did you forget to import it from "{module}"?' + ' (Suggestion: "from {module} import {name}")' + ).format(module=module, name=lowercased[fullname].rsplit(".", 1)[-1]) + self.note(hint, ctx, code=codes.NAME_DEFINED) + + def already_defined( + self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None, noun: str + ) -> None: + if isinstance(original_ctx, SymbolTableNode): + node: SymbolNode | None = original_ctx.node + elif isinstance(original_ctx, SymbolNode): + node = original_ctx + else: + node = None + + if isinstance(original_ctx, SymbolTableNode) and isinstance(original_ctx.node, MypyFile): + # Since this is an import, original_ctx.node points to the module definition. + # Therefore, its line number is always 1, which is not useful for this + # error message. + extra_msg = " (by an import)" + elif node and node.line != -1 and self.is_local_name(node.fullname): + # TODO: Using previous symbol node may give wrong line. We should use + # the line number where the binding was established instead. + extra_msg = f" on line {node.line}" + else: + extra_msg = " (possibly by an import)" + self.fail( + f'{noun} "{unmangle(name)}" already defined{extra_msg}', ctx, code=codes.NO_REDEF + ) + + def name_already_defined( + self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None = None + ) -> None: + self.already_defined(name, ctx, original_ctx, noun="Name") + + def attribute_already_defined( + self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None = None + ) -> None: + self.already_defined(name, ctx, original_ctx, noun="Attribute") + + def is_local_name(self, name: str) -> bool: + """Does name look like reference to a definition in the current module?""" + return self.is_defined_in_current_module(name) or "." not in name + + def in_checked_function(self) -> bool: + """Should we type-check the current function? + + - Yes if --check-untyped-defs is set. + - Yes outside functions. + - Yes in annotated functions. + - No otherwise. + """ + if self.options.check_untyped_defs or not self.function_stack: + return True + + current_index = len(self.function_stack) - 1 + while current_index >= 0: + current_func = self.function_stack[current_index] + if not isinstance(current_func, LambdaExpr): + return not current_func.is_dynamic() + + # Special case, `lambda` inherits the "checked" state from its parent. + # Because `lambda` itself cannot be annotated. + # `lambdas` can be deeply nested, so we try to find at least one other parent. + current_index -= 1 + + # This means that we only have a stack of `lambda` functions, + # no regular functions. + return True + + def fail( + self, + msg: str | ErrorMessage, + ctx: Context, + serious: bool = False, + *, + code: ErrorCode | None = None, + blocker: bool = False, + ) -> None: + if not serious and not self.in_checked_function(): + return + # In case it's a bug and we don't really have context + assert ctx is not None, msg + if isinstance(msg, ErrorMessage): + if code is None: + code = msg.code + msg = msg.value + self.errors.report( + ctx.line, + ctx.column, + msg, + blocker=blocker, + code=code, + end_line=ctx.end_line, + end_column=ctx.end_column, + ) + + def note(self, msg: str, ctx: Context, code: ErrorCode | None = None) -> None: + if not self.in_checked_function(): + return + self.errors.report(ctx.line, ctx.column, msg, severity="note", code=code) + + def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: + if feature not in self.options.enable_incomplete_feature: + self.fail( + f'"{feature}" support is experimental,' + f" use --enable-incomplete-feature={feature} to enable", + ctx, + ) + return False + return True + + def accept(self, node: Node) -> None: + try: + node.accept(self) + except Exception as err: + report_internal_error(err, self.errors.file, node.line, self.errors, self.options) + + def expr_to_analyzed_type( + self, + expr: Expression, + report_invalid_types: bool = True, + allow_placeholder: bool = False, + allow_type_any: bool = False, + allow_unbound_tvars: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + ) -> Type | None: + if isinstance(expr, CallExpr): + # This is a legacy syntax intended mostly for Python 2, we keep it for + # backwards compatibility, but new features like generic named tuples + # and recursive named tuples will be not supported. + expr.accept(self) + internal_name, info, tvar_defs = self.named_tuple_analyzer.check_namedtuple( + expr, None, self.is_func_scope() + ) + if tvar_defs: + self.fail("Generic named tuples are not supported for legacy class syntax", expr) + self.note("Use either Python 3 class syntax, or the assignment syntax", expr) + if internal_name is None: + # Some form of namedtuple is the only valid type that looks like a call + # expression. This isn't a valid type. + raise TypeTranslationError() + elif not info: + self.defer(expr) + return None + assert info.tuple_type, "NamedTuple without tuple type" + fallback = Instance(info, []) + return TupleType(info.tuple_type.items, fallback=fallback) + typ = self.expr_to_unanalyzed_type(expr) + return self.anal_type( + typ, + report_invalid_types=report_invalid_types, + allow_placeholder=allow_placeholder, + allow_type_any=allow_type_any, + allow_unbound_tvars=allow_unbound_tvars, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + ) + + def analyze_type_expr(self, expr: Expression) -> None: + # There are certain expressions that mypy does not need to semantically analyze, + # since they analyzed solely as type. (For example, indexes in type alias definitions + # and base classes in class defs). External consumers of the mypy AST may need + # them semantically analyzed, however, if they need to treat it as an expression + # and not a type. (Which is to say, mypyc needs to do this.) Do the analysis + # in a fresh tvar scope in order to suppress any errors about using type variables. + with self.tvar_scope_frame(TypeVarLikeScope()), self.allow_unbound_tvars_set(): + expr.accept(self) + + def type_analyzer( + self, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_placeholder: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + allow_type_any: bool = False, + ) -> TypeAnalyser: + if tvar_scope is None: + tvar_scope = self.tvar_scope + tpan = TypeAnalyser( + self, + tvar_scope, + self.plugin, + self.options, + self.cur_mod_node, + self.is_typeshed_stub_file, + allow_unbound_tvars=allow_unbound_tvars, + allow_tuple_literal=allow_tuple_literal, + report_invalid_types=report_invalid_types, + allow_placeholder=allow_placeholder, + allow_typed_dict_special_forms=allow_typed_dict_special_forms, + allow_final=allow_final, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + prohibit_self_type=prohibit_self_type, + prohibit_special_class_field_types=prohibit_special_class_field_types, + allow_type_any=allow_type_any, + ) + tpan.in_dynamic_func = bool(self.function_stack and self.function_stack[-1].is_dynamic()) + tpan.global_scope = not self.type and not self.function_stack + return tpan + + def expr_to_unanalyzed_type(self, node: Expression, allow_unpack: bool = False) -> ProperType: + return expr_to_unanalyzed_type( + node, self.options, self.is_stub_file, allow_unpack=allow_unpack + ) + + def anal_type( + self, + typ: Type, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_placeholder: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + allow_type_any: bool = False, + ) -> Type | None: + """Semantically analyze a type. + + Args: + typ: Type to analyze (if already analyzed, this is a no-op) + allow_placeholder: If True, may return PlaceholderType if + encountering an incomplete definition + + Return None only if some part of the type couldn't be bound *and* it + referred to an incomplete namespace or definition. In this case also + defer as needed. During a final iteration this won't return None; + instead report an error if the type can't be analyzed and return + AnyType. + + In case of other errors, report an error message and return AnyType. + + NOTE: The caller shouldn't defer even if this returns None or a + placeholder type. + """ + has_self_type = find_self_type( + typ, lambda name: self.lookup_qualified(name, typ, suppress_errors=True) + ) + if has_self_type and self.type and prohibit_self_type is None: + self.setup_self_type() + a = self.type_analyzer( + tvar_scope=tvar_scope, + allow_unbound_tvars=allow_unbound_tvars, + allow_tuple_literal=allow_tuple_literal, + allow_placeholder=allow_placeholder, + allow_typed_dict_special_forms=allow_typed_dict_special_forms, + allow_final=allow_final, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + report_invalid_types=report_invalid_types, + prohibit_self_type=prohibit_self_type, + prohibit_special_class_field_types=prohibit_special_class_field_types, + allow_type_any=allow_type_any, + ) + tag = self.track_incomplete_refs() + typ = typ.accept(a) + if self.found_incomplete_ref(tag): + # Something could not be bound yet. + return None + self.add_type_alias_deps(a.aliases_used) + return typ + + def class_type(self, self_type: Type) -> Type: + return TypeType.make_normalized(self_type) + + def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None: + self.patches.append((priority, patch)) + + def report_hang(self) -> None: + print("Deferral trace:") + for mod, line in self.deferral_debug_context: + print(f" {mod}:{line}") + self.errors.report( + -1, + -1, + "INTERNAL ERROR: maximum semantic analysis iteration count reached", + blocker=True, + ) + + def add_plugin_dependency(self, trigger: str, target: str | None = None) -> None: + """Add dependency from trigger to a target. + + If the target is not given explicitly, use the current target. + """ + if target is None: + target = self.scope.current_target() + self.cur_mod_node.plugin_deps.setdefault(trigger, set()).add(target) + + def add_type_alias_deps( + self, aliases_used: Collection[str], target: str | None = None + ) -> None: + """Add full names of type aliases on which the current node depends. + + This is used by fine-grained incremental mode to re-check the corresponding nodes. + If `target` is None, then the target node used will be the current scope. + """ + if not aliases_used: + return + if target is None: + target = self.scope.current_target() + self.cur_mod_node.alias_deps[target].update(aliases_used) + + def is_mangled_global(self, name: str) -> bool: + # A global is mangled if there exists at least one renamed variant. + return unmangle(name) + "'" in self.globals + + def is_initial_mangled_global(self, name: str) -> bool: + # If there are renamed definitions for a global, the first one has exactly one prime. + return name == unmangle(name) + "'" + + def parse_bool(self, expr: Expression) -> bool | None: + # This wrapper is preserved for plugins. + return parse_bool(expr) + + def parse_str_literal(self, expr: Expression) -> str | None: + """Attempt to find the string literal value of the given expression. Returns `None` if no + literal value can be found.""" + if isinstance(expr, StrExpr): + return expr.value + if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.type is not None: + values = try_getting_str_literals_from_type(expr.node.type) + if values is not None and len(values) == 1: + return values[0] + return None + + def set_future_import_flags(self, module_name: str) -> None: + if module_name in FUTURE_IMPORTS: + self.modules[self.cur_mod_id].future_import_flags.add(FUTURE_IMPORTS[module_name]) + + def is_future_flag_set(self, flag: str) -> bool: + return self.modules[self.cur_mod_id].is_future_flag_set(flag) + + def parse_dataclass_transform_spec(self, call: CallExpr) -> DataclassTransformSpec: + """Build a DataclassTransformSpec from the arguments passed to the given call to + typing.dataclass_transform.""" + parameters = DataclassTransformSpec() + for name, value in zip(call.arg_names, call.args): + # Skip any positional args. Note that any such args are invalid, but we can rely on + # typeshed to enforce this and don't need an additional error here. + if name is None: + continue + + # field_specifiers is currently the only non-boolean argument; check for it first so + # so the rest of the block can fail through to handling booleans + if name == "field_specifiers": + parameters.field_specifiers = self.parse_dataclass_transform_field_specifiers( + value + ) + continue + + boolean = require_bool_literal_argument(self, value, name) + if boolean is None: + continue + + if name == "eq_default": + parameters.eq_default = boolean + elif name == "order_default": + parameters.order_default = boolean + elif name == "kw_only_default": + parameters.kw_only_default = boolean + elif name == "frozen_default": + parameters.frozen_default = boolean + else: + self.fail(f'Unrecognized dataclass_transform parameter "{name}"', call) + + return parameters + + def parse_dataclass_transform_field_specifiers(self, arg: Expression) -> tuple[str, ...]: + if not isinstance(arg, TupleExpr): + self.fail('"field_specifiers" argument must be a tuple literal', arg) + return () + + names = [] + for specifier in arg.items: + if not isinstance(specifier, RefExpr): + self.fail('"field_specifiers" must only contain identifiers', specifier) + return () + names.append(specifier.fullname) + return tuple(names) + + # leafs + def visit_int_expr(self, o: IntExpr, /) -> None: + return None + + def visit_str_expr(self, o: StrExpr, /) -> None: + return None + + def visit_bytes_expr(self, o: BytesExpr, /) -> None: + return None + + def visit_float_expr(self, o: FloatExpr, /) -> None: + return None + + def visit_complex_expr(self, o: ComplexExpr, /) -> None: + return None + + def visit_ellipsis(self, o: EllipsisExpr, /) -> None: + return None + + def visit_temp_node(self, o: TempNode, /) -> None: + return None + + def visit_pass_stmt(self, o: PassStmt, /) -> None: + return None + + def visit_singleton_pattern(self, o: SingletonPattern, /) -> None: + return None + + def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> None: + """Try to parse a value Expression as a type expression. + If success then annotate the Expression with the type that it spells. + If fails then emit no errors and take no further action. + + A value expression that is parsable as a type expression may be used + where a TypeForm is expected to represent the spelled type. + + Unlike ExpressionChecker.try_parse_as_type_expression() + (used in the later TypeChecker pass), this function can recognize + ALL kinds of type expressions, including type expressions containing + string annotations. + + If the provided Expression will be parsable later in + ExpressionChecker.try_parse_as_type_expression(), this function will + skip parsing the Expression to improve performance, because the later + function is called many fewer times (i.e. only lazily in a rare TypeForm + type context) than this function is called (i.e. eagerly for EVERY + expression in certain syntactic positions). + """ + # Count every call to this method for profiling + self.type_expression_parse_count += 1 + + # Bail ASAP if the Expression matches a common pattern that cannot possibly + # be a valid type expression, because this function is called very frequently + if not isinstance(maybe_type_expr, MaybeTypeExpression): + return + # Check types in order from most common to least common, for best performance + if isinstance(maybe_type_expr, (NameExpr, MemberExpr)): + # Defer parsing to the later TypeChecker pass, + # and only lazily in contexts where a TypeForm is expected + return + elif isinstance(maybe_type_expr, StrExpr): + str_value = maybe_type_expr.value # cache + # Filter out string literals with common patterns that could not + # possibly be in a type expression + if _MULTIPLE_WORDS_NONTYPE_RE.match(str_value): + # A common pattern in string literals containing a sentence. + # But cannot be a type expression. + maybe_type_expr.as_type = None + return + # Filter out string literals which look like an identifier but + # cannot be a type expression, for a few common reasons + if _IDENTIFIER_RE.fullmatch(str_value): + sym = self.lookup(str_value, UnboundType(str_value), suppress_errors=True) + if sym is None: + # Does not refer to anything in the local symbol table + maybe_type_expr.as_type = None + return + else: # sym is not None + node = sym.node # cache + if isinstance(node, PlaceholderNode) and not node.becomes_typeinfo: + # Either: + # 1. f'Cannot resolve name "{t.name}" (possible cyclic definition)' + # 2. Reference to an unknown placeholder node. + maybe_type_expr.as_type = None + return + unbound_tvar_or_paramspec = ( + isinstance(node, (TypeVarExpr, TypeVarTupleExpr, ParamSpecExpr)) + and self.tvar_scope.get_binding(sym) is None + ) + if unbound_tvar_or_paramspec: + # Either: + # 1. unbound_tvar: 'Type variable "{}" is unbound' [codes.VALID_TYPE] + # 2. unbound_paramspec: f'ParamSpec "{name}" is unbound' [codes.VALID_TYPE] + maybe_type_expr.as_type = None + return + else: # does not look like an identifier + if '"' in str_value or "'" in str_value: + # Only valid inside a Literal[...] type + if "[" not in str_value: + # Cannot be a Literal[...] type + maybe_type_expr.as_type = None + return + elif str_value == "": + # Empty string is not a valid type + maybe_type_expr.as_type = None + return + elif isinstance(maybe_type_expr, IndexExpr): + if isinstance(maybe_type_expr.base, NameExpr): + if isinstance( + maybe_type_expr.base.node, Var + ) and not self.var_is_typing_special_form(maybe_type_expr.base.node): + # Leftmost part of IndexExpr refers to a Var. Not a valid type. + maybe_type_expr.as_type = None + return + elif isinstance(maybe_type_expr.base, MemberExpr): + next_leftmost = maybe_type_expr.base + while True: + leftmost = next_leftmost.expr + if not isinstance(leftmost, MemberExpr): + break + next_leftmost = leftmost + if isinstance(leftmost, NameExpr): + if isinstance(leftmost.node, Var) and not self.var_is_typing_special_form( + leftmost.node + ): + # Leftmost part of IndexExpr refers to a Var. Not a valid type. + maybe_type_expr.as_type = None + return + else: + # Leftmost part of IndexExpr is not a NameExpr. Not a valid type. + maybe_type_expr.as_type = None + return + else: + # IndexExpr base is neither a NameExpr nor MemberExpr. Not a valid type. + maybe_type_expr.as_type = None + return + elif isinstance(maybe_type_expr, OpExpr): + if maybe_type_expr.op != "|": + # Binary operators other than '|' never spell a valid type + maybe_type_expr.as_type = None + return + else: + assert_never(maybe_type_expr) + + with self.isolated_error_analysis(): + try: + t = self.expr_to_analyzed_type(maybe_type_expr) + if self.errors.is_errors(): + t = None + except TypeTranslationError: + # Not a type expression + t = None + + if DEBUG_TYPE_EXPRESSION_FULL_PARSE_FAILURES and t is None: + original_flushed_files = set(self.errors.flushed_files) # save + try: + errors = self.errors.new_messages() # capture + finally: + self.errors.flushed_files = original_flushed_files # restore + + print( + f"SA.try_parse_as_type_expression: Full parse failure: {maybe_type_expr}, errors={errors!r}" + ) + + # Count full parse attempts for profiling + if t is not None: + self.type_expression_full_parse_success_count += 1 + else: + self.type_expression_full_parse_failure_count += 1 + + maybe_type_expr.as_type = t + + @staticmethod + def var_is_typing_special_form(var: Var) -> bool: + return var.fullname.startswith("typing") and var.fullname in [ + "typing.Annotated", + "typing_extensions.Annotated", + "typing.Callable", + "typing.Literal", + "typing_extensions.Literal", + "typing.Optional", + "typing.TypeGuard", + "typing_extensions.TypeGuard", + "typing.TypeIs", + "typing_extensions.TypeIs", + "typing.Union", + ] + + @contextmanager + def isolated_error_analysis(self) -> Iterator[None]: + """ + Context manager for performing error analysis that should not + affect the main SemanticAnalyzer state. + + Upon entering this context, `self.errors` will start empty. + Within this context, you can analyze expressions for errors. + Upon exiting this context, the original `self.errors` will be restored, + and any errors collected during the analysis will be discarded. + """ + # Save state + original_errors = self.errors + original_num_incomplete_refs = self.num_incomplete_refs + original_progress = self.progress + original_deferred = self.deferred + original_deferral_debug_context_len = len(self.deferral_debug_context) + + self.errors = Errors(Options()) + try: + yield + finally: + # Restore state + self.errors = original_errors + self.num_incomplete_refs = original_num_incomplete_refs + self.progress = original_progress + self.deferred = original_deferred + del self.deferral_debug_context[original_deferral_debug_context_len:] + + +def replace_implicit_first_type(sig: FunctionLike, new: Type) -> FunctionLike: + if isinstance(sig, CallableType): + if len(sig.arg_types) == 0: + return sig + return sig.copy_modified(arg_types=[new] + sig.arg_types[1:]) + elif isinstance(sig, Overloaded): + return Overloaded( + [cast(CallableType, replace_implicit_first_type(i, new)) for i in sig.items] + ) + else: + assert False + + +def refers_to_fullname(node: Expression, fullnames: str | tuple[str, ...]) -> bool: + """Is node a name or member expression with the given full name?""" + if not isinstance(fullnames, tuple): + fullnames = (fullnames,) + + if not isinstance(node, RefExpr): + return False + if node.fullname in fullnames: + return True + if isinstance(node.node, TypeAlias) and not node.node.python_3_12_type_alias: + return is_named_instance(node.node.target, fullnames) + return False + + +def refers_to_class_or_function(node: Expression) -> bool: + """Does semantically analyzed node refer to a class?""" + return isinstance(node, RefExpr) and isinstance( + node.node, (TypeInfo, FuncDef, OverloadedFuncDef) + ) + + +def find_duplicate(list: list[T]) -> T | None: + """If the list has duplicates, return one of the duplicates. + + Otherwise, return None. + """ + for i in range(1, len(list)): + if list[i] in list[:i]: + return list[i] + return None + + +def remove_imported_names_from_symtable(names: SymbolTable, module: str) -> None: + """Remove all imported names from the symbol table of a module.""" + removed: list[str] = [] + for name, node in names.items(): + if node.node is None: + continue + fullname = node.node.fullname + prefix = fullname[: fullname.rfind(".")] + if prefix != module: + removed.append(name) + for name in removed: + del names[name] + + +def make_any_non_explicit(t: Type) -> Type: + """Replace all Any types within in with Any that has attribute 'explicit' set to False""" + return t.accept(MakeAnyNonExplicit()) + + +class MakeAnyNonExplicit(TrivialSyntheticTypeTranslator): + def visit_any(self, t: AnyType) -> Type: + if t.type_of_any == TypeOfAny.explicit: + return t.copy_modified(TypeOfAny.special_form) + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def make_any_non_unimported(t: Type) -> Type: + """Replace all Any types that come from unimported types with special form Any.""" + return t.accept(MakeAnyNonUnimported()) + + +class MakeAnyNonUnimported(TrivialSyntheticTypeTranslator): + def visit_any(self, t: AnyType) -> Type: + if t.type_of_any == TypeOfAny.from_unimported_type: + return t.copy_modified(TypeOfAny.special_form, missing_import_name=None) + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def apply_semantic_analyzer_patches(patches: list[tuple[int, Callable[[], None]]]) -> None: + """Call patch callbacks in the right order. + + This should happen after semantic analyzer pass 3. + """ + patches_by_priority = sorted(patches, key=lambda x: x[0]) + for priority, patch_func in patches_by_priority: + patch_func() + + +def names_modified_by_assignment(s: AssignmentStmt) -> list[NameExpr]: + """Return all unqualified (short) names assigned to in an assignment statement.""" + result: list[NameExpr] = [] + for lvalue in s.lvalues: + result += names_modified_in_lvalue(lvalue) + return result + + +def names_modified_in_lvalue(lvalue: Lvalue) -> list[NameExpr]: + """Return all NameExpr assignment targets in an Lvalue.""" + if isinstance(lvalue, NameExpr): + return [lvalue] + elif isinstance(lvalue, StarExpr): + return names_modified_in_lvalue(lvalue.expr) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + result: list[NameExpr] = [] + for item in lvalue.items: + result += names_modified_in_lvalue(item) + return result + return [] + + +def is_same_var_from_getattr(n1: SymbolNode | None, n2: SymbolNode | None) -> bool: + """Do n1 and n2 refer to the same Var derived from module-level __getattr__?""" + return ( + isinstance(n1, Var) + and n1.from_module_getattr + and isinstance(n2, Var) + and n2.from_module_getattr + and n1.fullname == n2.fullname + ) + + +def dummy_context() -> Context: + return TempNode(AnyType(TypeOfAny.special_form)) + + +def is_valid_replacement(old: SymbolTableNode, new: SymbolTableNode) -> bool: + """Can symbol table node replace an existing one? + + These are the only valid cases: + + 1. Placeholder gets replaced with a non-placeholder + 2. Placeholder that isn't known to become type replaced with a + placeholder that can become a type + """ + if isinstance(old.node, PlaceholderNode): + if isinstance(new.node, PlaceholderNode): + return not old.node.becomes_typeinfo and new.node.becomes_typeinfo + else: + return True + return False + + +def is_same_symbol(a: SymbolNode | None, b: SymbolNode | None) -> bool: + return ( + a == b + or (isinstance(a, PlaceholderNode) and isinstance(b, PlaceholderNode)) + or is_same_var_from_getattr(a, b) + ) + + +def is_trivial_body(block: Block) -> bool: + """Returns 'true' if the given body is "trivial" -- if it contains just a "pass", + "..." (ellipsis), or "raise NotImplementedError()". A trivial body may also + start with a statement containing just a string (e.g. a docstring). + + Note: Functions that raise other kinds of exceptions do not count as + "trivial". We use this function to help us determine when it's ok to + relax certain checks on body, but functions that raise arbitrary exceptions + are more likely to do non-trivial work. For example: + + def halt(self, reason: str = ...) -> NoReturn: + raise MyCustomError("Fatal error: " + reason, self.line, self.context) + + A function that raises just NotImplementedError is much less likely to be + this complex. + + Note: If you update this, you may also need to update + mypy.fastparse.is_possible_trivial_body! + """ + body = block.body + if not body: + # Functions have empty bodies only if the body is stripped or the function is + # generated or deserialized. In these cases the body is unknown. + return False + + # Skip a docstring + if isinstance(body[0], ExpressionStmt) and isinstance(body[0].expr, StrExpr): + body = block.body[1:] + + if len(body) == 0: + # There's only a docstring (or no body at all). + return True + elif len(body) > 1: + return False + + stmt = body[0] + + if isinstance(stmt, RaiseStmt): + expr = stmt.expr + if expr is None: + return False + if isinstance(expr, CallExpr): + expr = expr.callee + + return isinstance(expr, NameExpr) and expr.fullname == "builtins.NotImplementedError" + + return isinstance(stmt, PassStmt) or ( + isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr) + ) + + +def is_init_only(node: Var) -> bool: + return ( + isinstance(type := get_proper_type(node.type), Instance) + and type.type.fullname == "dataclasses.InitVar" + ) + + +def erase_func_annotations(func: FuncDef) -> None: + func.type_args = None + for arg in func.arguments: + arg.type_annotation = None + arg.variable.type = None + func.type = None + func.unanalyzed_type = None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_classprop.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_classprop.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5d8f2371df37c3f404f6926d7d90cd0395ea3215 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_classprop.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_classprop.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_classprop.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ad34122f6c84330b6c1c5b966c2c80d3686dfc --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_classprop.py @@ -0,0 +1,188 @@ +"""Calculate some properties of classes. + +These happen after semantic analysis and before type checking. +""" + +from __future__ import annotations + +from typing import Final + +from mypy.errors import Errors +from mypy.nodes import ( + IMPLICITLY_ABSTRACT, + IS_ABSTRACT, + CallExpr, + Decorator, + FuncDef, + Node, + OverloadedFuncDef, + PromoteExpr, + SymbolTable, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.types import MYPYC_NATIVE_INT_NAMES, Instance, ProperType + +# Hard coded type promotions (shared between all Python versions). +# These add extra ad-hoc edges to the subtyping relation. For example, +# int is considered a subtype of float, even though there is no +# subclass relationship. +# Note that the bytearray -> bytes promotion is a little unsafe +# as some functions only accept bytes objects. Here convenience +# trumps safety. +TYPE_PROMOTIONS: Final = { + "builtins.int": "float", + "builtins.float": "complex", + "builtins.bytearray": "bytes", + "builtins.memoryview": "bytes", +} + + +def calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: Errors) -> None: + """Calculate abstract status of a class. + + Set is_abstract of the type to True if the type has an unimplemented + abstract attribute. Also compute a list of abstract attributes. + Report error is required ABCMeta metaclass is missing. + """ + typ.is_abstract = False + typ.abstract_attributes = [] + if typ.typeddict_type: + return # TypedDict can't be abstract + concrete: set[str] = set() + # List of abstract attributes together with their abstract status + abstract: list[tuple[str, int]] = [] + abstract_in_this_class: list[str] = [] + if typ.is_newtype: + # Special case: NewTypes are considered as always non-abstract, so they can be used as: + # Config = NewType('Config', Mapping[str, str]) + # default = Config({'cannot': 'modify'}) # OK + return + for base in typ.mro: + for name, symnode in base.names.items(): + node = symnode.node + if isinstance(node, OverloadedFuncDef): + # Unwrap an overloaded function definition. We can just + # check arbitrarily the first overload item. If the + # different items have a different abstract status, there + # should be an error reported elsewhere. + if node.items: # can be empty for invalid overloads + func: Node | None = node.items[0] + else: + func = None + else: + func = node + if isinstance(func, Decorator): + func = func.func + if isinstance(func, FuncDef): + if ( + func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT) + and name not in concrete + ): + typ.is_abstract = True + abstract.append((name, func.abstract_status)) + if base is typ: + abstract_in_this_class.append(name) + elif isinstance(node, Var): + if node.is_abstract_var and name not in concrete: + typ.is_abstract = True + abstract.append((name, IS_ABSTRACT)) + if base is typ: + abstract_in_this_class.append(name) + concrete.add(name) + # In stubs, abstract classes need to be explicitly marked because it is too + # easy to accidentally leave a concrete class abstract by forgetting to + # implement some methods. + typ.abstract_attributes = sorted(abstract) + if is_stub_file: + if typ.declared_metaclass and typ.declared_metaclass.type.has_base("abc.ABCMeta"): + return + if typ.is_protocol: + return + if abstract and not abstract_in_this_class: + + def report(message: str, severity: str) -> None: + errors.report(typ.line, typ.column, message, severity=severity) + + attrs = ", ".join(f'"{attr}"' for attr, _ in sorted(abstract)) + report(f"Class {typ.fullname} has abstract attributes {attrs}", "error") + report( + "If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass", "note" + ) + if typ.is_final and abstract: + attrs = ", ".join(f'"{attr}"' for attr, _ in sorted(abstract)) + errors.report( + typ.line, typ.column, f"Final class {typ.fullname} has abstract attributes {attrs}" + ) + + +def check_protocol_status(info: TypeInfo, errors: Errors) -> None: + """Check that all classes in MRO of a protocol are protocols""" + if info.is_protocol: + for type in info.bases: + if not type.type.is_protocol and type.type.fullname != "builtins.object": + errors.report( + info.line, + info.column, + "All bases of a protocol must be protocols", + severity="error", + ) + + +def calculate_class_vars(info: TypeInfo) -> None: + """Try to infer additional class variables. + + Subclass attribute assignments with no type annotation are assumed + to be classvar if overriding a declared classvar from the base + class. + + This must happen after the main semantic analysis pass, since + this depends on base class bodies having been fully analyzed. + """ + for name, sym in info.names.items(): + node = sym.node + if isinstance(node, Var) and node.info and node.is_inferred and not node.is_classvar: + for base in info.mro[1:]: + member = base.names.get(name) + if member is not None and isinstance(member.node, Var) and member.node.is_classvar: + node.is_classvar = True + + +def add_type_promotion( + info: TypeInfo, module_names: SymbolTable, options: Options, builtin_names: SymbolTable +) -> None: + """Setup extra, ad-hoc subtyping relationships between classes (promotion). + + This includes things like 'int' being compatible with 'float'. + """ + defn = info.defn + promote_targets: list[ProperType] = [] + for decorator in defn.decorators: + if isinstance(decorator, CallExpr): + analyzed = decorator.analyzed + if isinstance(analyzed, PromoteExpr): + # _promote class decorator (undocumented feature). + promote_targets.append(analyzed.type) + if not promote_targets: + if defn.fullname in TYPE_PROMOTIONS: + target_sym = module_names.get(TYPE_PROMOTIONS[defn.fullname]) + if defn.fullname == "builtins.bytearray" and options.disable_bytearray_promotion: + target_sym = None + elif defn.fullname == "builtins.memoryview" and options.disable_memoryview_promotion: + target_sym = None + # With test stubs, the target may not exist. + if target_sym: + target_info = target_sym.node + assert isinstance(target_info, TypeInfo) + promote_targets.append(Instance(target_info, [])) + # Special case the promotions between 'int' and native integer types. + # These have promotions going both ways, such as from 'int' to 'i64' + # and 'i64' to 'int', for convenience. + if defn.fullname in MYPYC_NATIVE_INT_NAMES: + int_sym = builtin_names["int"] + assert isinstance(int_sym.node, TypeInfo) + int_sym.node._promote.append(Instance(defn.info, [])) + defn.info.alt_promote = Instance(int_sym.node, []) + if promote_targets: + defn.info._promote.extend(promote_targets) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_enum.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_enum.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ca0c9ece192a1a87841e0967b614cc42b7c624e7 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_enum.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_enum.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e267b4c781f7ae4173b0f83b598e86045b8f64 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_enum.py @@ -0,0 +1,269 @@ +"""Semantic analysis of call-based Enum definitions. + +This is conceptually part of mypy.semanal (semantic analyzer pass 2). +""" + +from __future__ import annotations + +from typing import Final, cast + +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + EXCLUDED_ENUM_ATTRIBUTES, + MDEF, + AssignmentStmt, + CallExpr, + Context, + DictExpr, + EnumCallExpr, + Expression, + ListExpr, + MemberExpr, + NameExpr, + RefExpr, + StrExpr, + SymbolTableNode, + TupleExpr, + TypeInfo, + Var, + is_StrExpr_list, +) +from mypy.options import Options +from mypy.semanal_shared import SemanticAnalyzerInterface +from mypy.types import LiteralType, get_proper_type + +# Note: 'enum.EnumMeta' is deliberately excluded from this list. Classes that directly use +# enum.EnumMeta do not necessarily automatically have the 'name' and 'value' attributes. +ENUM_BASES: Final = frozenset( + ("enum.Enum", "enum.IntEnum", "enum.Flag", "enum.IntFlag", "enum.StrEnum") +) +ENUM_SPECIAL_PROPS: Final = frozenset( + ( + "name", + "value", + "_name_", + "_value_", + *EXCLUDED_ENUM_ATTRIBUTES, + # Also attributes from `object`: + "__module__", + "__annotations__", + "__doc__", + "__slots__", + "__dict__", + ) +) + + +class EnumCallAnalyzer: + def __init__(self, options: Options, api: SemanticAnalyzerInterface) -> None: + self.options = options + self.api = api + + def process_enum_call(self, s: AssignmentStmt, is_func_scope: bool) -> bool: + """Check if s defines an Enum; if yes, store the definition in symbol table. + + Return True if this looks like an Enum definition (but maybe with errors), + otherwise return False. + """ + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)): + return False + lvalue = s.lvalues[0] + name = lvalue.name + enum_call = self.check_enum_call(s.rvalue, name, is_func_scope) + if enum_call is None: + return False + if isinstance(lvalue, MemberExpr): + self.fail("Enum type as attribute is not supported", lvalue) + return False + # Yes, it's a valid Enum definition. Add it to the symbol table. + self.api.add_symbol(name, enum_call, s) + return True + + def check_enum_call( + self, node: Expression, var_name: str, is_func_scope: bool + ) -> TypeInfo | None: + """Check if a call defines an Enum. + + Example: + + A = enum.Enum('A', 'foo bar') + + is equivalent to: + + class A(enum.Enum): + foo = 1 + bar = 2 + """ + if not isinstance(node, CallExpr): + return None + call = node + callee = call.callee + if not isinstance(callee, RefExpr): + return None + fullname = callee.fullname + if fullname not in ENUM_BASES: + return None + + new_class_name, items, values, ok = self.parse_enum_call_args( + call, fullname.split(".")[-1] + ) + if not ok: + # Error. Construct dummy return value. + name = var_name + if is_func_scope: + name += "@" + str(call.line) + info = self.build_enum_call_typeinfo(name, [], fullname, node.line) + else: + if new_class_name != var_name: + msg = f'String argument 1 "{new_class_name}" to {fullname}(...) does not match variable name "{var_name}"' + self.fail(msg, call) + + name = cast(StrExpr, call.args[0]).value + if name != var_name or is_func_scope: + # Give it a unique name derived from the line number. + name += "@" + str(call.line) + info = self.build_enum_call_typeinfo(name, items, fullname, call.line) + # Store generated TypeInfo under both names, see semanal_namedtuple for more details. + if name != var_name or is_func_scope: + self.api.add_symbol_skip_local(name, info) + call.analyzed = EnumCallExpr(info, items, values) + call.analyzed.set_line(call) + info.line = node.line + return info + + def build_enum_call_typeinfo( + self, name: str, items: list[str], fullname: str, line: int + ) -> TypeInfo: + base = self.api.named_type_or_none(fullname) + assert base is not None + info = self.api.basic_new_typeinfo(name, base, line) + info.metaclass_type = info.calculate_metaclass_type() + info.is_enum = True + for item in items: + var = Var(item) + var.info = info + var.is_property = True + # When an enum is created by its functional form `Enum(name, values)` + # - if it is a string it is first split by commas/whitespace + # - if it is an iterable of single items each item is assigned a value starting at `start` + # - if it is an iterable of (name, value) then the given values will be used + # either way, each item should be treated as if it has an explicit value. + var.has_explicit_value = True + var._fullname = f"{info.fullname}.{item}" + info.names[item] = SymbolTableNode(MDEF, var) + return info + + def parse_enum_call_args( + self, call: CallExpr, class_name: str + ) -> tuple[str, list[str], list[Expression | None], bool]: + """Parse arguments of an Enum call. + + Return a tuple of fields, values, was there an error. + """ + args = call.args + if not all(arg_kind in [ARG_POS, ARG_NAMED] for arg_kind in call.arg_kinds): + return self.fail_enum_call_arg(f"Unexpected arguments to {class_name}()", call) + if len(args) < 2: + return self.fail_enum_call_arg(f"Too few arguments for {class_name}()", call) + if len(args) > 6: + return self.fail_enum_call_arg(f"Too many arguments for {class_name}()", call) + valid_name = [None, "value", "names", "module", "qualname", "type", "start"] + for arg_name in call.arg_names: + if arg_name not in valid_name: + self.fail_enum_call_arg(f'Unexpected keyword argument "{arg_name}"', call) + value, names = None, None + for arg_name, arg in zip(call.arg_names, args): + if arg_name == "value": + value = arg + if arg_name == "names": + names = arg + if value is None: + value = args[0] + if names is None: + names = args[1] + if not isinstance(value, StrExpr): + return self.fail_enum_call_arg( + f"{class_name}() expects a string literal as the first argument", call + ) + new_class_name = value.value + + items = [] + values: list[Expression | None] = [] + if isinstance(names, StrExpr): + fields = names.value + for field in fields.replace(",", " ").split(): + items.append(field) + elif isinstance(names, (TupleExpr, ListExpr)): + seq_items = names.items + if is_StrExpr_list(seq_items): + items = [seq_item.value for seq_item in seq_items] + elif all( + isinstance(seq_item, (TupleExpr, ListExpr)) + and len(seq_item.items) == 2 + and isinstance(seq_item.items[0], StrExpr) + for seq_item in seq_items + ): + for seq_item in seq_items: + assert isinstance(seq_item, (TupleExpr, ListExpr)) + name, value = seq_item.items + assert isinstance(name, StrExpr) + items.append(name.value) + values.append(value) + else: + return self.fail_enum_call_arg( + "%s() with tuple or list expects strings or (name, value) pairs" % class_name, + call, + ) + elif isinstance(names, DictExpr): + for key, value in names.items: + if not isinstance(key, StrExpr): + return self.fail_enum_call_arg( + f"{class_name}() with dict literal requires string literals", call + ) + items.append(key.value) + values.append(value) + elif isinstance(args[1], RefExpr) and isinstance(args[1].node, Var): + proper_type = get_proper_type(args[1].node.type) + if ( + proper_type is not None + and isinstance(proper_type, LiteralType) + and isinstance(proper_type.value, str) + ): + fields = proper_type.value + for field in fields.replace(",", " ").split(): + items.append(field) + elif args[1].node.is_final and isinstance(args[1].node.final_value, str): + fields = args[1].node.final_value + for field in fields.replace(",", " ").split(): + items.append(field) + else: + return self.fail_enum_call_arg( + "Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members" + % class_name, + call, + ) + else: + # TODO: Allow dict(x=1, y=2) as a substitute for {'x': 1, 'y': 2}? + return self.fail_enum_call_arg( + "Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members" + % class_name, + call, + ) + if not items: + return self.fail_enum_call_arg(f"{class_name}() needs at least one item", call) + if not values: + values = [None] * len(items) + assert len(items) == len(values) + return new_class_name, items, values, True + + def fail_enum_call_arg( + self, message: str, context: Context + ) -> tuple[str, list[str], list[Expression | None], bool]: + self.fail(message, context) + return "", [], [], False + + # Helpers + + def fail(self, msg: str, ctx: Context) -> None: + self.api.fail(msg, ctx) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_infer.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_infer.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..928c14fe2661cf07bb558c94a71f5816d7758875 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_infer.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_infer.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_infer.py new file mode 100644 index 0000000000000000000000000000000000000000..89a073cdad473d89ebd3dff23321c91c2c3443d5 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_infer.py @@ -0,0 +1,131 @@ +"""Simple type inference for decorated functions during semantic analysis.""" + +from __future__ import annotations + +from mypy.nodes import ARG_POS, CallExpr, Decorator, Expression, FuncDef, RefExpr, Var +from mypy.semanal_shared import SemanticAnalyzerInterface +from mypy.typeops import function_type +from mypy.types import ( + AnyType, + CallableType, + ProperType, + Type, + TypeOfAny, + TypeVarType, + get_proper_type, +) +from mypy.typevars import has_no_typevars + + +def infer_decorator_signature_if_simple( + dec: Decorator, analyzer: SemanticAnalyzerInterface +) -> None: + """Try to infer the type of the decorated function. + + This lets us resolve additional references to decorated functions + during type checking. Otherwise the type might not be available + when we need it, since module top levels can't be deferred. + + This basically uses a simple special-purpose type inference + engine just for decorators. + """ + if dec.var.is_property: + # Decorators are expected to have a callable type (it's a little odd). + # TODO: this may result in wrong type if @property is applied to decorated method. + if dec.func.type is None: + dec.var.type = CallableType( + [AnyType(TypeOfAny.special_form)], + [ARG_POS], + [None], + AnyType(TypeOfAny.special_form), + analyzer.named_type("builtins.function"), + name=dec.var.name, + ) + elif isinstance(dec.func.type, CallableType): + dec.var.type = dec.func.type + return + decorator_preserves_type = True + for expr in dec.decorators: + preserve_type = False + if isinstance(expr, RefExpr) and isinstance(expr.node, FuncDef): + if expr.fullname == "typing.no_type_check": + return + if expr.node.type and is_identity_signature(expr.node.type): + preserve_type = True + if not preserve_type: + decorator_preserves_type = False + break + if decorator_preserves_type: + # No non-identity decorators left. We can trivially infer the type + # of the function here. + dec.var.type = function_type(dec.func, analyzer.named_type("builtins.function")) + if dec.decorators: + return_type = calculate_return_type(dec.decorators[0]) + if return_type and isinstance(return_type, AnyType): + # The outermost decorator will return Any so we know the type of the + # decorated function. + dec.var.type = AnyType(TypeOfAny.from_another_any, source_any=return_type) + sig = find_fixed_callable_return(dec.decorators[0]) + if sig: + # The outermost decorator always returns the same kind of function, + # so we know that this is the type of the decorated function. + orig_sig = function_type(dec.func, analyzer.named_type("builtins.function")) + sig.name = orig_sig.items[0].name + dec.var.type = sig + + +def is_identity_signature(sig: Type) -> bool: + """Is type a callable of form T -> T (where T is a type variable)?""" + sig = get_proper_type(sig) + if isinstance(sig, CallableType) and sig.arg_kinds == [ARG_POS]: + if isinstance(sig.arg_types[0], TypeVarType) and isinstance(sig.ret_type, TypeVarType): + return sig.arg_types[0].id == sig.ret_type.id + return False + + +def calculate_return_type(expr: Expression) -> ProperType | None: + """Return the return type if we can calculate it. + + This only uses information available during semantic analysis so this + will sometimes return None because of insufficient information (as + type inference hasn't run yet). + """ + if isinstance(expr, RefExpr): + if isinstance(expr.node, FuncDef): + typ = expr.node.type + if typ is None: + # No signature -> default to Any. + return AnyType(TypeOfAny.unannotated) + # Explicit Any return? + if isinstance(typ, CallableType): + return get_proper_type(typ.ret_type) + return None + elif isinstance(expr.node, Var): + return get_proper_type(expr.node.type) + elif isinstance(expr, CallExpr): + return calculate_return_type(expr.callee) + return None + + +def find_fixed_callable_return(expr: Expression) -> CallableType | None: + """Return the return type, if expression refers to a callable that returns a callable. + + But only do this if the return type has no type variables. Return None otherwise. + This approximates things a lot as this is supposed to be called before type checking + when full type information is not available yet. + """ + if isinstance(expr, RefExpr): + if isinstance(expr.node, FuncDef): + typ = expr.node.type + if typ: + if isinstance(typ, CallableType) and has_no_typevars(typ.ret_type): + ret_type = get_proper_type(typ.ret_type) + if isinstance(ret_type, CallableType): + return ret_type + elif isinstance(expr, CallExpr): + t = find_fixed_callable_return(expr.callee) + if t: + ret_type = get_proper_type(t.ret_type) + if isinstance(ret_type, CallableType): + return ret_type + return None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_main.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_main.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..eef4334ecc8c91465bc1e84e81aa9641029d2495 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_main.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_main.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_main.py new file mode 100644 index 0000000000000000000000000000000000000000..edc6ee4143f292e3fe2c09c357422effb0178421 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_main.py @@ -0,0 +1,538 @@ +"""Top-level logic for the semantic analyzer. + +The semantic analyzer binds names, resolves imports, detects various +special constructs that don't have dedicated AST nodes after parse +(such as 'cast' which looks like a call), populates symbol tables, and +performs various simple consistency checks. + +Semantic analysis of each SCC (strongly connected component; import +cycle) is performed in one unit. Each module is analyzed as multiple +separate *targets*; the module top level is one target and each function +is a target. Nested functions are not separate targets, however. This is +mostly identical to targets used by mypy daemon (but classes aren't +targets in semantic analysis). + +We first analyze each module top level in an SCC. If we encounter some +names that we can't bind because the target of the name may not have +been processed yet, we *defer* the current target for further +processing. Deferred targets will be analyzed additional times until +everything can be bound, or we reach a maximum number of iterations. + +We keep track of a set of incomplete namespaces, i.e. namespaces that we +haven't finished populating yet. References to these namespaces cause a +deferral if they can't be satisfied. Initially every module in the SCC +will be incomplete. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from contextlib import nullcontext +from itertools import groupby +from typing import TYPE_CHECKING, Final, TypeAlias as _TypeAlias + +import mypy.state +from mypy.checker import FineGrainedDeferredNode +from mypy.errors import Errors +from mypy.nodes import Decorator, FuncDef, MypyFile, OverloadedFuncDef, TypeInfo +from mypy.options import Options +from mypy.plugin import ClassDefContext +from mypy.plugins import dataclasses as dataclasses_plugin +from mypy.semanal import ( + SemanticAnalyzer, + apply_semantic_analyzer_patches, + remove_imported_names_from_symtable, +) +from mypy.semanal_classprop import ( + add_type_promotion, + calculate_class_abstract_status, + calculate_class_vars, + check_protocol_status, +) +from mypy.semanal_infer import infer_decorator_signature_if_simple +from mypy.semanal_shared import find_dataclass_transform_spec +from mypy.semanal_typeargs import TypeArgumentAnalyzer + +if TYPE_CHECKING: + from mypy.build import Graph, State + + +Patches: _TypeAlias = list[tuple[int, Callable[[], None]]] + + +# If we perform this many iterations, raise an exception since we are likely stuck. +MAX_ITERATIONS: Final = 20 + + +# Number of passes over core modules before going on to the rest of the builtin SCC. +CORE_WARMUP: Final = 2 +core_modules: Final = [ + "typing", + "_collections_abc", + "builtins", + "abc", + "collections", + "collections.abc", +] + + +def semantic_analysis_for_scc(graph: Graph, scc: list[str], errors: Errors) -> None: + """Perform semantic analysis for all modules in a SCC (import cycle). + + Assume that reachability analysis has already been performed. + + The scc will be processed roughly in the order the modules are included + in the list. + """ + patches: Patches = [] + # Note that functions can't define new module-level attributes + # using 'global x', since module top levels are fully processed + # before functions. This limitation is unlikely to go away soon. + process_top_levels(graph, scc, patches) + process_functions(graph, scc, patches) + # We use patch callbacks to fix up things when we expect relatively few + # callbacks to be required. + apply_semantic_analyzer_patches(patches) + # Run class decorator hooks (they requite complete MROs and no placeholders). + apply_class_plugin_hooks(graph, scc, errors) + # This pass might need fallbacks calculated above and the results of hooks. + check_type_arguments(graph, scc, errors) + calculate_class_properties(graph, scc, errors) + check_blockers(graph, scc) + # Clean-up builtins, so that TypeVar etc. are not accessible without importing. + if "builtins" in scc: + cleanup_builtin_scc(graph["builtins"]) + + # Report TypeForm profiling stats + if len(scc) >= 1: + # Get manager from any state in the SCC (they all share the same manager) + manager = graph[scc[0]].manager + analyzer = manager.semantic_analyzer + manager.add_stats( + type_expression_parse_count=analyzer.type_expression_parse_count, + type_expression_full_parse_success_count=analyzer.type_expression_full_parse_success_count, + type_expression_full_parse_failure_count=analyzer.type_expression_full_parse_failure_count, + ) + + +def cleanup_builtin_scc(state: State) -> None: + """Remove imported names from builtins namespace. + + This way names imported from typing in builtins.pyi aren't available + by default (without importing them). We can only do this after processing + the whole SCC is finished, when the imported names aren't needed for + processing builtins.pyi itself. + """ + assert state.tree is not None + remove_imported_names_from_symtable(state.tree.names, "builtins") + + +def semantic_analysis_for_targets( + state: State, nodes: list[FineGrainedDeferredNode], graph: Graph +) -> None: + """Semantically analyze only selected nodes in a given module. + + This essentially mirrors the logic of semantic_analysis_for_scc() + except that we process only some targets. This is used in fine-grained + incremental mode, when propagating an update. + """ + patches: Patches = [] + if any(isinstance(n.node, MypyFile) for n in nodes): + # Process module top level first (if needed). + process_top_levels(graph, [state.id], patches) + analyzer = state.manager.semantic_analyzer + for n in nodes: + if isinstance(n.node, MypyFile): + # Already done above. + continue + process_top_level_function( + analyzer, state, state.id, n.node.fullname, n.node, n.active_typeinfo, patches + ) + apply_semantic_analyzer_patches(patches) + apply_class_plugin_hooks(graph, [state.id], state.manager.errors) + check_type_arguments_in_targets(nodes, state, state.manager.errors) + calculate_class_properties(graph, [state.id], state.manager.errors) + + +def process_top_levels(graph: Graph, scc: list[str], patches: Patches) -> None: + # Process top levels until everything has been bound. + + # Reverse order of the scc so the first modules in the original list will be + # be processed first. This helps with performance. + scc = list(reversed(scc)) # noqa: FURB187 intentional copy + + # Initialize ASTs and symbol tables. + for id in scc: + state = graph[id] + assert state.tree is not None + state.manager.semantic_analyzer.prepare_file(state.tree) + + # Initially all namespaces in the SCC are incomplete (well they are empty). + state.manager.incomplete_namespaces.update(scc) + + worklist = scc.copy() + # HACK: process core stuff first. This is mostly needed to support defining + # named tuples in builtin SCC. + if all(m in worklist for m in core_modules): + worklist += list(reversed(core_modules)) * CORE_WARMUP + final_iteration = False + iteration = 0 + analyzer = state.manager.semantic_analyzer + analyzer.deferral_debug_context.clear() + + while worklist: + iteration += 1 + if iteration > MAX_ITERATIONS: + # Just pick some module inside the current SCC for error context. + assert state.tree is not None + with analyzer.file_context(state.tree, state.options): + analyzer.report_hang() + break + if final_iteration: + # Give up. It's impossible to bind all names. + state.manager.incomplete_namespaces.clear() + all_deferred: list[str] = [] + any_progress = False + while worklist: + next_id = worklist.pop() + state = graph[next_id] + assert state.tree is not None + deferred, incomplete, progress = semantic_analyze_target( + next_id, next_id, state, state.tree, None, final_iteration, patches + ) + all_deferred += deferred + any_progress = any_progress or progress + if not incomplete: + state.manager.incomplete_namespaces.discard(next_id) + if final_iteration: + assert not all_deferred, "Must not defer during final iteration" + # Reverse to process the targets in the same order on every iteration. This avoids + # processing the same target twice in a row, which is inefficient. + worklist = list(reversed(all_deferred)) + final_iteration = not any_progress + # Functions/methods that define/infer attributes are processed as part of top-levels. + # We need to clear the locals for those between fine-grained iterations. + analyzer.saved_locals.clear() + + +def order_by_subclassing(targets: list[FullTargetInfo]) -> Iterator[FullTargetInfo]: + """Make sure that superclass methods are always processed before subclass methods. + + This algorithm is not very optimal, but it is simple and should work well for lists + that are already almost correctly ordered. + """ + + # First, group the targets by their TypeInfo (since targets are sorted by line, + # we know that each TypeInfo will appear as group key only once). + grouped = [(k, list(g)) for k, g in groupby(targets, key=lambda x: x[3])] + remaining_infos = {info for info, _ in grouped if info is not None} + + next_group = 0 + while grouped: + if next_group >= len(grouped): + # This should never happen, if there is an MRO cycle, it should be reported + # and fixed during top-level processing. + raise ValueError("Cannot order method targets by MRO") + next_info, group = grouped[next_group] + if next_info is None: + # Trivial case, not methods but functions, process them straight away. + yield from group + grouped.pop(next_group) + continue + if any(parent in remaining_infos for parent in next_info.mro[1:]): + # We cannot process this method group yet, try a next one. + next_group += 1 + continue + yield from group + grouped.pop(next_group) + remaining_infos.discard(next_info) + # Each time after processing a method group we should retry from start, + # since there may be some groups that are not blocked on parents anymore. + next_group = 0 + + +def process_functions(graph: Graph, scc: list[str], patches: Patches) -> None: + # Process functions. + all_targets = [] + for module in scc: + tree = graph[module].tree + assert tree is not None + # In principle, functions can be processed in arbitrary order, + # but _methods_ must be processed in the order they are defined, + # because some features (most notably partial types) depend on + # order of definitions on self. + # + # There can be multiple generated methods per line. Use target + # name as the second sort key to get a repeatable sort order. + targets = sorted(get_all_leaf_targets(tree), key=lambda x: (x[1].line, x[0])) + all_targets.extend( + [(module, target, node, active_type) for target, node, active_type in targets] + ) + + for module, target, node, active_type in order_by_subclassing(all_targets): + analyzer = graph[module].manager.semantic_analyzer + assert isinstance(node, (FuncDef, OverloadedFuncDef, Decorator)), node + process_top_level_function( + analyzer, graph[module], module, target, node, active_type, patches + ) + + +def process_top_level_function( + analyzer: SemanticAnalyzer, + state: State, + module: str, + target: str, + node: FuncDef | OverloadedFuncDef | Decorator, + active_type: TypeInfo | None, + patches: Patches, +) -> None: + """Analyze single top-level function or method. + + Process the body of the function (including nested functions) again and again, + until all names have been resolved (or iteration limit reached). + """ + # We need one more iteration after incomplete is False (e.g. to report errors, if any). + final_iteration = False + incomplete = True + # Start in the incomplete state (no missing names will be reported on first pass). + # Note that we use module name, since functions don't create qualified names. + deferred = [module] + analyzer.deferral_debug_context.clear() + analyzer.incomplete_namespaces.add(module) + iteration = 0 + while deferred: + iteration += 1 + if iteration == MAX_ITERATIONS: + # Just pick some module inside the current SCC for error context. + assert state.tree is not None + with analyzer.file_context(state.tree, state.options): + analyzer.report_hang() + break + if not (deferred or incomplete) or final_iteration: + # OK, this is one last pass, now missing names will be reported. + analyzer.incomplete_namespaces.discard(module) + deferred, incomplete, progress = semantic_analyze_target( + target, module, state, node, active_type, final_iteration, patches + ) + if not incomplete: + state.manager.incomplete_namespaces.discard(module) + if final_iteration: + assert not deferred, "Must not defer during final iteration" + if not progress: + final_iteration = True + + analyzer.incomplete_namespaces.discard(module) + # After semantic analysis is done, discard local namespaces + # to avoid memory hoarding. + analyzer.saved_locals.clear() + + +TargetInfo: _TypeAlias = tuple[ + str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None +] + +# Same as above but includes module as first item. +FullTargetInfo: _TypeAlias = tuple[ + str, str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None +] + + +def get_all_leaf_targets(file: MypyFile) -> list[TargetInfo]: + """Return all leaf targets in a symbol table (module-level and methods).""" + result: list[TargetInfo] = [] + for fullname, node, active_type in file.local_definitions(): + if isinstance(node.node, (FuncDef, OverloadedFuncDef, Decorator)): + result.append((fullname, node.node, active_type)) + return result + + +def semantic_analyze_target( + target: str, + module: str, + state: State, + node: MypyFile | FuncDef | OverloadedFuncDef | Decorator, + active_type: TypeInfo | None, + final_iteration: bool, + patches: Patches, +) -> tuple[list[str], bool, bool]: + """Semantically analyze a single target. + + Return tuple with these items: + - list of deferred targets + - was some definition incomplete (need to run another pass) + - were any new names defined (or placeholders replaced) + """ + state.manager.processed_targets.append((module, target)) + tree = state.tree + assert tree is not None + analyzer = state.manager.semantic_analyzer + # TODO: Move initialization to somewhere else + analyzer.global_decls = [set()] + analyzer.nonlocal_decls = [set()] + analyzer.globals = tree.names + analyzer.imports = set() + analyzer.progress = False + with state.wrap_context(check_blockers=False): + refresh_node = node + if isinstance(refresh_node, Decorator): + # Decorator expressions will be processed as part of the module top level. + refresh_node = refresh_node.func + analyzer.refresh_partial( + refresh_node, + patches, + final_iteration, + file_node=tree, + options=state.options, + active_type=active_type, + ) + if isinstance(node, Decorator): + infer_decorator_signature_if_simple(node, analyzer) + + # Clear out some stale data to avoid memory leaks and astmerge + # validity check confusion + analyzer.statement = None + del analyzer.cur_mod_node + + if analyzer.deferred: + return [target], analyzer.incomplete, analyzer.progress + else: + return [], analyzer.incomplete, analyzer.progress + + +def check_type_arguments(graph: Graph, scc: list[str], errors: Errors) -> None: + for module in scc: + state = graph[module] + assert state.tree + analyzer = TypeArgumentAnalyzer( + errors, + state.options, + state.tree.is_typeshed_file(state.options), + state.manager.semantic_analyzer.named_type, + ) + with state.wrap_context(): + with mypy.state.state.strict_optional_set(state.options.strict_optional): + state.tree.accept(analyzer) + + +def check_type_arguments_in_targets( + targets: list[FineGrainedDeferredNode], state: State, errors: Errors +) -> None: + """Check type arguments against type variable bounds and restrictions. + + This mirrors the logic in check_type_arguments() except that we process only + some targets. This is used in fine grained incremental mode. + """ + assert state.tree + analyzer = TypeArgumentAnalyzer( + errors, + state.options, + state.tree.is_typeshed_file(state.options), + state.manager.semantic_analyzer.named_type, + ) + with state.wrap_context(): + with mypy.state.state.strict_optional_set(state.options.strict_optional): + for target in targets: + func: FuncDef | OverloadedFuncDef | None = None + if isinstance(target.node, (FuncDef, OverloadedFuncDef)): + func = target.node + saved = (state.id, target.active_typeinfo, func) # module, class, function + with errors.scope.saved_scope(saved) if errors.scope else nullcontext(): + analyzer.recurse_into_functions = func is not None + target.node.accept(analyzer) + + +def apply_class_plugin_hooks(graph: Graph, scc: list[str], errors: Errors) -> None: + """Apply class plugin hooks within a SCC. + + We run these after to the main semantic analysis so that the hooks + don't need to deal with incomplete definitions such as placeholder + types. + + Note that some hooks incorrectly run during the main semantic + analysis pass, for historical reasons. + """ + num_passes = 0 + incomplete = True + # If we encounter a base class that has not been processed, we'll run another + # pass. This should eventually reach a fixed point. + while incomplete: + assert num_passes < 10, "Internal error: too many class plugin hook passes" + num_passes += 1 + incomplete = False + for module in scc: + state = graph[module] + tree = state.tree + assert tree + for _, node, _ in tree.local_definitions(): + if isinstance(node.node, TypeInfo): + if not apply_hooks_to_class( + state.manager.semantic_analyzer, + module, + node.node, + state.options, + tree, + errors, + ): + incomplete = True + + +def apply_hooks_to_class( + self: SemanticAnalyzer, + module: str, + info: TypeInfo, + options: Options, + file_node: MypyFile, + errors: Errors, +) -> bool: + # TODO: Move more class-related hooks here? + defn = info.defn + ok = True + for decorator in defn.decorators: + with self.file_context(file_node, options, info): + hook = None + + decorator_name = self.get_fullname_for_hook(decorator) + if decorator_name: + hook = self.plugin.get_class_decorator_hook_2(decorator_name) + # Special case: if the decorator is itself decorated with + # typing.dataclass_transform, apply the hook for the dataclasses plugin + # TODO: remove special casing here + if hook is None and find_dataclass_transform_spec(decorator): + hook = dataclasses_plugin.dataclass_class_maker_callback + + if hook: + ok = ok and hook(ClassDefContext(defn, decorator, self)) + + # Check if the class definition itself triggers a dataclass transform (via a parent class/ + # metaclass) + spec = find_dataclass_transform_spec(info) + if spec is not None: + with self.file_context(file_node, options, info): + # We can't use the normal hook because reason = defn, and ClassDefContext only accepts + # an Expression for reason + ok = ok and dataclasses_plugin.DataclassTransformer(defn, defn, spec, self).transform() + + return ok + + +def calculate_class_properties(graph: Graph, scc: list[str], errors: Errors) -> None: + builtins = graph["builtins"].tree + assert builtins + for module in scc: + state = graph[module] + tree = state.tree + assert tree + for _, node, _ in tree.local_definitions(): + if isinstance(node.node, TypeInfo): + with state.manager.semantic_analyzer.file_context(tree, state.options, node.node): + calculate_class_abstract_status(node.node, tree.is_stub, errors) + check_protocol_status(node.node, errors) + calculate_class_vars(node.node) + add_type_promotion( + node.node, tree.names, graph[module].options, builtins.names + ) + + +def check_blockers(graph: Graph, scc: list[str]) -> None: + for module in scc: + graph[module].check_blockers() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_namedtuple.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_namedtuple.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..09d6dea082cf3f74cd8a332995664d1c20fd1e13 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_namedtuple.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_namedtuple.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_namedtuple.py new file mode 100644 index 0000000000000000000000000000000000000000..9a51bced4885df9c46f2718929f0c1f94ca13478 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_namedtuple.py @@ -0,0 +1,726 @@ +"""Semantic analysis of named tuple definitions. + +This is conceptually part of mypy.semanal. +""" + +from __future__ import annotations + +import keyword +from collections.abc import Container, Iterator, Mapping +from contextlib import contextmanager +from typing import Final, cast + +from mypy.errorcodes import ARG_TYPE, ErrorCode +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.messages import MessageBuilder +from mypy.nodes import ( + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + MDEF, + Argument, + AssignmentStmt, + Block, + CallExpr, + ClassDef, + Context, + Decorator, + EllipsisExpr, + Expression, + ExpressionStmt, + FuncBase, + FuncDef, + ListExpr, + NamedTupleExpr, + NameExpr, + PassStmt, + PlaceholderNode, + RefExpr, + Statement, + StrExpr, + SymbolTable, + SymbolTableNode, + TempNode, + TupleExpr, + TypeInfo, + TypeVarExpr, + Var, + is_StrExpr_list, +) +from mypy.options import Options +from mypy.semanal_shared import ( + PRIORITY_FALLBACKS, + SemanticAnalyzerInterface, + calculate_tuple_fallback, + has_placeholder, + set_callable_name, +) +from mypy.types import ( + TYPED_NAMEDTUPLE_NAMES, + AnyType, + CallableType, + LiteralType, + TupleType, + Type, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarType, + UnboundType, + has_type_vars, +) +from mypy.util import get_unique_redefinition_name + +# Matches "_prohibited" in typing.py, but adds __annotations__, which works at runtime but can't +# easily be supported in a static checker. +NAMEDTUPLE_PROHIBITED_NAMES: Final = ( + "__new__", + "__init__", + "__slots__", + "__getnewargs__", + "_fields", + "_field_defaults", + "_field_types", + "_make", + "_replace", + "_asdict", + "_source", + "__annotations__", +) + +NAMEDTUP_CLASS_ERROR: Final = ( + 'Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"' +) + +SELF_TVAR_NAME: Final = "_NT" + + +class NamedTupleAnalyzer: + def __init__( + self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder + ) -> None: + self.options = options + self.api = api + self.msg = msg + + def analyze_namedtuple_classdef( + self, defn: ClassDef, is_stub_file: bool, is_func_scope: bool + ) -> tuple[bool, TypeInfo | None]: + """Analyze if given class definition can be a named tuple definition. + + Return a tuple where first item indicates whether this can possibly be a named tuple, + and the second item is the corresponding TypeInfo (may be None if not ready and should be + deferred). + """ + for base_expr in defn.base_type_exprs: + if isinstance(base_expr, RefExpr): + self.api.accept(base_expr) + if base_expr.fullname in TYPED_NAMEDTUPLE_NAMES: + result = self.check_namedtuple_classdef(defn, is_stub_file) + if result is None: + # This is a valid named tuple, but some types are incomplete. + return True, None + items, types, default_items, statements = result + if is_func_scope and "@" not in defn.name: + defn.name += "@" + str(defn.line) + existing_info = None + if isinstance(defn.analyzed, NamedTupleExpr): + existing_info = defn.analyzed.info + info = self.build_namedtuple_typeinfo( + defn.name, items, types, default_items, defn.line, existing_info + ) + defn.analyzed = NamedTupleExpr(info, is_typed=True) + defn.analyzed.line = defn.line + defn.analyzed.column = defn.column + defn.defs.body = statements + # All done: this is a valid named tuple with all types known. + return True, info + # This can't be a valid named tuple. + return False, None + + def check_namedtuple_classdef( + self, defn: ClassDef, is_stub_file: bool + ) -> tuple[list[str], list[Type], dict[str, Expression], list[Statement]] | None: + """Parse and validate fields in named tuple class definition. + + Return a four tuple: + * field names + * field types + * field default values + * valid statements + or None, if any of the types are not ready. + """ + if len(defn.base_type_exprs) > 1: + self.fail("NamedTuple should be a single base", defn) + items: list[str] = [] + types: list[Type] = [] + default_items: dict[str, Expression] = {} + statements: list[Statement] = [] + for stmt in defn.defs.body: + statements.append(stmt) + if not isinstance(stmt, AssignmentStmt): + # Still allow pass or ... (for empty namedtuples). + if isinstance(stmt, PassStmt) or ( + isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr) + ): + continue + # Also allow methods, including decorated ones. + if isinstance(stmt, (Decorator, FuncBase)): + continue + # And docstrings. + if isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr): + continue + statements.pop() + defn.removed_statements.append(stmt) + self.fail(NAMEDTUP_CLASS_ERROR, stmt) + elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr): + # An assignment, but an invalid one. + statements.pop() + defn.removed_statements.append(stmt) + self.fail(NAMEDTUP_CLASS_ERROR, stmt) + else: + # Append name and type in this case... + name = stmt.lvalues[0].name + items.append(name) + if stmt.type is None: + types.append(AnyType(TypeOfAny.unannotated)) + else: + # We never allow recursive types at function scope. Although it is + # possible to support this for named tuples, it is still tricky, and + # it would be inconsistent with type aliases. + analyzed = self.api.anal_type( + stmt.type, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="NamedTuple item type", + prohibit_special_class_field_types="NamedTuple", + ) + if analyzed is None: + # Something is incomplete. We need to defer this named tuple. + return None + types.append(analyzed) + # ...despite possible minor failures that allow further analysis. + if name.startswith("_"): + self.fail( + f"NamedTuple field name cannot start with an underscore: {name}", stmt + ) + if stmt.type is None or hasattr(stmt, "new_syntax") and not stmt.new_syntax: + self.fail(NAMEDTUP_CLASS_ERROR, stmt) + elif isinstance(stmt.rvalue, TempNode): + # x: int assigns rvalue to TempNode(AnyType()) + if default_items: + self.fail( + "Non-default NamedTuple fields cannot follow default fields", stmt + ) + else: + default_items[name] = stmt.rvalue + if defn.keywords: + for_function = ' for "__init_subclass__" of "NamedTuple"' + for key in defn.keywords: + self.msg.unexpected_keyword_argument_for_function(for_function, key, defn) + return items, types, default_items, statements + + def check_namedtuple( + self, node: Expression, var_name: str | None, is_func_scope: bool + ) -> tuple[str | None, TypeInfo | None, list[TypeVarLikeType]]: + """Check if a call defines a namedtuple. + + The optional var_name argument is the name of the variable to + which this is assigned, if any. + + Return a tuple of two items: + * Internal name of the named tuple (e.g. the name passed as an argument to namedtuple) + or None if it is not a valid named tuple + * Corresponding TypeInfo, or None if not ready. + + If the definition is invalid but looks like a namedtuple, + report errors but return (some) TypeInfo. + """ + if not isinstance(node, CallExpr): + return None, None, [] + call = node + callee = call.callee + if not isinstance(callee, RefExpr): + return None, None, [] + fullname = callee.fullname + if fullname == "collections.namedtuple": + is_typed = False + elif fullname in TYPED_NAMEDTUPLE_NAMES: + is_typed = True + else: + return None, None, [] + result = self.parse_namedtuple_args(call, fullname) + if result: + items, types, defaults, typename, tvar_defs, ok = result + else: + # Error. Construct dummy return value. + if var_name: + name = var_name + if is_func_scope: + name += "@" + str(call.line) + else: + name = var_name = "namedtuple@" + str(call.line) + info = self.build_namedtuple_typeinfo(name, [], [], {}, node.line, None) + self.store_namedtuple_info(info, var_name, call, is_typed) + if name != var_name or is_func_scope: + # NOTE: we skip local namespaces since they are not serialized. + self.api.add_symbol_skip_local(name, info) + return var_name, info, [] + if not ok: + # This is a valid named tuple but some types are not ready. + return typename, None, [] + + # We use the variable name as the class name if it exists. If + # it doesn't, we use the name passed as an argument. We prefer + # the variable name because it should be unique inside a + # module, and so we don't need to disambiguate it with a line + # number. + if var_name: + name = var_name + else: + name = typename + + if var_name is None or is_func_scope: + # There are two special cases where need to give it a unique name derived + # from the line number: + # * This is a base class expression, since it often matches the class name: + # class NT(NamedTuple('NT', [...])): + # ... + # * This is a local (function or method level) named tuple, since + # two methods of a class can define a named tuple with the same name, + # and they will be stored in the same namespace (see below). + name += "@" + str(call.line) + if defaults: + default_items = { + arg_name: default for arg_name, default in zip(items[-len(defaults) :], defaults) + } + else: + default_items = {} + + existing_info = None + if isinstance(node.analyzed, NamedTupleExpr): + existing_info = node.analyzed.info + info = self.build_namedtuple_typeinfo( + name, items, types, default_items, node.line, existing_info + ) + + # If var_name is not None (i.e. this is not a base class expression), we always + # store the generated TypeInfo under var_name in the current scope, so that + # other definitions can use it. + if var_name: + self.store_namedtuple_info(info, var_name, call, is_typed) + else: + call.analyzed = NamedTupleExpr(info, is_typed=is_typed) + call.analyzed.set_line(call) + # There are three cases where we need to store the generated TypeInfo + # second time (for the purpose of serialization): + # * If there is a name mismatch like One = NamedTuple('Other', [...]) + # we also store the info under name 'Other@lineno', this is needed + # because classes are (de)serialized using their actual fullname, not + # the name of l.h.s. + # * If this is a method level named tuple. It can leak from the method + # via assignment to self attribute and therefore needs to be serialized + # (local namespaces are not serialized). + # * If it is a base class expression. It was not stored above, since + # there is no var_name (but it still needs to be serialized + # since it is in MRO of some class). + if name != var_name or is_func_scope: + # NOTE: we skip local namespaces since they are not serialized. + self.api.add_symbol_skip_local(name, info) + return typename, info, tvar_defs + + def store_namedtuple_info( + self, info: TypeInfo, name: str, call: CallExpr, is_typed: bool + ) -> None: + self.api.add_symbol(name, info, call) + call.analyzed = NamedTupleExpr(info, is_typed=is_typed) + call.analyzed.set_line(call) + + def parse_namedtuple_args( + self, call: CallExpr, fullname: str + ) -> None | (tuple[list[str], list[Type], list[Expression], str, list[TypeVarLikeType], bool]): + """Parse a namedtuple() call into data needed to construct a type. + + Returns a 6-tuple: + - List of argument names + - List of argument types + - List of default values + - First argument of namedtuple + - All typevars found in the field definition + - Whether all types are ready. + + Return None if the definition didn't typecheck. + """ + type_name = "NamedTuple" if fullname in TYPED_NAMEDTUPLE_NAMES else "namedtuple" + # TODO: Share code with check_argument_count in checkexpr.py? + args = call.args + if len(args) < 2: + self.fail(f'Too few arguments for "{type_name}()"', call) + return None + defaults: list[Expression] = [] + rename = False + if len(args) > 2: + # Typed namedtuple doesn't support additional arguments. + if fullname in TYPED_NAMEDTUPLE_NAMES: + self.fail('Too many arguments for "NamedTuple()"', call) + return None + for i, arg_name in enumerate(call.arg_names[2:], 2): + if arg_name == "defaults": + arg = args[i] + # We don't care what the values are, as long as the argument is an iterable + # and we can count how many defaults there are. + if isinstance(arg, (ListExpr, TupleExpr)): + defaults = list(arg.items) + else: + self.fail( + "List or tuple literal expected as the defaults argument to " + "{}()".format(type_name), + arg, + ) + elif arg_name == "rename": + arg = args[i] + if isinstance(arg, NameExpr) and arg.name in ("True", "False"): + rename = arg.name == "True" + else: + self.fail( + f'Boolean literal expected as the "rename" argument to {type_name}()', + arg, + code=ARG_TYPE, + ) + if call.arg_kinds[:2] != [ARG_POS, ARG_POS]: + self.fail(f'Unexpected arguments to "{type_name}()"', call) + return None + if not isinstance(args[0], StrExpr): + self.fail(f'"{type_name}()" expects a string literal as the first argument', call) + return None + typename = args[0].value + types: list[Type] = [] + tvar_defs = [] + if not isinstance(args[1], (ListExpr, TupleExpr)): + if fullname == "collections.namedtuple" and isinstance(args[1], StrExpr): + str_expr = args[1] + items = str_expr.value.replace(",", " ").split() + else: + self.fail( + 'List or tuple literal expected as the second argument to "{}()"'.format( + type_name + ), + call, + ) + return None + else: + listexpr = args[1] + if fullname == "collections.namedtuple": + # The fields argument contains just names, with implicit Any types. + if not is_StrExpr_list(listexpr.items): + self.fail('String literal expected as "namedtuple()" item', call) + return None + items = [item.value for item in listexpr.items] + else: + type_exprs = [ + t.items[1] + for t in listexpr.items + if isinstance(t, TupleExpr) and len(t.items) == 2 + ] + tvar_defs = self.api.get_and_bind_all_tvars(type_exprs) + # The fields argument contains (name, type) tuples. + result = self.parse_namedtuple_fields_with_types(listexpr.items, call) + if result is None: + # One of the types is not ready, defer. + return None + items, types, _, ok = result + if not ok: + return [], [], [], typename, [], False + if not types: + types = [AnyType(TypeOfAny.unannotated) for _ in items] + processed_items = [] + seen_names: set[str] = set() + for i, item in enumerate(items): + problem = self.check_namedtuple_field_name(item, seen_names) + if problem is None: + processed_items.append(item) + seen_names.add(item) + else: + if not rename: + self.fail(f'"{type_name}()" {problem}', call) + # Even if rename=False, we pretend that it is True. + # At runtime namedtuple creation would throw an error; + # applying the rename logic means we create a more sensible + # namedtuple. + new_name = f"_{i}" + processed_items.append(new_name) + seen_names.add(new_name) + + if len(defaults) > len(items): + self.fail(f'Too many defaults given in call to "{type_name}()"', call) + defaults = defaults[: len(items)] + return processed_items, types, defaults, typename, tvar_defs, True + + def parse_namedtuple_fields_with_types( + self, nodes: list[Expression], context: Context + ) -> tuple[list[str], list[Type], list[Expression], bool] | None: + """Parse typed named tuple fields. + + Return (names, types, defaults, whether types are all ready), or None if error occurred. + """ + items: list[str] = [] + types: list[Type] = [] + for item in nodes: + if isinstance(item, TupleExpr): + if len(item.items) != 2: + self.fail('Invalid "NamedTuple()" field definition', item) + return None + name, type_node = item.items + if isinstance(name, StrExpr): + items.append(name.value) + else: + self.fail('Invalid "NamedTuple()" field name', item) + return None + try: + type = expr_to_unanalyzed_type(type_node, self.options, self.api.is_stub_file) + except TypeTranslationError: + self.fail("Invalid field type", type_node) + return None + # We never allow recursive types at function scope. + analyzed = self.api.anal_type( + type, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="NamedTuple item type", + prohibit_special_class_field_types="NamedTuple", + ) + # Workaround #4987 and avoid introducing a bogus UnboundType + if isinstance(analyzed, UnboundType): + analyzed = AnyType(TypeOfAny.from_error) + # These should be all known, otherwise we would defer in visit_assignment_stmt(). + if analyzed is None: + return [], [], [], False + types.append(analyzed) + else: + self.fail('Tuple expected as "NamedTuple()" field', item) + return None + return items, types, [], True + + def build_namedtuple_typeinfo( + self, + name: str, + items: list[str], + types: list[Type], + default_items: Mapping[str, Expression], + line: int, + existing_info: TypeInfo | None, + ) -> TypeInfo: + strtype = self.api.named_type("builtins.str") + implicit_any = AnyType(TypeOfAny.special_form) + basetuple_type = self.api.named_type("builtins.tuple", [implicit_any]) + dictype = self.api.named_type("builtins.dict", [strtype, implicit_any]) + # Actual signature should return OrderedDict[str, Union[types]] + ordereddictype = self.api.named_type("builtins.dict", [strtype, implicit_any]) + fallback = self.api.named_type("builtins.tuple", [implicit_any]) + # Note: actual signature should accept an invariant version of Iterable[UnionType[types]]. + # but it can't be expressed. 'new' and 'len' should be callable types. + iterable_type = self.api.named_type_or_none("typing.Iterable", [implicit_any]) + function_type = self.api.named_type("builtins.function") + + literals: list[Type] = [LiteralType(item, strtype) for item in items] + match_args_type = TupleType(literals, basetuple_type) + + info = existing_info or self.api.basic_new_typeinfo(name, fallback, line) + info.is_named_tuple = True + tuple_base = TupleType(types, fallback) + if has_placeholder(tuple_base): + self.api.process_placeholder( + None, "NamedTuple item", info, force_progress=tuple_base != info.tuple_type + ) + info.update_tuple_type(tuple_base) + info.line = line + # For use by mypyc. + info.metadata["namedtuple"] = {"fields": items.copy()} + + # We can't calculate the complete fallback type until after semantic + # analysis, since otherwise base classes might be incomplete. Postpone a + # callback function that patches the fallback. + if not has_placeholder(tuple_base) and not has_type_vars(tuple_base): + self.api.schedule_patch( + PRIORITY_FALLBACKS, lambda: calculate_tuple_fallback(tuple_base) + ) + + def add_field( + var: Var, is_initialized_in_class: bool = False, is_property: bool = False + ) -> None: + var.info = info + var.is_initialized_in_class = is_initialized_in_class + var.is_property = is_property + var._fullname = f"{info.fullname}.{var.name}" + info.names[var.name] = SymbolTableNode(MDEF, var) + + fields = [Var(item, typ) for item, typ in zip(items, types)] + for var in fields: + add_field(var, is_property=True) + # We can't share Vars between fields and method arguments, since they + # have different full names (the latter are normally used as local variables + # in functions, so their full names are set to short names when generated methods + # are analyzed). + vars = [Var(item, typ) for item, typ in zip(items, types)] + + tuple_of_strings = TupleType([strtype for _ in items], basetuple_type) + add_field(Var("_fields", tuple_of_strings), is_initialized_in_class=True) + add_field(Var("_field_types", dictype), is_initialized_in_class=True) + add_field(Var("_field_defaults", dictype), is_initialized_in_class=True) + add_field(Var("_source", strtype), is_initialized_in_class=True) + add_field(Var("__annotations__", ordereddictype), is_initialized_in_class=True) + add_field(Var("__doc__", strtype), is_initialized_in_class=True) + if self.options.python_version >= (3, 10): + add_field(Var("__match_args__", match_args_type), is_initialized_in_class=True) + + assert info.tuple_type is not None # Set by update_tuple_type() above. + shared_self_type = TypeVarType( + name=SELF_TVAR_NAME, + fullname=f"{info.fullname}.{SELF_TVAR_NAME}", + # Namespace is patched per-method below. + id=self.api.tvar_scope.new_unique_func_id(), + values=[], + upper_bound=info.tuple_type, + default=AnyType(TypeOfAny.from_omitted_generics), + ) + + def add_method( + funcname: str, + ret: Type | None, # None means use (patched) self-type + args: list[Argument], + is_classmethod: bool = False, + is_new: bool = False, + ) -> None: + fullname = f"{info.fullname}.{funcname}" + self_type = shared_self_type.copy_modified( + id=TypeVarId(shared_self_type.id.raw_id, namespace=fullname) + ) + if ret is None: + ret = self_type + if is_classmethod or is_new: + first = [Argument(Var("_cls"), TypeType.make_normalized(self_type), None, ARG_POS)] + else: + first = [Argument(Var("_self"), self_type, None, ARG_POS)] + args = first + args + + types = [arg.type_annotation for arg in args] + items = [arg.variable.name for arg in args] + arg_kinds = [arg.kind for arg in args] + assert None not in types + signature = CallableType(cast(list[Type], types), arg_kinds, items, ret, function_type) + signature.variables = (self_type,) + func = FuncDef(funcname, args, Block([])) + func.info = info + func.is_class = is_classmethod + func.type = set_callable_name(signature, func) + func._fullname = fullname + func.line = line + if is_classmethod: + v = Var(funcname, func.type) + v.is_classmethod = True + v.info = info + v._fullname = func._fullname + func.is_decorated = True + dec = Decorator(func, [NameExpr("classmethod")], v) + dec.line = line + sym = SymbolTableNode(MDEF, dec) + else: + sym = SymbolTableNode(MDEF, func) + sym.plugin_generated = True + info.names[funcname] = sym + + add_method( + "_replace", + ret=None, + args=[Argument(var, var.type, EllipsisExpr(), ARG_NAMED_OPT) for var in vars], + ) + if self.options.python_version >= (3, 13): + add_method( + "__replace__", + ret=None, + args=[Argument(var, var.type, EllipsisExpr(), ARG_NAMED_OPT) for var in vars], + ) + + def make_init_arg(var: Var) -> Argument: + default = default_items.get(var.name, None) + kind = ARG_POS if default is None else ARG_OPT + return Argument(var, var.type, default, kind) + + add_method("__new__", ret=None, args=[make_init_arg(var) for var in vars], is_new=True) + add_method("_asdict", args=[], ret=ordereddictype) + add_method( + "_make", + ret=None, + is_classmethod=True, + args=[Argument(Var("iterable", iterable_type), iterable_type, None, ARG_POS)], + ) + + self_tvar_expr = TypeVarExpr( + SELF_TVAR_NAME, + info.fullname + "." + SELF_TVAR_NAME, + [], + info.tuple_type, + AnyType(TypeOfAny.from_omitted_generics), + ) + info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr) + return info + + @contextmanager + def save_namedtuple_body(self, named_tuple_info: TypeInfo) -> Iterator[None]: + """Preserve the generated body of class-based named tuple and then restore it. + + Temporarily clear the names dict so we don't get errors about duplicate names + that were already set in build_namedtuple_typeinfo (we already added the tuple + field names while generating the TypeInfo, and actual duplicates are + already reported). + """ + nt_names = named_tuple_info.names + named_tuple_info.names = SymbolTable() + + yield + + # Make sure we didn't use illegal names, then reset the names in the typeinfo. + for prohibited in NAMEDTUPLE_PROHIBITED_NAMES: + if prohibited in named_tuple_info.names: + if nt_names.get(prohibited) is named_tuple_info.names[prohibited]: + continue + ctx = named_tuple_info.names[prohibited].node + assert ctx is not None + self.fail(f'Cannot overwrite NamedTuple attribute "{prohibited}"', ctx) + + # Restore the names in the original symbol table. This ensures that the symbol + # table contains the field objects created by build_namedtuple_typeinfo. Exclude + # __doc__, which can legally be overwritten by the class. + for key, value in nt_names.items(): + if key in named_tuple_info.names: + if key == "__doc__": + continue + sym = named_tuple_info.names[key] + if isinstance(sym.node, (FuncBase, Decorator)) and not sym.plugin_generated: + # Keep user-defined methods as is. + continue + # Do not retain placeholders - we'll get back here if they cease to + # be placeholders later. If we keep placeholders alive, they may never + # be reached again, making it to cacheable symtable. + if not isinstance(sym.node, PlaceholderNode): + # Keep existing (user-provided) definitions under mangled names, so they + # get semantically analyzed. + r_key = get_unique_redefinition_name(key, named_tuple_info.names) + named_tuple_info.names[r_key] = sym + named_tuple_info.names[key] = value + + # Helpers + + def check_namedtuple_field_name(self, field: str, seen_names: Container[str]) -> str | None: + """Return None for valid fields, a string description for invalid ones.""" + if field in seen_names: + return f'has duplicate field name "{field}"' + elif not field.isidentifier(): + return f'field name "{field}" is not a valid identifier' + elif field.startswith("_"): + return f'field name "{field}" starts with an underscore' + elif keyword.iskeyword(field): + return f'field name "{field}" is a keyword' + return None + + def fail(self, msg: str, ctx: Context, code: ErrorCode | None = None) -> None: + self.api.fail(msg, ctx, code=code) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_newtype.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_newtype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ca9ec454d8703893570ef7e984596341ea04142f Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_newtype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_newtype.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_newtype.py new file mode 100644 index 0000000000000000000000000000000000000000..0c717b5d9a0e74efd0e96cc1b8094cc8c23fd2d6 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_newtype.py @@ -0,0 +1,273 @@ +"""Semantic analysis of NewType definitions. + +This is conceptually part of mypy.semanal (semantic analyzer pass 2). +""" + +from __future__ import annotations + +from mypy import errorcodes as codes +from mypy.errorcodes import ErrorCode +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.messages import MessageBuilder, format_type +from mypy.nodes import ( + ARG_POS, + MDEF, + Argument, + AssignmentStmt, + Block, + CallExpr, + Context, + FuncDef, + NameExpr, + NewTypeExpr, + PlaceholderNode, + RefExpr, + StrExpr, + SymbolTableNode, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.semanal_shared import SemanticAnalyzerInterface, has_placeholder +from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type +from mypy.types import ( + AnyType, + CallableType, + Instance, + NoneType, + PlaceholderType, + TupleType, + Type, + TypeOfAny, + get_proper_type, +) + + +class NewTypeAnalyzer: + def __init__( + self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder + ) -> None: + self.options = options + self.api = api + self.msg = msg + + def process_newtype_declaration(self, s: AssignmentStmt) -> bool: + """Check if s declares a NewType; if yes, store it in symbol table. + + Return True if it's a NewType declaration. The current target may be + deferred as a side effect if the base type is not ready, even if + the return value is True. + + The logic in this function mostly copies the logic for visit_class_def() + with a single (non-Generic) base. + """ + var_name, call = self.analyze_newtype_declaration(s) + if var_name is None or call is None: + return False + name = var_name + # OK, now we know this is a NewType. But the base type may be not ready yet, + # add placeholder as we do for ClassDef. + + if self.api.is_func_scope(): + name += "@" + str(s.line) + fullname = self.api.qualified_name(name) + + if not call.analyzed or isinstance(call.analyzed, NewTypeExpr) and not call.analyzed.info: + # Start from labeling this as a future class, as we do for normal ClassDefs. + placeholder = PlaceholderNode(fullname, s, s.line, becomes_typeinfo=True) + self.api.add_symbol(var_name, placeholder, s, can_defer=False) + + old_type, should_defer = self.check_newtype_args(var_name, call, s) + old_type = get_proper_type(old_type) + if not isinstance(call.analyzed, NewTypeExpr): + call.analyzed = NewTypeExpr(var_name, old_type, line=call.line, column=call.column) + else: + call.analyzed.old_type = old_type + if old_type is None: + if should_defer: + # Base type is not ready. + self.api.defer() + return True + + # Create the corresponding class definition if the aliased type is subtypeable + assert isinstance(call.analyzed, NewTypeExpr) + if isinstance(old_type, TupleType): + newtype_class_info = self.build_newtype_typeinfo( + name, old_type, old_type.partial_fallback, s.line, call.analyzed.info + ) + newtype_class_info.update_tuple_type(old_type) + elif isinstance(old_type, Instance): + if old_type.type.is_protocol: + self.fail("NewType cannot be used with protocol classes", s) + newtype_class_info = self.build_newtype_typeinfo( + name, old_type, old_type, s.line, call.analyzed.info + ) + else: + if old_type is not None: + message = "Argument 2 to NewType(...) must be subclassable (got {})" + self.fail( + message.format(format_type(old_type, self.options)), + s, + code=codes.VALID_NEWTYPE, + ) + # Otherwise the error was already reported. + old_type = AnyType(TypeOfAny.from_error) + object_type = self.api.named_type("builtins.object") + newtype_class_info = self.build_newtype_typeinfo( + name, old_type, object_type, s.line, call.analyzed.info + ) + newtype_class_info.fallback_to_any = True + + check_for_explicit_any( + old_type, self.options, self.api.is_typeshed_stub_file, self.msg, context=s + ) + + if self.options.disallow_any_unimported and has_any_from_unimported_type(old_type): + self.msg.unimported_type_becomes_any("Argument 2 to NewType(...)", old_type, s) + + # If so, add it to the symbol table. + assert isinstance(call.analyzed, NewTypeExpr) + # As we do for normal classes, create the TypeInfo only once, then just + # update base classes on next iterations (to get rid of placeholders there). + if not call.analyzed.info: + call.analyzed.info = newtype_class_info + else: + call.analyzed.info.bases = newtype_class_info.bases + self.api.add_symbol(var_name, call.analyzed.info, s) + if self.api.is_func_scope(): + self.api.add_symbol_skip_local(name, call.analyzed.info) + newtype_class_info.line = s.line + return True + + def analyze_newtype_declaration(self, s: AssignmentStmt) -> tuple[str | None, CallExpr | None]: + """Return the NewType call expression if `s` is a newtype declaration or None otherwise.""" + name, call = None, None + if ( + len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and isinstance(s.rvalue, CallExpr) + and isinstance(s.rvalue.callee, RefExpr) + and (s.rvalue.callee.fullname in ("typing.NewType", "typing_extensions.NewType")) + ): + name = s.lvalues[0].name + + if s.type: + self.fail("Cannot declare the type of a NewType declaration", s) + + names = self.api.current_symbol_table() + existing = names.get(name) + # Give a better error message than generic "Name already defined". + if ( + existing + and not isinstance(existing.node, PlaceholderNode) + and not s.rvalue.analyzed + ): + self.fail(f'Cannot redefine "{name}" as a NewType', s) + + # This dummy NewTypeExpr marks the call as sufficiently analyzed; it will be + # overwritten later with a fully complete NewTypeExpr if there are no other + # errors with the NewType() call. + call = s.rvalue + + return name, call + + def check_newtype_args( + self, name: str, call: CallExpr, context: Context + ) -> tuple[Type | None, bool]: + """Analyze base type in NewType call. + + Return a tuple (type, should defer). + """ + has_failed = False + args, arg_kinds = call.args, call.arg_kinds + if len(args) != 2 or arg_kinds[0] != ARG_POS or arg_kinds[1] != ARG_POS: + self.fail("NewType(...) expects exactly two positional arguments", context) + return None, False + + # Check first argument + if not isinstance(args[0], StrExpr): + self.fail("Argument 1 to NewType(...) must be a string literal", context) + has_failed = True + elif args[0].value != name: + msg = 'String argument 1 "{}" to NewType(...) does not match variable name "{}"' + self.fail(msg.format(args[0].value, name), context) + has_failed = True + + # Check second argument + msg = "Argument 2 to NewType(...) must be a valid type" + try: + unanalyzed_type = expr_to_unanalyzed_type(args[1], self.options, self.api.is_stub_file) + except TypeTranslationError: + self.fail(msg, context) + return None, False + + # We want to use our custom error message (see above), so we suppress + # the default error message for invalid types here. + old_type = get_proper_type( + self.api.anal_type( + unanalyzed_type, + report_invalid_types=False, + allow_placeholder=not self.api.is_func_scope(), + ) + ) + should_defer = False + if isinstance(old_type, PlaceholderType): + old_type = None + if old_type is None: + should_defer = True + + # The caller of this function assumes that if we return a Type, it's always + # a valid one. So, we translate AnyTypes created from errors into None. + if isinstance(old_type, AnyType) and old_type.is_from_error: + self.fail(msg, context) + return None, False + + return None if has_failed else old_type, should_defer + + def build_newtype_typeinfo( + self, + name: str, + old_type: Type, + base_type: Instance, + line: int, + existing_info: TypeInfo | None, + ) -> TypeInfo: + info = existing_info or self.api.basic_new_typeinfo(name, base_type, line) + info.bases = [base_type] # Update in case there were nested placeholders. + info.is_newtype = True + + # Add __init__ method + args = [ + Argument(Var("self"), NoneType(), None, ARG_POS), + self.make_argument("item", old_type), + ] + signature = CallableType( + arg_types=[Instance(info, []), old_type], + arg_kinds=[arg.kind for arg in args], + arg_names=["self", "item"], + ret_type=NoneType(), + fallback=self.api.named_type("builtins.function"), + name=name, + ) + init_func = FuncDef("__init__", args, Block([]), typ=signature) + init_func.info = info + init_func._fullname = info.fullname + ".__init__" + if not existing_info: + updated = True + else: + previous_sym = info.names["__init__"].node + assert isinstance(previous_sym, FuncDef) + updated = old_type != previous_sym.arguments[1].variable.type + info.names["__init__"] = SymbolTableNode(MDEF, init_func) + + if has_placeholder(old_type): + self.api.process_placeholder(None, "NewType base", info, force_progress=updated) + return info + + # Helpers + + def make_argument(self, name: str, type: Type) -> Argument: + return Argument(Var(name), type, None, ARG_POS) + + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.api.fail(msg, ctx, code=code) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_pass1.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_pass1.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..d7cf5042aa8bcaa14541687221a3a7b6b31f0202 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_pass1.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_pass1.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_pass1.py new file mode 100644 index 0000000000000000000000000000000000000000..266fd236a01f622b22e69e427f8475e68cfb064a --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_pass1.py @@ -0,0 +1,159 @@ +"""Block/import reachability analysis.""" + +from __future__ import annotations + +from mypy.nodes import ( + AssertStmt, + AssignmentStmt, + Block, + ClassDef, + ExpressionStmt, + ForStmt, + FuncDef, + IfStmt, + Import, + ImportAll, + ImportFrom, + MatchStmt, + MypyFile, + ReturnStmt, +) +from mypy.options import Options +from mypy.reachability import ( + assert_will_always_fail, + infer_reachability_of_if_statement, + infer_reachability_of_match_statement, +) +from mypy.traverser import TraverserVisitor + + +class SemanticAnalyzerPreAnalysis(TraverserVisitor): + """Analyze reachability of blocks and imports and other local things. + + This runs before semantic analysis, so names have not been bound. Imports are + also not resolved yet, so we can only access the current module. + + This determines static reachability of blocks and imports due to version and + platform checks, among others. + + The main entry point is 'visit_file'. + + Reachability of imports needs to be determined very early in the build since + this affects which modules will ultimately be processed. + + Consider this example: + + import sys + + def do_stuff() -> None: + if sys.version_info >= (3, 10): + import xyz # Only available in Python 3.10+ + xyz.whatever() + ... + + The block containing 'import xyz' is unreachable in Python 3 mode. The import + shouldn't be processed in Python 3 mode, even if the module happens to exist. + """ + + def visit_file(self, file: MypyFile, fnam: str, mod_id: str, options: Options) -> None: + self.platform = options.platform + self.cur_mod_id = mod_id + self.cur_mod_node = file + self.options = options + self.is_global_scope = True + self.skipped_lines: set[int] = set() + + for i, defn in enumerate(file.defs): + defn.accept(self) + if isinstance(defn, AssertStmt) and assert_will_always_fail(defn, options): + # We've encountered an assert that's always false, + # e.g. assert sys.platform == 'lol'. Truncate the + # list of statements. This mutates file.defs too. + if i < len(file.defs) - 1: + next_def, last = file.defs[i + 1], file.defs[-1] + if last.end_line is not None: + # We are on a Python version recent enough to support end lines. + self.skipped_lines |= set(range(next_def.line, last.end_line + 1)) + file.imports = [ + i for i in file.imports if (i.line, i.column) <= (defn.line, defn.column) + ] + del file.defs[i + 1 :] + break + file.skipped_lines = self.skipped_lines + + def visit_func_def(self, node: FuncDef) -> None: + old_global_scope = self.is_global_scope + self.is_global_scope = False + super().visit_func_def(node) + self.is_global_scope = old_global_scope + file_node = self.cur_mod_node + if ( + self.is_global_scope + and file_node.is_stub + and node.name == "__getattr__" + and file_node.is_package_init_file() + ): + # __init__.pyi with __getattr__ means that any submodules are assumed + # to exist, even if there is no stub. Note that we can't verify that the + # return type is compatible, since we haven't bound types yet. + file_node.is_partial_stub_package = True + + def visit_class_def(self, node: ClassDef) -> None: + old_global_scope = self.is_global_scope + self.is_global_scope = False + super().visit_class_def(node) + self.is_global_scope = old_global_scope + + def visit_import_from(self, node: ImportFrom) -> None: + node.is_top_level = self.is_global_scope + super().visit_import_from(node) + + def visit_import_all(self, node: ImportAll) -> None: + node.is_top_level = self.is_global_scope + super().visit_import_all(node) + + def visit_import(self, node: Import) -> None: + node.is_top_level = self.is_global_scope + super().visit_import(node) + + def visit_if_stmt(self, s: IfStmt) -> None: + infer_reachability_of_if_statement(s, self.options) + for expr in s.expr: + expr.accept(self) + for node in s.body: + node.accept(self) + if s.else_body: + s.else_body.accept(self) + + def visit_block(self, b: Block) -> None: + if b.is_unreachable: + if b.end_line is not None: + # We are on a Python version recent enough to support end lines. + self.skipped_lines |= set(range(b.line, b.end_line + 1)) + return + super().visit_block(b) + + def visit_match_stmt(self, s: MatchStmt) -> None: + infer_reachability_of_match_statement(s, self.options) + for guard in s.guards: + if guard is not None: + guard.accept(self) + for body in s.bodies: + body.accept(self) + + # The remaining methods are an optimization: don't visit nested expressions + # of common statements, since they can have no effect. + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + pass + + def visit_expression_stmt(self, s: ExpressionStmt) -> None: + pass + + def visit_return_stmt(self, s: ReturnStmt) -> None: + pass + + def visit_for_stmt(self, s: ForStmt) -> None: + s.body.accept(self) + if s.else_body is not None: + s.else_body.accept(self) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_shared.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_shared.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ed1762f4faa906efaeeb55ad49a8ac183c3347be Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_shared.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_shared.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..a85d4ed00b5e678aa4dcd296a7525c7718708191 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_shared.py @@ -0,0 +1,495 @@ +"""Shared definitions used by different parts of semantic analysis.""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Callable +from typing import Final, Literal, Protocol, overload + +from mypy_extensions import trait + +from mypy.errorcodes import LITERAL_REQ, ErrorCode +from mypy.nodes import ( + CallExpr, + ClassDef, + Context, + DataclassTransformSpec, + Decorator, + Expression, + FuncDef, + NameExpr, + Node, + OverloadedFuncDef, + RefExpr, + SymbolNode, + SymbolTable, + SymbolTableNode, + TypeInfo, +) +from mypy.plugin import SemanticAnalyzerPluginInterface +from mypy.tvar_scope import TypeVarLikeScope +from mypy.type_visitor import ANY_STRATEGY, BoolTypeQuery +from mypy.typeops import make_simplified_union +from mypy.types import ( + TPDICT_FB_NAMES, + AnyType, + FunctionLike, + Instance, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PlaceholderType, + ProperType, + TupleType, + Type, + TypeOfAny, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + UnpackType, + flatten_nested_tuples, + get_proper_type, +) + +# Subclasses can override these Var attributes with incompatible types. This can also be +# set for individual attributes using 'allow_incompatible_override' of Var. +ALLOW_INCOMPATIBLE_OVERRIDE: Final = ("__slots__", "__deletable__", "__match_args__") + + +# Priorities for ordering of patches within the "patch" phase of semantic analysis +# (after the main pass): + +# Fix fallbacks (does subtype checks). +PRIORITY_FALLBACKS: Final = 1 + + +@trait +class SemanticAnalyzerCoreInterface: + """A core abstract interface to generic semantic analyzer functionality. + + This is implemented by both semantic analyzer passes 2 and 3. + """ + + @abstractmethod + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode: + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None: + raise NotImplementedError + + @abstractmethod + def fail( + self, + msg: str, + ctx: Context, + serious: bool = False, + *, + blocker: bool = False, + code: ErrorCode | None = None, + ) -> None: + raise NotImplementedError + + @abstractmethod + def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + raise NotImplementedError + + @abstractmethod + def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: + raise NotImplementedError + + @abstractmethod + def record_incomplete_ref(self) -> None: + raise NotImplementedError + + @abstractmethod + def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None: + raise NotImplementedError + + @abstractmethod + def is_incomplete_namespace(self, fullname: str) -> bool: + """Is a module or class namespace potentially missing some definitions?""" + raise NotImplementedError + + @property + @abstractmethod + def final_iteration(self) -> bool: + """Is this the final iteration of semantic analysis?""" + raise NotImplementedError + + @abstractmethod + def is_future_flag_set(self, flag: str) -> bool: + """Is the specific __future__ feature imported""" + raise NotImplementedError + + @property + @abstractmethod + def is_stub_file(self) -> bool: + raise NotImplementedError + + @abstractmethod + def is_func_scope(self) -> bool: + raise NotImplementedError + + @property + @abstractmethod + def type(self) -> TypeInfo | None: + raise NotImplementedError + + +@trait +class SemanticAnalyzerInterface(SemanticAnalyzerCoreInterface): + """A limited abstract interface to some generic semantic analyzer pass 2 functionality. + + We use this interface for various reasons: + + * Looser coupling + * Cleaner import graph + * Less need to pass around callback functions + """ + + tvar_scope: TypeVarLikeScope + + @abstractmethod + def lookup( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + raise NotImplementedError + + @abstractmethod + def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance: + raise NotImplementedError + + @abstractmethod + def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None: + raise NotImplementedError + + @abstractmethod + def accept(self, node: Node) -> None: + raise NotImplementedError + + @abstractmethod + def anal_type( + self, + typ: Type, + /, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_placeholder: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + ) -> Type | None: + raise NotImplementedError + + @abstractmethod + def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]: + raise NotImplementedError + + @abstractmethod + def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: + raise NotImplementedError + + @abstractmethod + def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None: + raise NotImplementedError + + @abstractmethod + def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> bool: + """Add node to the current symbol table.""" + raise NotImplementedError + + @abstractmethod + def current_symbol_table(self) -> SymbolTable: + """Get currently active symbol table. + + May be module, class, or local namespace. + """ + raise NotImplementedError + + @abstractmethod + def add_symbol( + self, + name: str, + node: SymbolNode, + context: Context, + module_public: bool = True, + module_hidden: bool = False, + can_defer: bool = True, + ) -> bool: + """Add symbol to the current symbol table.""" + raise NotImplementedError + + @abstractmethod + def add_symbol_skip_local(self, name: str, node: SymbolNode) -> None: + """Add symbol to the current symbol table, skipping locals. + + This is used to store symbol nodes in a symbol table that + is going to be serialized (local namespaces are not serialized). + See implementation docstring for more details. + """ + raise NotImplementedError + + @abstractmethod + def parse_bool(self, expr: Expression) -> bool | None: + raise NotImplementedError + + @abstractmethod + def qualified_name(self, name: str) -> str: + raise NotImplementedError + + @property + @abstractmethod + def is_typeshed_stub_file(self) -> bool: + raise NotImplementedError + + @abstractmethod + def process_placeholder( + self, name: str | None, kind: str, ctx: Context, force_progress: bool = False + ) -> None: + raise NotImplementedError + + +def set_callable_name(sig: Type, fdef: FuncDef) -> ProperType: + sig = get_proper_type(sig) + if isinstance(sig, FunctionLike): + if fdef.info: + if fdef.info.fullname in TPDICT_FB_NAMES: + # Avoid exposing the internal _TypedDict name. + class_name = "TypedDict" + else: + class_name = fdef.info.name + return sig.with_name(f"{fdef.name} of {class_name}") + else: + return sig.with_name(fdef.name) + else: + return sig + + +def calculate_tuple_fallback(typ: TupleType) -> None: + """Calculate a precise item type for the fallback of a tuple type. + + This must be called only after the main semantic analysis pass, since joins + aren't available before that. + + Note that there is an apparent chicken and egg problem with respect + to verifying type arguments against bounds. Verifying bounds might + require fallbacks, but we might use the bounds to calculate the + fallbacks. In practice this is not a problem, since the worst that + can happen is that we have invalid type argument values, and these + can happen in later stages as well (they will generate errors, but + we don't prevent their existence). + """ + fallback = typ.partial_fallback + assert fallback.type.fullname == "builtins.tuple" + items = [] + for item in flatten_nested_tuples(typ.items): + # TODO: this duplicates some logic in typeops.tuple_fallback(). + if isinstance(item, UnpackType): + unpacked_type = get_proper_type(item.type) + if isinstance(unpacked_type, TypeVarTupleType): + unpacked_type = get_proper_type(unpacked_type.upper_bound) + if ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ): + items.append(unpacked_type.args[0]) + else: + # This is called before semanal_typeargs.py fixes broken unpacks, + # where the error should also be generated. + items.append(AnyType(TypeOfAny.from_error)) + else: + items.append(item) + fallback.args = (make_simplified_union(items),) + + +class _NamedTypeCallback(Protocol): + def __call__(self, fullname: str, args: list[Type] | None = None) -> Instance: ... + + +def paramspec_args( + name: str, + fullname: str, + id: TypeVarId, + *, + named_type_func: _NamedTypeCallback, + line: int = -1, + column: int = -1, + prefix: Parameters | None = None, +) -> ParamSpecType: + return ParamSpecType( + name, + fullname, + id, + flavor=ParamSpecFlavor.ARGS, + upper_bound=named_type_func("builtins.tuple", [named_type_func("builtins.object")]), + default=AnyType(TypeOfAny.from_omitted_generics), + line=line, + column=column, + prefix=prefix, + ) + + +def paramspec_kwargs( + name: str, + fullname: str, + id: TypeVarId, + *, + named_type_func: _NamedTypeCallback, + line: int = -1, + column: int = -1, + prefix: Parameters | None = None, +) -> ParamSpecType: + return ParamSpecType( + name, + fullname, + id, + flavor=ParamSpecFlavor.KWARGS, + upper_bound=named_type_func( + "builtins.dict", [named_type_func("builtins.str"), named_type_func("builtins.object")] + ), + default=AnyType(TypeOfAny.from_omitted_generics), + line=line, + column=column, + prefix=prefix, + ) + + +class HasPlaceholders(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_placeholder_type(self, t: PlaceholderType) -> bool: + return True + + +def has_placeholder(typ: Type) -> bool: + """Check if a type contains any placeholder types (recursively).""" + return typ.accept(HasPlaceholders()) + + +def find_dataclass_transform_spec(node: Node | None) -> DataclassTransformSpec | None: + """ + Find the dataclass transform spec for the given node, if any exists. + + Per PEP 681 (https://peps.python.org/pep-0681/#the-dataclass-transform-decorator), dataclass + transforms can be specified in multiple ways, including decorator functions and + metaclasses/base classes. This function resolves the spec from any of these variants. + """ + + # The spec only lives on the function/class definition itself, so we need to unwrap down to that + # point + if isinstance(node, CallExpr): + # Like dataclasses.dataclass, transform-based decorators can be applied either with or + # without parameters; ie, both of these forms are accepted: + # + # @typing.dataclass_transform + # class Foo: ... + # @typing.dataclass_transform(eq=True, order=True, ...) + # class Bar: ... + # + # We need to unwrap the call for the second variant. + node = node.callee + + if isinstance(node, RefExpr): + node = node.node + + if isinstance(node, Decorator): + # typing.dataclass_transform usage must always result in a Decorator; it always uses the + # `@dataclass_transform(...)` syntax and never `@dataclass_transform` + node = node.func + + if isinstance(node, OverloadedFuncDef): + # The dataclass_transform decorator may be attached to any single overload, so we must + # search them all. + # Note that using more than one decorator is undefined behavior, so we can just take the + # first that we find. + for candidate in node.items: + spec = find_dataclass_transform_spec(candidate) + if spec is not None: + return spec + return find_dataclass_transform_spec(node.impl) + + # For functions, we can directly consult the AST field for the spec + if isinstance(node, FuncDef): + return node.dataclass_transform_spec + + if isinstance(node, ClassDef): + node = node.info + if isinstance(node, TypeInfo): + # Search all parent classes to see if any are decorated with `typing.dataclass_transform` + for base in node.mro[1:]: + if base.dataclass_transform_spec is not None: + return base.dataclass_transform_spec + + # Check if there is a metaclass that is decorated with `typing.dataclass_transform` + # + # Note that PEP 681 only discusses using a metaclass that is directly decorated with + # `typing.dataclass_transform`; subclasses thereof should be treated with dataclass + # semantics rather than as transforms: + # + # > If dataclass_transform is applied to a class, dataclass-like semantics will be assumed + # > for any class that directly or indirectly derives from the decorated class or uses the + # > decorated class as a metaclass. + # + # The wording doesn't make this entirely explicit, but Pyright (the reference + # implementation for this PEP) only handles directly-decorated metaclasses. + metaclass_type = node.metaclass_type + if metaclass_type is not None and metaclass_type.type.dataclass_transform_spec is not None: + return metaclass_type.type.dataclass_transform_spec + + return None + + +# Never returns `None` if a default is given +@overload +def require_bool_literal_argument( + api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, + expression: Expression, + name: str, + default: Literal[True, False], +) -> bool: ... + + +@overload +def require_bool_literal_argument( + api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, + expression: Expression, + name: str, + default: None = None, +) -> bool | None: ... + + +def require_bool_literal_argument( + api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, + expression: Expression, + name: str, + default: bool | None = None, +) -> bool | None: + """Attempt to interpret an expression as a boolean literal, and fail analysis if we can't.""" + value = parse_bool(expression) + if value is None: + api.fail( + f'"{name}" argument must be a True or False literal', expression, code=LITERAL_REQ + ) + return default + + return value + + +def parse_bool(expr: Expression) -> bool | None: + if isinstance(expr, NameExpr): + if expr.fullname == "builtins.True": + return True + if expr.fullname == "builtins.False": + return False + return None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeargs.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeargs.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..76dc2e4a4f9a4ac5820ad399b06b2782ac8e2b64 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeargs.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeargs.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeargs.py new file mode 100644 index 0000000000000000000000000000000000000000..0f62a4aa8b1a2ea8d71ef25988dc0c4d8b3d71df --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeargs.py @@ -0,0 +1,306 @@ +"""Verify properties of type arguments, like 'int' in C[int] being valid. + +This must happen after semantic analysis since there can be placeholder +types until the end of semantic analysis, and these break various type +operations, including subtype checks. +""" + +from __future__ import annotations + +from collections.abc import Callable + +from mypy import errorcodes as codes, message_registry +from mypy.errorcodes import ErrorCode +from mypy.errors import Errors +from mypy.message_registry import INVALID_PARAM_SPEC_LOCATION, INVALID_PARAM_SPEC_LOCATION_NOTE +from mypy.messages import format_type +from mypy.mixedtraverser import MixedTraverserVisitor +from mypy.nodes import Block, ClassDef, Context, FakeInfo, FuncItem, MypyFile +from mypy.options import Options +from mypy.scope import Scope +from mypy.subtypes import is_same_type, is_subtype +from mypy.types import ( + AnyType, + CallableType, + Instance, + Parameters, + ParamSpecType, + TupleType, + Type, + TypeAliasType, + TypeOfAny, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UnpackType, + flatten_nested_tuples, + get_proper_type, + get_proper_types, + split_with_prefix_and_suffix, +) +from mypy.typevartuples import erased_vars + + +class TypeArgumentAnalyzer(MixedTraverserVisitor): + def __init__( + self, + errors: Errors, + options: Options, + is_typeshed_file: bool, + named_type: Callable[[str, list[Type]], Instance], + ) -> None: + super().__init__() + self.errors = errors + self.options = options + self.is_typeshed_file = is_typeshed_file + self.named_type = named_type + self.scope = Scope() + # Should we also analyze function definitions, or only module top-levels? + self.recurse_into_functions = True + # Keep track of the type aliases already visited. This is needed to avoid + # infinite recursion on types like A = Union[int, List[A]]. + self.seen_aliases: set[TypeAliasType] = set() + + def visit_mypy_file(self, o: MypyFile) -> None: + self.errors.set_file(o.path, o.fullname, scope=self.scope, options=self.options) + with self.scope.module_scope(o.fullname): + super().visit_mypy_file(o) + + def visit_func(self, defn: FuncItem) -> None: + if not self.recurse_into_functions: + return + with self.scope.function_scope(defn): + super().visit_func(defn) + + def visit_class_def(self, defn: ClassDef) -> None: + with self.scope.class_scope(defn.info): + super().visit_class_def(defn) + + def visit_block(self, o: Block) -> None: + if not o.is_unreachable: + super().visit_block(o) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + super().visit_type_alias_type(t) + if t.is_recursive: + if t in self.seen_aliases: + # Avoid infinite recursion on recursive type aliases. + return + self.seen_aliases.add(t) + assert t.alias is not None, f"Unfixed type alias {t.type_ref}" + is_error, is_invalid = self.validate_args( + t.alias.name, tuple(t.args), t.alias.alias_tvars, t + ) + if is_invalid: + # If there is an arity error (e.g. non-Parameters used for ParamSpec etc.), + # then it is safer to erase the arguments completely, to avoid crashes later. + # TODO: can we move this logic to typeanal.py? + t.args = erased_vars(t.alias.alias_tvars, TypeOfAny.from_error) + if not is_error: + # If there was already an error for the alias itself, there is no point in checking + # the expansion, most likely it will result in the same kind of error. + if t.args: + # Since we always allow unbounded type variables in alias definitions, we need + # to verify the arguments satisfy the upper bounds of the expansion as well. + get_proper_type(t).accept(self) + if t.is_recursive: + self.seen_aliases.discard(t) + + def visit_tuple_type(self, t: TupleType) -> None: + t.items = flatten_nested_tuples(t.items) + for i, it in enumerate(t.items): + if self.check_non_paramspec(it, "tuple", t): + t.items[i] = AnyType(TypeOfAny.from_error) + + # We could also normalize Tuple[*tuple[X, ...]] -> tuple[X, ...] like in + # expand_type() but we can't do this here since it is not a translator visitor, + # and we need to return an Instance instead of TupleType. + super().visit_tuple_type(t) + + def visit_callable_type(self, t: CallableType) -> None: + super().visit_callable_type(t) + t.normalize_trivial_unpack() + + def visit_instance(self, t: Instance) -> None: + super().visit_instance(t) + # Type argument counts were checked in the main semantic analyzer pass. We assume + # that the counts are correct here. + info = t.type + if isinstance(info, FakeInfo): + return # https://github.com/python/mypy/issues/11079 + _, is_invalid = self.validate_args(info.name, t.args, info.defn.type_vars, t) + if is_invalid: + t.args = tuple(erased_vars(info.defn.type_vars, TypeOfAny.from_error)) + if t.type.fullname == "builtins.tuple" and len(t.args) == 1: + # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...] + arg = t.args[0] + if isinstance(arg, UnpackType): + unpacked = get_proper_type(arg.type) + if isinstance(unpacked, Instance): + assert unpacked.type.fullname == "builtins.tuple" + t.args = unpacked.args + + def check_non_paramspec(self, arg: Type, tv_kind: str, context: Context) -> bool: + if isinstance(arg, ParamSpecType): + self.fail( + INVALID_PARAM_SPEC_LOCATION.format(format_type(arg, self.options)), + context, + code=codes.VALID_TYPE, + ) + self.note( + INVALID_PARAM_SPEC_LOCATION_NOTE.format(arg.name), context, code=codes.VALID_TYPE + ) + return True + if isinstance(arg, Parameters): + self.fail( + f"Cannot use {format_type(arg, self.options)} for {tv_kind}," + " only for ParamSpec", + context, + code=codes.VALID_TYPE, + ) + return True + + return False + + def validate_args( + self, name: str, args: tuple[Type, ...], type_vars: list[TypeVarLikeType], ctx: Context + ) -> tuple[bool, bool]: + if any(isinstance(v, TypeVarTupleType) for v in type_vars): + prefix = next(i for (i, v) in enumerate(type_vars) if isinstance(v, TypeVarTupleType)) + tvt = type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + start, middle, end = split_with_prefix_and_suffix( + tuple(args), prefix, len(type_vars) - prefix - 1 + ) + args = start + (TupleType(list(middle), tvt.tuple_fallback),) + end + + is_error = False + is_invalid = False + for arg, tvar in zip(args, type_vars): + context = ctx if arg.line < 0 else arg + if isinstance(tvar, TypeVarType): + if self.check_non_paramspec(arg, "regular type variable", context): + is_invalid = True + continue + + if self.in_type_alias_expr and isinstance(arg, TypeVarType): + # Type aliases are allowed to use unconstrained type variables + # error will be checked at substitution point. + continue + if tvar.values: + if isinstance(arg, TypeVarType): + arg_values = arg.values + if not arg_values: + is_error = True + self.fail( + message_registry.INVALID_TYPEVAR_AS_TYPEARG.format(arg.name, name), + context, + code=codes.TYPE_VAR, + ) + continue + else: + arg_values = [arg] + if self.check_type_var_values( + name, arg_values, tvar.name, tvar.values, context + ): + is_error = True + # Check against upper bound. Since it's object the vast majority of the time, + # add fast path to avoid a potentially slow subtype check. + upper_bound = tvar.upper_bound + object_upper_bound = ( + type(upper_bound) is Instance + and upper_bound.type.fullname == "builtins.object" + ) + if not object_upper_bound and not is_subtype(arg, upper_bound): + is_error = True + self.fail( + message_registry.INVALID_TYPEVAR_ARG_BOUND.format( + format_type(arg, self.options), + name, + format_type(upper_bound, self.options), + ), + context, + code=codes.TYPE_VAR, + ) + elif isinstance(tvar, ParamSpecType): + if not isinstance( + get_proper_type(arg), (ParamSpecType, Parameters, AnyType, UnboundType) + ): + is_invalid = True + self.fail( + "Can only replace ParamSpec with a parameter types list or" + f" another ParamSpec, got {format_type(arg, self.options)}", + context, + code=codes.VALID_TYPE, + ) + elif isinstance(tvar, TypeVarTupleType): + p_arg = get_proper_type(arg) + assert isinstance(p_arg, TupleType) + for it in p_arg.items: + if self.check_non_paramspec(it, "TypeVarTuple", context): + is_invalid = True + if is_invalid: + is_error = True + return is_error, is_invalid + + def visit_unpack_type(self, typ: UnpackType) -> None: + super().visit_unpack_type(typ) + proper_type = get_proper_type(typ.type) + if isinstance(proper_type, TupleType): + return + if isinstance(proper_type, TypeVarTupleType): + return + # TODO: this should probably be .has_base("builtins.tuple"), also elsewhere. This is + # tricky however, since this needs map_instance_to_supertype() available in many places. + if isinstance(proper_type, Instance) and proper_type.type.fullname == "builtins.tuple": + return + if not isinstance(proper_type, (UnboundType, AnyType)): + # Avoid extra errors if there were some errors already. Also interpret plain Any + # as tuple[Any, ...] (this is better for the code in type checker). + self.fail( + message_registry.INVALID_UNPACK.format(format_type(proper_type, self.options)), + typ.type, + code=codes.VALID_TYPE, + ) + typ.type = self.named_type("builtins.tuple", [AnyType(TypeOfAny.from_error)]) + + def check_type_var_values( + self, name: str, actuals: list[Type], arg_name: str, valids: list[Type], context: Context + ) -> bool: + if self.in_type_alias_expr: + # See testValidTypeAliasValues - we do not enforce typevar compatibility + # at the definition site. We check instantiation validity later. + return False + is_error = False + for actual in get_proper_types(actuals): + # We skip UnboundType here, since they may appear in defn.bases, + # the error will be caught when visiting info.bases, that have bound type + # variables. + if not isinstance(actual, (AnyType, UnboundType)) and not any( + is_same_type(actual, value) for value in valids + ): + is_error = True + if len(actuals) > 1 or not isinstance(actual, Instance): + self.fail( + message_registry.INVALID_TYPEVAR_ARG_VALUE.format(name), + context, + code=codes.TYPE_VAR, + ) + else: + class_name = f'"{name}"' + actual_type_name = f'"{actual.type.name}"' + self.fail( + message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format( + arg_name, class_name, actual_type_name + ), + context, + code=codes.TYPE_VAR, + ) + return is_error + + def fail(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None: + self.errors.report(context.line, context.column, msg, code=code) + + def note(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None: + self.errors.report(context.line, context.column, msg, severity="note", code=code) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeddict.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeddict.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..7c6776c632e20d68c088f1dc5de497734cb4e117 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeddict.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeddict.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeddict.py new file mode 100644 index 0000000000000000000000000000000000000000..3655e4c89dd4b9ef982c89cdc88897c6e34eda38 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/semanal_typeddict.py @@ -0,0 +1,631 @@ +"""Semantic analysis of TypedDict definitions.""" + +from __future__ import annotations + +from collections.abc import Collection +from typing import Final + +from mypy import errorcodes as codes, message_registry +from mypy.errorcodes import ErrorCode +from mypy.expandtype import expand_type +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.message_registry import TYPEDDICT_OVERRIDE_MERGE +from mypy.messages import MessageBuilder +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + AssignmentStmt, + CallExpr, + ClassDef, + Context, + DictExpr, + EllipsisExpr, + Expression, + ExpressionStmt, + IndexExpr, + NameExpr, + PassStmt, + RefExpr, + Statement, + StrExpr, + TempNode, + TupleExpr, + TypeAlias, + TypedDictExpr, + TypeInfo, +) +from mypy.options import Options +from mypy.semanal_shared import ( + SemanticAnalyzerInterface, + has_placeholder, + require_bool_literal_argument, +) +from mypy.state import state +from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type +from mypy.types import ( + TPDICT_NAMES, + AnyType, + ReadOnlyType, + RequiredType, + Type, + TypedDictType, + TypeOfAny, + TypeVarLikeType, + get_proper_type, +) + +TPDICT_CLASS_ERROR: Final = ( + 'Invalid statement in TypedDict definition; expected "field_name: field_type"' +) + + +class TypedDictAnalyzer: + def __init__( + self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder + ) -> None: + self.options = options + self.api = api + self.msg = msg + + def analyze_typeddict_classdef(self, defn: ClassDef) -> tuple[bool, TypeInfo | None]: + """Analyze a class that may define a TypedDict. + + Assume that base classes have been analyzed already. + + Note: Unlike normal classes, we won't create a TypeInfo until + the whole definition of the TypeDict (including the body and all + key names and types) is complete. This is mostly because we + store the corresponding TypedDictType in the TypeInfo. + + Return (is this a TypedDict, new TypeInfo). Specifics: + * If we couldn't finish due to incomplete reference anywhere in + the definition, return (True, None). + * If this is not a TypedDict, return (False, None). + """ + possible = False + for base_expr in defn.base_type_exprs: + if isinstance(base_expr, CallExpr): + base_expr = base_expr.callee + if isinstance(base_expr, IndexExpr): + base_expr = base_expr.base + if isinstance(base_expr, RefExpr): + self.api.accept(base_expr) + if base_expr.fullname in TPDICT_NAMES or self.is_typeddict(base_expr): + possible = True + if isinstance(base_expr.node, TypeInfo) and base_expr.node.is_final: + err = message_registry.CANNOT_INHERIT_FROM_FINAL + self.fail(err.format(base_expr.node.name).value, defn, code=err.code) + if not possible: + return False, None + existing_info = None + if isinstance(defn.analyzed, TypedDictExpr): + existing_info = defn.analyzed.info + + field_types: dict[str, Type] | None + if ( + len(defn.base_type_exprs) == 1 + and isinstance(defn.base_type_exprs[0], RefExpr) + and defn.base_type_exprs[0].fullname in TPDICT_NAMES + ): + # Building a new TypedDict + field_types, statements, required_keys, readonly_keys = ( + self.analyze_typeddict_classdef_fields(defn) + ) + if field_types is None: + return True, None # Defer + if self.api.is_func_scope() and "@" not in defn.name: + defn.name += "@" + str(defn.line) + info = self.build_typeddict_typeinfo( + defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info + ) + defn.analyzed = TypedDictExpr(info) + defn.analyzed.line = defn.line + defn.analyzed.column = defn.column + defn.defs.body = statements + return True, info + + # Extending/merging existing TypedDicts + typeddict_bases: list[Expression] = [] + typeddict_bases_set = set() + for expr in defn.base_type_exprs: + ok, maybe_type_info, _ = self.check_typeddict(expr, None, False) + if ok and maybe_type_info is not None: + # expr is a CallExpr + info = maybe_type_info + typeddict_bases_set.add(info.fullname) + typeddict_bases.append(expr) + elif isinstance(expr, RefExpr) and expr.fullname in TPDICT_NAMES: + if "TypedDict" not in typeddict_bases_set: + typeddict_bases_set.add("TypedDict") + else: + self.fail('Duplicate base class "TypedDict"', defn) + elif ( + isinstance(expr, RefExpr) + and self.is_typeddict(expr) + or isinstance(expr, IndexExpr) + and self.is_typeddict(expr.base) + ): + info = self._parse_typeddict_base(expr, defn) + if info.fullname not in typeddict_bases_set: + typeddict_bases_set.add(info.fullname) + typeddict_bases.append(expr) + else: + self.fail(f'Duplicate base class "{info.name}"', defn) + else: + self.fail("All bases of a new TypedDict must be TypedDict types", defn) + + field_types = {} + required_keys = set() + readonly_keys = set() + # Iterate over bases in reverse order so that leftmost base class' keys take precedence + for base in reversed(typeddict_bases): + self.add_keys_and_types_from_base( + base, field_types, required_keys, readonly_keys, defn + ) + new_field_types, new_statements, new_required_keys, new_readonly_keys = ( + self.analyze_typeddict_classdef_fields(defn, oldfields=field_types) + ) + if new_field_types is None: + return True, None # Defer + field_types.update(new_field_types) + required_keys.update(new_required_keys) + readonly_keys.update(new_readonly_keys) + info = self.build_typeddict_typeinfo( + defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info + ) + defn.analyzed = TypedDictExpr(info) + defn.analyzed.line = defn.line + defn.analyzed.column = defn.column + defn.defs.body = new_statements + return True, info + + def add_keys_and_types_from_base( + self, + base: Expression, + field_types: dict[str, Type], + required_keys: set[str], + readonly_keys: set[str], + ctx: Context, + ) -> None: + info = self._parse_typeddict_base(base, ctx) + base_args: list[Type] = [] + if isinstance(base, IndexExpr): + args = self.analyze_base_args(base, ctx) + if args is None: + return + base_args = args + + assert info.typeddict_type is not None + base_typed_dict = info.typeddict_type + base_items = base_typed_dict.items + valid_items = base_items.copy() + + # Always fix invalid bases to avoid crashes. + tvars = info.defn.type_vars + if len(base_args) != len(tvars): + any_kind = TypeOfAny.from_omitted_generics + if base_args: + self.fail(f'Invalid number of type arguments for "{info.name}"', ctx) + any_kind = TypeOfAny.from_error + base_args = [AnyType(any_kind) for _ in tvars] + + with state.strict_optional_set(self.options.strict_optional): + valid_items = self.map_items_to_base(valid_items, tvars, base_args) + for key in base_items: + if key in field_types: + self.fail(TYPEDDICT_OVERRIDE_MERGE.format(key), ctx) + + field_types.update(valid_items) + required_keys.update(base_typed_dict.required_keys) + readonly_keys.update(base_typed_dict.readonly_keys) + + def _parse_typeddict_base(self, base: Expression, ctx: Context) -> TypeInfo: + if isinstance(base, RefExpr): + if isinstance(base.node, TypeInfo): + return base.node + elif isinstance(base.node, TypeAlias): + # Only old TypeAlias / plain assignment, PEP695 `type` stmt + # cannot be used as a base class + target = get_proper_type(base.node.target) + assert isinstance(target, TypedDictType) + return target.fallback.type + else: + assert False + elif isinstance(base, IndexExpr): + assert isinstance(base.base, RefExpr) + return self._parse_typeddict_base(base.base, ctx) + else: + assert isinstance(base, CallExpr) + assert isinstance(base.analyzed, TypedDictExpr) + return base.analyzed.info + + def analyze_base_args(self, base: IndexExpr, ctx: Context) -> list[Type] | None: + """Analyze arguments of base type expressions as types. + + We need to do this, because normal base class processing happens after + the TypedDict special-casing (plus we get a custom error message). + """ + base_args = [] + if isinstance(base.index, TupleExpr): + args = base.index.items + else: + args = [base.index] + + for arg_expr in args: + try: + type = expr_to_unanalyzed_type(arg_expr, self.options, self.api.is_stub_file) + except TypeTranslationError: + self.fail("Invalid TypedDict type argument", ctx) + return None + analyzed = self.api.anal_type( + type, + allow_typed_dict_special_forms=True, + allow_placeholder=not self.api.is_func_scope(), + ) + if analyzed is None: + return None + base_args.append(analyzed) + return base_args + + def map_items_to_base( + self, valid_items: dict[str, Type], tvars: list[TypeVarLikeType], base_args: list[Type] + ) -> dict[str, Type]: + """Map item types to how they would look in their base with type arguments applied. + + Note it is safe to use expand_type() during semantic analysis, because it should never + (indirectly) call is_subtype(). + """ + mapped_items = {} + for key in valid_items: + type_in_base = valid_items[key] + if not tvars: + mapped_items[key] = type_in_base + continue + # TODO: simple zip can't be used for variadic types. + mapped_items[key] = expand_type( + type_in_base, {t.id: a for (t, a) in zip(tvars, base_args)} + ) + return mapped_items + + def analyze_typeddict_classdef_fields( + self, defn: ClassDef, oldfields: Collection[str] | None = None + ) -> tuple[dict[str, Type] | None, list[Statement], set[str], set[str]]: + """Analyze fields defined in a TypedDict class definition. + + This doesn't consider inherited fields (if any). Also consider totality, + if given. + + Return tuple with these items: + * Dict of key -> type (or None if found an incomplete reference -> deferral) + * List of statements from defn.defs.body that are legally allowed to be a + part of a TypedDict definition + * Set of required keys + """ + fields: dict[str, Type] = {} + readonly_keys = set[str]() + required_keys = set[str]() + statements: list[Statement] = [] + + total: bool | None = True + for key in defn.keywords: + if key == "total": + total = require_bool_literal_argument( + self.api, defn.keywords["total"], "total", True + ) + continue + for_function = ' for "__init_subclass__" of "TypedDict"' + self.msg.unexpected_keyword_argument_for_function(for_function, key, defn) + + for stmt in defn.defs.body: + if not isinstance(stmt, AssignmentStmt): + # Still allow pass or ... (for empty TypedDict's) and docstrings + if isinstance(stmt, PassStmt) or ( + isinstance(stmt, ExpressionStmt) + and isinstance(stmt.expr, (EllipsisExpr, StrExpr)) + ): + statements.append(stmt) + else: + defn.removed_statements.append(stmt) + self.fail(TPDICT_CLASS_ERROR, stmt) + elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr): + # An assignment, but an invalid one. + defn.removed_statements.append(stmt) + self.fail(TPDICT_CLASS_ERROR, stmt) + else: + name = stmt.lvalues[0].name + if name in (oldfields or []): + self.fail(f'Overwriting TypedDict field "{name}" while extending', stmt) + if name in fields: + self.fail(f'Duplicate TypedDict key "{name}"', stmt) + continue + # Append stmt, name, and type in this case... + statements.append(stmt) + + field_type: Type + if stmt.unanalyzed_type is None: + field_type = AnyType(TypeOfAny.unannotated) + else: + analyzed = self.api.anal_type( + stmt.unanalyzed_type, + allow_typed_dict_special_forms=True, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="TypedDict item type", + prohibit_special_class_field_types="TypedDict", + ) + if analyzed is None: + return None, [], set(), set() # Need to defer + field_type = analyzed + if not has_placeholder(analyzed): + stmt.type = self.extract_meta_info(analyzed, stmt)[0] + + field_type, required, readonly = self.extract_meta_info(field_type) + fields[name] = field_type + + if (total or required is True) and required is not False: + required_keys.add(name) + if readonly: + readonly_keys.add(name) + + # ...despite possible minor failures that allow further analysis. + if stmt.type is None or hasattr(stmt, "new_syntax") and not stmt.new_syntax: + self.fail(TPDICT_CLASS_ERROR, stmt) + elif not isinstance(stmt.rvalue, TempNode): + # x: int assigns rvalue to TempNode(AnyType()) + self.fail("Right hand side values are not supported in TypedDict", stmt) + + return fields, statements, required_keys, readonly_keys + + def extract_meta_info( + self, typ: Type, context: Context | None = None + ) -> tuple[Type, bool | None, bool]: + """Unwrap all metadata types.""" + is_required = None # default, no modification + readonly = False # by default all is mutable + + seen_required = False + seen_readonly = False + while isinstance(typ, (RequiredType, ReadOnlyType)): + if isinstance(typ, RequiredType): + if context is not None and seen_required: + self.fail( + '"{}" type cannot be nested'.format( + "Required[]" if typ.required else "NotRequired[]" + ), + context, + code=codes.VALID_TYPE, + ) + is_required = typ.required + seen_required = True + typ = typ.item + if isinstance(typ, ReadOnlyType): + if context is not None and seen_readonly: + self.fail('"ReadOnly[]" type cannot be nested', context, code=codes.VALID_TYPE) + readonly = True + seen_readonly = True + typ = typ.item + return typ, is_required, readonly + + def check_typeddict( + self, node: Expression, var_name: str | None, is_func_scope: bool + ) -> tuple[bool, TypeInfo | None, list[TypeVarLikeType]]: + """Check if a call defines a TypedDict. + + The optional var_name argument is the name of the variable to + which this is assigned, if any. + + Return a pair (is it a typed dict, corresponding TypeInfo). + + If the definition is invalid but looks like a TypedDict, + report errors but return (some) TypeInfo. If some type is not ready, + return (True, None). + """ + if not isinstance(node, CallExpr): + return False, None, [] + call = node + callee = call.callee + if not isinstance(callee, RefExpr): + return False, None, [] + fullname = callee.fullname + if fullname not in TPDICT_NAMES: + return False, None, [] + res = self.parse_typeddict_args(call) + if res is None: + # This is a valid typed dict, but some type is not ready. + # The caller should defer this until next iteration. + return True, None, [] + name, items, types, total, tvar_defs, ok = res + if not ok: + # Error. Construct dummy return value. + if var_name: + name = var_name + if is_func_scope: + name += "@" + str(call.line) + else: + name = var_name = "TypedDict@" + str(call.line) + info = self.build_typeddict_typeinfo(name, {}, set(), set(), call.line, None) + else: + if var_name is not None and name != var_name: + self.fail( + 'First argument "{}" to TypedDict() does not match variable name "{}"'.format( + name, var_name + ), + node, + code=codes.NAME_MATCH, + ) + if name != var_name or is_func_scope: + # Give it a unique name derived from the line number. + name += "@" + str(call.line) + required_keys = { + field + for (field, t) in zip(items, types) + if (total or (isinstance(t, RequiredType) and t.required)) + and not (isinstance(t, RequiredType) and not t.required) + } + readonly_keys = { + field for (field, t) in zip(items, types) if isinstance(t, ReadOnlyType) + } + types = [ # unwrap Required[T] or ReadOnly[T] to just T + t.item if isinstance(t, (RequiredType, ReadOnlyType)) else t for t in types + ] + + # Perform various validations after unwrapping. + for t in types: + check_for_explicit_any( + t, self.options, self.api.is_typeshed_stub_file, self.msg, context=call + ) + if self.options.disallow_any_unimported: + for t in types: + if has_any_from_unimported_type(t): + self.msg.unimported_type_becomes_any("Type of a TypedDict key", t, call) + + existing_info = None + if isinstance(node.analyzed, TypedDictExpr): + existing_info = node.analyzed.info + info = self.build_typeddict_typeinfo( + name, + dict(zip(items, types)), + required_keys, + readonly_keys, + call.line, + existing_info, + ) + info.line = node.line + # Store generated TypeInfo under both names, see semanal_namedtuple for more details. + if name != var_name or is_func_scope: + self.api.add_symbol_skip_local(name, info) + if var_name: + self.api.add_symbol(var_name, info, node) + call.analyzed = TypedDictExpr(info) + call.analyzed.set_line(call) + return True, info, tvar_defs + + def parse_typeddict_args( + self, call: CallExpr + ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool] | None: + """Parse typed dict call expression. + + Return names, types, totality, was there an error during parsing. + If some type is not ready, return None. + """ + # TODO: Share code with check_argument_count in checkexpr.py? + args = call.args + if len(args) < 2: + return self.fail_typeddict_arg("Too few arguments for TypedDict()", call) + if len(args) > 3: + return self.fail_typeddict_arg("Too many arguments for TypedDict()", call) + # TODO: Support keyword arguments + if call.arg_kinds not in ([ARG_POS, ARG_POS], [ARG_POS, ARG_POS, ARG_NAMED]): + return self.fail_typeddict_arg("Unexpected arguments to TypedDict()", call) + if len(args) == 3 and call.arg_names[2] != "total": + return self.fail_typeddict_arg( + f'Unexpected keyword argument "{call.arg_names[2]}" for "TypedDict"', call + ) + if not isinstance(args[0], StrExpr): + return self.fail_typeddict_arg( + "TypedDict() expects a string literal as the first argument", call + ) + if not isinstance(args[1], DictExpr): + return self.fail_typeddict_arg( + "TypedDict() expects a dictionary literal as the second argument", call + ) + total: bool | None = True + if len(args) == 3: + total = require_bool_literal_argument(self.api, call.args[2], "total") + if total is None: + return "", [], [], True, [], False + dictexpr = args[1] + tvar_defs = self.api.get_and_bind_all_tvars([t for k, t in dictexpr.items]) + res = self.parse_typeddict_fields_with_types(dictexpr.items) + if res is None: + # One of the types is not ready, defer. + return None + items, types, ok = res + assert total is not None + return args[0].value, items, types, total, tvar_defs, ok + + def parse_typeddict_fields_with_types( + self, dict_items: list[tuple[Expression | None, Expression]] + ) -> tuple[list[str], list[Type], bool] | None: + """Parse typed dict items passed as pairs (name expression, type expression). + + Return names, types, was there an error. If some type is not ready, return None. + """ + seen_keys = set() + items: list[str] = [] + types: list[Type] = [] + for field_name_expr, field_type_expr in dict_items: + if isinstance(field_name_expr, StrExpr): + key = field_name_expr.value + items.append(key) + if key in seen_keys: + self.fail(f'Duplicate TypedDict key "{key}"', field_name_expr) + seen_keys.add(key) + else: + name_context = field_name_expr or field_type_expr + self.fail_typeddict_arg("Invalid TypedDict() field name", name_context) + return [], [], False + try: + type = expr_to_unanalyzed_type( + field_type_expr, self.options, self.api.is_stub_file + ) + except TypeTranslationError: + self.fail_typeddict_arg("Use dict literal for nested TypedDict", field_type_expr) + return [], [], False + analyzed = self.api.anal_type( + type, + allow_typed_dict_special_forms=True, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="TypedDict item type", + prohibit_special_class_field_types="TypedDict", + ) + if analyzed is None: + return None + types.append(analyzed) + return items, types, True + + def fail_typeddict_arg( + self, message: str, context: Context + ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool]: + self.fail(message, context) + return "", [], [], True, [], False + + def build_typeddict_typeinfo( + self, + name: str, + item_types: dict[str, Type], + required_keys: set[str], + readonly_keys: set[str], + line: int, + existing_info: TypeInfo | None, + ) -> TypeInfo: + # Prefer typing then typing_extensions if available. + fallback = ( + self.api.named_type_or_none("typing._TypedDict", []) + or self.api.named_type_or_none("typing_extensions._TypedDict", []) + or self.api.named_type_or_none("mypy_extensions._TypedDict", []) + ) + assert fallback is not None + info = existing_info or self.api.basic_new_typeinfo(name, fallback, line) + typeddict_type = TypedDictType(item_types, required_keys, readonly_keys, fallback) + if has_placeholder(typeddict_type): + self.api.process_placeholder( + None, "TypedDict item", info, force_progress=typeddict_type != info.typeddict_type + ) + info.update_typeddict_type(typeddict_type) + return info + + # Helpers + + def is_typeddict(self, expr: Expression) -> bool: + return isinstance(expr, RefExpr) and ( + isinstance(expr.node, TypeInfo) + and expr.node.typeddict_type is not None + or isinstance(expr.node, TypeAlias) + and isinstance(get_proper_type(expr.node.target), TypedDictType) + ) + + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.api.fail(msg, ctx, code=code) + + def note(self, msg: str, ctx: Context) -> None: + self.api.note(msg, ctx) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/sharedparse.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/sharedparse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..6cf7e0458bd097147caeaa20a8ebbfeeb254cb42 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/sharedparse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/sharedparse.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/sharedparse.py new file mode 100644 index 0000000000000000000000000000000000000000..71d1dee8f7d6e20c4daabdfcdf0b433a69e0be33 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/sharedparse.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import Final + +"""Shared logic between our three mypy parser files.""" + + +_NON_BINARY_MAGIC_METHODS: Final = { + "__abs__", + "__call__", + "__complex__", + "__contains__", + "__buffer__", + "__del__", + "__delattr__", + "__delitem__", + "__enter__", + "__exit__", + "__float__", + "__getattr__", + "__getattribute__", + "__getitem__", + "__hex__", + "__init__", + "__init_subclass__", + "__int__", + "__invert__", + "__iter__", + "__len__", + "__long__", + "__neg__", + "__new__", + "__oct__", + "__pos__", + "__release_buffer__", + "__repr__", + "__reversed__", + "__setattr__", + "__setitem__", + "__str__", +} + +MAGIC_METHODS_ALLOWING_KWARGS: Final = { + "__init__", + "__init_subclass__", + "__new__", + "__call__", + "__setattr__", +} + +BINARY_MAGIC_METHODS: Final = { + "__add__", + "__and__", + "__divmod__", + "__eq__", + "__floordiv__", + "__ge__", + "__gt__", + "__iadd__", + "__iand__", + "__idiv__", + "__ifloordiv__", + "__ilshift__", + "__imatmul__", + "__imod__", + "__imul__", + "__ior__", + "__ipow__", + "__irshift__", + "__isub__", + "__itruediv__", + "__ixor__", + "__le__", + "__lshift__", + "__lt__", + "__matmul__", + "__mod__", + "__mul__", + "__ne__", + "__or__", + "__pow__", + "__radd__", + "__rand__", + "__rdiv__", + "__rfloordiv__", + "__rlshift__", + "__rmatmul__", + "__rmod__", + "__rmul__", + "__ror__", + "__rpow__", + "__rrshift__", + "__rshift__", + "__rsub__", + "__rtruediv__", + "__rxor__", + "__sub__", + "__truediv__", + "__xor__", +} + +assert not (_NON_BINARY_MAGIC_METHODS & BINARY_MAGIC_METHODS) + +MAGIC_METHODS: Final = _NON_BINARY_MAGIC_METHODS | BINARY_MAGIC_METHODS + +MAGIC_METHODS_POS_ARGS_ONLY: Final = MAGIC_METHODS - MAGIC_METHODS_ALLOWING_KWARGS + + +def special_function_elide_names(name: str) -> bool: + return name in MAGIC_METHODS_POS_ARGS_ONLY + + +def argument_elide_name(name: str | None) -> bool: + return name is not None and name.startswith("__") and not name.endswith("__") diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/solve.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/solve.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e10fec17aeddea111416b707c68b158e18523236 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/solve.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/solve.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..e3709106996cdc79beacb5b53e171bf5893edcc0 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/solve.py @@ -0,0 +1,598 @@ +"""Type inference constraint solving""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable, Sequence +from typing import TypeAlias as _TypeAlias + +from mypy.constraints import SUBTYPE_OF, SUPERTYPE_OF, Constraint, infer_constraints, neg_op +from mypy.expandtype import expand_type +from mypy.graph_utils import prepare_sccs, strongly_connected_components, topsort +from mypy.join import join_type_list +from mypy.meet import meet_type_list, meet_types +from mypy.subtypes import is_subtype +from mypy.typeops import get_all_type_vars +from mypy.types import ( + AnyType, + Instance, + NoneType, + ParamSpecType, + ProperType, + TupleType, + Type, + TypeOfAny, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UninhabitedType, + UnionType, + UnpackType, + get_proper_type, +) +from mypy.typestate import type_state + +Bounds: _TypeAlias = "dict[TypeVarId, set[Type]]" +Graph: _TypeAlias = "set[tuple[TypeVarId, TypeVarId]]" +Solutions: _TypeAlias = "dict[TypeVarId, Type | None]" + + +def solve_constraints( + original_vars: Sequence[TypeVarLikeType], + constraints: list[Constraint], + strict: bool = True, + allow_polymorphic: bool = False, + skip_unsatisfied: bool = False, +) -> tuple[list[Type | None], list[TypeVarLikeType]]: + """Solve type constraints. + + Return the best type(s) for type variables; each type can be None if the value of + the variable could not be solved. + + If a variable has no constraints, if strict=True then arbitrarily + pick UninhabitedType as the value of the type variable. If strict=False, pick AnyType. + If allow_polymorphic=True, then use the full algorithm that can potentially return + free type variables in solutions (these require special care when applying). Otherwise, + use a simplified algorithm that just solves each type variable individually if possible. + + The skip_unsatisfied flag matches the same one in applytype.apply_generic_arguments(). + """ + vars = [tv.id for tv in original_vars] + if not vars: + return [], [] + + originals = {tv.id: tv for tv in original_vars} + extra_vars: list[TypeVarId] = [] + # Get additional type variables from generic actuals. + for c in constraints: + extra_vars.extend([v.id for v in c.extra_tvars if v.id not in vars + extra_vars]) + originals.update({v.id: v for v in c.extra_tvars if v.id not in originals}) + + if allow_polymorphic: + # Constraints inferred from unions require special handling in polymorphic inference. + constraints = skip_reverse_union_constraints(constraints) + + # Collect a list of constraints for each type variable. + cmap: dict[TypeVarId, list[Constraint]] = {tv: [] for tv in vars + extra_vars} + for con in constraints: + if con.type_var in vars + extra_vars: + cmap[con.type_var].append(con) + + if allow_polymorphic: + if constraints: + solutions, free_vars = solve_with_dependent( + vars + extra_vars, constraints, vars, originals + ) + else: + solutions = {} + free_vars = [] + else: + solutions = {} + free_vars = [] + for tv, cs in cmap.items(): + if not cs: + continue + lowers = [c.target for c in cs if c.op == SUPERTYPE_OF] + uppers = [c.target for c in cs if c.op == SUBTYPE_OF] + solution = solve_one(lowers, uppers) + + # Do not leak type variables in non-polymorphic solutions. + if solution is None or not get_vars( + solution, [tv for tv in extra_vars if tv not in vars] + ): + solutions[tv] = solution + + res: list[Type | None] = [] + for v in vars: + if v in solutions: + res.append(solutions[v]) + else: + # No constraints for type variable -- 'UninhabitedType' is the most specific type. + candidate: Type + if strict: + candidate = UninhabitedType() + candidate.ambiguous = True + else: + candidate = AnyType(TypeOfAny.special_form) + res.append(candidate) + + if not free_vars and not skip_unsatisfied: + # Most of the validation for solutions is done in applytype.py, but here we can + # quickly test solutions w.r.t. to upper bounds, and use the latter (if possible), + # if solutions are actually not valid (due to poor inference context). + res = pre_validate_solutions(res, original_vars, constraints) + + return res, free_vars + + +def solve_with_dependent( + vars: list[TypeVarId], + constraints: list[Constraint], + original_vars: list[TypeVarId], + originals: dict[TypeVarId, TypeVarLikeType], +) -> tuple[Solutions, list[TypeVarLikeType]]: + """Solve set of constraints that may depend on each other, like T <: List[S]. + + The whole algorithm consists of five steps: + * Propagate via linear constraints and use secondary constraints to get transitive closure + * Find dependencies between type variables, group them in SCCs, and sort topologically + * Check that all SCC are intrinsically linear, we can't solve (express) T <: List[T] + * Variables in leaf SCCs that don't have constant bounds are free (choose one per SCC) + * Solve constraints iteratively starting from leaves, updating bounds after each step. + """ + graph, lowers, uppers = transitive_closure(vars, constraints) + + dmap = compute_dependencies(vars, graph, lowers, uppers) + sccs = list(strongly_connected_components(set(vars), dmap)) + if not all(check_linear(scc, lowers, uppers) for scc in sccs): + return {}, [] + raw_batches = list(topsort(prepare_sccs(sccs, dmap))) + + free_vars = [] + free_solutions = {} + for scc in raw_batches[0]: + # If there are no bounds on this SCC, then the only meaningful solution we can + # express, is that each variable is equal to a new free variable. For example, + # if we have T <: S, S <: U, we deduce: T = S = U = . + if all(not lowers[tv] and not uppers[tv] for tv in scc): + best_free = choose_free([originals[tv] for tv in scc], original_vars) + if best_free: + # TODO: failing to choose may cause leaking type variables, + # we need to fail gracefully instead. + free_vars.append(best_free.id) + free_solutions[best_free.id] = best_free + + # Update lowers/uppers with free vars, so these can now be used + # as valid solutions. + for l, u in graph: + if l in free_vars: + lowers[u].add(free_solutions[l]) + if u in free_vars: + uppers[l].add(free_solutions[u]) + + # Flatten the SCCs that are independent, we can solve them together, + # since we don't need to update any targets in between. + batches = [] + for batch in raw_batches: + next_bc = [] + for scc in batch: + next_bc.extend(list(scc)) + batches.append(next_bc) + + solutions: dict[TypeVarId, Type | None] = {} + for flat_batch in batches: + res = solve_iteratively(flat_batch, graph, lowers, uppers) + solutions.update(res) + return solutions, [free_solutions[tv] for tv in free_vars] + + +def solve_iteratively( + batch: list[TypeVarId], graph: Graph, lowers: Bounds, uppers: Bounds +) -> Solutions: + """Solve transitive closure sequentially, updating upper/lower bounds after each step. + + Transitive closure is represented as a linear graph plus lower/upper bounds for each + type variable, see transitive_closure() docstring for details. + + We solve for type variables that appear in `batch`. If a bound is not constant (i.e. it + looks like T :> F[S, ...]), we substitute solutions found so far in the target F[S, ...] + after solving the batch. + + Importantly, after solving each variable in a batch, we move it from linear graph to + upper/lower bounds, this way we can guarantee consistency of solutions (see comment below + for an example when this is important). + """ + solutions = {} + s_batch = set(batch) + while s_batch: + for tv in sorted(s_batch, key=lambda x: x.raw_id): + if lowers[tv] or uppers[tv]: + solvable_tv = tv + break + else: + break + # Solve each solvable type variable separately. + s_batch.remove(solvable_tv) + result = solve_one(lowers[solvable_tv], uppers[solvable_tv]) + solutions[solvable_tv] = result + if result is None: + # TODO: support backtracking lower/upper bound choices and order within SCCs. + # (will require switching this function from iterative to recursive). + continue + + # Update the (transitive) bounds from graph if there is a solution. + # This is needed to guarantee solutions will never contradict the initial + # constraints. For example, consider {T <: S, T <: A, S :> B} with A :> B. + # If we would not update the uppers/lowers from graph, we would infer T = A, S = B + # which is not correct. + for l, u in graph.copy(): + if l == u: + continue + if l == solvable_tv: + lowers[u].add(result) + graph.remove((l, u)) + if u == solvable_tv: + uppers[l].add(result) + graph.remove((l, u)) + + # We can update uppers/lowers only once after solving the whole SCC, + # since uppers/lowers can't depend on type variables in the SCC + # (and we would reject such SCC as non-linear and therefore not solvable). + subs = {tv: s for (tv, s) in solutions.items() if s is not None} + for tv in lowers: + lowers[tv] = {expand_type(lt, subs) for lt in lowers[tv]} + for tv in uppers: + uppers[tv] = {expand_type(ut, subs) for ut in uppers[tv]} + return solutions + + +def _join_sorted_key(t: Type) -> int: + t = get_proper_type(t) + if isinstance(t, UnionType): + return -2 + if isinstance(t, NoneType): + return -1 + return 0 + + +def solve_one(lowers: Iterable[Type], uppers: Iterable[Type]) -> Type | None: + """Solve constraints by finding by using meets of upper bounds, and joins of lower bounds.""" + + candidate: Type | None = None + + # Filter out previous results of failed inference, they will only spoil the current pass... + new_uppers = [] + for u in uppers: + pu = get_proper_type(u) + if not isinstance(pu, UninhabitedType) or not pu.ambiguous: + new_uppers.append(u) + uppers = new_uppers + + # ...unless this is the only information we have, then we just pass it on. + lowers = list(lowers) + if not uppers and not lowers: + candidate = UninhabitedType() + candidate.ambiguous = True + return candidate + + bottom: Type | None = None + top: Type | None = None + + # Process each bound separately, and calculate the lower and upper + # bounds based on constraints. Note that we assume that the constraint + # targets do not have constraint references. + if type_state.infer_unions and lowers: + # This deviates from the general mypy semantics because + # recursive types are union-heavy in 95% of cases. + # Retain `None` when no bottoms were provided to avoid bogus `Never` inference. + bottom = UnionType.make_union(lowers) + else: + # The order of lowers is non-deterministic. + # We attempt to sort lowers because joins are non-associative. For instance: + # join(join(int, str), int | str) == join(object, int | str) == object + # join(int, join(str, int | str)) == join(int, int | str) == int | str + # Note that joins in theory should be commutative, but in practice some bugs mean this is + # also a source of non-deterministic type checking results. + sorted_lowers = sorted(lowers, key=_join_sorted_key) + if sorted_lowers: + bottom = join_type_list(sorted_lowers) + + for target in uppers: + if top is None: + top = target + else: + top = meet_types(top, target) + + p_top = get_proper_type(top) + p_bottom = get_proper_type(bottom) + if isinstance(p_top, AnyType) or isinstance(p_bottom, AnyType): + source_any = top if isinstance(p_top, AnyType) else bottom + assert isinstance(source_any, ProperType) and isinstance(source_any, AnyType) + return AnyType(TypeOfAny.from_another_any, source_any=source_any) + elif bottom is None: + if top: + candidate = top + else: + # No constraints for type variable + return None + elif top is None: + candidate = bottom + elif is_subtype(bottom, top): + candidate = bottom + else: + candidate = None + return candidate + + +def choose_free( + scc: list[TypeVarLikeType], original_vars: list[TypeVarId] +) -> TypeVarLikeType | None: + """Choose the best solution for an SCC containing only type variables. + + This is needed to preserve e.g. the upper bound in a situation like this: + def dec(f: Callable[[T], S]) -> Callable[[T], S]: ... + + @dec + def test(x: U) -> U: ... + + where U <: A. + """ + + if len(scc) == 1: + # Fast path, choice is trivial. + return scc[0] + + common_upper_bound = meet_type_list([t.upper_bound for t in scc]) + common_upper_bound_p = get_proper_type(common_upper_bound) + # We include None for when strict-optional is disabled. + if isinstance(common_upper_bound_p, (UninhabitedType, NoneType)): + # This will cause to infer Never, which is better than a free TypeVar + # that has an upper bound Never. + return None + + values: list[Type] = [] + for tv in scc: + if isinstance(tv, TypeVarType) and tv.values: + if values: + # It is too tricky to support multiple TypeVars with values + # within the same SCC. + return None + values = tv.values.copy() + + if values and not is_trivial_bound(common_upper_bound_p): + # If there are both values and upper bound present, we give up, + # since type variables having both are not supported. + return None + + # For convenience with current type application machinery, we use a stable + # choice that prefers the original type variables (not polymorphic ones) in SCC. + best = min(scc, key=lambda x: (x.id not in original_vars, x.id.raw_id)) + if isinstance(best, TypeVarType): + return best.copy_modified(values=values, upper_bound=common_upper_bound) + if is_trivial_bound(common_upper_bound_p, allow_tuple=True): + # TODO: support more cases for ParamSpecs/TypeVarTuples + return best + return None + + +def is_trivial_bound(tp: ProperType, allow_tuple: bool = False) -> bool: + if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple": + return allow_tuple and is_trivial_bound(get_proper_type(tp.args[0])) + return isinstance(tp, Instance) and tp.type.fullname == "builtins.object" + + +def find_linear(c: Constraint) -> tuple[bool, TypeVarId | None]: + """Find out if this constraint represent a linear relationship, return target id if yes.""" + if isinstance(c.origin_type_var, TypeVarType): + if isinstance(c.target, TypeVarType): + return True, c.target.id + if isinstance(c.origin_type_var, ParamSpecType): + if isinstance(c.target, ParamSpecType) and not c.target.prefix.arg_types: + return True, c.target.id + if isinstance(c.origin_type_var, TypeVarTupleType): + target = get_proper_type(c.target) + if isinstance(target, TupleType) and len(target.items) == 1: + item = target.items[0] + if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType): + return True, item.type.id + return False, None + + +def transitive_closure( + tvars: list[TypeVarId], constraints: list[Constraint] +) -> tuple[Graph, Bounds, Bounds]: + """Find transitive closure for given constraints on type variables. + + Transitive closure gives maximal set of lower/upper bounds for each type variable, + such that we cannot deduce any further bounds by chaining other existing bounds. + + The transitive closure is represented by: + * A set of lower and upper bounds for each type variable, where only constant and + non-linear terms are included in the bounds. + * A graph of linear constraints between type variables (represented as a set of pairs) + Such separation simplifies reasoning, and allows an efficient and simple incremental + transitive closure algorithm that we use here. + + For example if we have initial constraints [T <: S, S <: U, U <: int], the transitive + closure is given by: + * {} <: T <: {int} + * {} <: S <: {int} + * {} <: U <: {int} + * {T <: S, S <: U, T <: U} + """ + uppers: Bounds = defaultdict(set) + lowers: Bounds = defaultdict(set) + graph: Graph = {(tv, tv) for tv in tvars} + + remaining = set(constraints) + while remaining: + c = remaining.pop() + # Note that ParamSpec constraint P <: Q may be considered linear only if Q has no prefix, + # for cases like P <: Concatenate[T, Q] we should consider this non-linear and put {P} and + # {T, Q} into separate SCCs. Similarly, Ts <: Tuple[*Us] considered linear, while + # Ts <: Tuple[*Us, U] is non-linear. + is_linear, target_id = find_linear(c) + if is_linear and target_id in tvars: + assert target_id is not None + if c.op == SUBTYPE_OF: + lower, upper = c.type_var, target_id + else: + lower, upper = target_id, c.type_var + if (lower, upper) in graph: + continue + graph |= { + (l, u) for l in tvars for u in tvars if (l, lower) in graph and (upper, u) in graph + } + for u in tvars: + if (upper, u) in graph: + lowers[u] |= lowers[lower] + for l in tvars: + if (l, lower) in graph: + uppers[l] |= uppers[upper] + for lt in lowers[lower]: + for ut in uppers[upper]: + add_secondary_constraints(remaining, lt, ut) + elif c.op == SUBTYPE_OF: + if c.target in uppers[c.type_var]: + continue + for l in tvars: + if (l, c.type_var) in graph: + uppers[l].add(c.target) + for lt in lowers[c.type_var]: + add_secondary_constraints(remaining, lt, c.target) + else: + assert c.op == SUPERTYPE_OF + if c.target in lowers[c.type_var]: + continue + for u in tvars: + if (c.type_var, u) in graph: + lowers[u].add(c.target) + for ut in uppers[c.type_var]: + add_secondary_constraints(remaining, c.target, ut) + return graph, lowers, uppers + + +def add_secondary_constraints(cs: set[Constraint], lower: Type, upper: Type) -> None: + """Add secondary constraints inferred between lower and upper (in place).""" + if isinstance(get_proper_type(upper), UnionType) and isinstance( + get_proper_type(lower), UnionType + ): + # When both types are unions, this can lead to inferring spurious constraints, + # for example Union[T, int] <: S <: Union[T, int] may infer T <: int. + # To avoid this, just skip them for now. + return + # TODO: what if secondary constraints result in inference against polymorphic actual? + cs.update(set(infer_constraints(lower, upper, SUBTYPE_OF))) + cs.update(set(infer_constraints(upper, lower, SUPERTYPE_OF))) + + +def compute_dependencies( + tvars: list[TypeVarId], graph: Graph, lowers: Bounds, uppers: Bounds +) -> dict[TypeVarId, list[TypeVarId]]: + """Compute dependencies between type variables induced by constraints. + + If we have a constraint like T <: List[S], we say that T depends on S, since + we will need to solve for S first before we can solve for T. + """ + res = {} + for tv in tvars: + deps = set() + for lt in lowers[tv]: + deps |= get_vars(lt, tvars) + for ut in uppers[tv]: + deps |= get_vars(ut, tvars) + for other in tvars: + if other == tv: + continue + if (tv, other) in graph or (other, tv) in graph: + deps.add(other) + res[tv] = list(deps) + return res + + +def check_linear(scc: set[TypeVarId], lowers: Bounds, uppers: Bounds) -> bool: + """Check there are only linear constraints between type variables in SCC. + + Linear are constraints like T <: S (while T <: F[S] are non-linear). + """ + for tv in scc: + if any(get_vars(lt, list(scc)) for lt in lowers[tv]): + return False + if any(get_vars(ut, list(scc)) for ut in uppers[tv]): + return False + return True + + +def skip_reverse_union_constraints(cs: list[Constraint]) -> list[Constraint]: + """Avoid ambiguities for constraints inferred from unions during polymorphic inference. + + Polymorphic inference implicitly relies on assumption that a reverse of a linear constraint + is a linear constraint. This is however not true in presence of union types, for example + T :> Union[S, int] vs S <: T. Trying to solve such constraints would be detected ambiguous + as (T, S) form a non-linear SCC. However, simply removing the linear part results in a valid + solution T = Union[S, int], S = . A similar scenario is when we get T <: Union[T, int], + such constraints carry no information, and will equally confuse linearity check. + + TODO: a cleaner solution may be to avoid inferring such constraints in first place, but + this would require passing around a flag through all infer_constraints() calls. + """ + reverse_union_cs = set() + for c in cs: + p_target = get_proper_type(c.target) + if isinstance(p_target, UnionType): + for item in p_target.items: + if isinstance(item, TypeVarType): + if item == c.origin_type_var and c.op == SUBTYPE_OF: + reverse_union_cs.add(c) + continue + # These two forms are semantically identical, but are different from + # the point of view of Constraint.__eq__(). + reverse_union_cs.add(Constraint(item, neg_op(c.op), c.origin_type_var)) + reverse_union_cs.add(Constraint(c.origin_type_var, c.op, item)) + return [c for c in cs if c not in reverse_union_cs] + + +def get_vars(target: Type, vars: list[TypeVarId]) -> set[TypeVarId]: + """Find type variables for which we are solving in a target type.""" + return {tv.id for tv in get_all_type_vars(target)} & set(vars) + + +def pre_validate_solutions( + solutions: list[Type | None], + original_vars: Sequence[TypeVarLikeType], + constraints: list[Constraint], +) -> list[Type | None]: + """Check is each solution satisfies the upper bound of the corresponding type variable. + + If it doesn't satisfy the bound, check if bound itself satisfies all constraints, and + if yes, use it instead as a fallback solution. + """ + new_solutions: list[Type | None] = [] + for t, s in zip(original_vars, solutions): + if is_callable_protocol(t.upper_bound): + # This is really ad-hoc, but a proper fix would be much more complex, + # and otherwise this may cause crash in a relatively common scenario. + new_solutions.append(s) + continue + if s is not None and not is_subtype(s, t.upper_bound): + bound_satisfies_all = True + for c in constraints: + if c.op == SUBTYPE_OF and not is_subtype(t.upper_bound, c.target): + bound_satisfies_all = False + break + if c.op == SUPERTYPE_OF and not is_subtype(c.target, t.upper_bound): + bound_satisfies_all = False + break + if bound_satisfies_all: + new_solutions.append(t.upper_bound) + continue + new_solutions.append(s) + return new_solutions + + +def is_callable_protocol(t: Type) -> bool: + proper_t = get_proper_type(t) + if isinstance(proper_t, Instance) and proper_t.type.is_protocol: + return "__call__" in proper_t.type.protocol_members + return False diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/split_namespace.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/split_namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..d1720cce82b04bde33c815ab97e96fd4df5835dd --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/split_namespace.py @@ -0,0 +1,35 @@ +"""Split namespace for argparse to allow separating options by prefix. + +We use this to direct some options to an Options object and some to a +regular namespace. +""" + +# In its own file largely because mypyc doesn't support its use of +# __getattr__/__setattr__ and has some issues with __dict__ + +from __future__ import annotations + +import argparse +from typing import Any + + +class SplitNamespace(argparse.Namespace): + def __init__(self, standard_namespace: object, alt_namespace: object, alt_prefix: str) -> None: + self.__dict__["_standard_namespace"] = standard_namespace + self.__dict__["_alt_namespace"] = alt_namespace + self.__dict__["_alt_prefix"] = alt_prefix + + def _get(self) -> tuple[Any, Any]: + return (self._standard_namespace, self._alt_namespace) + + def __setattr__(self, name: str, value: Any) -> None: + if name.startswith(self._alt_prefix): + setattr(self._alt_namespace, name[len(self._alt_prefix) :], value) + else: + setattr(self._standard_namespace, name, value) + + def __getattr__(self, name: str) -> Any: + if name.startswith(self._alt_prefix): + return getattr(self._alt_namespace, name[len(self._alt_prefix) :]) + else: + return getattr(self._standard_namespace, name) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/state.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/state.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..254e82da29c067d753bf5003f9576d479deea603 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/state.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/state.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/state.py new file mode 100644 index 0000000000000000000000000000000000000000..a3055bf6b2085d7a230b7df8fa7fb153228312fe --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/state.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Final + +# These are global mutable state. Don't add anything here unless there's a very +# good reason. + + +class StrictOptionalState: + # Wrap this in a class since it's faster that using a module-level attribute. + + def __init__(self, strict_optional: bool) -> None: + # Value varies by file being processed + self.strict_optional = strict_optional + + @contextmanager + def strict_optional_set(self, value: bool) -> Iterator[None]: + saved = self.strict_optional + self.strict_optional = value + try: + yield + finally: + self.strict_optional = saved + + +state: Final = StrictOptionalState(strict_optional=True) +find_occurrences: tuple[str, str] | None = None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stats.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stats.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..83742c576d460bfb75de71e15d55deb0e3105e49 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stats.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stats.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..e3499d23456350cf39121b72231d53a57569bde8 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stats.py @@ -0,0 +1,494 @@ +"""Utilities for calculating and reporting statistics about types.""" + +from __future__ import annotations + +import os +from collections import Counter +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Final + +from mypy import nodes +from mypy.argmap import map_formals_to_actuals +from mypy.nodes import ( + AssignmentExpr, + AssignmentStmt, + BreakStmt, + BytesExpr, + CallExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ContinueStmt, + EllipsisExpr, + Expression, + ExpressionStmt, + FloatExpr, + FuncDef, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + MemberExpr, + MypyFile, + NameExpr, + Node, + OpExpr, + PassStmt, + RefExpr, + StrExpr, + TypeApplication, + UnaryExpr, + YieldFromExpr, +) +from mypy.traverser import TraverserVisitor +from mypy.type_visitor import ANY_STRATEGY, BoolTypeQuery +from mypy.typeanal import collect_all_inner_types +from mypy.types import ( + AnyType, + CallableType, + FunctionLike, + Instance, + TupleType, + Type, + TypeOfAny, + TypeVarType, + get_proper_type, + get_proper_types, +) +from mypy.util import correct_relative_import + +TYPE_EMPTY: Final = 0 +TYPE_UNANALYZED: Final = 1 # type of non-typechecked code +TYPE_PRECISE: Final = 2 +TYPE_IMPRECISE: Final = 3 +TYPE_ANY: Final = 4 + +precision_names: Final = ["empty", "unanalyzed", "precise", "imprecise", "any"] + + +class StatisticsVisitor(TraverserVisitor): + def __init__( + self, + inferred: bool, + filename: str, + modules: dict[str, MypyFile], + typemap: dict[Expression, Type] | None = None, + all_nodes: bool = False, + visit_untyped_defs: bool = True, + ) -> None: + self.inferred = inferred + self.filename = filename + self.modules = modules + self.typemap = typemap + self.all_nodes = all_nodes + self.visit_untyped_defs = visit_untyped_defs + + self.num_precise_exprs = 0 + self.num_imprecise_exprs = 0 + self.num_any_exprs = 0 + + self.num_simple_types = 0 + self.num_generic_types = 0 + self.num_tuple_types = 0 + self.num_function_types = 0 + self.num_typevar_types = 0 + self.num_complex_types = 0 + self.num_any_types = 0 + + self.line = -1 + + self.line_map: dict[int, int] = {} + + self.type_of_any_counter: Counter[int] = Counter() + self.any_line_map: dict[int, list[AnyType]] = {} + + # For each scope (top level/function), whether the scope was type checked + # (annotated function). + # + # TODO: Handle --check-untyped-defs + self.checked_scopes = [True] + + self.output: list[str] = [] + + TraverserVisitor.__init__(self) + + def visit_mypy_file(self, o: MypyFile) -> None: + self.cur_mod_node = o + self.cur_mod_id = o.fullname + super().visit_mypy_file(o) + + def visit_import_from(self, imp: ImportFrom) -> None: + self.process_import(imp) + + def visit_import_all(self, imp: ImportAll) -> None: + self.process_import(imp) + + def process_import(self, imp: ImportFrom | ImportAll) -> None: + import_id, ok = correct_relative_import( + self.cur_mod_id, imp.relative, imp.id, self.cur_mod_node.is_package_init_file() + ) + if ok and import_id in self.modules: + kind = TYPE_PRECISE + else: + kind = TYPE_ANY + self.record_line(imp.line, kind) + + def visit_import(self, imp: Import) -> None: + if all(id in self.modules for id, _ in imp.ids): + kind = TYPE_PRECISE + else: + kind = TYPE_ANY + self.record_line(imp.line, kind) + + def visit_func_def(self, o: FuncDef) -> None: + with self.enter_scope(o): + self.line = o.line + if len(o.expanded) > 1 and o.expanded != [o] * len(o.expanded): + if o in o.expanded: + print( + "{}:{}: ERROR: cycle in function expansion; skipping".format( + self.filename, o.line + ) + ) + return + for defn in o.expanded: + assert isinstance(defn, FuncDef) + self.visit_func_def(defn) + else: + if o.type: + assert isinstance(o.type, CallableType) + sig = o.type + arg_types = sig.arg_types + if sig.arg_names and sig.arg_names[0] == "self" and not self.inferred: + arg_types = arg_types[1:] + for arg in arg_types: + self.type(arg) + self.type(sig.ret_type) + elif self.all_nodes: + self.record_line(self.line, TYPE_ANY) + if not o.is_dynamic() or self.visit_untyped_defs: + super().visit_func_def(o) + + @contextmanager + def enter_scope(self, o: FuncDef) -> Iterator[None]: + self.checked_scopes.append(o.type is not None and self.checked_scopes[-1]) + yield None + self.checked_scopes.pop() + + def is_checked_scope(self) -> bool: + return self.checked_scopes[-1] + + def visit_class_def(self, o: ClassDef) -> None: + self.record_line(o.line, TYPE_PRECISE) # TODO: Look at base classes + # Override this method because we don't want to analyze base_type_exprs (base_type_exprs + # are base classes in a class declaration). + # While base_type_exprs are technically expressions, type analyzer does not visit them and + # they are not in the typemap. + for d in o.decorators: + d.accept(self) + o.defs.accept(self) + + def visit_type_application(self, o: TypeApplication) -> None: + self.line = o.line + for t in o.types: + self.type(t) + super().visit_type_application(o) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + self.line = o.line + if isinstance(o.rvalue, nodes.CallExpr) and isinstance( + o.rvalue.analyzed, nodes.TypeVarExpr + ): + # Type variable definition -- not a real assignment. + return + if o.type: + # If there is an explicit type, don't visit the l.h.s. as an expression + # to avoid double-counting and mishandling special forms. + self.type(o.type) + o.rvalue.accept(self) + return + elif self.inferred and not self.all_nodes: + # if self.all_nodes is set, lvalues will be visited later + for lvalue in o.lvalues: + if isinstance(lvalue, nodes.TupleExpr): + items = lvalue.items + else: + items = [lvalue] + for item in items: + if isinstance(item, RefExpr) and item.is_inferred_def: + if self.typemap is not None: + self.type(self.typemap.get(item)) + super().visit_assignment_stmt(o) + + def visit_expression_stmt(self, o: ExpressionStmt) -> None: + if isinstance(o.expr, (StrExpr, BytesExpr)): + # Docstring + self.record_line(o.line, TYPE_EMPTY) + else: + super().visit_expression_stmt(o) + + def visit_pass_stmt(self, o: PassStmt) -> None: + self.record_precise_if_checked_scope(o) + + def visit_break_stmt(self, o: BreakStmt) -> None: + self.record_precise_if_checked_scope(o) + + def visit_continue_stmt(self, o: ContinueStmt) -> None: + self.record_precise_if_checked_scope(o) + + def visit_name_expr(self, o: NameExpr) -> None: + if o.fullname in ("builtins.None", "builtins.True", "builtins.False", "builtins.Ellipsis"): + self.record_precise_if_checked_scope(o) + else: + self.process_node(o) + super().visit_name_expr(o) + + def visit_yield_from_expr(self, o: YieldFromExpr) -> None: + if o.expr: + o.expr.accept(self) + + def visit_call_expr(self, o: CallExpr) -> None: + self.process_node(o) + if o.analyzed: + o.analyzed.accept(self) + else: + o.callee.accept(self) + for a in o.args: + a.accept(self) + self.record_call_target_precision(o) + + def record_call_target_precision(self, o: CallExpr) -> None: + """Record precision of formal argument types used in a call.""" + if not self.typemap or o.callee not in self.typemap: + # Type not available. + return + callee_type = get_proper_type(self.typemap[o.callee]) + if isinstance(callee_type, CallableType): + self.record_callable_target_precision(o, callee_type) + else: + pass # TODO: Handle overloaded functions, etc. + + def record_callable_target_precision(self, o: CallExpr, callee: CallableType) -> None: + """Record imprecision caused by callee argument types. + + This only considers arguments passed in a call expression. Arguments + with default values that aren't provided in a call arguably don't + contribute to typing imprecision at the *call site* (but they + contribute at the function definition). + """ + assert self.typemap + typemap = self.typemap + actual_to_formal = map_formals_to_actuals( + o.arg_kinds, + o.arg_names, + callee.arg_kinds, + callee.arg_names, + lambda n: typemap[o.args[n]], + ) + for formals in actual_to_formal: + for n in formals: + formal = get_proper_type(callee.arg_types[n]) + if isinstance(formal, AnyType): + self.record_line(o.line, TYPE_ANY) + elif is_imprecise(formal): + self.record_line(o.line, TYPE_IMPRECISE) + + def visit_member_expr(self, o: MemberExpr) -> None: + self.process_node(o) + super().visit_member_expr(o) + + def visit_op_expr(self, o: OpExpr) -> None: + self.process_node(o) + super().visit_op_expr(o) + + def visit_comparison_expr(self, o: ComparisonExpr) -> None: + self.process_node(o) + super().visit_comparison_expr(o) + + def visit_index_expr(self, o: IndexExpr) -> None: + self.process_node(o) + super().visit_index_expr(o) + + def visit_assignment_expr(self, o: AssignmentExpr) -> None: + self.process_node(o) + super().visit_assignment_expr(o) + + def visit_unary_expr(self, o: UnaryExpr) -> None: + self.process_node(o) + super().visit_unary_expr(o) + + def visit_str_expr(self, o: StrExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_bytes_expr(self, o: BytesExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_int_expr(self, o: IntExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_float_expr(self, o: FloatExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_complex_expr(self, o: ComplexExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_ellipsis(self, o: EllipsisExpr) -> None: + self.record_precise_if_checked_scope(o) + + # Helpers + + def process_node(self, node: Expression) -> None: + if self.all_nodes: + if self.typemap is not None: + self.line = node.line + self.type(self.typemap.get(node)) + + def record_precise_if_checked_scope(self, node: Node) -> None: + if isinstance(node, Expression) and self.typemap and node not in self.typemap: + kind = TYPE_UNANALYZED + elif self.is_checked_scope(): + kind = TYPE_PRECISE + else: + kind = TYPE_ANY + self.record_line(node.line, kind) + + def type(self, t: Type | None) -> None: + t = get_proper_type(t) + + if not t: + # If an expression does not have a type, it is often due to dead code. + # Don't count these because there can be an unanalyzed value on a line with other + # analyzed expressions, which overwrite the TYPE_UNANALYZED. + self.record_line(self.line, TYPE_UNANALYZED) + return + + if isinstance(t, AnyType) and is_special_form_any(t): + # TODO: What if there is an error in special form definition? + self.record_line(self.line, TYPE_PRECISE) + return + + if isinstance(t, AnyType): + self.log(" !! Any type around line %d" % self.line) + self.num_any_exprs += 1 + self.record_line(self.line, TYPE_ANY) + elif (not self.all_nodes and is_imprecise(t)) or (self.all_nodes and is_imprecise2(t)): + self.log(" !! Imprecise type around line %d" % self.line) + self.num_imprecise_exprs += 1 + self.record_line(self.line, TYPE_IMPRECISE) + else: + self.num_precise_exprs += 1 + self.record_line(self.line, TYPE_PRECISE) + + for typ in get_proper_types(collect_all_inner_types(t)) + [t]: + if isinstance(typ, AnyType): + typ = get_original_any(typ) + if is_special_form_any(typ): + continue + self.type_of_any_counter[typ.type_of_any] += 1 + self.num_any_types += 1 + if self.line in self.any_line_map: + self.any_line_map[self.line].append(typ) + else: + self.any_line_map[self.line] = [typ] + elif isinstance(typ, Instance): + if typ.args: + if any(is_complex(arg) for arg in typ.args): + self.num_complex_types += 1 + else: + self.num_generic_types += 1 + else: + self.num_simple_types += 1 + elif isinstance(typ, FunctionLike): + self.num_function_types += 1 + elif isinstance(typ, TupleType): + if any(is_complex(item) for item in typ.items): + self.num_complex_types += 1 + else: + self.num_tuple_types += 1 + elif isinstance(typ, TypeVarType): + self.num_typevar_types += 1 + + def log(self, string: str) -> None: + self.output.append(string) + + def record_line(self, line: int, precision: int) -> None: + self.line_map[line] = max(precision, self.line_map.get(line, TYPE_EMPTY)) + + +def dump_type_stats( + tree: MypyFile, + path: str, + modules: dict[str, MypyFile], + inferred: bool = False, + typemap: dict[Expression, Type] | None = None, +) -> None: + if is_special_module(path): + return + print(path) + visitor = StatisticsVisitor(inferred, filename=tree.fullname, modules=modules, typemap=typemap) + tree.accept(visitor) + for line in visitor.output: + print(line) + print(" ** precision **") + print(" precise ", visitor.num_precise_exprs) + print(" imprecise", visitor.num_imprecise_exprs) + print(" any ", visitor.num_any_exprs) + print(" ** kinds **") + print(" simple ", visitor.num_simple_types) + print(" generic ", visitor.num_generic_types) + print(" function ", visitor.num_function_types) + print(" tuple ", visitor.num_tuple_types) + print(" TypeVar ", visitor.num_typevar_types) + print(" complex ", visitor.num_complex_types) + print(" any ", visitor.num_any_types) + + +def is_special_module(path: str) -> bool: + return os.path.basename(path) in ("abc.pyi", "typing.pyi", "builtins.pyi") + + +def is_imprecise(t: Type) -> bool: + return t.accept(HasAnyQuery()) + + +class HasAnyQuery(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_any(self, t: AnyType) -> bool: + return not is_special_form_any(t) + + +def is_imprecise2(t: Type) -> bool: + return t.accept(HasAnyQuery2()) + + +class HasAnyQuery2(HasAnyQuery): + def visit_callable_type(self, t: CallableType) -> bool: + # We don't want to flag references to functions with some Any + # argument types (etc.) since they generally don't mean trouble. + return False + + +def is_generic(t: Type) -> bool: + t = get_proper_type(t) + return isinstance(t, Instance) and bool(t.args) + + +def is_complex(t: Type) -> bool: + t = get_proper_type(t) + return is_generic(t) or isinstance(t, (FunctionLike, TupleType, TypeVarType)) + + +def is_special_form_any(t: AnyType) -> bool: + return get_original_any(t).type_of_any == TypeOfAny.special_form + + +def get_original_any(t: AnyType) -> AnyType: + if t.type_of_any == TypeOfAny.from_another_any: + assert t.source_any + assert t.source_any.type_of_any != TypeOfAny.from_another_any + t = t.source_any + return t diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/strconv.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/strconv.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..105969d42bef3ec4d013c6873470ca6eb9bf91f4 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/strconv.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/strconv.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/strconv.py new file mode 100644 index 0000000000000000000000000000000000000000..b26f1d8d71a8e4494c58837a080871fb48eeaa6f --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/strconv.py @@ -0,0 +1,707 @@ +"""Conversion of parse tree nodes to strings.""" + +from __future__ import annotations + +import os +import re +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import mypy.nodes +from mypy.options import Options +from mypy.util import IdMapper, short_type +from mypy.visitor import NodeVisitor + +if TYPE_CHECKING: + import mypy.patterns + import mypy.types + + +class StrConv(NodeVisitor[str]): + """Visitor for converting a node to a human-readable string. + + For example, an MypyFile node from program '1' is converted into + something like this: + + MypyFile:1( + fnam + ExpressionStmt:1( + IntExpr(1))) + """ + + __slots__ = ["options", "show_ids", "id_mapper"] + + def __init__(self, *, show_ids: bool = False, options: Options) -> None: + self.options = options + self.show_ids = show_ids + self.id_mapper: IdMapper | None = None + if show_ids: + self.id_mapper = IdMapper() + + def stringify_type(self, t: mypy.types.Type) -> str: + import mypy.types + + return t.accept(mypy.types.TypeStrVisitor(id_mapper=self.id_mapper, options=self.options)) + + def get_id(self, o: object) -> int | None: + if self.id_mapper: + return self.id_mapper.id(o) + return None + + def format_id(self, o: object) -> str: + if self.id_mapper: + return f"<{self.get_id(o)}>" + else: + return "" + + def dump(self, nodes: Sequence[object], obj: mypy.nodes.Context) -> str: + """Convert a list of items to a multiline pretty-printed string. + + The tag is produced from the type name of obj and its line + number. See mypy.util.dump_tagged for a description of the nodes + argument. + """ + tag = short_type(obj) + ":" + str(obj.line) + if self.show_ids: + assert self.id_mapper is not None + tag += f"<{self.get_id(obj)}>" + return dump_tagged(nodes, tag, self) + + def func_helper(self, o: mypy.nodes.FuncItem) -> list[object]: + """Return a list in a format suitable for dump() that represents the + arguments and the body of a function. The caller can then decorate the + array with information specific to methods, global functions or + anonymous functions. + """ + args: list[mypy.nodes.Var | tuple[str, list[mypy.nodes.Node]]] = [] + extra: list[tuple[str, list[mypy.nodes.Var]]] = [] + for arg in o.arguments: + kind: mypy.nodes.ArgKind = arg.kind + if kind.is_required(): + args.append(arg.variable) + elif kind.is_optional(): + assert arg.initializer is not None + args.append(("default", [arg.variable, arg.initializer])) + elif kind == mypy.nodes.ARG_STAR: + extra.append(("VarArg", [arg.variable])) + elif kind == mypy.nodes.ARG_STAR2: + extra.append(("DictVarArg", [arg.variable])) + a: list[Any] = [] + if o.type_args: + for p in o.type_args: + a.append(self.type_param(p)) + if args: + a.append(("Args", args)) + if o.type: + a.append(o.type) + if o.is_generator: + a.append("Generator") + a.extend(extra) + a.append(o.body) + return a + + # Top-level structures + + def visit_mypy_file(self, o: mypy.nodes.MypyFile) -> str: + # Skip implicit definitions. + a: list[Any] = [o.defs] + if o.is_bom: + a.insert(0, "BOM") + # Omit path to special file with name "main". This is used to simplify + # test case descriptions; the file "main" is used by default in many + # test cases. + if o.path != "main": + # Insert path. Normalize directory separators to / to unify test + # case# output in all platforms. + a.insert(0, o.path.replace(os.getcwd() + os.sep, "").replace(os.sep, "/")) + if o.ignored_lines: + a.append("IgnoredLines(%s)" % ", ".join(str(line) for line in sorted(o.ignored_lines))) + return self.dump(a, o) + + def visit_import(self, o: mypy.nodes.Import) -> str: + a = [] + for id, as_id in o.ids: + if as_id is not None: + a.append(f"{id} : {as_id}") + else: + a.append(id) + return f"Import:{o.line}({', '.join(a)})" + + def visit_import_from(self, o: mypy.nodes.ImportFrom) -> str: + a = [] + for name, as_name in o.names: + if as_name is not None: + a.append(f"{name} : {as_name}") + else: + a.append(name) + return f"ImportFrom:{o.line}({'.' * o.relative + o.id}, [{', '.join(a)}])" + + def visit_import_all(self, o: mypy.nodes.ImportAll) -> str: + return f"ImportAll:{o.line}({'.' * o.relative + o.id})" + + # Definitions + + def visit_func_def(self, o: mypy.nodes.FuncDef) -> str: + a = self.func_helper(o) + a.insert(0, o.name) + arg_kinds = {arg.kind for arg in o.arguments} + if len(arg_kinds & {mypy.nodes.ARG_NAMED, mypy.nodes.ARG_NAMED_OPT}) > 0: + a.insert(1, f"MaxPos({o.max_pos})") + if o.is_coroutine: + a.insert(1, "Async") + if o.abstract_status in (mypy.nodes.IS_ABSTRACT, mypy.nodes.IMPLICITLY_ABSTRACT): + a.insert(-1, "Abstract") + if o.is_static: + a.insert(-1, "Static") + if o.is_class: + a.insert(-1, "Class") + if o.is_property: + a.insert(-1, "Property") + return self.dump(a, o) + + def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef) -> str: + a: Any = o.items.copy() + if o.type: + a.insert(0, o.type) + if o.impl: + a.insert(0, o.impl) + if o.is_static: + a.insert(-1, "Static") + if o.is_class: + a.insert(-1, "Class") + return self.dump(a, o) + + def visit_class_def(self, o: mypy.nodes.ClassDef) -> str: + a = [o.name, o.defs.body] + # Display base types unless they are implicitly just builtins.object + # (in this case base_type_exprs is empty). + if o.base_type_exprs: + if o.info and o.info.bases: + if len(o.info.bases) != 1 or o.info.bases[0].type.fullname != "builtins.object": + a.insert(1, ("BaseType", o.info.bases)) + else: + a.insert(1, ("BaseTypeExpr", o.base_type_exprs)) + if o.type_vars: + a.insert(1, ("TypeVars", o.type_vars)) + if o.metaclass: + a.insert(1, f"Metaclass({o.metaclass.accept(self)})") + if o.keywords: + keyword_items = [f"{k}={v.accept(self)}" for k, v in o.keywords.items()] + a.insert(1, f"Keywords({', '.join(keyword_items)})") + if o.decorators: + a.insert(1, ("Decorators", o.decorators)) + if o.info and o.info._promote: + a.insert(1, f"Promote([{','.join(self.stringify_type(p) for p in o.info._promote)}])") + if o.info and o.info.tuple_type: + a.insert(1, ("TupleType", [o.info.tuple_type])) + if o.info and o.info.fallback_to_any: + a.insert(1, "FallbackToAny") + if o.type_args: + for p in reversed(o.type_args): + a.insert(1, self.type_param(p)) + return self.dump(a, o) + + def visit_var(self, o: mypy.nodes.Var) -> str: + lst = "" + # Add :nil line number tag if no line number is specified to remain + # compatible with old test case descriptions that assume this. + if o.line < 0: + lst = ":nil" + return "Var" + lst + "(" + o.name + ")" + + def visit_global_decl(self, o: mypy.nodes.GlobalDecl) -> str: + return self.dump([o.names], o) + + def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl) -> str: + return self.dump([o.names], o) + + def visit_decorator(self, o: mypy.nodes.Decorator) -> str: + return self.dump([o.var, o.decorators, o.func], o) + + def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> str: + return self.dump([o.name, o.target, o.alias_tvars, o.no_args], o) + + def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> str: + return self.dump([o.fullname], o) + + # Statements + + def visit_block(self, o: mypy.nodes.Block) -> str: + return self.dump(o.body, o) + + def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt) -> str: + return self.dump([o.expr], o) + + def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt) -> str: + a: list[Any] = [] + if len(o.lvalues) > 1: + a = [("Lvalues", o.lvalues)] + else: + a = [o.lvalues[0]] + a.append(o.rvalue) + if o.type: + a.append(o.type) + return self.dump(a, o) + + def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt) -> str: + return self.dump([o.op, o.lvalue, o.rvalue], o) + + def visit_while_stmt(self, o: mypy.nodes.WhileStmt) -> str: + a: list[Any] = [o.expr, o.body] + if o.else_body: + a.append(("Else", o.else_body.body)) + return self.dump(a, o) + + def visit_for_stmt(self, o: mypy.nodes.ForStmt) -> str: + a: list[Any] = [] + if o.is_async: + a.append(("Async", "")) + a.append(o.index) + if o.index_type: + a.append(o.index_type) + a.extend([o.expr, o.body]) + if o.else_body: + a.append(("Else", o.else_body.body)) + return self.dump(a, o) + + def visit_return_stmt(self, o: mypy.nodes.ReturnStmt) -> str: + return self.dump([o.expr], o) + + def visit_if_stmt(self, o: mypy.nodes.IfStmt) -> str: + a: list[Any] = [] + for i in range(len(o.expr)): + a.append(("If", [o.expr[i]])) + a.append(("Then", o.body[i].body)) + + if not o.else_body: + return self.dump(a, o) + else: + return self.dump([a, ("Else", o.else_body.body)], o) + + def visit_break_stmt(self, o: mypy.nodes.BreakStmt) -> str: + return self.dump([], o) + + def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt) -> str: + return self.dump([], o) + + def visit_pass_stmt(self, o: mypy.nodes.PassStmt) -> str: + return self.dump([], o) + + def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt) -> str: + return self.dump([o.expr, o.from_expr], o) + + def visit_assert_stmt(self, o: mypy.nodes.AssertStmt) -> str: + if o.msg is not None: + return self.dump([o.expr, o.msg], o) + else: + return self.dump([o.expr], o) + + def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> str: + return self.dump([o.expr], o) + + def visit_del_stmt(self, o: mypy.nodes.DelStmt) -> str: + return self.dump([o.expr], o) + + def visit_try_stmt(self, o: mypy.nodes.TryStmt) -> str: + a: list[Any] = [o.body] + if o.is_star: + a.append("*") + + for i in range(len(o.vars)): + a.append(o.types[i]) + if o.vars[i]: + a.append(o.vars[i]) + a.append(o.handlers[i]) + + if o.else_body: + a.append(("Else", o.else_body.body)) + if o.finally_body: + a.append(("Finally", o.finally_body.body)) + + return self.dump(a, o) + + def visit_with_stmt(self, o: mypy.nodes.WithStmt) -> str: + a: list[Any] = [] + if o.is_async: + a.append(("Async", "")) + for i in range(len(o.expr)): + a.append(("Expr", [o.expr[i]])) + if o.target[i]: + a.append(("Target", [o.target[i]])) + if o.unanalyzed_type: + a.append(o.unanalyzed_type) + return self.dump(a + [o.body], o) + + def visit_match_stmt(self, o: mypy.nodes.MatchStmt) -> str: + a: list[Any] = [o.subject] + for i in range(len(o.patterns)): + a.append(("Pattern", [o.patterns[i]])) + if o.guards[i] is not None: + a.append(("Guard", [o.guards[i]])) + a.append(("Body", o.bodies[i].body)) + return self.dump(a, o) + + def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt) -> str: + a: list[Any] = [o.name] + for p in o.type_args: + a.append(self.type_param(p)) + a.append(o.value) + return self.dump(a, o) + + def type_param(self, p: mypy.nodes.TypeParam) -> list[Any]: + a: list[Any] = [] + if p.kind == mypy.nodes.PARAM_SPEC_KIND: + prefix = "**" + elif p.kind == mypy.nodes.TYPE_VAR_TUPLE_KIND: + prefix = "*" + else: + prefix = "" + a.append(prefix + p.name) + if p.upper_bound: + a.append(p.upper_bound) + if p.values: + a.append(("Values", p.values)) + if p.default: + a.append(("Default", [p.default])) + return [("TypeParam", a)] + + # Expressions + + # Simple expressions + + def visit_int_expr(self, o: mypy.nodes.IntExpr) -> str: + return f"IntExpr({o.value})" + + def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str: + return f"StrExpr({self.str_repr(o.value)})" + + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr) -> str: + return f"BytesExpr({self.str_repr(o.value)})" + + def str_repr(self, s: str) -> str: + s = re.sub(r"\\u[0-9a-fA-F]{4}", lambda m: "\\" + m.group(0), s) + return re.sub("[^\\x20-\\x7e]", lambda m: r"\u%.4x" % ord(m.group(0)), s) + + def visit_float_expr(self, o: mypy.nodes.FloatExpr) -> str: + return f"FloatExpr({o.value})" + + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr) -> str: + return f"ComplexExpr({o.value})" + + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr) -> str: + return "Ellipsis" + + def visit_star_expr(self, o: mypy.nodes.StarExpr) -> str: + return self.dump([o.expr], o) + + def visit_name_expr(self, o: mypy.nodes.NameExpr) -> str: + pretty = self.pretty_name( + o.name, o.kind, o.fullname, o.is_inferred_def or o.is_special_form, o.node + ) + if isinstance(o.node, mypy.nodes.Var) and o.node.is_final: + final_value = o.node.final_value + if final_value is not None: + pretty += f" = {o.node.final_value}" + return short_type(o) + "(" + pretty + ")" + + def pretty_name( + self, + name: str, + kind: int | None, + fullname: str | None, + is_inferred_def: bool, + target_node: mypy.nodes.Node | None = None, + ) -> str: + n = name + if is_inferred_def: + n += "*" + if target_node: + id = self.format_id(target_node) + else: + id = "" + if isinstance(target_node, mypy.nodes.MypyFile) and name == fullname: + n += id + elif kind == mypy.nodes.GDEF or (fullname != name and fullname): + # Append fully qualified name for global references. + n += f" [{fullname}{id}]" + elif kind == mypy.nodes.LDEF: + # Add tag to signify a local reference. + n += f" [l{id}]" + elif kind == mypy.nodes.MDEF: + # Add tag to signify a member reference. + n += f" [m{id}]" + else: + n += id + return n + + def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> str: + pretty = self.pretty_name(o.name, o.kind, o.fullname, o.is_inferred_def, o.node) + return self.dump([o.expr, pretty], o) + + def visit_yield_expr(self, o: mypy.nodes.YieldExpr) -> str: + return self.dump([o.expr], o) + + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> str: + if o.expr: + return self.dump([o.expr.accept(self)], o) + else: + return self.dump([], o) + + def visit_call_expr(self, o: mypy.nodes.CallExpr) -> str: + if o.analyzed: + return o.analyzed.accept(self) + args: list[mypy.nodes.Expression] = [] + extra: list[str | tuple[str, list[Any]]] = [] + for i, kind in enumerate(o.arg_kinds): + if kind in [mypy.nodes.ARG_POS, mypy.nodes.ARG_STAR]: + args.append(o.args[i]) + if kind == mypy.nodes.ARG_STAR: + extra.append("VarArg") + elif kind == mypy.nodes.ARG_NAMED: + extra.append(("KwArgs", [o.arg_names[i], o.args[i]])) + elif kind == mypy.nodes.ARG_STAR2: + extra.append(("DictVarArg", [o.args[i]])) + else: + raise RuntimeError(f"unknown kind {kind}") + a: list[Any] = [o.callee, ("Args", args)] + return self.dump(a + extra, o) + + def visit_op_expr(self, o: mypy.nodes.OpExpr) -> str: + if o.analyzed: + return o.analyzed.accept(self) + return self.dump([o.op, o.left, o.right], o) + + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr) -> str: + return self.dump([o.operators, o.operands], o) + + def visit_cast_expr(self, o: mypy.nodes.CastExpr) -> str: + return self.dump([o.expr, o.type], o) + + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr) -> str: + return self.dump([o.type], o) + + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr) -> str: + return self.dump([o.expr, o.type], o) + + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr) -> str: + if o.kind == mypy.nodes.REVEAL_TYPE: + return self.dump([o.expr], o) + else: + # REVEAL_LOCALS + return self.dump([o.local_nodes], o) + + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> str: + return self.dump([o.target, o.value], o) + + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> str: + return self.dump([o.op, o.expr], o) + + def visit_list_expr(self, o: mypy.nodes.ListExpr) -> str: + return self.dump(o.items, o) + + def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> str: + return self.dump([[k, v] for k, v in o.items], o) + + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr) -> str: + items_repr: list[object] = [] + for item in o.items: + if isinstance(item, tuple): + value_expr, source, conversion, format_spec = item + interpolation: list[object] = [ + ("Value", [value_expr]), + f"Source({source!r})", + f"Conversion({conversion!r})", + ] + if format_spec is None: + interpolation.append("FormatSpec(None)") + else: + interpolation.append(("FormatSpec", [format_spec])) + items_repr.append(("Interpolation", interpolation)) + else: + items_repr.append(item) + return self.dump(items_repr, o) + + def visit_set_expr(self, o: mypy.nodes.SetExpr) -> str: + return self.dump(o.items, o) + + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> str: + return self.dump(o.items, o) + + def visit_index_expr(self, o: mypy.nodes.IndexExpr) -> str: + if o.analyzed: + return o.analyzed.accept(self) + return self.dump([o.base, o.index], o) + + def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> str: + return self.dump([o.name, o.call], o) + + def visit_type_application(self, o: mypy.nodes.TypeApplication) -> str: + return self.dump([o.expr, ("Types", o.types)], o) + + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr) -> str: + import mypy.types + + a: list[Any] = [] + if o.variance == mypy.nodes.COVARIANT: + a += ["Variance(COVARIANT)"] + if o.variance == mypy.nodes.CONTRAVARIANT: + a += ["Variance(CONTRAVARIANT)"] + if o.values: + a += [("Values", o.values)] + if not mypy.types.is_named_instance(o.upper_bound, "builtins.object"): + a += [f"UpperBound({self.stringify_type(o.upper_bound)})"] + return self.dump(a, o) + + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr) -> str: + import mypy.types + + a: list[Any] = [] + if o.variance == mypy.nodes.COVARIANT: + a += ["Variance(COVARIANT)"] + if o.variance == mypy.nodes.CONTRAVARIANT: + a += ["Variance(CONTRAVARIANT)"] + if not mypy.types.is_named_instance(o.upper_bound, "builtins.object"): + a += [f"UpperBound({self.stringify_type(o.upper_bound)})"] + return self.dump(a, o) + + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr) -> str: + import mypy.types + + a: list[Any] = [] + if o.variance == mypy.nodes.COVARIANT: + a += ["Variance(COVARIANT)"] + if o.variance == mypy.nodes.CONTRAVARIANT: + a += ["Variance(CONTRAVARIANT)"] + if not mypy.types.is_named_instance(o.upper_bound, "builtins.object"): + a += [f"UpperBound({self.stringify_type(o.upper_bound)})"] + return self.dump(a, o) + + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr) -> str: + return f"TypeAliasExpr({self.stringify_type(o.node.target)})" + + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr) -> str: + return f"NamedTupleExpr:{o.line}({o.info.name}, {self.stringify_type(o.info.tuple_type) if o.info.tuple_type is not None else None})" + + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr) -> str: + return f"EnumCallExpr:{o.line}({o.info.name}, {o.items})" + + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr) -> str: + return f"TypedDictExpr:{o.line}({o.info.name})" + + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr) -> str: + return f"PromoteExpr:{o.line}({self.stringify_type(o.type)})" + + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr) -> str: + return f"NewTypeExpr:{o.line}({o.name}, {self.dump([o.old_type], o)})" + + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr) -> str: + a = self.func_helper(o) + return self.dump(a, o) + + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr) -> str: + condlists = o.condlists if any(o.condlists) else None + return self.dump([o.left_expr, o.indices, o.sequences, condlists], o) + + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension) -> str: + return self.dump([o.generator], o) + + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension) -> str: + return self.dump([o.generator], o) + + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension) -> str: + condlists = o.condlists if any(o.condlists) else None + return self.dump([o.key, o.value, o.indices, o.sequences, condlists], o) + + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr) -> str: + return self.dump([("Condition", [o.cond]), o.if_expr, o.else_expr], o) + + def visit_slice_expr(self, o: mypy.nodes.SliceExpr) -> str: + a: list[Any] = [o.begin_index, o.end_index, o.stride] + if not a[0]: + a[0] = "" + if not a[1]: + a[1] = "" + return self.dump(a, o) + + def visit_temp_node(self, o: mypy.nodes.TempNode) -> str: + return self.dump([o.type], o) + + def visit_as_pattern(self, o: mypy.patterns.AsPattern) -> str: + return self.dump([o.pattern, o.name], o) + + def visit_or_pattern(self, o: mypy.patterns.OrPattern) -> str: + return self.dump(o.patterns, o) + + def visit_value_pattern(self, o: mypy.patterns.ValuePattern) -> str: + return self.dump([o.expr], o) + + def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern) -> str: + return self.dump([o.value], o) + + def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern) -> str: + return self.dump(o.patterns, o) + + def visit_starred_pattern(self, o: mypy.patterns.StarredPattern) -> str: + return self.dump([o.capture], o) + + def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern) -> str: + a: list[Any] = [] + for i in range(len(o.keys)): + a.append(("Key", [o.keys[i]])) + a.append(("Value", [o.values[i]])) + if o.rest is not None: + a.append(("Rest", [o.rest])) + return self.dump(a, o) + + def visit_class_pattern(self, o: mypy.patterns.ClassPattern) -> str: + a: list[Any] = [o.class_ref] + if len(o.positionals) > 0: + a.append(("Positionals", o.positionals)) + for i in range(len(o.keyword_keys)): + a.append(("Keyword", [o.keyword_keys[i], o.keyword_values[i]])) + + return self.dump(a, o) + + +def dump_tagged(nodes: Sequence[object], tag: str | None, str_conv: StrConv) -> str: + """Convert an array into a pretty-printed multiline string representation. + + The format is + tag( + item1.. + itemN) + Individual items are formatted like this: + - arrays are flattened + - pairs (str, array) are converted recursively, so that str is the tag + - other items are converted to strings and indented + """ + from mypy.types import Type, TypeStrVisitor + + a: list[str] = [] + if tag: + a.append(tag + "(") + for n in nodes: + if isinstance(n, list): + if n: + a.append(dump_tagged(n, None, str_conv)) + elif isinstance(n, tuple): + s = dump_tagged(n[1], n[0], str_conv) + a.append(indent(s, 2)) + elif isinstance(n, mypy.nodes.Node): + a.append(indent(n.accept(str_conv), 2)) + elif isinstance(n, Type): + a.append( + indent(n.accept(TypeStrVisitor(str_conv.id_mapper, options=str_conv.options)), 2) + ) + elif n is not None: + a.append(indent(str(n), 2)) + if tag: + a[-1] += ")" + return "\n".join(a) + + +def indent(s: str, n: int) -> str: + """Indent all the lines in s (separated by newlines) by n spaces.""" + s = " " * n + s + s = s.replace("\n", "\n" + " " * n) + return s diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubdoc.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubdoc.py new file mode 100644 index 0000000000000000000000000000000000000000..f0588343000a746c55c38894b42b29fa40e93e07 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubdoc.py @@ -0,0 +1,545 @@ +"""Parsing/inferring signatures from documentation. + +This module provides several functions to generate better stubs using +docstrings and Sphinx docs (.rst files). +""" + +from __future__ import annotations + +import contextlib +import io +import keyword +import re +import tokenize +from collections.abc import MutableMapping, MutableSequence, Sequence +from typing import Any, Final, NamedTuple, TypeAlias as _TypeAlias + +import mypy.util + +# Type alias for signatures strings in format ('func_name', '(arg, opt_arg=False)'). +Sig: _TypeAlias = tuple[str, str] + + +_TYPE_RE: Final = re.compile(r"^[a-zA-Z_][\w\[\], .\"\'|]*(\.[a-zA-Z_][\w\[\], ]*)*$") +_ARG_NAME_RE: Final = re.compile(r"\**[A-Za-z_][A-Za-z0-9_]*$") + + +def is_valid_type(s: str) -> bool: + """Try to determine whether a string might be a valid type annotation.""" + if s in ("True", "False", "retval"): + return False + if "," in s and "[" not in s: + return False + return _TYPE_RE.match(s) is not None + + +class ArgSig: + """Signature info for a single argument.""" + + def __init__( + self, + name: str, + type: str | None = None, + *, + default: bool = False, + default_value: str = "...", + ) -> None: + self.name = name + self.type = type + # Does this argument have a default value? + self.default = default + self.default_value = default_value + + def is_star_arg(self) -> bool: + return self.name.startswith("*") and not self.name.startswith("**") + + def is_star_kwarg(self) -> bool: + return self.name.startswith("**") + + def __repr__(self) -> str: + return "ArgSig(name={}, type={}, default={})".format( + repr(self.name), repr(self.type), repr(self.default) + ) + + def __eq__(self, other: Any) -> bool: + if isinstance(other, ArgSig): + return ( + self.name == other.name + and self.type == other.type + and self.default == other.default + and self.default_value == other.default_value + ) + return False + + +class FunctionSig(NamedTuple): + name: str + args: list[ArgSig] + ret_type: str | None + type_args: str = "" # TODO implement in stubgenc and remove the default + docstring: str | None = None + + def is_special_method(self) -> bool: + return bool( + self.name.startswith("__") + and self.name.endswith("__") + and self.args + and self.args[0].name in ("self", "cls") + ) + + def has_catchall_args(self) -> bool: + """Return if this signature has catchall args: (*args, **kwargs)""" + if self.args and self.args[0].name in ("self", "cls"): + args = self.args[1:] + else: + args = self.args + return ( + len(args) == 2 + and all(a.type in (None, "object", "Any", "typing.Any") for a in args) + and args[0].is_star_arg() + and args[1].is_star_kwarg() + ) + + def is_catchall_signature(self) -> bool: + """Return if this signature is the catchall identity: (*args, **kwargs) -> Any""" + return self.has_catchall_args() and self.ret_type in (None, "Any", "typing.Any") + + def format_sig( + self, + indent: str = "", + is_async: bool = False, + any_val: str | None = None, + docstring: str | None = None, + include_docstrings: bool = False, + ) -> str: + args: list[str] = [] + for arg in self.args: + arg_def = arg.name + + if arg_def in keyword.kwlist: + arg_def = "_" + arg_def + + if ( + arg.type is None + and any_val is not None + and arg.name not in ("self", "cls") + and not arg.name.startswith("*") + ): + arg_type: str | None = any_val + else: + arg_type = arg.type + if arg_type: + arg_def += ": " + arg_type + if arg.default: + arg_def += f" = {arg.default_value}" + + elif arg.default: + arg_def += f"={arg.default_value}" + + args.append(arg_def) + + retfield = "" + ret_type = self.ret_type if self.ret_type else any_val + if ret_type is not None: + retfield = " -> " + ret_type + + prefix = "async " if is_async else "" + sig = f"{indent}{prefix}def {self.name}{self.type_args}({', '.join(args)}){retfield}:" + # if this object has a docstring it's probably produced by a SignatureGenerator, so it + # takes precedence over the passed docstring, which acts as a fallback. + doc = (self.docstring or docstring) if include_docstrings else None + if doc: + suffix = f"\n{indent} {mypy.util.quote_docstring(doc)}" + else: + suffix = " ..." + return f"{sig}{suffix}" + + +# States of the docstring parser. +STATE_INIT: Final = 1 +STATE_FUNCTION_NAME: Final = 2 +STATE_ARGUMENT_LIST: Final = 3 +STATE_ARGUMENT_TYPE: Final = 4 +STATE_ARGUMENT_DEFAULT: Final = 5 +STATE_RETURN_VALUE: Final = 6 +STATE_OPEN_BRACKET: Final = 7 # For generic types. + + +class DocStringParser: + """Parse function signatures in documentation.""" + + def __init__(self, function_name: str) -> None: + # Only search for signatures of function with this name. + self.function_name = function_name + self.state = [STATE_INIT] + self.accumulator = "" + self.arg_type: str | None = None + self.arg_name = "" + self.arg_default: str | None = None + self.ret_type = "Any" + self.found = False + self.args: list[ArgSig] = [] + self.pos_only: int | None = None + self.keyword_only: int | None = None + # Valid signatures found so far. + self.signatures: list[FunctionSig] = [] + + def add_token(self, token: tokenize.TokenInfo) -> None: + """Process next token from the token stream.""" + if ( + token.type == tokenize.NAME + and token.string == self.function_name + and self.state[-1] == STATE_INIT + ): + self.state.append(STATE_FUNCTION_NAME) + + elif ( + token.type == tokenize.OP + and token.string == "(" + and self.state[-1] == STATE_FUNCTION_NAME + ): + self.state.pop() + self.accumulator = "" + self.found = True + self.state.append(STATE_ARGUMENT_LIST) + + elif self.state[-1] == STATE_FUNCTION_NAME: + # Reset state, function name not followed by '('. + self.state.pop() + + elif ( + token.type == tokenize.OP + and token.string in ("[", "(", "{") + and self.state[-1] != STATE_INIT + ): + self.accumulator += token.string + self.state.append(STATE_OPEN_BRACKET) + + elif ( + token.type == tokenize.OP + and token.string in ("]", ")", "}") + and self.state[-1] == STATE_OPEN_BRACKET + ): + self.accumulator += token.string + self.state.pop() + + elif ( + token.type == tokenize.OP + and token.string == ":" + and self.state[-1] == STATE_ARGUMENT_LIST + ): + self.arg_name = self.accumulator + self.accumulator = "" + self.state.append(STATE_ARGUMENT_TYPE) + + elif ( + token.type == tokenize.OP + and token.string == ":" + and self.state[-1] == STATE_ARGUMENT_TYPE + and self.accumulator == "" + ): + # We thought we were after the colon of an "arg_name: arg_type" + # stanza, so we were expecting an "arg_type" now. However, we ended + # up with "arg_name::" (with two colons). That's a C++ type name, + # not an argument name followed by a Python type. This function + # signature is malformed / invalid. + self.reset() + + elif ( + token.type == tokenize.OP + and token.string == "=" + and self.state[-1] in (STATE_ARGUMENT_LIST, STATE_ARGUMENT_TYPE) + ): + if self.state[-1] == STATE_ARGUMENT_TYPE: + self.arg_type = self.accumulator + self.state.pop() + else: + self.arg_name = self.accumulator + self.accumulator = "" + self.state.append(STATE_ARGUMENT_DEFAULT) + + elif ( + token.type == tokenize.OP + and token.string in (",", ")") + and self.state[-1] + in (STATE_ARGUMENT_LIST, STATE_ARGUMENT_DEFAULT, STATE_ARGUMENT_TYPE) + ): + if self.state[-1] == STATE_ARGUMENT_DEFAULT: + self.arg_default = self.accumulator + self.state.pop() + elif self.state[-1] == STATE_ARGUMENT_TYPE: + self.arg_type = self.accumulator + self.state.pop() + elif self.state[-1] == STATE_ARGUMENT_LIST: + if self.accumulator == "*": + if self.keyword_only is not None: + # Error condition: cannot have * twice + self.reset() + return + self.keyword_only = len(self.args) + self.accumulator = "" + else: + if self.accumulator.startswith("*"): + self.keyword_only = len(self.args) + 1 + self.arg_name = self.accumulator + if not ( + token.string == ")" and self.accumulator.strip() == "" + ) and not _ARG_NAME_RE.match(self.arg_name): + # Invalid argument name. + self.reset() + return + + if token.string == ")": + if ( + self.state[-1] == STATE_ARGUMENT_LIST + and self.keyword_only is not None + and self.keyword_only == len(self.args) + and not self.arg_name + ): + # Error condition: * must be followed by arguments + self.reset() + return + self.state.pop() + + # arg_name is empty when there are no args. e.g. func() + if self.arg_name: + if self.arg_type and not is_valid_type(self.arg_type): + # wrong type, use Any + self.args.append( + ArgSig(name=self.arg_name, type=None, default=bool(self.arg_default)) + ) + else: + self.args.append( + ArgSig( + name=self.arg_name, type=self.arg_type, default=bool(self.arg_default) + ) + ) + self.arg_name = "" + self.arg_type = None + self.arg_default = None + self.accumulator = "" + elif ( + token.type == tokenize.OP + and token.string == "/" + and self.state[-1] == STATE_ARGUMENT_LIST + ): + if token.string == "/": + if self.pos_only is not None or self.keyword_only is not None or not self.args: + # Error cases: + # - / shows up more than once + # - / shows up after * + # - / shows up before any arguments + self.reset() + return + self.pos_only = len(self.args) + self.state.append(STATE_ARGUMENT_TYPE) + self.accumulator = "" + + elif token.type == tokenize.OP and token.string == "->" and self.state[-1] == STATE_INIT: + self.accumulator = "" + self.state.append(STATE_RETURN_VALUE) + + # ENDMAKER is necessary for python 3.4 and 3.5. + elif token.type in (tokenize.NEWLINE, tokenize.ENDMARKER) and self.state[-1] in ( + STATE_INIT, + STATE_RETURN_VALUE, + ): + if self.state[-1] == STATE_RETURN_VALUE: + if not is_valid_type(self.accumulator): + self.reset() + return + self.ret_type = self.accumulator + self.accumulator = "" + self.state.pop() + + if self.found: + self.signatures.append( + FunctionSig(name=self.function_name, args=self.args, ret_type=self.ret_type) + ) + self.found = False + self.args = [] + self.ret_type = "Any" + # Leave state as INIT. + else: + self.accumulator += token.string + + def reset(self) -> None: + self.state = [STATE_INIT] + self.args = [] + self.found = False + self.accumulator = "" + + def get_signatures(self) -> list[FunctionSig]: + """Return sorted copy of the list of signatures found so far.""" + + def has_arg(name: str, signature: FunctionSig) -> bool: + return any(x.name == name for x in signature.args) + + def args_kwargs(signature: FunctionSig) -> bool: + return has_arg("*args", signature) and has_arg("**kwargs", signature) + + # Move functions with (*args, **kwargs) in their signature to last place. + return sorted(self.signatures, key=lambda x: 1 if args_kwargs(x) else 0) + + +def infer_sig_from_docstring(docstr: str | None, name: str) -> list[FunctionSig] | None: + """Convert function signature to list of FunctionSig + + Look for function signatures of function in docstring. Signature is a string of + the format () -> or perhaps without + the return type. + + Returns empty list, when no signature is found, one signature in typical case, + multiple signatures, if docstring specifies multiple signatures for overload functions. + Return None if the docstring is empty. + + Arguments: + * docstr: docstring + * name: name of function for which signatures are to be found + """ + if not (isinstance(docstr, str) and docstr): + return None + + state = DocStringParser(name) + # Return all found signatures, even if there is a parse error after some are found. + with contextlib.suppress(tokenize.TokenError): + try: + tokens = tokenize.tokenize(io.BytesIO(docstr.encode("utf-8")).readline) + for token in tokens: + state.add_token(token) + except IndentationError: + return None + sigs = state.get_signatures() + + def is_unique_args(sig: FunctionSig) -> bool: + """return true if function argument names are unique""" + return len(sig.args) == len({arg.name for arg in sig.args}) + + # Return only signatures that have unique argument names. Mypy fails on non-unique arg names. + return [sig for sig in sigs if is_unique_args(sig)] + + +def infer_arg_sig_from_anon_docstring(docstr: str) -> list[ArgSig]: + """Convert signature in form of "(self: TestClass, arg0: str='ada')" to List[TypedArgList].""" + ret = infer_sig_from_docstring("stub" + docstr, "stub") + if ret: + return ret[0].args + return [] + + +def infer_ret_type_sig_from_docstring(docstr: str, name: str) -> str | None: + """Convert signature in form of "func(self: TestClass, arg0) -> int" to their return type.""" + ret = infer_sig_from_docstring(docstr, name) + if ret: + return ret[0].ret_type + return None + + +def infer_ret_type_sig_from_anon_docstring(docstr: str) -> str | None: + """Convert signature in form of "(self: TestClass, arg0) -> int" to their return type.""" + lines = ["stub" + line.strip() for line in docstr.splitlines() if line.strip().startswith("(")] + return infer_ret_type_sig_from_docstring("".join(lines), "stub") + + +def parse_signature(sig: str) -> tuple[str, list[str], list[str]] | None: + """Split function signature into its name, positional an optional arguments. + + The expected format is "func_name(arg, opt_arg=False)". Return the name of function + and lists of positional and optional argument names. + """ + m = re.match(r"([.a-zA-Z0-9_]+)\(([^)]*)\)", sig) + if not m: + return None + name = m.group(1) + name = name.split(".")[-1] + arg_string = m.group(2) + if not arg_string.strip(): + # Simple case -- no arguments. + return name, [], [] + + args = [arg.strip() for arg in arg_string.split(",")] + positional = [] + optional = [] + i = 0 + while i < len(args): + # Accept optional arguments as in both formats: x=None and [x]. + if args[i].startswith("[") or "=" in args[i]: + break + positional.append(args[i].rstrip("[")) + i += 1 + if args[i - 1].endswith("["): + break + while i < len(args): + arg = args[i] + arg = arg.strip("[]") + arg = arg.split("=")[0] + optional.append(arg) + i += 1 + return name, positional, optional + + +def build_signature(positional: Sequence[str], optional: Sequence[str]) -> str: + """Build function signature from lists of positional and optional argument names.""" + args: MutableSequence[str] = [] + args.extend(positional) + for arg in optional: + if arg.startswith("*"): + args.append(arg) + else: + args.append(f"{arg}=...") + sig = f"({', '.join(args)})" + # Ad-hoc fixes. + sig = sig.replace("(self)", "") + return sig + + +def parse_all_signatures(lines: Sequence[str]) -> tuple[list[Sig], list[Sig]]: + """Parse all signatures in a given reST document. + + Return lists of found signatures for functions and classes. + """ + sigs = [] + class_sigs = [] + for line in lines: + line = line.strip() + m = re.match(r"\.\. *(function|method|class) *:: *[a-zA-Z_]", line) + if m: + sig = line.split("::")[1].strip() + parsed = parse_signature(sig) + if parsed: + name, fixed, optional = parsed + if m.group(1) != "class": + sigs.append((name, build_signature(fixed, optional))) + else: + class_sigs.append((name, build_signature(fixed, optional))) + + return sorted(sigs), sorted(class_sigs) + + +def find_unique_signatures(sigs: Sequence[Sig]) -> list[Sig]: + """Remove names with duplicate found signatures.""" + sig_map: MutableMapping[str, list[str]] = {} + for name, sig in sigs: + sig_map.setdefault(name, []).append(sig) + + result = [] + for name, name_sigs in sig_map.items(): + if len(set(name_sigs)) == 1: + result.append((name, name_sigs[0])) + return sorted(result) + + +def infer_prop_type_from_docstring(docstr: str | None) -> str | None: + """Check for Google/Numpy style docstring type annotation for a property. + + The docstring has the format ": ". + In the type string, we allow the following characters: + * dot: because sometimes classes are annotated using full path + * brackets: to allow type hints like List[int] + * comma/space: things like Tuple[int, int] + """ + if not docstr: + return None + test_str = r"^([a-zA-Z0-9_, \.\[\]]*): " + m = re.match(test_str, docstr) + return m.group(1) if m else None diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgen.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgen.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e09ac5b371d48396b774c5bcb561298500c7f6bb Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgen.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgen.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgen.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6335e9e34f98e6077065c013b1676877a731e2 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgen.py @@ -0,0 +1,2055 @@ +#!/usr/bin/env python3 +"""Generator of dynamically typed draft stubs for arbitrary modules. + +The logic of this script can be split in three steps: +* parsing options and finding sources: + - use runtime imports be default (to find also C modules) + - or use mypy's mechanisms, if importing is prohibited +* (optionally) semantically analysing the sources using mypy (as a single set) +* emitting the stubs text: + - for Python modules: from ASTs using ASTStubGenerator + - for C modules using runtime introspection and (optionally) Sphinx docs + +During first and third steps some problematic files can be skipped, but any +blocking error during second step will cause the whole program to stop. + +Basic usage: + + $ stubgen foo.py bar.py some_directory + => Generate out/foo.pyi, out/bar.pyi, and stubs for some_directory (recursively). + + $ stubgen -m urllib.parse + => Generate out/urllib/parse.pyi. + + $ stubgen -p urllib + => Generate stubs for whole urllib package (recursively). + +For C modules, you can get more precise function signatures by parsing .rst (Sphinx) +documentation for extra information. For this, use the --doc-dir option: + + $ stubgen --doc-dir /Python-3.4.2/Doc/library -m curses + +Note: The generated stubs should be verified manually. + +TODO: + - maybe use .rst docs also for Python modules + - maybe export more imported names if there is no __all__ (this affects ssl.SSLError, for example) + - a quick and dirty heuristic would be to turn this on if a module has something like + 'from x import y as _y' + - we don't seem to always detect properties ('closed' in 'io', for example) +""" + +from __future__ import annotations + +import argparse +import keyword +import os +import os.path +import sys +import traceback +from collections.abc import Iterable, Iterator +from typing import Final + +import mypy.build +import mypy.mixedtraverser +import mypy.parse +import mypy.traverser +import mypy.util +import mypy.version +from mypy.build import build +from mypy.errors import CompileError, Errors +from mypy.find_sources import InvalidSourceList, create_source_list +from mypy.modulefinder import ( + BuildSource, + FindModuleCache, + ModuleNotFoundReason, + SearchPaths, + default_lib_path, +) +from mypy.moduleinspect import ModuleInspect, is_pyc_only +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + ARG_STAR, + ARG_STAR2, + IS_ABSTRACT, + NOT_ABSTRACT, + AssignmentStmt, + Block, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + Decorator, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + Expression, + ExpressionStmt, + FloatExpr, + FuncBase, + FuncDef, + GeneratorExpr, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MemberExpr, + MypyFile, + NameExpr, + OpExpr, + OverloadedFuncDef, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + TemplateStrExpr, + TempNode, + TupleExpr, + TypeAliasStmt, + TypeInfo, + UnaryExpr, + Var, +) +from mypy.options import Options as MypyOptions +from mypy.plugins.dataclasses import DATACLASS_FIELD_SPECIFIERS +from mypy.semanal_shared import find_dataclass_transform_spec +from mypy.sharedparse import MAGIC_METHODS_POS_ARGS_ONLY +from mypy.stubdoc import ArgSig, FunctionSig +from mypy.stubgenc import InspectionStubGenerator, generate_stub_for_c_module +from mypy.stubutil import ( + TYPING_BUILTIN_REPLACEMENTS, + BaseStubGenerator, + CantImport, + ClassInfo, + FunctionContext, + common_dir_prefix, + fail_missing, + find_module_path_and_all_py3, + generate_guarded, + infer_method_arg_types, + infer_method_ret_type, + remove_misplaced_type_comments, + report_missing, + walk_packages, +) +from mypy.traverser import ( + all_yield_expressions, + has_return_statement, + has_yield_expression, + has_yield_from_expression, +) +from mypy.types import ( + DATACLASS_TRANSFORM_NAMES, + OVERLOAD_NAMES, + TPDICT_NAMES, + TYPE_VAR_LIKE_NAMES, + TYPED_NAMEDTUPLE_NAMES, + AnyType, + CallableType, + Instance, + TupleType, + Type, + UnboundType, + get_proper_type, +) +from mypy.visitor import NodeVisitor + +# Common ways of naming package containing vendored modules. +VENDOR_PACKAGES: Final = ["packages", "vendor", "vendored", "_vendor", "_vendored_packages"] + +# Avoid some file names that are unnecessary or likely to cause trouble (\n for end of path). +BLACKLIST: Final = [ + "/six.py\n", # Likely vendored six; too dynamic for us to handle + "/vendored/", # Vendored packages + "/vendor/", # Vendored packages + "/_vendor/", + "/_vendored_packages/", +] + +# These methods are expected to always return a non-trivial value. +METHODS_WITH_RETURN_VALUE: Final = { + "__ne__", + "__eq__", + "__lt__", + "__le__", + "__gt__", + "__ge__", + "__hash__", + "__iter__", +} + + +class Options: + """Represents stubgen options. + + This class is mutable to simplify testing. + """ + + def __init__( + self, + pyversion: tuple[int, int], + no_import: bool, + inspect: bool, + doc_dir: str, + search_path: list[str], + interpreter: str, + parse_only: bool, + ignore_errors: bool, + include_private: bool, + output_dir: str, + modules: list[str], + packages: list[str], + files: list[str], + verbose: bool, + quiet: bool, + export_less: bool, + include_docstrings: bool, + ) -> None: + # See parse_options for descriptions of the flags. + self.pyversion = pyversion + self.no_import = no_import + self.inspect = inspect + self.doc_dir = doc_dir + self.search_path = search_path + self.interpreter = interpreter + self.decointerpreter = interpreter + self.parse_only = parse_only + self.ignore_errors = ignore_errors + self.include_private = include_private + self.output_dir = output_dir + self.modules = modules + self.packages = packages + self.files = files + self.verbose = verbose + self.quiet = quiet + self.export_less = export_less + self.include_docstrings = include_docstrings + + +class StubSource: + """A single source for stub: can be a Python or C module. + + A simple extension of BuildSource that also carries the AST and + the value of __all__ detected at runtime. + """ + + def __init__( + self, module: str, path: str | None = None, runtime_all: list[str] | None = None + ) -> None: + self.source = BuildSource(path, module, None) + self.runtime_all = runtime_all + self.ast: MypyFile | None = None + + def __repr__(self) -> str: + return f"StubSource({self.source})" + + @property + def module(self) -> str: + return self.source.module + + @property + def path(self) -> str | None: + return self.source.path + + +# What was generated previously in the stub file. We keep track of these to generate +# nicely formatted output (add empty line between non-empty classes, for example). +EMPTY: Final = "EMPTY" +FUNC: Final = "FUNC" +CLASS: Final = "CLASS" +EMPTY_CLASS: Final = "EMPTY_CLASS" +VAR: Final = "VAR" +NOT_IN_ALL: Final = "NOT_IN_ALL" + +# Indicates that we failed to generate a reasonable output +# for a given node. These should be manually replaced by a user. + +ERROR_MARKER: Final = "" + + +class AliasPrinter(NodeVisitor[str]): + """Visitor used to collect type aliases _and_ type variable definitions. + + Visit r.h.s of the definition to get the string representation of type alias. + """ + + def __init__(self, stubgen: ASTStubGenerator) -> None: + self.stubgen = stubgen + super().__init__() + + def visit_call_expr(self, node: CallExpr) -> str: + # Call expressions are not usually types, but we also treat `X = TypeVar(...)` as a + # type alias that has to be preserved (even if TypeVar is not the same as an alias) + callee = node.callee.accept(self) + args = [] + for name, arg, kind in zip(node.arg_names, node.args, node.arg_kinds): + if kind == ARG_POS: + args.append(arg.accept(self)) + elif kind == ARG_STAR: + args.append("*" + arg.accept(self)) + elif kind == ARG_STAR2: + args.append("**" + arg.accept(self)) + elif kind == ARG_NAMED: + args.append(f"{name}={arg.accept(self)}") + else: + raise ValueError(f"Unknown argument kind {kind} in call") + return f"{callee}({', '.join(args)})" + + def _visit_ref_expr(self, node: NameExpr | MemberExpr) -> str: + fullname = self.stubgen.get_fullname(node) + if fullname in TYPING_BUILTIN_REPLACEMENTS: + return self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=False) + qualname = get_qualified_name(node) + self.stubgen.import_tracker.require_name(qualname) + return qualname + + def visit_name_expr(self, node: NameExpr) -> str: + return self._visit_ref_expr(node) + + def visit_member_expr(self, o: MemberExpr) -> str: + return self._visit_ref_expr(o) + + def _visit_literal_node( + self, node: StrExpr | BytesExpr | IntExpr | FloatExpr | ComplexExpr + ) -> str: + return repr(node.value) + + def visit_str_expr(self, node: StrExpr) -> str: + return self._visit_literal_node(node) + + def visit_bytes_expr(self, node: BytesExpr) -> str: + return f"b{self._visit_literal_node(node)}" + + def visit_int_expr(self, node: IntExpr) -> str: + return self._visit_literal_node(node) + + def visit_float_expr(self, node: FloatExpr) -> str: + return self._visit_literal_node(node) + + def visit_complex_expr(self, node: ComplexExpr) -> str: + return self._visit_literal_node(node) + + def visit_index_expr(self, node: IndexExpr) -> str: + base_fullname = self.stubgen.get_fullname(node.base) + if base_fullname == "typing.Union": + if isinstance(node.index, TupleExpr): + return " | ".join([item.accept(self) for item in node.index.items]) + return node.index.accept(self) + if base_fullname == "typing.Optional": + if isinstance(node.index, TupleExpr): + return self.stubgen.add_name("_typeshed.Incomplete") + return f"{node.index.accept(self)} | None" + base = node.base.accept(self) + index = node.index.accept(self) + if len(index) > 2 and index.startswith("(") and index.endswith(")"): + index = index[1:-1].rstrip(",") + return f"{base}[{index}]" + + def visit_tuple_expr(self, node: TupleExpr) -> str: + suffix = "," if len(node.items) == 1 else "" + return f"({', '.join(n.accept(self) for n in node.items)}{suffix})" + + def visit_list_expr(self, node: ListExpr) -> str: + return f"[{', '.join(n.accept(self) for n in node.items)}]" + + def visit_set_expr(self, node: SetExpr) -> str: + return f"{{{', '.join(n.accept(self) for n in node.items)}}}" + + def visit_dict_expr(self, o: DictExpr) -> str: + dict_items = [] + for key, value in o.items: + # This is currently only used for TypedDict where all keys are strings. + assert isinstance(key, StrExpr) + dict_items.append(f"{key.accept(self)}: {value.accept(self)}") + return f"{{{', '.join(dict_items)}}}" + + def visit_template_str_expr(self, o: TemplateStrExpr) -> str: + return self.stubgen.add_name("_typeshed.Incomplete") + + def visit_ellipsis(self, node: EllipsisExpr) -> str: + return "..." + + def visit_op_expr(self, o: OpExpr) -> str: + return f"{o.left.accept(self)} {o.op} {o.right.accept(self)}" + + def visit_unary_expr(self, o: UnaryExpr, /) -> str: + return f"{o.op}{o.expr.accept(self)}" + + def visit_slice_expr(self, o: SliceExpr, /) -> str: + blocks = [ + o.begin_index.accept(self) if o.begin_index is not None else "", + o.end_index.accept(self) if o.end_index is not None else "", + ] + if o.stride is not None: + blocks.append(o.stride.accept(self)) + return ":".join(blocks) + + def visit_star_expr(self, o: StarExpr) -> str: + return f"*{o.expr.accept(self)}" + + def visit_lambda_expr(self, o: LambdaExpr) -> str: + # TODO: Required for among other things dataclass.field default_factory + return self.stubgen.add_name("_typeshed.Incomplete") + + def _visit_unsupported_expr(self, o: object) -> str: + # Something we do not understand. + return self.stubgen.add_name("_typeshed.Incomplete") + + def visit_comparison_expr(self, o: ComparisonExpr) -> str: + return self._visit_unsupported_expr(o) + + def visit_cast_expr(self, o: CastExpr) -> str: + return self._visit_unsupported_expr(o) + + def visit_conditional_expr(self, o: ConditionalExpr) -> str: + return self._visit_unsupported_expr(o) + + def visit_list_comprehension(self, o: ListComprehension) -> str: + return self._visit_unsupported_expr(o) + + def visit_set_comprehension(self, o: SetComprehension) -> str: + return self._visit_unsupported_expr(o) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> str: + return self._visit_unsupported_expr(o) + + def visit_generator_expr(self, o: GeneratorExpr) -> str: + return self._visit_unsupported_expr(o) + + +def find_defined_names(file: MypyFile) -> set[str]: + finder = DefinitionFinder() + file.accept(finder) + return finder.names + + +def get_assigned_names(lvalues: Iterable[Expression]) -> Iterator[str]: + for lvalue in lvalues: + if isinstance(lvalue, NameExpr): + yield lvalue.name + elif isinstance(lvalue, TupleExpr): + yield from get_assigned_names(lvalue.items) + + +class DefinitionFinder(mypy.traverser.TraverserVisitor): + """Find names of things defined at the top level of a module.""" + + def __init__(self) -> None: + # Short names of things defined at the top level. + self.names: set[str] = set() + + def visit_class_def(self, o: ClassDef) -> None: + # Don't recurse into classes, as we only keep track of top-level definitions. + self.names.add(o.name) + + def visit_func_def(self, o: FuncDef) -> None: + # Don't recurse, as we only keep track of top-level definitions. + self.names.add(o.name) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + for name in get_assigned_names(o.lvalues): + self.names.add(name) + + def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: + self.names.add(o.name.name) + + +def find_referenced_names(file: MypyFile) -> set[str]: + finder = ReferenceFinder() + file.accept(finder) + return finder.refs + + +def is_none_expr(expr: Expression) -> bool: + return isinstance(expr, NameExpr) and expr.name == "None" + + +class ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor): + """Find all name references (both local and global).""" + + # TODO: Filter out local variable and class attribute references + + def __init__(self) -> None: + # Short names of things defined at the top level. + self.refs: set[str] = set() + + def visit_block(self, block: Block) -> None: + if not block.is_unreachable: + super().visit_block(block) + + def visit_name_expr(self, e: NameExpr) -> None: + self.refs.add(e.name) + + def visit_instance(self, t: Instance) -> None: + self.add_ref(t.type.name) + super().visit_instance(t) + + def visit_unbound_type(self, t: UnboundType) -> None: + if t.name: + self.add_ref(t.name) + + def visit_tuple_type(self, t: TupleType) -> None: + # Ignore fallback + for item in t.items: + item.accept(self) + + def visit_callable_type(self, t: CallableType) -> None: + # Ignore fallback + for arg in t.arg_types: + arg.accept(self) + t.ret_type.accept(self) + + def add_ref(self, fullname: str) -> None: + self.refs.add(fullname) + while "." in fullname: + fullname = fullname.rsplit(".", 1)[0] + self.refs.add(fullname) + + +class ASTStubGenerator(BaseStubGenerator, mypy.traverser.TraverserVisitor): + """Generate stub text from a mypy AST.""" + + def __init__( + self, + _all_: list[str] | None = None, + include_private: bool = False, + analyzed: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + ) -> None: + super().__init__(_all_, include_private, export_less, include_docstrings) + self._decorators: list[str] = [] + # Stack of defined variables (per scope). + self._vars: list[list[str]] = [[]] + # What was generated previously in the stub file. + self._state = EMPTY + self._class_stack: list[ClassDef] = [] + # Was the tree semantically analysed before? + self.analyzed = analyzed + # Short names of methods defined in the body of the current class + self.method_names: set[str] = set() + self.processing_enum = False + self.processing_dataclass = False + self.dataclass_field_specifier: tuple[str, ...] = () + + @property + def _current_class(self) -> ClassDef | None: + return self._class_stack[-1] if self._class_stack else None + + def visit_mypy_file(self, o: MypyFile) -> None: + self.module_name = o.fullname # Current module being processed + self.path = o.path + self.set_defined_names(find_defined_names(o)) + self.referenced_names = find_referenced_names(o) + super().visit_mypy_file(o) + self.check_undefined_names() + + def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None: + """@property with setters and getters, @overload chain and some others.""" + overload_chain = False + for item in o.items: + if not isinstance(item, Decorator): + continue + if self.is_private_name(item.func.name, item.func.fullname): + continue + + self.process_decorator(item) + if not overload_chain: + self.visit_func_def(item.func) + if item.func.is_overload: + overload_chain = True + elif item.func.is_overload: + self.visit_func_def(item.func) + else: + # skip the overload implementation and clear the decorator we just processed + self.clear_decorators() + + def get_default_function_sig(self, func_def: FuncDef, ctx: FunctionContext) -> FunctionSig: + args = self._get_func_args(func_def, ctx) + retname = self._get_func_return(func_def, ctx) + type_args = self.format_type_args(func_def) + return FunctionSig(func_def.name, args, retname, type_args) + + def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]: + args: list[ArgSig] = [] + + # Ignore pos-only status of magic methods whose args names are elided by mypy at parse + actually_pos_only_args = o.name not in MAGIC_METHODS_POS_ARGS_ONLY + pos_only_marker_position = 0 # Where to insert "/", if any + for i, arg_ in enumerate(o.arguments): + var = arg_.variable + kind = arg_.kind + name = var.name + annotated_type = ( + o.unanalyzed_type.arg_types[i] + if isinstance(o.unanalyzed_type, CallableType) + else None + ) + # I think the name check is incorrect: there are libraries which + # name their 0th argument other than self/cls + is_self_arg = i == 0 and name == "self" + is_cls_arg = i == 0 and name == "cls" + typename: str | None = None + if annotated_type and not is_self_arg and not is_cls_arg: + # Luckily, an argument explicitly annotated with "Any" has + # type "UnboundType" and will not match. + if not isinstance(get_proper_type(annotated_type), AnyType): + typename = self.print_annotation(annotated_type) + + if actually_pos_only_args and arg_.pos_only: + pos_only_marker_position += 1 + + if kind.is_named() and not any(arg.name.startswith("*") for arg in args): + args.append(ArgSig("*")) + + default = "..." + if arg_.initializer: + if not typename: + typename = self.get_str_type_of_node(arg_.initializer, can_be_incomplete=False) + potential_default, valid = self.get_str_default_of_node(arg_.initializer) + if valid and len(potential_default) <= 200: + default = potential_default + elif kind == ARG_STAR: + name = f"*{name}" + elif kind == ARG_STAR2: + name = f"**{name}" + + args.append( + ArgSig(name, typename, default=bool(arg_.initializer), default_value=default) + ) + if pos_only_marker_position: + args.insert(pos_only_marker_position, ArgSig("/")) + + if ctx.class_info is not None and all( + arg.type is None and arg.default is False for arg in args + ): + new_args = infer_method_arg_types( + ctx.name, ctx.class_info.self_var, [arg.name for arg in args] + ) + + if ctx.name == "__exit__": + self.import_tracker.add_import("types") + self.import_tracker.require_name("types") + + if new_args is not None: + args = new_args + + return args + + def _get_func_return(self, o: FuncDef, ctx: FunctionContext) -> str | None: + if o.name != "__init__" and isinstance(o.unanalyzed_type, CallableType): + if isinstance(get_proper_type(o.unanalyzed_type.ret_type), AnyType): + # Luckily, a return type explicitly annotated with "Any" has + # type "UnboundType" and will enter the else branch. + return None # implicit Any + else: + return self.print_annotation(o.unanalyzed_type.ret_type) + if o.abstract_status == IS_ABSTRACT or o.name in METHODS_WITH_RETURN_VALUE: + # Always assume abstract methods return Any unless explicitly annotated. Also + # some dunder methods should not have a None return type. + return None # implicit Any + retname = infer_method_ret_type(o.name) + if retname is not None: + return retname + if has_yield_expression(o) or has_yield_from_expression(o): + generator_name = self.add_name("collections.abc.Generator") + yield_name = "None" + send_name: str | None = None + return_name: str | None = None + if has_yield_from_expression(o): + yield_name = send_name = self.add_name("_typeshed.Incomplete") + else: + for expr, in_assignment in all_yield_expressions(o): + if expr.expr is not None and not is_none_expr(expr.expr): + yield_name = self.add_name("_typeshed.Incomplete") + if in_assignment: + send_name = self.add_name("_typeshed.Incomplete") + if has_return_statement(o): + return_name = self.add_name("_typeshed.Incomplete") + if return_name is not None: + if send_name is None: + send_name = "None" + return f"{generator_name}[{yield_name}, {send_name}, {return_name}]" + elif send_name is not None: + return f"{generator_name}[{yield_name}, {send_name}]" + else: + return f"{generator_name}[{yield_name}]" + if not has_return_statement(o) and o.abstract_status == NOT_ABSTRACT: + return "None" + return None + + def _get_func_docstring(self, node: FuncDef) -> str | None: + if not node.body.body: + return None + expr = node.body.body[0] + if isinstance(expr, ExpressionStmt) and isinstance(expr.expr, StrExpr): + return expr.expr.value + return None + + def visit_func_def(self, o: FuncDef) -> None: + is_dataclass_generated = ( + self.analyzed and self.processing_dataclass and o.info.names[o.name].plugin_generated + ) + if is_dataclass_generated: + # Skip methods generated by the @dataclass decorator + return + if ( + self.is_private_name(o.name, o.fullname) + or self.is_not_in_all(o.name) + or (self.is_recorded_name(o.name) and not o.is_overload) + ): + self.clear_decorators() + return + if self.is_top_level() and self._state not in (EMPTY, FUNC): + self.add("\n") + if not self.is_top_level(): + self_inits = find_self_initializers(o) + for init, value, annotation in self_inits: + if init in self.method_names: + # Can't have both an attribute and a method/property with the same name. + continue + init_code = self.get_init(init, value, annotation) + if init_code: + self.add(init_code) + + if self._class_stack: + if len(o.arguments): + self_var = o.arguments[0].variable.name + else: + self_var = "self" + class_info: ClassInfo | None = None + for class_def in self._class_stack: + class_info = ClassInfo(class_def.name, self_var, parent=class_info) + else: + class_info = None + + ctx = FunctionContext( + module_name=self.module_name, + name=o.name, + docstring=self._get_func_docstring(o), + is_abstract=o.abstract_status != NOT_ABSTRACT, + class_info=class_info, + ) + + self.record_name(o.name) + + default_sig = self.get_default_function_sig(o, ctx) + sigs = self.get_signatures(default_sig, self.sig_generators, ctx) + + for output in self.format_func_def( + sigs, is_coroutine=o.is_coroutine, decorators=self._decorators, docstring=ctx.docstring + ): + self.add(output + "\n") + + self.clear_decorators() + self._state = FUNC + + def visit_decorator(self, o: Decorator) -> None: + if self.is_private_name(o.func.name, o.func.fullname): + return + self.process_decorator(o) + self.visit_func_def(o.func) + + def process_decorator(self, o: Decorator) -> None: + """Process a series of decorators. + + Only preserve certain special decorators such as @abstractmethod. + """ + o.func.is_overload = False + for decorator in o.original_decorators: + d = decorator + if isinstance(d, CallExpr): + d = d.callee + if not isinstance(d, (NameExpr, MemberExpr)): + continue + qualname = get_qualified_name(d) + fullname = self.get_fullname(d) + if fullname in ( + "builtins.property", + "builtins.staticmethod", + "builtins.classmethod", + "functools.cached_property", + ): + self.add_decorator(qualname, require_name=True) + elif fullname in ( + "asyncio.coroutine", + "asyncio.coroutines.coroutine", + "types.coroutine", + ): + o.func.is_awaitable_coroutine = True + self.add_decorator(qualname, require_name=True) + elif fullname == "abc.abstractmethod": + self.add_decorator(qualname, require_name=True) + o.func.abstract_status = IS_ABSTRACT + elif fullname in ( + "abc.abstractproperty", + "abc.abstractstaticmethod", + "abc.abstractclassmethod", + ): + abc_module = qualname.rpartition(".")[0] + if not abc_module: + self.import_tracker.add_import("abc") + builtin_decorator_replacement = fullname[len("abc.abstract") :] + self.add_decorator(builtin_decorator_replacement, require_name=False) + self.add_decorator(f"{abc_module or 'abc'}.abstractmethod", require_name=True) + o.func.abstract_status = IS_ABSTRACT + elif fullname in OVERLOAD_NAMES: + self.add_decorator(qualname, require_name=True) + o.func.is_overload = True + elif qualname.endswith((".setter", ".deleter")): + self.add_decorator(qualname, require_name=False) + elif fullname in DATACLASS_TRANSFORM_NAMES: + p = AliasPrinter(self) + self._decorators.append(f"@{decorator.accept(p)}") + elif isinstance(decorator, (NameExpr, MemberExpr)): + p = AliasPrinter(self) + self._decorators.append(f"@{decorator.accept(p)}") + + def get_fullname(self, expr: Expression) -> str: + """Return the expression's full name.""" + if ( + self.analyzed + and isinstance(expr, (NameExpr, MemberExpr)) + and expr.fullname + and not (isinstance(expr.node, Var) and expr.node.is_suppressed_import) + ): + return expr.fullname + name = get_qualified_name(expr) + return self.resolve_name(name) + + def visit_class_def(self, o: ClassDef) -> None: + self._class_stack.append(o) + self.method_names = find_method_names(o.defs.body) + sep: int | None = None + if self.is_top_level() and self._state != EMPTY: + sep = len(self._output) + self.add("\n") + decorators = self.get_class_decorators(o) + for d in decorators: + self.add(f"{self._indent}@{d}\n") + self.record_name(o.name) + base_types = self.get_base_types(o) + if base_types: + for base in base_types: + self.import_tracker.require_name(base) + if self.analyzed and o.info.is_enum: + self.processing_enum = True + if isinstance(o.metaclass, (NameExpr, MemberExpr)): + meta = o.metaclass.accept(AliasPrinter(self)) + base_types.append("metaclass=" + meta) + elif self.analyzed and o.info.is_abstract and not o.info.is_protocol: + base_types.append("metaclass=abc.ABCMeta") + self.import_tracker.add_import("abc") + self.import_tracker.require_name("abc") + bases = f"({', '.join(base_types)})" if base_types else "" + type_args = self.format_type_args(o) + self.add(f"{self._indent}class {o.name}{type_args}{bases}:\n") + self.indent() + if self._include_docstrings and o.docstring: + docstring = mypy.util.quote_docstring(o.docstring) + self.add(f"{self._indent}{docstring}\n") + n = len(self._output) + self._vars.append([]) + if self.analyzed and (spec := find_dataclass_transform_spec(o)): + self.processing_dataclass = True + self.dataclass_field_specifier = spec.field_specifiers + super().visit_class_def(o) + self.dedent() + self._vars.pop() + self._vars[-1].append(o.name) + if len(self._output) == n: + if self._state == EMPTY_CLASS and sep is not None: + self._output[sep] = "" + if not (self._include_docstrings and o.docstring): + self._output[-1] = self._output[-1][:-1] + " ...\n" + self._state = EMPTY_CLASS + else: + self._state = CLASS + self.method_names = set() + self.processing_dataclass = False + self.dataclass_field_specifier = () + self._class_stack.pop(-1) + self.processing_enum = False + + def get_base_types(self, cdef: ClassDef) -> list[str]: + """Get list of base classes for a class.""" + base_types: list[str] = [] + p = AliasPrinter(self) + for base in cdef.base_type_exprs + cdef.removed_base_type_exprs: + if isinstance(base, (NameExpr, MemberExpr)): + if self.get_fullname(base) != "builtins.object": + base_types.append(get_qualified_name(base)) + elif isinstance(base, IndexExpr): + base_types.append(base.accept(p)) + elif isinstance(base, CallExpr): + # namedtuple(typename, fields), NamedTuple(typename, fields) calls can + # be used as a base class. The first argument is a string literal that + # is usually the same as the class name. + # + # Note: + # A call-based named tuple as a base class cannot be safely converted to + # a class-based NamedTuple definition because class attributes defined + # in the body of the class inheriting from the named tuple call are not + # namedtuple fields at runtime. + if self.is_namedtuple(base): + nt_fields = self._get_namedtuple_fields(base) + assert isinstance(base.args[0], StrExpr) + typename = base.args[0].value + if nt_fields is None: + # Invalid namedtuple() call, cannot determine fields + base_types.append(self.add_name("_typeshed.Incomplete")) + continue + fields_str = ", ".join(f"({f!r}, {t})" for f, t in nt_fields) + namedtuple_name = self.add_name("typing.NamedTuple") + base_types.append(f"{namedtuple_name}({typename!r}, [{fields_str}])") + elif self.is_typed_namedtuple(base): + base_types.append(base.accept(p)) + else: + # At this point, we don't know what the base class is, so we + # just use Incomplete as the base class. + base_types.append(self.add_name("_typeshed.Incomplete")) + for name, value in cdef.keywords.items(): + if name == "metaclass": + continue # handled separately + processed_value = value.accept(p) or "..." # at least, don't crash + base_types.append(f"{name}={processed_value}") + return base_types + + def get_class_decorators(self, cdef: ClassDef) -> list[str]: + decorators: list[str] = [] + p = AliasPrinter(self) + for d in cdef.decorators: + if self.is_dataclass(d): + decorators.append(d.accept(p)) + self.import_tracker.require_name(get_qualified_name(d)) + self.processing_dataclass = True + if self.is_dataclass_transform(d): + decorators.append(d.accept(p)) + self.import_tracker.require_name(get_qualified_name(d)) + return decorators + + def is_dataclass(self, expr: Expression) -> bool: + if isinstance(expr, CallExpr): + expr = expr.callee + return self.get_fullname(expr) == "dataclasses.dataclass" + + def is_dataclass_transform(self, expr: Expression) -> bool: + if isinstance(expr, CallExpr): + expr = expr.callee + if self.get_fullname(expr) in DATACLASS_TRANSFORM_NAMES: + return True + if (spec := find_dataclass_transform_spec(expr)) is not None: + self.processing_dataclass = True + self.dataclass_field_specifier = spec.field_specifiers + return True + return False + + def visit_block(self, o: Block) -> None: + # Unreachable statements may be partially uninitialized and that may + # cause trouble. + if not o.is_unreachable: + super().visit_block(o) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + foundl = [] + + for lvalue in o.lvalues: + if isinstance(lvalue, NameExpr) and isinstance(o.rvalue, CallExpr): + if self.is_namedtuple(o.rvalue) or self.is_typed_namedtuple(o.rvalue): + self.process_namedtuple(lvalue, o.rvalue) + foundl.append(False) # state is updated in process_namedtuple + continue + if self.is_typeddict(o.rvalue): + self.process_typeddict(lvalue, o.rvalue) + foundl.append(False) # state is updated in process_typeddict + continue + if ( + isinstance(lvalue, NameExpr) + and self.is_alias_expression(o.rvalue) + and not self.is_private_name(lvalue.name) + ): + is_explicit_type_alias = ( + o.unanalyzed_type and getattr(o.type, "name", None) == "TypeAlias" + ) + if is_explicit_type_alias: + self.process_typealias(lvalue, o.rvalue, is_explicit_type_alias=True) + continue + + if not o.unanalyzed_type: + self.process_typealias(lvalue, o.rvalue) + continue + + if isinstance(lvalue, (TupleExpr, ListExpr)): + items = lvalue.items + if isinstance(o.unanalyzed_type, TupleType): # type: ignore[misc] + annotations: Iterable[Type | None] = o.unanalyzed_type.items + else: + annotations = [None] * len(items) + else: + items = [lvalue] + annotations = [o.unanalyzed_type] + sep = False + found = False + for item, annotation in zip(items, annotations): + if isinstance(item, NameExpr): + init = self.get_init(item.name, o.rvalue, annotation) + if init: + found = True + if not sep and self.is_top_level() and self._state not in (EMPTY, VAR): + init = "\n" + init + sep = True + self.add(init) + self.record_name(item.name) + foundl.append(found) + + if all(foundl): + self._state = VAR + + def is_namedtuple(self, expr: CallExpr) -> bool: + return self.get_fullname(expr.callee) == "collections.namedtuple" + + def is_typed_namedtuple(self, expr: CallExpr) -> bool: + return self.get_fullname(expr.callee) in TYPED_NAMEDTUPLE_NAMES + + def _get_namedtuple_fields(self, call: CallExpr) -> list[tuple[str, str]] | None: + if self.is_namedtuple(call): + fields_arg = call.args[1] + if isinstance(fields_arg, StrExpr): + field_names = fields_arg.value.replace(",", " ").split() + elif isinstance(fields_arg, (ListExpr, TupleExpr)): + field_names = [] + for field in fields_arg.items: + if not isinstance(field, StrExpr): + return None + field_names.append(field.value) + else: + return None # Invalid namedtuple fields type + if field_names: + incomplete = self.add_name("_typeshed.Incomplete") + return [(field_name, incomplete) for field_name in field_names] + else: + return [] + + elif self.is_typed_namedtuple(call): + fields_arg = call.args[1] + if not isinstance(fields_arg, (ListExpr, TupleExpr)): + return None + fields: list[tuple[str, str]] = [] + p = AliasPrinter(self) + for field in fields_arg.items: + if not (isinstance(field, TupleExpr) and len(field.items) == 2): + return None + field_name, field_type = field.items + if not isinstance(field_name, StrExpr): + return None + fields.append((field_name.value, field_type.accept(p))) + return fields + else: + return None # Not a named tuple call + + def process_namedtuple(self, lvalue: NameExpr, rvalue: CallExpr) -> None: + if self._state == CLASS: + self.add("\n") + + if not isinstance(rvalue.args[0], StrExpr): + self.annotate_as_incomplete(lvalue) + return + + fields = self._get_namedtuple_fields(rvalue) + if fields is None: + self.annotate_as_incomplete(lvalue) + return + bases = self.add_name("typing.NamedTuple") + # TODO: Add support for generic NamedTuples. Requires `Generic` as base class. + class_def = f"{self._indent}class {lvalue.name}({bases}):" + if len(fields) == 0: + self.add(f"{class_def} ...\n") + self._state = EMPTY_CLASS + else: + if self._state not in (EMPTY, CLASS): + self.add("\n") + self.add(f"{class_def}\n") + for f_name, f_type in fields: + self.add(f"{self._indent} {f_name}: {f_type}\n") + self._state = CLASS + + def is_typeddict(self, expr: CallExpr) -> bool: + return self.get_fullname(expr.callee) in TPDICT_NAMES + + def process_typeddict(self, lvalue: NameExpr, rvalue: CallExpr) -> None: + if self._state == CLASS: + self.add("\n") + + if not isinstance(rvalue.args[0], StrExpr): + self.annotate_as_incomplete(lvalue) + return + + items: list[tuple[str, Expression]] = [] + total: Expression | None = None + if len(rvalue.args) > 1 and rvalue.arg_kinds[1] == ARG_POS: + if not isinstance(rvalue.args[1], DictExpr): + self.annotate_as_incomplete(lvalue) + return + for attr_name, attr_type in rvalue.args[1].items: + if not isinstance(attr_name, StrExpr): + self.annotate_as_incomplete(lvalue) + return + items.append((attr_name.value, attr_type)) + if len(rvalue.args) > 2: + if rvalue.arg_kinds[2] != ARG_NAMED or rvalue.arg_names[2] != "total": + self.annotate_as_incomplete(lvalue) + return + total = rvalue.args[2] + else: + for arg_name, arg in zip(rvalue.arg_names[1:], rvalue.args[1:]): + if not isinstance(arg_name, str): + self.annotate_as_incomplete(lvalue) + return + if arg_name == "total": + total = arg + else: + items.append((arg_name, arg)) + p = AliasPrinter(self) + if any(not key.isidentifier() or keyword.iskeyword(key) for key, _ in items): + # Keep the call syntax if there are non-identifier or reserved keyword keys. + self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n") + self._state = VAR + else: + bases = self.add_name("typing_extensions.TypedDict") + # TODO: Add support for generic TypedDicts. Requires `Generic` as base class. + if total is not None: + bases += f", total={total.accept(p)}" + class_def = f"{self._indent}class {lvalue.name}({bases}):" + if len(items) == 0: + self.add(f"{class_def} ...\n") + self._state = EMPTY_CLASS + else: + if self._state not in (EMPTY, CLASS): + self.add("\n") + self.add(f"{class_def}\n") + for key, key_type in items: + self.add(f"{self._indent} {key}: {key_type.accept(p)}\n") + self._state = CLASS + + def annotate_as_incomplete(self, lvalue: NameExpr) -> None: + incomplete = self.add_name("_typeshed.Incomplete") + self.add(f"{self._indent}{lvalue.name}: {incomplete}\n") + self._state = VAR + + def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool: + """Return True for things that look like target for an alias. + + Used to know if assignments look like type aliases, function alias, + or module alias. + """ + # Assignment of TypeVar(...) and other typevar-likes are passed through + if isinstance(expr, CallExpr) and self.get_fullname(expr.callee) in TYPE_VAR_LIKE_NAMES: + return True + elif isinstance(expr, EllipsisExpr): + return not top_level + elif isinstance(expr, NameExpr): + if expr.name in ("True", "False"): + return False + elif expr.name == "None": + return not top_level + else: + return not self.is_private_name(expr.name) + elif isinstance(expr, MemberExpr) and self.analyzed: + # Also add function and module aliases. + return ( + top_level + and isinstance(expr.node, (FuncDef, Decorator, MypyFile)) + or isinstance(expr.node, TypeInfo) + ) and not self.is_private_member(expr.node.fullname) + elif isinstance(expr, IndexExpr) and ( + (isinstance(expr.base, NameExpr) and not self.is_private_name(expr.base.name)) + or ( # Also some known aliases that could be member expression + isinstance(expr.base, MemberExpr) + and not self.is_private_member(get_qualified_name(expr.base)) + and self.get_fullname(expr.base).startswith( + ("builtins.", "typing.", "typing_extensions.", "collections.abc.") + ) + ) + ): + if isinstance(expr.index, TupleExpr): + indices = expr.index.items + else: + indices = [expr.index] + if expr.base.name == "Callable" and len(indices) == 2: + args, ret = indices + if isinstance(args, EllipsisExpr): + indices = [ret] + elif isinstance(args, ListExpr): + indices = args.items + [ret] + else: + return False + return all(self.is_alias_expression(i, top_level=False) for i in indices) + elif isinstance(expr, OpExpr) and expr.op == "|": + return self.is_alias_expression( + expr.left, top_level=False + ) and self.is_alias_expression(expr.right, top_level=False) + else: + return False + + def process_typealias( + self, lvalue: NameExpr, rvalue: Expression, is_explicit_type_alias: bool = False + ) -> None: + p = AliasPrinter(self) + if is_explicit_type_alias: + self.import_tracker.require_name("TypeAlias") + self.add(f"{self._indent}{lvalue.name}: TypeAlias = {rvalue.accept(p)}\n") + else: + self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n") + self.record_name(lvalue.name) + self._vars[-1].append(lvalue.name) + + def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: + """Type aliases defined with the `type` keyword (PEP 695).""" + p = AliasPrinter(self) + name = o.name.name + rvalue = o.value.expr() + type_args = self.format_type_args(o) + self.add(f"{self._indent}type {name}{type_args} = {rvalue.accept(p)}\n") + self.record_name(name) + self._vars[-1].append(name) + + def visit_if_stmt(self, o: IfStmt) -> None: + # Ignore if __name__ == '__main__'. + expr = o.expr[0] + if ( + isinstance(expr, ComparisonExpr) + and isinstance(expr.operands[0], NameExpr) + and isinstance(expr.operands[1], StrExpr) + and expr.operands[0].name == "__name__" + and "__main__" in expr.operands[1].value + ): + return + super().visit_if_stmt(o) + + def visit_import_all(self, o: ImportAll) -> None: + self.add_import_line(f"from {'.' * o.relative}{o.id} import *\n") + + def visit_import_from(self, o: ImportFrom) -> None: + exported_names: set[str] = set() + import_names = [] + module, relative = translate_module_name(o.id, o.relative) + if self.module_name: + full_module, ok = mypy.util.correct_relative_import( + self.module_name, relative, module, self.path.endswith(".__init__.py") + ) + if not ok: + full_module = module + else: + full_module = module + if module == "__future__": + return # Not preserved + for name, as_name in o.names: + if name == "six": + # Vendored six -- translate into plain 'import six'. + self.visit_import(Import([("six", None)])) + continue + if self.should_reexport(name, full_module, as_name is not None): + self.import_tracker.reexport(name) + as_name = name + import_names.append((name, as_name)) + self.import_tracker.add_import_from("." * relative + module, import_names) + self._vars[-1].extend(alias or name for name, alias in import_names) + for name, alias in import_names: + self.record_name(alias or name) + + if self._all_: + # Include "import from"s that import names defined in __all__. + names = [ + name + for name, alias in o.names + if name in self._all_ and alias is None and name not in self.IGNORED_DUNDERS + ] + exported_names.update(names) + + def visit_import(self, o: Import) -> None: + for id, as_id in o.ids: + self.import_tracker.add_import(id, as_id) + if as_id is None: + target_name = id.split(".")[0] + else: + target_name = as_id + self._vars[-1].append(target_name) + self.record_name(target_name) + + def get_init( + self, lvalue: str, rvalue: Expression, annotation: Type | None = None + ) -> str | None: + """Return initializer for a variable. + + Return None if we've generated one already or if the variable is internal. + """ + if lvalue in self._vars[-1]: + # We've generated an initializer already for this variable. + return None + # TODO: Only do this at module top level. + if self.is_private_name(lvalue) or self.is_not_in_all(lvalue): + return None + self._vars[-1].append(lvalue) + if annotation is not None: + typename = self.print_annotation(annotation) + if ( + isinstance(annotation, UnboundType) + and not annotation.args + and annotation.name == "Final" + and self.import_tracker.module_for.get("Final") in self.TYPING_MODULE_NAMES + ): + # Final without type argument is invalid in stubs. + final_arg = self.get_str_type_of_node(rvalue) + typename += f"[{final_arg}]" + elif self.processing_enum: + initializer, _ = self.get_str_default_of_node(rvalue) + return f"{self._indent}{lvalue} = {initializer}\n" + elif self.processing_dataclass: + # attribute without annotation is not a dataclass field, don't add annotation. + return f"{self._indent}{lvalue} = ...\n" + else: + typename = self.get_str_type_of_node(rvalue) + initializer = self.get_assign_initializer(rvalue) + return f"{self._indent}{lvalue}: {typename}{initializer}\n" + + def get_assign_initializer(self, rvalue: Expression) -> str: + """Does this rvalue need some special initializer value?""" + if not self._current_class: + return "" + # Current rules + # 1. Return `...` if we are dealing with `NamedTuple` or `dataclass` field and + # it has an existing default value + if ( + self._current_class.info + and self._current_class.info.is_named_tuple + and not isinstance(rvalue, TempNode) + ): + return " = ..." + if self.processing_dataclass: + if isinstance(rvalue, CallExpr): + fullname = self.get_fullname(rvalue.callee) + if fullname in (self.dataclass_field_specifier or DATACLASS_FIELD_SPECIFIERS): + p = AliasPrinter(self) + return f" = {rvalue.accept(p)}" + if not (isinstance(rvalue, TempNode) and rvalue.no_rhs): + return " = ..." + # TODO: support other possible cases, where initializer is important + + # By default, no initializer is required: + return "" + + def add_decorator(self, name: str, require_name: bool = False) -> None: + if require_name: + self.import_tracker.require_name(name) + self._decorators.append(f"@{name}") + + def clear_decorators(self) -> None: + self._decorators.clear() + + def is_private_member(self, fullname: str) -> bool: + parts = fullname.split(".") + return any(self.is_private_name(part) for part in parts) + + def get_str_type_of_node(self, rvalue: Expression, *, can_be_incomplete: bool = True) -> str: + rvalue = self.maybe_unwrap_unary_expr(rvalue) + + if isinstance(rvalue, IntExpr): + return "int" + if isinstance(rvalue, StrExpr): + return "str" + if isinstance(rvalue, BytesExpr): + return "bytes" + if isinstance(rvalue, FloatExpr): + return "float" + if isinstance(rvalue, ComplexExpr): # 1j + return "complex" + if isinstance(rvalue, OpExpr) and rvalue.op in ("-", "+"): # -1j + 1 + if isinstance(self.maybe_unwrap_unary_expr(rvalue.left), ComplexExpr) or isinstance( + self.maybe_unwrap_unary_expr(rvalue.right), ComplexExpr + ): + return "complex" + if isinstance(rvalue, NameExpr) and rvalue.name in ("True", "False"): + return "bool" + if can_be_incomplete: + return self.add_name("_typeshed.Incomplete") + else: + return "" + + def maybe_unwrap_unary_expr(self, expr: Expression) -> Expression: + """Unwrap (possibly nested) unary expressions. + + But, some unary expressions can change the type of expression. + While we want to preserve it. For example, `~True` is `int`. + So, we only allow a subset of unary expressions to be unwrapped. + """ + if not isinstance(expr, UnaryExpr): + return expr + + # First, try to unwrap `[+-]+ (int|float|complex)` expr: + math_ops = ("+", "-") + if expr.op in math_ops: + while isinstance(expr, UnaryExpr): + if expr.op not in math_ops or not isinstance( + expr.expr, (IntExpr, FloatExpr, ComplexExpr, UnaryExpr) + ): + break + expr = expr.expr + return expr + + # Next, try `not bool` expr: + if expr.op == "not": + while isinstance(expr, UnaryExpr): + if expr.op != "not" or not isinstance(expr.expr, (NameExpr, UnaryExpr)): + break + if isinstance(expr.expr, NameExpr) and expr.expr.name not in ("True", "False"): + break + expr = expr.expr + return expr + + # This is some other unary expr, we cannot do anything with it (yet?). + return expr + + def get_str_default_of_node(self, rvalue: Expression) -> tuple[str, bool]: + """Get a string representation of the default value of a node. + + Returns a 2-tuple of the default and whether or not it is valid. + """ + if isinstance(rvalue, NameExpr): + if rvalue.name in ("None", "True", "False"): + return rvalue.name, True + elif isinstance(rvalue, (IntExpr, FloatExpr)): + return f"{rvalue.value}", True + elif isinstance(rvalue, UnaryExpr): + if isinstance(rvalue.expr, (IntExpr, FloatExpr)): + return f"{rvalue.op}{rvalue.expr.value}", True + elif isinstance(rvalue, StrExpr): + return repr(rvalue.value), True + elif isinstance(rvalue, BytesExpr): + return "b" + repr(rvalue.value).replace("\\\\", "\\"), True + elif isinstance(rvalue, TupleExpr): + items_defaults = [] + for e in rvalue.items: + e_default, valid = self.get_str_default_of_node(e) + if not valid: + break + items_defaults.append(e_default) + else: + closing = ",)" if len(items_defaults) == 1 else ")" + default = "(" + ", ".join(items_defaults) + closing + return default, True + elif isinstance(rvalue, ListExpr): + items_defaults = [] + for e in rvalue.items: + e_default, valid = self.get_str_default_of_node(e) + if not valid: + break + items_defaults.append(e_default) + else: + default = "[" + ", ".join(items_defaults) + "]" + return default, True + elif isinstance(rvalue, SetExpr): + items_defaults = [] + for e in rvalue.items: + e_default, valid = self.get_str_default_of_node(e) + if not valid: + break + items_defaults.append(e_default) + else: + if items_defaults: + default = "{" + ", ".join(items_defaults) + "}" + return default, True + elif isinstance(rvalue, DictExpr): + items_defaults = [] + for k, v in rvalue.items: + if k is None: + break + k_default, k_valid = self.get_str_default_of_node(k) + v_default, v_valid = self.get_str_default_of_node(v) + if not (k_valid and v_valid): + break + items_defaults.append(f"{k_default}: {v_default}") + else: + default = "{" + ", ".join(items_defaults) + "}" + return default, True + return "...", False + + def should_reexport(self, name: str, full_module: str, name_is_alias: bool) -> bool: + is_private = self.is_private_name(name, full_module + "." + name) + if ( + not name_is_alias + and name not in self.referenced_names + and (not self._all_ or name in self.IGNORED_DUNDERS) + and not is_private + and full_module not in ("abc", "asyncio") + self.TYPING_MODULE_NAMES + ): + # An imported name that is never referenced in the module is assumed to be + # exported, unless there is an explicit __all__. Note that we need to special + # case 'abc' since some references are deleted during semantic analysis. + return True + return super().should_reexport(name, full_module, name_is_alias) + + +def find_method_names(defs: list[Statement]) -> set[str]: + # TODO: Traverse into nested definitions + result = set() + for defn in defs: + if isinstance(defn, FuncDef): + result.add(defn.name) + elif isinstance(defn, Decorator): + result.add(defn.func.name) + elif isinstance(defn, OverloadedFuncDef): + for item in defn.items: + result.update(find_method_names([item])) + return result + + +class SelfTraverser(mypy.traverser.TraverserVisitor): + def __init__(self) -> None: + self.results: list[tuple[str, Expression, Type | None]] = [] + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + lvalue = o.lvalues[0] + if ( + isinstance(lvalue, MemberExpr) + and isinstance(lvalue.expr, NameExpr) + and lvalue.expr.name == "self" + ): + self.results.append((lvalue.name, o.rvalue, o.unanalyzed_type)) + + +def find_self_initializers(fdef: FuncBase) -> list[tuple[str, Expression, Type | None]]: + """Find attribute initializers in a method. + + Return a list of pairs (attribute name, r.h.s. expression). + """ + traverser = SelfTraverser() + fdef.accept(traverser) + return traverser.results + + +def get_qualified_name(o: Expression) -> str: + if isinstance(o, NameExpr): + return o.name + elif isinstance(o, MemberExpr): + return f"{get_qualified_name(o.expr)}.{o.name}" + else: + return ERROR_MARKER + + +def remove_blacklisted_modules(modules: list[StubSource]) -> list[StubSource]: + return [ + module for module in modules if module.path is None or not is_blacklisted_path(module.path) + ] + + +def split_pyc_from_py(modules: list[StubSource]) -> tuple[list[StubSource], list[StubSource]]: + py_modules = [] + pyc_modules = [] + for mod in modules: + if is_pyc_only(mod.path): + pyc_modules.append(mod) + else: + py_modules.append(mod) + return pyc_modules, py_modules + + +def is_blacklisted_path(path: str) -> bool: + return any(substr in (normalize_path_separators(path) + "\n") for substr in BLACKLIST) + + +def normalize_path_separators(path: str) -> str: + return path.replace("\\", "/") if sys.platform == "win32" else path + + +def collect_build_targets( + options: Options, mypy_opts: MypyOptions +) -> tuple[list[StubSource], list[StubSource], list[StubSource]]: + """Collect files for which we need to generate stubs. + + Return list of py modules, pyc modules, and C modules. + """ + if options.packages or options.modules: + if options.no_import: + py_modules = find_module_paths_using_search( + options.modules, options.packages, options.search_path, options.pyversion + ) + c_modules: list[StubSource] = [] + else: + # Using imports is the default, since we can also find C modules. + py_modules, c_modules = find_module_paths_using_imports( + options.modules, options.packages, options.verbose, options.quiet + ) + else: + # Use mypy native source collection for files and directories. + try: + source_list = create_source_list(options.files, mypy_opts) + except InvalidSourceList as e: + raise SystemExit(str(e)) from e + py_modules = [StubSource(m.module, m.path) for m in source_list] + c_modules = [] + + py_modules = remove_blacklisted_modules(py_modules) + pyc_mod, py_mod = split_pyc_from_py(py_modules) + return py_mod, pyc_mod, c_modules + + +def find_module_paths_using_imports( + modules: list[str], packages: list[str], verbose: bool, quiet: bool +) -> tuple[list[StubSource], list[StubSource]]: + """Find path and runtime value of __all__ (if possible) for modules and packages. + + This function uses runtime Python imports to get the information. + """ + with ModuleInspect() as inspect: + py_modules: list[StubSource] = [] + c_modules: list[StubSource] = [] + found = list(walk_packages(inspect, packages, verbose)) + modules = modules + found + modules = [ + mod for mod in modules if not is_non_library_module(mod) + ] # We don't want to run any tests or scripts + for mod in modules: + try: + result = find_module_path_and_all_py3(inspect, mod, verbose) + except CantImport as e: + tb = traceback.format_exc() + if verbose: + sys.stderr.write(tb) + if not quiet: + report_missing(mod, e.message, tb) + continue + if not result: + c_modules.append(StubSource(mod)) + else: + path, runtime_all = result + py_modules.append(StubSource(mod, path, runtime_all)) + return py_modules, c_modules + + +def is_non_library_module(module: str) -> bool: + """Does module look like a test module or a script?""" + if module.endswith( + ( + ".tests", + ".test", + ".testing", + "_tests", + "_test_suite", + "test_util", + "test_utils", + "test_base", + ".__main__", + ".conftest", # Used by pytest + ".setup", # Typically an install script + ) + ): + return True + if module.split(".")[-1].startswith("test_"): + return True + if ( + ".tests." in module + or ".test." in module + or ".testing." in module + or ".SelfTest." in module + ): + return True + return False + + +def translate_module_name(module: str, relative: int) -> tuple[str, int]: + for pkg in VENDOR_PACKAGES: + for alt in "six.moves", "six": + substr = f"{pkg}.{alt}" + if module.endswith("." + substr) or (module == substr and relative): + return alt, 0 + if "." + substr + "." in module: + return alt + "." + module.partition("." + substr + ".")[2], 0 + return module, relative + + +def find_module_paths_using_search( + modules: list[str], packages: list[str], search_path: list[str], pyversion: tuple[int, int] +) -> list[StubSource]: + """Find sources for modules and packages requested. + + This function just looks for source files at the file system level. + This is used if user passes --no-import, and will not find C modules. + Exit if some of the modules or packages can't be found. + """ + result: list[StubSource] = [] + typeshed_path = default_lib_path(mypy.build.default_data_dir(), pyversion, None) + search_paths = SearchPaths((".",) + tuple(search_path), (), (), tuple(typeshed_path)) + cache = FindModuleCache(search_paths, fscache=None, options=None) + for module in modules: + m_result = cache.find_module(module) + if isinstance(m_result, ModuleNotFoundReason): + fail_missing(module, m_result) + module_path = None + else: + module_path = m_result + result.append(StubSource(module, module_path)) + for package in packages: + p_result = cache.find_modules_recursive(package) + if p_result: + fail_missing(package, ModuleNotFoundReason.NOT_FOUND) + sources = [StubSource(m.module, m.path) for m in p_result] + result.extend(sources) + + result = [m for m in result if not is_non_library_module(m.module)] + + return result + + +def mypy_options(stubgen_options: Options) -> MypyOptions: + """Generate mypy options using the flag passed by user.""" + options = MypyOptions() + options.follow_imports = "skip" + options.incremental = False + options.ignore_errors = True + options.semantic_analysis_only = True + options.python_version = stubgen_options.pyversion + options.show_traceback = True + options.transform_source = remove_misplaced_type_comments + options.preserve_asts = True + options.include_docstrings = stubgen_options.include_docstrings + + # Override cache_dir if provided in the environment + environ_cache_dir = os.getenv("MYPY_CACHE_DIR", "") + if environ_cache_dir.strip(): + options.cache_dir = environ_cache_dir + options.cache_dir = os.path.expanduser(options.cache_dir) + + return options + + +def parse_source_file(mod: StubSource, mypy_options: MypyOptions) -> None: + """Parse a source file. + + On success, store AST in the corresponding attribute of the stub source. + If there are syntax errors, print them and exit. + """ + assert mod.path is not None, "Not found module was not skipped" + with open(mod.path, "rb") as f: + data = f.read() + source = mypy.util.decode_python_encoding(data) + errors = Errors(mypy_options) + mod.ast = mypy.parse.parse( + source, fnam=mod.path, module=mod.module, errors=errors, options=mypy_options + ) + mod.ast._fullname = mod.module + if errors.is_blockers(): + # Syntax error! + for m in errors.new_messages(): + sys.stderr.write(f"{m}\n") + sys.exit(1) + + +def generate_asts_for_modules( + py_modules: list[StubSource], parse_only: bool, mypy_options: MypyOptions, verbose: bool +) -> None: + """Use mypy to parse (and optionally analyze) source files.""" + if not py_modules: + return # Nothing to do here, but there may be C modules + if verbose: + print(f"Processing {len(py_modules)} files...") + if parse_only: + for mod in py_modules: + parse_source_file(mod, mypy_options) + return + # Perform full semantic analysis of the source set. + try: + res = build([module.source for module in py_modules], mypy_options) + except CompileError as e: + raise SystemExit(f"Critical error during semantic analysis: {e}") from e + + for mod in py_modules: + mod.ast = res.graph[mod.module].tree + # Use statically inferred __all__ if there is no runtime one. + if mod.runtime_all is None: + mod_names = res.manager.semantic_analyzer.modules[mod.module].names + if "__all__" in mod_names: + mod.runtime_all = [name for name, sym in mod_names.items() if sym.module_public] + + +def generate_stub_for_py_module( + mod: StubSource, + target: str, + *, + parse_only: bool = False, + inspect: bool = False, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + doc_dir: str = "", + all_modules: list[str], +) -> None: + """Use analysed (or just parsed) AST to generate type stub for single file. + + If directory for target doesn't exist it will created. Existing stub + will be overwritten. + """ + if inspect: + ngen = InspectionStubGenerator( + module_name=mod.module, + known_modules=all_modules, + _all_=mod.runtime_all, + doc_dir=doc_dir, + include_private=include_private, + export_less=export_less, + include_docstrings=include_docstrings, + ) + ngen.generate_module() + output = ngen.output() + + else: + gen = ASTStubGenerator( + mod.runtime_all, + include_private=include_private, + analyzed=not parse_only, + export_less=export_less, + include_docstrings=include_docstrings, + ) + assert mod.ast is not None, "This function must be used only with analyzed modules" + mod.ast.accept(gen) + output = gen.output() + + # Write output to file. + subdir = os.path.dirname(target) + if subdir and not os.path.isdir(subdir): + os.makedirs(subdir) + with open(target, "w", encoding="utf-8") as file: + file.write(output) + + +def generate_stubs(options: Options) -> None: + """Main entry point for the program.""" + mypy_opts = mypy_options(options) + py_modules, pyc_modules, c_modules = collect_build_targets(options, mypy_opts) + all_modules = py_modules + pyc_modules + c_modules + all_module_names = sorted(m.module for m in all_modules) + # Use parsed sources to generate stubs for Python modules. + generate_asts_for_modules(py_modules, options.parse_only, mypy_opts, options.verbose) + files = [] + for mod in py_modules + pyc_modules: + assert mod.path is not None, "Not found module was not skipped" + target = mod.module.replace(".", "/") + if os.path.basename(mod.path) in ["__init__.py", "__init__.pyc"]: + target += "/__init__.pyi" + else: + target += ".pyi" + target = os.path.join(options.output_dir, target) + files.append(target) + with generate_guarded(mod.module, target, options.ignore_errors, options.verbose): + generate_stub_for_py_module( + mod, + target, + parse_only=options.parse_only, + inspect=options.inspect or mod in pyc_modules, + include_private=options.include_private, + export_less=options.export_less, + include_docstrings=options.include_docstrings, + doc_dir=options.doc_dir, + all_modules=all_module_names, + ) + + # Separately analyse C modules using different logic. + for mod in c_modules: + if any(py_mod.module.startswith(mod.module + ".") for py_mod in all_modules): + target = mod.module.replace(".", "/") + "/__init__.pyi" + else: + target = mod.module.replace(".", "/") + ".pyi" + target = os.path.join(options.output_dir, target) + files.append(target) + with generate_guarded(mod.module, target, options.ignore_errors, options.verbose): + generate_stub_for_c_module( + mod.module, + target, + known_modules=all_module_names, + doc_dir=options.doc_dir, + include_private=options.include_private, + export_less=options.export_less, + include_docstrings=options.include_docstrings, + ) + num_modules = len(all_modules) + if not options.quiet and num_modules > 0: + print("Processed %d modules" % num_modules) + if len(files) == 1: + print(f"Generated {files[0]}") + else: + print(f"Generated files under {common_dir_prefix(files)}" + os.sep) + + +HEADER = """%(prog)s [-h] [more options, see -h] + [-m MODULE] [-p PACKAGE] [files ...]""" + +DESCRIPTION = """ +Generate draft stubs for modules. + +Stubs are generated in directory ./out, to avoid overriding files with +manual changes. This directory is assumed to exist. +""" + + +def parse_options(args: list[str]) -> Options: + parser = argparse.ArgumentParser( + prog="stubgen", usage=HEADER, description=DESCRIPTION, fromfile_prefix_chars="@" + ) + + parser.add_argument( + "--ignore-errors", + action="store_true", + help="ignore errors when trying to generate stubs for modules", + ) + parser.add_argument( + "--no-import", + action="store_true", + help="don't import the modules, just parse and analyze them " + "(doesn't work with C extension modules and might not " + "respect __all__)", + ) + parser.add_argument( + "--no-analysis", + "--parse-only", + dest="parse_only", + action="store_true", + help="don't perform semantic analysis of sources, just parse them " + "(only applies to Python modules, might affect quality of stubs. " + "Not compatible with --inspect-mode)", + ) + parser.add_argument( + "--inspect-mode", + dest="inspect", + action="store_true", + help="import and inspect modules instead of parsing source code." + "This is the default behavior for c modules and pyc-only packages, but " + "it is also useful for pure python modules with dynamically generated members.", + ) + parser.add_argument( + "--include-private", + action="store_true", + help="generate stubs for objects and members considered private " + "(single leading underscore and no trailing underscores)", + ) + parser.add_argument( + "--export-less", + action="store_true", + help="don't implicitly export all names imported from other modules in the same package", + ) + parser.add_argument( + "--include-docstrings", + action="store_true", + help="include existing docstrings with the stubs", + ) + parser.add_argument("-v", "--verbose", action="store_true", help="show more verbose messages") + parser.add_argument("-q", "--quiet", action="store_true", help="show fewer messages") + parser.add_argument( + "--doc-dir", + metavar="PATH", + default="", + help="use .rst documentation in PATH (this may result in " + "better stubs in some cases; consider setting this to " + "DIR/Python-X.Y.Z/Doc/library)", + ) + parser.add_argument( + "--search-path", + metavar="PATH", + default="", + help="specify module search directories, separated by ':' " + "(currently only used if --no-import is given)", + ) + parser.add_argument( + "-o", + "--output", + metavar="PATH", + dest="output_dir", + default="out", + help="change the output directory [default: %(default)s]", + ) + parser.add_argument( + "-m", + "--module", + action="append", + metavar="MODULE", + dest="modules", + default=[], + help="generate stub for module; can repeat for more modules", + ) + parser.add_argument( + "-p", + "--package", + action="append", + metavar="PACKAGE", + dest="packages", + default=[], + help="generate stubs for package recursively; can be repeated", + ) + parser.add_argument( + metavar="files", + nargs="*", + dest="files", + help="generate stubs for given files or directories", + ) + parser.add_argument( + "--version", action="version", version="%(prog)s " + mypy.version.__version__ + ) + + ns = parser.parse_args(args) + + pyversion = sys.version_info[:2] + ns.interpreter = sys.executable + + if ns.modules + ns.packages and ns.files: + parser.error("May only specify one of: modules/packages or files.") + if ns.quiet and ns.verbose: + parser.error("Cannot specify both quiet and verbose messages") + if ns.inspect and ns.parse_only: + parser.error("Cannot specify both --parse-only/--no-analysis and --inspect-mode") + + # Create the output folder if it doesn't already exist. + os.makedirs(ns.output_dir, exist_ok=True) + + return Options( + pyversion=pyversion, + no_import=ns.no_import, + inspect=ns.inspect, + doc_dir=ns.doc_dir, + search_path=ns.search_path.split(":"), + interpreter=ns.interpreter, + ignore_errors=ns.ignore_errors, + parse_only=ns.parse_only, + include_private=ns.include_private, + output_dir=ns.output_dir, + modules=ns.modules, + packages=ns.packages, + files=ns.files, + verbose=ns.verbose, + quiet=ns.quiet, + export_less=ns.export_less, + include_docstrings=ns.include_docstrings, + ) + + +def main(args: list[str] | None = None) -> None: + mypy.util.check_python_version("stubgen") + # Make sure that the current directory is in sys.path so that + # stubgen can be run on packages in the current directory. + if not ("" in sys.path or "." in sys.path): + sys.path.insert(0, "") + + options = parse_options(sys.argv[1:] if args is None else args) + generate_stubs(options) + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgenc.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgenc.py new file mode 100644 index 0000000000000000000000000000000000000000..d86818adf2a4314ff15048cc09ec1e0a46e74b95 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubgenc.py @@ -0,0 +1,1046 @@ +#!/usr/bin/env python3 +"""Stub generator for C modules. + +The public interface is via the mypy.stubgen module. +""" + +from __future__ import annotations + +import enum +import glob +import importlib +import inspect +import keyword +import os.path +from collections.abc import Callable, Mapping +from types import FunctionType, ModuleType +from typing import Any + +from mypy.fastparse import parse_type_comment +from mypy.moduleinspect import is_c_module +from mypy.stubdoc import ( + ArgSig, + FunctionSig, + Sig, + find_unique_signatures, + infer_arg_sig_from_anon_docstring, + infer_prop_type_from_docstring, + infer_ret_type_sig_from_anon_docstring, + infer_ret_type_sig_from_docstring, + infer_sig_from_docstring, + parse_all_signatures, +) +from mypy.stubutil import ( + BaseStubGenerator, + ClassInfo, + FunctionContext, + SignatureGenerator, + infer_method_arg_types, + infer_method_ret_type, +) +from mypy.util import quote_docstring + + +class ExternalSignatureGenerator(SignatureGenerator): + def __init__( + self, func_sigs: dict[str, str] | None = None, class_sigs: dict[str, str] | None = None + ) -> None: + """ + Takes a mapping of function/method names to signatures and class name to + class signatures (usually corresponds to __init__). + """ + self.func_sigs = func_sigs or {} + self.class_sigs = class_sigs or {} + + @classmethod + def from_doc_dir(cls, doc_dir: str) -> ExternalSignatureGenerator: + """Instantiate from a directory of .rst files.""" + all_sigs: list[Sig] = [] + all_class_sigs: list[Sig] = [] + for path in glob.glob(f"{doc_dir}/*.rst"): + with open(path) as f: + loc_sigs, loc_class_sigs = parse_all_signatures(f.readlines()) + all_sigs += loc_sigs + all_class_sigs += loc_class_sigs + sigs = dict(find_unique_signatures(all_sigs)) + class_sigs = dict(find_unique_signatures(all_class_sigs)) + return ExternalSignatureGenerator(sigs, class_sigs) + + def get_function_sig( + self, default_sig: FunctionSig, ctx: FunctionContext + ) -> list[FunctionSig] | None: + # method: + if ( + ctx.class_info + and ctx.name in ("__new__", "__init__") + and ctx.name not in self.func_sigs + and ctx.class_info.name in self.class_sigs + ): + return [ + FunctionSig( + name=ctx.name, + args=infer_arg_sig_from_anon_docstring(self.class_sigs[ctx.class_info.name]), + ret_type=infer_method_ret_type(ctx.name), + ) + ] + + # function: + if ctx.name not in self.func_sigs: + return None + + inferred = [ + FunctionSig( + name=ctx.name, + args=infer_arg_sig_from_anon_docstring(self.func_sigs[ctx.name]), + ret_type=None, + ) + ] + if ctx.class_info: + return self.remove_self_type(inferred, ctx.class_info.self_var) + else: + return inferred + + def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None: + return None + + +class DocstringSignatureGenerator(SignatureGenerator): + def get_function_sig( + self, default_sig: FunctionSig, ctx: FunctionContext + ) -> list[FunctionSig] | None: + inferred = infer_sig_from_docstring(ctx.docstring, ctx.name) + if inferred: + assert ctx.docstring is not None + if is_pybind11_overloaded_function_docstring(ctx.docstring, ctx.name): + # Remove pybind11 umbrella (*args, **kwargs) for overloaded functions + del inferred[-1] + + if ctx.class_info: + if not inferred and ctx.name == "__init__": + # look for class-level constructor signatures of the form () + inferred = infer_sig_from_docstring(ctx.class_info.docstring, ctx.class_info.name) + if inferred: + inferred = [sig._replace(name="__init__") for sig in inferred] + return self.remove_self_type(inferred, ctx.class_info.self_var) + else: + return inferred + + def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None: + """Infer property type from docstring or docstring signature.""" + if ctx.docstring is not None: + inferred = infer_ret_type_sig_from_anon_docstring(ctx.docstring) + if inferred: + return inferred + inferred = infer_ret_type_sig_from_docstring(ctx.docstring, ctx.name) + if inferred: + return inferred + inferred = infer_prop_type_from_docstring(ctx.docstring) + return inferred + else: + return None + + +def is_pybind11_overloaded_function_docstring(docstring: str, name: str) -> bool: + return docstring.startswith(f"{name}(*args, **kwargs)\nOverloaded function.\n\n") + + +def generate_stub_for_c_module( + module_name: str, + target: str, + known_modules: list[str], + doc_dir: str = "", + *, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, +) -> None: + """Generate stub for C module. + + Signature generators are called in order until a list of signatures is returned. The order + is: + - signatures inferred from .rst documentation (if given) + - simple runtime introspection (looking for docstrings and attributes + with simple builtin types) + - fallback based special method names or "(*args, **kwargs)" + + If directory for target doesn't exist it will be created. Existing stub + will be overwritten. + """ + subdir = os.path.dirname(target) + if subdir and not os.path.isdir(subdir): + os.makedirs(subdir) + + gen = InspectionStubGenerator( + module_name, + known_modules, + doc_dir, + include_private=include_private, + export_less=export_less, + include_docstrings=include_docstrings, + ) + gen.generate_module() + output = gen.output() + + with open(target, "w", encoding="utf-8") as file: + file.write(output) + + +class CFunctionStub: + """ + Class that mimics a C function in order to provide parseable docstrings. + """ + + def __init__(self, name: str, doc: str, is_abstract: bool = False) -> None: + self.__name__ = name + self.__doc__ = doc + self.__abstractmethod__ = is_abstract + + @classmethod + def _from_sig(cls, sig: FunctionSig, is_abstract: bool = False) -> CFunctionStub: + return CFunctionStub(sig.name, sig.format_sig()[:-4], is_abstract) + + @classmethod + def _from_sigs(cls, sigs: list[FunctionSig], is_abstract: bool = False) -> CFunctionStub: + return CFunctionStub( + sigs[0].name, "\n".join(sig.format_sig()[:-4] for sig in sigs), is_abstract + ) + + def __get__(self) -> None: # noqa: PLE0302 + """ + This exists to make this object look like a method descriptor and thus + return true for CStubGenerator.ismethod() + """ + pass + + +_Missing = enum.Enum("_Missing", "VALUE") + + +class InspectionStubGenerator(BaseStubGenerator): + """Stub generator that does not parse code. + + Generation is performed by inspecting the module's contents, and thus works + for highly dynamic modules, pyc files, and C modules (via the CStubGenerator + subclass). + """ + + def __init__( + self, + module_name: str, + known_modules: list[str], + doc_dir: str = "", + _all_: list[str] | None = None, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + module: ModuleType | None = None, + ) -> None: + self.doc_dir = doc_dir + if module is None: + self.module = importlib.import_module(module_name) + else: + self.module = module + self.is_c_module = is_c_module(self.module) + self.known_modules = known_modules + self.resort_members = self.is_c_module + super().__init__(_all_, include_private, export_less, include_docstrings) + self.module_name = module_name + if self.is_c_module: + # Add additional implicit imports. + # C-extensions are given more latitude since they do not import the typing module. + self.known_imports.update( + { + "typing": [ + "Any", + "Callable", + "ClassVar", + "Dict", + "Iterable", + "Iterator", + "List", + "Literal", + "NamedTuple", + "Optional", + "Tuple", + "Union", + ] + } + ) + + def get_default_function_sig(self, func: object, ctx: FunctionContext) -> FunctionSig: + argspec = None + if not self.is_c_module: + # Get the full argument specification of the function + try: + argspec = inspect.getfullargspec(func) + except TypeError: + # some callables cannot be inspected, e.g. functools.partial + pass + if argspec is None: + if ctx.class_info is not None: + # method: + return FunctionSig( + name=ctx.name, + args=infer_c_method_args(ctx.name, ctx.class_info.self_var), + ret_type=infer_method_ret_type(ctx.name), + ) + else: + # function: + return FunctionSig( + name=ctx.name, + args=[ArgSig(name="*args"), ArgSig(name="**kwargs")], + ret_type=None, + ) + + # Extract the function arguments, defaults, and varargs + args = argspec.args + defaults = argspec.defaults + varargs = argspec.varargs + kwargs = argspec.varkw + annotations = argspec.annotations + kwonlyargs = argspec.kwonlyargs + kwonlydefaults = argspec.kwonlydefaults + + def get_annotation(key: str) -> str | None: + if key not in annotations: + return None + argtype = annotations[key] + if argtype is None: + return "None" + if not isinstance(argtype, str): + return self.get_type_fullname(argtype) + return argtype + + arglist: list[ArgSig] = [] + + # Add the arguments to the signature + def add_args( + args: list[str], get_default_value: Callable[[int, str], object | _Missing] + ) -> None: + for i, arg in enumerate(args): + # Check if the argument has a default value + default_value = get_default_value(i, arg) + if default_value is not _Missing.VALUE: + if arg in annotations: + argtype = get_annotation(arg) + else: + argtype = self.get_type_annotation(default_value) + if argtype == "None": + # None is not a useful annotation, but we can infer that the arg + # is optional + incomplete = self.add_name("_typeshed.Incomplete") + argtype = f"{incomplete} | None" + + arglist.append(ArgSig(arg, argtype, default=True)) + else: + arglist.append(ArgSig(arg, get_annotation(arg), default=False)) + + def get_pos_default(i: int, _arg: str) -> Any | _Missing: + if defaults and i >= len(args) - len(defaults): + return defaults[i - (len(args) - len(defaults))] + else: + return _Missing.VALUE + + add_args(args, get_pos_default) + + # Add *args if present + if varargs: + arglist.append(ArgSig(f"*{varargs}", get_annotation(varargs))) + # if we have keyword only args, then we need to add "*" + elif kwonlyargs: + arglist.append(ArgSig("*")) + + def get_kw_default(_i: int, arg: str) -> Any | _Missing: + if kwonlydefaults and arg in kwonlydefaults: + return kwonlydefaults[arg] + else: + return _Missing.VALUE + + add_args(kwonlyargs, get_kw_default) + + # Add **kwargs if present + if kwargs: + arglist.append(ArgSig(f"**{kwargs}", get_annotation(kwargs))) + + # add types for known special methods + if ctx.class_info is not None and all( + arg.type is None and arg.default is False for arg in arglist + ): + new_args = infer_method_arg_types( + ctx.name, ctx.class_info.self_var, [arg.name for arg in arglist if arg.name] + ) + if new_args is not None: + arglist = new_args + + ret_type = get_annotation("return") or infer_method_ret_type(ctx.name) + return FunctionSig(ctx.name, arglist, ret_type) + + def get_sig_generators(self) -> list[SignatureGenerator]: + if not self.is_c_module: + return [] + else: + sig_generators: list[SignatureGenerator] = [DocstringSignatureGenerator()] + if self.doc_dir: + # Collect info from docs (if given). Always check these first. + sig_generators.insert(0, ExternalSignatureGenerator.from_doc_dir(self.doc_dir)) + return sig_generators + + def strip_or_import(self, type_name: str) -> str: + """Strips unnecessary module names from typ. + + If typ represents a type that is inside module or is a type coming from builtins, remove + module declaration from it. Return stripped name of the type. + + Arguments: + typ: name of the type + """ + local_modules = ["builtins", self.module_name] + parsed_type = parse_type_comment(type_name, 0, 0, None)[1] + assert parsed_type is not None, type_name + return self.print_annotation(parsed_type, self.known_modules, local_modules) + + def get_obj_module(self, obj: object) -> str | None: + """Return module name of the object.""" + return getattr(obj, "__module__", None) + + def is_defined_in_module(self, obj: object) -> bool: + """Check if object is considered defined in the current module.""" + module = self.get_obj_module(obj) + return module is None or module == self.module_name + + def generate_module(self) -> None: + all_items = self.get_members(self.module) + if self.resort_members: + all_items = sorted(all_items, key=lambda x: x[0]) + items = [] + for name, obj in all_items: + if inspect.ismodule(obj) and obj.__name__ in self.known_modules: + module_name = obj.__name__ + if module_name.startswith(self.module_name + "."): + # from {.rel_name} import {mod_name} as {name} + pkg_name, mod_name = module_name.rsplit(".", 1) + rel_module = pkg_name[len(self.module_name) :] or "." + self.import_tracker.add_import_from(rel_module, [(mod_name, name)]) + self.import_tracker.reexport(name) + else: + # import {module_name} as {name} + self.import_tracker.add_import(module_name, name) + self.import_tracker.reexport(name) + elif self.is_defined_in_module(obj) and not inspect.ismodule(obj): + # process this below + items.append((name, obj)) + else: + # from {obj_module} import {obj_name} + obj_module_name = self.get_obj_module(obj) + if obj_module_name: + self.import_tracker.add_import_from(obj_module_name, [(name, None)]) + if self.should_reexport(name, obj_module_name, name_is_alias=False): + self.import_tracker.reexport(name) + + self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)}) + + if self.resort_members: + functions: list[str] = [] + types: list[str] = [] + variables: list[str] = [] + else: + output: list[str] = [] + functions = types = variables = output + + for name, obj in items: + if self.is_function(obj): + self.generate_function_stub(name, obj, output=functions) + elif inspect.isclass(obj): + self.generate_class_stub(name, obj, output=types) + else: + self.generate_variable_stub(name, obj, output=variables) + + self._output = [] + + if self.resort_members: + for line in variables: + self._output.append(line + "\n") + for line in types: + if line.startswith("class") and self._output and self._output[-1]: + self._output.append("\n") + self._output.append(line + "\n") + if self._output and functions: + self._output.append("\n") + for line in functions: + self._output.append(line + "\n") + else: + for i, line in enumerate(output): + if ( + self._output + and line.startswith("class") + and ( + not self._output[-1].startswith("class") + or (len(output) > i + 1 and output[i + 1].startswith(" ")) + ) + ) or ( + self._output + and self._output[-1].startswith("def") + and not line.startswith("def") + ): + self._output.append("\n") + self._output.append(line + "\n") + self.check_undefined_names() + + def is_skipped_attribute(self, attr: str) -> bool: + return ( + attr + in ( + "__class__", + "__getattribute__", + "__str__", + "__repr__", + "__doc__", + "__dict__", + "__module__", + "__weakref__", + "__annotations__", + "__firstlineno__", + "__static_attributes__", + "__annotate__", + ) + or attr in self.IGNORED_DUNDERS + or is_pybind_skipped_attribute(attr) # For pickling + or keyword.iskeyword(attr) + ) + + def get_members(self, obj: object) -> list[tuple[str, Any]]: + obj_dict: Mapping[str, Any] = getattr(obj, "__dict__") # noqa: B009 + results = [] + for name in obj_dict: + if self.is_skipped_attribute(name): + continue + # Try to get the value via getattr + try: + value = getattr(obj, name) + except AttributeError: + continue + else: + results.append((name, value)) + return results + + def get_type_annotation(self, obj: object) -> str: + """ + Given an instance, return a string representation of its type that is valid + to use as a type annotation. + """ + if obj is None or obj is type(None): + return "None" + elif inspect.isclass(obj): + return f"type[{self.get_type_fullname(obj)}]" + elif isinstance(obj, FunctionType): + return self.add_name("typing.Callable") + elif isinstance(obj, ModuleType): + return self.add_name("types.ModuleType", require=False) + else: + return self.get_type_fullname(type(obj)) + + def is_function(self, obj: object) -> bool: + if self.is_c_module: + return inspect.isbuiltin(obj) + else: + return inspect.isfunction(obj) + + def is_method(self, class_info: ClassInfo, name: str, obj: object) -> bool: + if self.is_c_module: + return inspect.ismethoddescriptor(obj) or type(obj) in ( + type(str.index), + type(str.__add__), + type(str.__new__), + ) + else: + # this is valid because it is only called on members of a class + return inspect.isfunction(obj) + + def is_classmethod(self, class_info: ClassInfo, name: str, obj: object) -> bool: + if self.is_c_module: + return inspect.isbuiltin(obj) or type(obj).__name__ in ( + "classmethod", + "classmethod_descriptor", + ) + else: + return inspect.ismethod(obj) + + def is_staticmethod(self, class_info: ClassInfo | None, name: str, obj: object) -> bool: + if class_info is None: + return False + elif self.is_c_module: + raw_lookup: Mapping[str, Any] = getattr(class_info.cls, "__dict__") # noqa: B009 + raw_value = raw_lookup.get(name, obj) + return isinstance(raw_value, staticmethod) + else: + return isinstance(inspect.getattr_static(class_info.cls, name), staticmethod) + + @staticmethod + def is_abstract_method(obj: object) -> bool: + return getattr(obj, "__abstractmethod__", False) + + @staticmethod + def is_property(class_info: ClassInfo, name: str, obj: object) -> bool: + return inspect.isdatadescriptor(obj) or hasattr(obj, "fget") + + @staticmethod + def is_property_readonly(prop: Any) -> bool: + return hasattr(prop, "fset") and prop.fset is None + + def is_static_property(self, obj: object) -> bool: + """For c-modules, whether the property behaves like an attribute""" + if self.is_c_module: + # StaticProperty is from boost-python + return type(obj).__name__ in ("pybind11_static_property", "StaticProperty") + else: + return False + + def process_inferred_sigs(self, inferred: list[FunctionSig]) -> None: + for i, sig in enumerate(inferred): + for arg in sig.args: + if arg.type is not None: + arg.type = self.strip_or_import(arg.type) + if sig.ret_type is not None: + inferred[i] = sig._replace(ret_type=self.strip_or_import(sig.ret_type)) + + def generate_function_stub( + self, name: str, obj: object, *, output: list[str], class_info: ClassInfo | None = None + ) -> None: + """Generate stub for a single function or method. + + The result (always a single line) will be appended to 'output'. + If necessary, any required names will be added to 'imports'. + The 'class_name' is used to find signature of __init__ or __new__ in + 'class_sigs'. + """ + docstring: Any = getattr(obj, "__doc__", None) + if not isinstance(docstring, str): + docstring = None + + ctx = FunctionContext( + self.module_name, + name, + docstring=docstring, + is_abstract=self.is_abstract_method(obj), + class_info=class_info, + ) + if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name): + return + + self.record_name(ctx.name) + default_sig = self.get_default_function_sig(obj, ctx) + inferred = self.get_signatures(default_sig, self.sig_generators, ctx) + self.process_inferred_sigs(inferred) + + decorators = [] + if len(inferred) > 1: + decorators.append("@{}".format(self.add_name("typing.overload"))) + + if ctx.is_abstract: + decorators.append("@{}".format(self.add_name("abc.abstractmethod"))) + + if class_info is not None: + if self.is_staticmethod(class_info, name, obj): + decorators.append("@staticmethod") + else: + for sig in inferred: + if not sig.args or sig.args[0].name not in ("self", "cls"): + sig.args.insert(0, ArgSig(name=class_info.self_var)) + # a sig generator indicates @classmethod by specifying the cls arg. + if inferred[0].args and inferred[0].args[0].name == "cls": + decorators.append("@classmethod") + + docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None + output.extend(self.format_func_def(inferred, decorators=decorators, docstring=docstring)) + self._fix_iter(ctx, inferred, output) + + def _indent_docstring(self, docstring: str) -> str: + """Fix indentation of docstring extracted from pybind11 or other binding generators.""" + lines = docstring.splitlines(keepends=True) + indent = self._indent + " " + if len(lines) > 1: + if not all(line.startswith(indent) or not line.strip() for line in lines): + # if the docstring is not indented, then indent all but the first line + for i, line in enumerate(lines[1:]): + if line.strip(): + lines[i + 1] = indent + line + # if there's a trailing newline, add a final line to visually indent the quoted docstring + if lines[-1].endswith("\n"): + if len(lines) > 1: + lines.append(indent) + else: + lines[-1] = lines[-1][:-1] + return "".join(lines) + + def _fix_iter( + self, ctx: FunctionContext, inferred: list[FunctionSig], output: list[str] + ) -> None: + """Ensure that objects which implement old-style iteration via __getitem__ + are considered iterable. + """ + if ( + ctx.class_info + and ctx.class_info.cls is not None + and ctx.name == "__getitem__" + and "__iter__" not in ctx.class_info.cls.__dict__ + ): + item_type: str | None = None + for sig in inferred: + if sig.args and sig.args[-1].type == "int": + item_type = sig.ret_type + break + if item_type is None: + return + obj = CFunctionStub( + "__iter__", f"def __iter__(self) -> typing.Iterator[{item_type}]\n" + ) + self.generate_function_stub("__iter__", obj, output=output, class_info=ctx.class_info) + + def generate_property_stub( + self, + name: str, + raw_obj: object, + obj: object, + static_properties: list[str], + rw_properties: list[str], + ro_properties: list[str], + class_info: ClassInfo | None = None, + ) -> None: + """Generate property stub using introspection of 'obj'. + + Try to infer type from docstring, append resulting lines to 'output'. + + raw_obj : object before evaluation of descriptor (if any) + obj : object after evaluation of descriptor + """ + + docstring = getattr(raw_obj, "__doc__", None) + fget = getattr(raw_obj, "fget", None) + if fget: + alt_docstr = getattr(fget, "__doc__", None) + if alt_docstr and docstring: + docstring += "\n" + alt_docstr + elif alt_docstr: + docstring = alt_docstr + + ctx = FunctionContext( + self.module_name, name, docstring=docstring, is_abstract=False, class_info=class_info + ) + + if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name): + return + + self.record_name(ctx.name) + static = self.is_static_property(raw_obj) + readonly = self.is_property_readonly(raw_obj) + if static: + ret_type: str | None = self.strip_or_import(self.get_type_annotation(obj)) + else: + default_sig = self.get_default_function_sig(raw_obj, ctx) + ret_type = default_sig.ret_type + + inferred_type = self.get_property_type(ret_type, self.sig_generators, ctx) + if inferred_type is not None: + inferred_type = self.strip_or_import(inferred_type) + + if static: + classvar = self.add_name("typing.ClassVar") + trailing_comment = " # read-only" if readonly else "" + if inferred_type is None: + inferred_type = self.add_name("_typeshed.Incomplete") + + static_properties.append( + f"{self._indent}{name}: {classvar}[{inferred_type}] = ...{trailing_comment}" + ) + else: # regular property + if readonly: + docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None + ro_properties.append(f"{self._indent}@property") + sig = FunctionSig(name, [ArgSig("self")], inferred_type, docstring=docstring) + ro_properties.append( + sig.format_sig( + indent=self._indent, include_docstrings=self._include_docstrings + ) + ) + else: + if inferred_type is None: + inferred_type = self.add_name("_typeshed.Incomplete") + + rw_properties.append(f"{self._indent}{name}: {inferred_type}") + + def get_type_fullname(self, typ: type) -> str: + """Given a type, return a string representation""" + if typ is Any: + return "Any" + typename = getattr(typ, "__qualname__", typ.__name__) + module_name = self.get_obj_module(typ) + if module_name is None: + # This should not normally happen, but some types may resist our + # introspection attempts too hard. See + # https://github.com/python/mypy/issues/19031 + return "_typeshed.Incomplete" + if module_name != "builtins": + typename = f"{module_name}.{typename}" + return typename + + def get_base_types(self, obj: type) -> list[str]: + all_bases = type.mro(obj) + if all_bases[-1] is object: + # TODO: Is this always object? + del all_bases[-1] + # remove pybind11_object. All classes generated by pybind11 have pybind11_object in their MRO, + # which only overrides a few functions in object type + if all_bases and all_bases[-1].__name__ == "pybind11_object": + del all_bases[-1] + # remove the class itself + all_bases = all_bases[1:] + # Remove base classes of other bases as redundant. + bases: list[type] = [] + for base in all_bases: + if not any(issubclass(b, base) for b in bases): + bases.append(base) + return [self.strip_or_import(self.get_type_fullname(base)) for base in bases] + + def generate_class_stub( + self, class_name: str, cls: type, output: list[str], parent_class: ClassInfo | None = None + ) -> None: + """Generate stub for a single class using runtime introspection. + + The result lines will be appended to 'output'. If necessary, any + required names will be added to 'imports'. + """ + raw_lookup: Mapping[str, Any] = getattr(cls, "__dict__") # noqa: B009 + items = self.get_members(cls) + if self.resort_members: + items = sorted(items, key=lambda x: method_name_sort_key(x[0])) + names = {x[0] for x in items} + methods: list[str] = [] + types: list[str] = [] + static_properties: list[str] = [] + rw_properties: list[str] = [] + ro_properties: list[str] = [] + attrs: list[tuple[str, Any]] = [] + + self.record_name(class_name) + self.indent() + + class_info = ClassInfo( + class_name, "", getattr(cls, "__doc__", None), cls, parent=parent_class + ) + + for attr, value in items: + # use unevaluated descriptors when dealing with property inspection + raw_value = raw_lookup.get(attr, value) + if self.is_method(class_info, attr, value) or self.is_classmethod( + class_info, attr, value + ): + if attr == "__new__": + # TODO: We should support __new__. + if "__init__" in names: + # Avoid duplicate functions if both are present. + # But is there any case where .__new__() has a + # better signature than __init__() ? + continue + attr = "__init__" + # FIXME: make this nicer + if self.is_staticmethod(class_info, attr, value): + class_info.self_var = "" + elif self.is_classmethod(class_info, attr, value): + class_info.self_var = "cls" + else: + class_info.self_var = "self" + self.generate_function_stub(attr, value, output=methods, class_info=class_info) + elif self.is_property(class_info, attr, raw_value): + self.generate_property_stub( + attr, + raw_value, + value, + static_properties, + rw_properties, + ro_properties, + class_info, + ) + elif inspect.isclass(value) and self.is_defined_in_module(value): + self.generate_class_stub(attr, value, types, parent_class=class_info) + else: + attrs.append((attr, value)) + + for attr, value in attrs: + if attr == "__hash__" and value is None: + # special case for __hash__ + continue + prop_type_name = self.strip_or_import(self.get_type_annotation(value)) + classvar = self.add_name("typing.ClassVar") + static_properties.append(f"{self._indent}{attr}: {classvar}[{prop_type_name}] = ...") + + self.dedent() + + bases = self.get_base_types(cls) + if bases: + bases_str = "(%s)" % ", ".join(bases) + else: + bases_str = "" + + if class_info.docstring and self._include_docstrings: + doc = quote_docstring(self._indent_docstring(class_info.docstring)) + doc = f" {self._indent}{doc}" + docstring = doc.splitlines(keepends=False) + else: + docstring = [] + + if docstring or types or static_properties or rw_properties or methods or ro_properties: + output.append(f"{self._indent}class {class_name}{bases_str}:") + output.extend(docstring) + for line in types: + if ( + output + and output[-1] + and not output[-1].strip().startswith("class") + and line.strip().startswith("class") + ): + output.append("") + output.append(line) + output.extend(static_properties) + output.extend(rw_properties) + output.extend(methods) + output.extend(ro_properties) + else: + output.append(f"{self._indent}class {class_name}{bases_str}: ...") + + def generate_variable_stub(self, name: str, obj: object, output: list[str]) -> None: + """Generate stub for a single variable using runtime introspection. + + The result lines will be appended to 'output'. If necessary, any + required names will be added to 'imports'. + """ + if self.is_private_name(name, f"{self.module_name}.{name}") or self.is_not_in_all(name): + return + self.record_name(name) + type_str = self.strip_or_import(self.get_type_annotation(obj)) + output.append(f"{name}: {type_str}") + + +def method_name_sort_key(name: str) -> tuple[int, str]: + """Sort methods in classes in a typical order. + + I.e.: constructor, normal methods, special methods. + """ + if name in ("__new__", "__init__"): + return 0, name + if name.startswith("__") and name.endswith("__"): + return 2, name + return 1, name + + +def is_pybind_skipped_attribute(attr: str) -> bool: + return attr.startswith("__pybind11_module_local_") + + +def infer_c_method_args( + name: str, self_var: str = "self", arg_names: list[str] | None = None +) -> list[ArgSig]: + args: list[ArgSig] | None = None + if name.startswith("__") and name.endswith("__"): + name = name[2:-2] + if name in ( + "hash", + "iter", + "next", + "sizeof", + "copy", + "deepcopy", + "reduce", + "getinitargs", + "int", + "float", + "trunc", + "complex", + "bool", + "abs", + "bytes", + "dir", + "len", + "reversed", + "round", + "index", + "enter", + ): + args = [] + elif name == "getitem": + args = [ArgSig(name="index")] + elif name == "setitem": + args = [ArgSig(name="index"), ArgSig(name="object")] + elif name in ("delattr", "getattr"): + args = [ArgSig(name="name")] + elif name == "setattr": + args = [ArgSig(name="name"), ArgSig(name="value")] + elif name == "getstate": + args = [] + elif name == "setstate": + args = [ArgSig(name="state")] + elif name in ("eq", "ne", "lt", "le", "gt", "ge"): + args = [ArgSig(name="other", type="object")] + elif name in ( + "add", + "radd", + "sub", + "rsub", + "mul", + "rmul", + "mod", + "rmod", + "floordiv", + "rfloordiv", + "truediv", + "rtruediv", + "divmod", + "rdivmod", + "pow", + "rpow", + "xor", + "rxor", + "or", + "ror", + "and", + "rand", + "lshift", + "rlshift", + "rshift", + "rrshift", + "contains", + "delitem", + "iadd", + "iand", + "ifloordiv", + "ilshift", + "imod", + "imul", + "ior", + "ipow", + "irshift", + "isub", + "itruediv", + "ixor", + ): + args = [ArgSig(name="other")] + elif name in ("neg", "pos", "invert"): + args = [] + elif name == "get": + args = [ArgSig(name="instance"), ArgSig(name="owner")] + elif name == "set": + args = [ArgSig(name="instance"), ArgSig(name="value")] + elif name == "reduce_ex": + args = [ArgSig(name="protocol")] + elif name == "exit": + args = [ + ArgSig(name="type", type="type[BaseException] | None"), + ArgSig(name="value", type="BaseException | None"), + ArgSig(name="traceback", type="types.TracebackType | None"), + ] + if args is None: + args = infer_method_arg_types(name, self_var, arg_names) + else: + args = [ArgSig(name=self_var)] + args + if args is None: + args = [ArgSig(name="*args"), ArgSig(name="**kwargs")] + return args diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubinfo.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubinfo.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..62984610ce86457b3688b87db68584237dd38cbc Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubinfo.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubinfo.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8423f1c4e3b6cbf7612967d580f17958bfa8bc --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubinfo.py @@ -0,0 +1,328 @@ +from __future__ import annotations + + +def is_module_from_legacy_bundled_package(module: str) -> bool: + top_level = module.split(".", 1)[0] + return top_level in legacy_bundled_packages + + +def stub_distribution_name(module: str) -> str | None: + top_level = module.split(".", 1)[0] + + dist = legacy_bundled_packages.get(top_level) + if dist: + return dist + dist = non_bundled_packages_flat.get(top_level) + if dist: + return dist + + if top_level in non_bundled_packages_namespace: + namespace = non_bundled_packages_namespace[top_level] + components = module.split(".") + for i in range(len(components), 0, -1): + module = ".".join(components[:i]) + dist = namespace.get(module) + if dist: + return dist + + return None + + +# Stubs for these third-party packages used to be shipped with mypy. +# +# Map package name to PyPI stub distribution name. +legacy_bundled_packages: dict[str, str] = { + "aiofiles": "types-aiofiles", + "bleach": "types-bleach", + "cachetools": "types-cachetools", + "click_spinner": "types-click-spinner", + "croniter": "types-croniter", + "dateparser": "types-dateparser", + "dateutil": "types-python-dateutil", + "decorator": "types-decorator", + "deprecated": "types-Deprecated", + "docutils": "types-docutils", + "first": "types-first", + "markdown": "types-Markdown", + "mock": "types-mock", + "paramiko": "types-paramiko", + "polib": "types-polib", + "pycurl": "types-pycurl", + "pymysql": "types-PyMySQL", + "pyrfc3339": "types-pyRFC3339", + "pytz": "types-pytz", + "requests": "types-requests", + "retry": "types-retry", + "simplejson": "types-simplejson", + "singledispatch": "types-singledispatch", + "six": "types-six", + "tabulate": "types-tabulate", + "toml": "types-toml", + "ujson": "types-ujson", + "waitress": "types-waitress", + "yaml": "types-PyYAML", +} + +# Map package name to PyPI stub distribution name from typeshed. +# Stubs for these packages were never bundled with mypy. Don't +# include packages that have a release that includes PEP 561 type +# information. +# +# Note that these packages are omitted for now: +# pika: typeshed's stubs are on PyPI as types-pika-ts. +# types-pika already exists on PyPI, and is more complete in many ways, +# but is a non-typeshed stubs package. +non_bundled_packages_flat: dict[str, str] = { + "_cffi_backend": "types-cffi", + "_jsonnet": "types-jsonnet", + "_win32typing": "types-pywin32", + "antlr4": "types-antlr4-python3-runtime", + "assertpy": "types-assertpy", + "atheris": "types-atheris", + "auth0": "types-auth0-python", + "authlib": "types-Authlib", + "aws_xray_sdk": "types-aws-xray-sdk", + "binaryornot": "types-binaryornot", + "boltons": "types-boltons", + "braintree": "types-braintree", + "bugbear": "types-flake8-bugbear", + "capturer": "types-capturer", + "cffi": "types-cffi", + "channels": "types-channels", + "chevron": "types-chevron", + "click_default_group": "types-click-default-group", + "click_log": "types-click-log", + "click_shell": "types-click-shell", + "click_web": "types-click-web", + "colorama": "types-colorama", + "colorful": "types-colorful", + "commctrl": "types-pywin32", + "consolemenu": "types-console-menu", + "convertdate": "types-convertdate", + "cronlog": "types-python-crontab", + "crontab": "types-python-crontab", + "crontabs": "types-python-crontab", + "dateparser_data": "types-dateparser", + "dde": "types-pywin32", + "defusedxml": "types-defusedxml", + "dirhash": "types-dirhash", + "django_filters": "types-django-filter", + "docker": "types-docker", + "dockerfile_parse": "types-dockerfile-parse", + "editdistance": "types-editdistance", + "entrypoints": "types-entrypoints", + "ephem": "types-ephem", + "et_xmlfile": "types-et_xmlfile", + "fanstatic": "types-fanstatic", + "farmhash": "types-pyfarmhash", + "flake8_builtins": "types-flake8-builtins", + "flake8_docstrings": "types-flake8-docstrings", + "flake8_rst_docstrings": "types-flake8-rst-docstrings", + "flake8_simplify": "types-flake8-simplify", + "flake8_typing_imports": "types-flake8-typing-imports", + "flake8": "types-flake8", + "flask_cors": "types-Flask-Cors", + "flask_migrate": "types-Flask-Migrate", + "flask_socketio": "types-Flask-SocketIO", + "fpdf": "types-fpdf2", + "gdb": "types-gdb", + "geopandas": "types-geopandas", + "gevent": "types-gevent", + "greenlet": "types-greenlet", + "grpc_channelz": "types-grpcio-channelz", + "grpc_health": "types-grpcio-health-checking", + "grpc_reflection": "types-grpcio-reflection", + "grpc_status": "types-grpcio-status", + "grpc": "types-grpcio", + "gunicorn": "types-gunicorn", + "hdbcli": "types-hdbcli", + "hnswlib": "types-hnswlib", + "html5lib": "types-html5lib", + "httplib2": "types-httplib2", + "hvac": "types-hvac", + "ibm_db": "types-ibm-db", + "icalendar": "types-icalendar", + "import_export": "types-django-import-export", + "inifile": "types-inifile", + "isapi": "types-pywin32", + "jack": "types-JACK-Client", + "jenkins": "types-python-jenkins", + "Jetson": "types-Jetson.GPIO", + "jks": "types-pyjks", + "jmespath": "types-jmespath", + "jose": "types-python-jose", + "jsonschema": "types-jsonschema", + "jwcrypto": "types-jwcrypto", + "keyboard": "types-keyboard", + "ldap3": "types-ldap3", + "lunardate": "types-lunardate", + "lupa": "types-lupa", + "lzstring": "types-lzstring", + "m3u8": "types-m3u8", + "management": "types-django-import-export", + "mmapfile": "types-pywin32", + "mmsystem": "types-pywin32", + "mypy_extensions": "types-mypy-extensions", + "MySQLdb": "types-mysqlclient", + "nanoid": "types-nanoid", + "nanoleafapi": "types-nanoleafapi", + "netaddr": "types-netaddr", + "netifaces": "types-netifaces", + "networkx": "types-networkx", + "nmap": "types-python-nmap", + "ntsecuritycon": "types-pywin32", + "oauthlib": "types-oauthlib", + "objgraph": "types-objgraph", + "odbc": "types-pywin32", + "olefile": "types-olefile", + "openpyxl": "types-openpyxl", + "opentracing": "types-opentracing", + "parsimonious": "types-parsimonious", + "passlib": "types-passlib", + "passpy": "types-passpy", + "peewee": "types-peewee", + "pep8ext_naming": "types-pep8-naming", + "perfmon": "types-pywin32", + "pexpect": "types-pexpect", + "playhouse": "types-peewee", + "pony": "types-pony", + "portpicker": "types-portpicker", + "psutil": "types-psutil", + "psycopg2": "types-psycopg2", + "punq": "types-punq", + "pyasn1": "types-pyasn1", + "pyaudio": "types-pyaudio", + "pyautogui": "types-PyAutoGUI", + "pycocotools": "types-pycocotools", + "pyflakes": "types-pyflakes", + "pygments": "types-Pygments", + "pyi_splash": "types-pyinstaller", + "PyInstaller": "types-pyinstaller", + "pyluach": "types-pyluach", + "pymeeus": "types-PyMeeus", + "pynput": "types-pynput", + "pyperclip": "types-pyperclip", + "pyscreeze": "types-PyScreeze", + "pysftp": "types-pysftp", + "pytest_lazyfixture": "types-pytest-lazy-fixture", + "python_http_client": "types-python-http-client", + "pythoncom": "types-pywin32", + "pythonwin": "types-pywin32", + "pywintypes": "types-pywin32", + "qrbill": "types-qrbill", + "qrcode": "types-qrcode", + "ratelimit": "types-ratelimit", + "regex": "types-regex", + "regutil": "types-pywin32", + "reportlab": "types-reportlab", + "requests_oauthlib": "types-requests-oauthlib", + "rfc3339_validator": "types-rfc3339-validator", + "RPi": "types-RPi.GPIO", + "s2clientprotocol": "types-s2clientprotocol", + "sass": "types-libsass", + "sassutils": "types-libsass", + "seaborn": "types-seaborn", + "send2trash": "types-Send2Trash", + "serial": "types-pyserial", + "servicemanager": "types-pywin32", + "setuptools": "types-setuptools", + "shapely": "types-shapely", + "simple_websocket": "types-simple-websocket", + "slumber": "types-slumber", + "socks": "types-PySocks", + "sockshandler": "types-PySocks", + "sspicon": "types-pywin32", + "str2bool": "types-str2bool", + "tensorflow": "types-tensorflow", + "tgcrypto": "types-TgCrypto", + "timer": "types-pywin32", + "toposort": "types-toposort", + "tqdm": "types-tqdm", + "translationstring": "types-translationstring", + "ttkthemes": "types-ttkthemes", + "tzdata": "types-tzdata", + "unidiff": "types-unidiff", + "untangle": "types-untangle", + "usersettings": "types-usersettings", + "uwsgi": "types-uWSGI", + "uwsgidecorators": "types-uWSGI", + "vobject": "types-vobject", + "watchpoints": "types-watchpoints", + "webencodings": "types-webencodings", + "webob": "types-WebOb", + "whatthepatch": "types-whatthepatch", + "win2kras": "types-pywin32", + "win32": "types-pywin32", + "win32api": "types-pywin32", + "win32clipboard": "types-pywin32", + "win32com": "types-pywin32", + "win32comext": "types-pywin32", + "win32con": "types-pywin32", + "win32console": "types-pywin32", + "win32cred": "types-pywin32", + "win32crypt": "types-pywin32", + "win32cryptcon": "types-pywin32", + "win32event": "types-pywin32", + "win32evtlog": "types-pywin32", + "win32evtlogutil": "types-pywin32", + "win32file": "types-pywin32", + "win32gui_struct": "types-pywin32", + "win32gui": "types-pywin32", + "win32help": "types-pywin32", + "win32inet": "types-pywin32", + "win32inetcon": "types-pywin32", + "win32job": "types-pywin32", + "win32lz": "types-pywin32", + "win32net": "types-pywin32", + "win32netcon": "types-pywin32", + "win32pdh": "types-pywin32", + "win32pdhquery": "types-pywin32", + "win32pipe": "types-pywin32", + "win32print": "types-pywin32", + "win32process": "types-pywin32", + "win32profile": "types-pywin32", + "win32ras": "types-pywin32", + "win32security": "types-pywin32", + "win32service": "types-pywin32", + "win32serviceutil": "types-pywin32", + "win32timezone": "types-pywin32", + "win32trace": "types-pywin32", + "win32transaction": "types-pywin32", + "win32ts": "types-pywin32", + "win32ui": "types-pywin32", + "win32uiole": "types-pywin32", + "win32verstamp": "types-pywin32", + "win32wnet": "types-pywin32", + "winerror": "types-pywin32", + "winioctlcon": "types-pywin32", + "winnt": "types-pywin32", + "winperf": "types-pywin32", + "winxpgui": "types-pywin32", + "winxptheme": "types-pywin32", + "workalendar": "types-workalendar", + "wtforms": "types-WTForms", + "wurlitzer": "types-wurlitzer", + "www_authenticate": "types-www-authenticate", + "xdg": "types-pyxdg", + "xdgenvpy": "types-xdgenvpy", + "Xlib": "types-python-xlib", + "xlrd": "types-xlrd", + "xmldiff": "types-xmldiff", + "xmltodict": "types-xmltodict", + "yt_dlp": "types-yt-dlp", + "zstd": "types-zstd", + "zxcvbn": "types-zxcvbn", + # Stub packages that are not from typeshed + # Since these can be installed automatically via --install-types, we have a high trust bar + # for additions here + "pandas": "pandas-stubs", # https://github.com/pandas-dev/pandas-stubs + "lxml": "lxml-stubs", # https://github.com/lxml/lxml-stubs + "scipy": "scipy-stubs", # https://github.com/scipy/scipy-stubs +} + + +non_bundled_packages_namespace: dict[str, dict[str, str]] = { + "backports": {"backports.ssl_match_hostname": "types-backports.ssl_match_hostname"}, + "google": {"google.cloud.ndb": "types-google-cloud-ndb", "google.protobuf": "types-protobuf"}, + "paho": {"paho.mqtt": "types-paho-mqtt"}, +} diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubtest.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubtest.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf0de84d9890f01c10a5ea694385806d7434688 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubtest.py @@ -0,0 +1,2590 @@ +"""Tests for stubs. + +Verify that various things in stubs are consistent with how things behave at runtime. + +""" + +from __future__ import annotations + +import argparse +import collections.abc +import copy +import enum +import functools +import importlib +import inspect +import keyword +import os +import pkgutil +import re +import struct +import symtable +import sys +import traceback +import types +import typing +import typing_extensions +import warnings +from collections import defaultdict +from collections.abc import Iterator +from contextlib import redirect_stderr, redirect_stdout +from functools import singledispatch +from pathlib import Path +from typing import Any, Final, Generic, TypeVar, Union, get_origin +from typing_extensions import is_typeddict + +import mypy.build +import mypy.checkexpr +import mypy.erasetype +import mypy.modulefinder +import mypy.nodes +import mypy.state +import mypy.subtypes +import mypy.types +import mypy.version +from mypy import nodes +from mypy.config_parser import parse_config_file +from mypy.evalexpr import UNKNOWN, evaluate_expression +from mypy.maptype import map_instance_to_supertype +from mypy.options import Options +from mypy.util import FancyFormatter, bytes_to_human_readable_repr, is_dunder, plural_s + + +class Missing: + """Marker object for things that are missing (from a stub or the runtime).""" + + def __repr__(self) -> str: + return "MISSING" + + +MISSING: Final = Missing() + +T = TypeVar("T") +MaybeMissing: typing_extensions.TypeAlias = T | Missing + + +class Unrepresentable: + """Marker object for unrepresentable parameter defaults.""" + + def __repr__(self) -> str: + return "" + + +UNREPRESENTABLE: Final = Unrepresentable() + + +_formatter: Final = FancyFormatter(sys.stdout, sys.stderr, False) + + +def _style(message: str, **kwargs: Any) -> str: + """Wrapper around mypy.util for fancy formatting.""" + kwargs.setdefault("color", "none") + return _formatter.style(message, **kwargs) + + +def _truncate(message: str, length: int) -> str: + if len(message) > length: + return message[: length - 3] + "..." + return message + + +class StubtestFailure(Exception): + pass + + +class Error: + def __init__( + self, + object_path: list[str], + message: str, + stub_object: MaybeMissing[nodes.Node], + runtime_object: MaybeMissing[Any], + *, + stub_desc: str | None = None, + runtime_desc: str | None = None, + ) -> None: + """Represents an error found by stubtest. + + :param object_path: Location of the object with the error, + e.g. ``["module", "Class", "method"]`` + :param message: Error message + :param stub_object: The mypy node representing the stub + :param runtime_object: Actual object obtained from the runtime + :param stub_desc: Specialised description for the stub object, should you wish + :param runtime_desc: Specialised description for the runtime object, should you wish + + """ + self.object_path = object_path + self.object_desc = ".".join(object_path) + self.message = message + self.stub_object = stub_object + self.runtime_object = runtime_object + self.stub_desc = stub_desc or str(getattr(stub_object, "type", stub_object)) + + if runtime_desc is None: + runtime_sig = safe_inspect_signature(runtime_object) + if runtime_sig is None: + self.runtime_desc = _truncate(repr(runtime_object), 100) + else: + runtime_is_async = inspect.iscoroutinefunction(runtime_object) + description = describe_runtime_callable(runtime_sig, is_async=runtime_is_async) + self.runtime_desc = _truncate(description, 100) + else: + self.runtime_desc = runtime_desc + + def is_missing_stub(self) -> bool: + """Whether or not the error is for something missing from the stub.""" + return isinstance(self.stub_object, Missing) + + def is_positional_only_related(self) -> bool: + """Whether or not the error is for something being (or not being) positional-only.""" + # TODO: This is hacky, use error codes or something more resilient + return "should be positional" in self.message + + def is_disjoint_base_related(self) -> bool: + """Whether or not the error is related to @disjoint_base.""" + # TODO: This is hacky, use error codes or something more resilient + return "@disjoint_base" in self.message + + def is_private_type_check_only_related(self) -> bool: + """Whether or not the error is related to @type_check_only on private types.""" + # TODO: This is hacky, use error codes or something more resilient + return self.message.endswith('Maybe mark it as "@type_check_only"?') + + def get_description(self, concise: bool = False) -> str: + """Returns a description of the error. + + :param concise: Whether to return a concise, one-line description + + """ + if concise: + return _style(self.object_desc, bold=True) + " " + self.message + + stub_line = None + stub_file = None + if not isinstance(self.stub_object, Missing): + stub_line = self.stub_object.line + stub_node = get_stub(self.object_path[0]) + if stub_node is not None: + stub_file = stub_node.path or None + + stub_loc_str = "" + if stub_file: + stub_loc_str += f" in file {Path(stub_file)}" + if stub_line: + stub_loc_str += f"{':' if stub_file else ' at line '}{stub_line}" + + runtime_line = None + runtime_file = None + if not isinstance(self.runtime_object, Missing): + try: + runtime_line = inspect.getsourcelines(self.runtime_object)[1] + except (OSError, TypeError, SyntaxError): + pass + try: + runtime_file = inspect.getsourcefile(self.runtime_object) + except TypeError: + pass + + runtime_loc_str = "" + if runtime_file: + runtime_loc_str += f" in file {Path(runtime_file)}" + if runtime_line: + runtime_loc_str += f"{':' if runtime_file else ' at line '}{runtime_line}" + + output = [ + _style("error: ", color="red", bold=True), + _style(self.object_desc, bold=True), + " ", + self.message, + "\n", + "Stub:", + _style(stub_loc_str, dim=True), + "\n", + _style(self.stub_desc + "\n", color="blue", dim=True), + "Runtime:", + _style(runtime_loc_str, dim=True), + "\n", + _style(self.runtime_desc + "\n", color="blue", dim=True), + ] + return "".join(output) + + +# ==================== +# Core logic +# ==================== + + +def silent_import_module(module_name: str) -> types.ModuleType: + with open(os.devnull, "w") as devnull: + with warnings.catch_warnings(), redirect_stdout(devnull), redirect_stderr(devnull): + warnings.simplefilter("ignore") + runtime = importlib.import_module(module_name) + # Also run the equivalent of `from module import *` + # This could have the additional effect of loading not-yet-loaded submodules + # mentioned in __all__ + __import__(module_name, fromlist=["*"]) + return runtime + + +def test_module(module_name: str) -> Iterator[Error]: + """Tests a given module's stub against introspecting it at runtime. + + Requires the stub to have been built already, accomplished by a call to ``build_stubs``. + + :param module_name: The module to test + + """ + stub = get_stub(module_name) + if stub is None: + if not is_probably_private(module_name.split(".")[-1]): + runtime_desc = repr(sys.modules[module_name]) if module_name in sys.modules else "N/A" + yield Error( + [module_name], "failed to find stubs", MISSING, None, runtime_desc=runtime_desc + ) + return + + try: + runtime = silent_import_module(module_name) + except KeyboardInterrupt: + raise + except BaseException as e: + note = "" + if isinstance(e, ModuleNotFoundError): + note = " Maybe install the runtime package or alter PYTHONPATH?" + yield Error( + [module_name], f"failed to import.{note} {type(e).__name__}: {e}", stub, MISSING + ) + return + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + try: + yield from verify(stub, runtime, [module_name]) + except Exception as e: + bottom_frame = list(traceback.walk_tb(e.__traceback__))[-1][0] + bottom_module = bottom_frame.f_globals.get("__name__", "") + # Pass on any errors originating from stubtest or mypy + # These can occur expectedly, e.g. StubtestFailure + if bottom_module == "__main__" or bottom_module.split(".")[0] == "mypy": + raise + yield Error( + [module_name], + f"encountered unexpected error, {type(e).__name__}: {e}", + stub, + runtime, + stub_desc="N/A", + runtime_desc=( + "This is most likely the fault of something very dynamic in your library. " + "It's also possible this is a bug in stubtest.\nIf in doubt, please " + "open an issue at https://github.com/python/mypy\n\n" + + traceback.format_exc().strip() + ), + ) + + +@singledispatch +def verify( + stub: MaybeMissing[nodes.Node], runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + """Entry point for comparing a stub to a runtime object. + + We use single dispatch based on the type of ``stub``. + + :param stub: The mypy node representing a part of the stub + :param runtime: The runtime object corresponding to ``stub`` + + """ + yield Error(object_path, "is an unknown mypy node", stub, runtime) + + +def _verify_exported_names( + object_path: list[str], stub: nodes.MypyFile, runtime_all_as_set: set[str] +) -> Iterator[Error]: + # note that this includes the case the stub simply defines `__all__: list[str]` + assert "__all__" in stub.names + public_names_in_stub = {m for m, o in stub.names.items() if o.module_public} + names_in_stub_not_runtime = sorted(public_names_in_stub - runtime_all_as_set) + names_in_runtime_not_stub = sorted(runtime_all_as_set - public_names_in_stub) + if not (names_in_runtime_not_stub or names_in_stub_not_runtime): + return + yield Error( + object_path + ["__all__"], + ( + "names exported from the stub do not correspond to the names exported at runtime. " + "This is probably due to things being missing from the stub or an inaccurate `__all__` in the stub" + ), + # Pass in MISSING instead of the stub and runtime objects, as the line numbers aren't very + # relevant here, and it makes for a prettier error message + # This means this error will be ignored when using `--ignore-missing-stub`, which is + # desirable in at least the `names_in_runtime_not_stub` case + stub_object=MISSING, + runtime_object=MISSING, + stub_desc=(f"Names exported in the stub but not at runtime: {names_in_stub_not_runtime}"), + runtime_desc=( + f"Names exported at runtime but not in the stub: {names_in_runtime_not_stub}" + ), + ) + + +@functools.lru_cache +def _module_symbol_table(runtime: types.ModuleType) -> symtable.SymbolTable | None: + """Retrieve the symbol table for the module (or None on failure). + + 1) Use inspect to retrieve the source code of the module + 2) Use symtable to parse the source (and use what symtable knows for its purposes) + """ + try: + source = inspect.getsource(runtime) + except (OSError, TypeError, SyntaxError): + return None + + try: + return symtable.symtable(source, runtime.__name__, "exec") + except SyntaxError: + return None + + +@verify.register(nodes.MypyFile) +def verify_mypyfile( + stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + if not isinstance(runtime, types.ModuleType): + # Can possibly happen: + yield Error(object_path, "is not a module", stub, runtime) # type: ignore[unreachable] + return + + runtime_all_as_set: set[str] | None + + if hasattr(runtime, "__all__"): + runtime_all_as_set = set(runtime.__all__) + if "__all__" in stub.names: + # Only verify the contents of the stub's __all__ + # if the stub actually defines __all__ + yield from _verify_exported_names(object_path, stub, runtime_all_as_set) + else: + yield Error(object_path + ["__all__"], "is not present in stub", MISSING, runtime) + else: + runtime_all_as_set = None + + # Check things in the stub + to_check = {m for m, o in stub.names.items() if not o.module_hidden} + + def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool: + """Heuristics to determine whether a name originates from another module.""" + obj = getattr(r, attr) + if isinstance(obj, types.ModuleType): + return False + + symbol_table = _module_symbol_table(r) + if symbol_table is not None: + try: + symbol = symbol_table.lookup(attr) + except KeyError: + pass + else: + if symbol.is_imported(): + # symtable says we got this from another module + return False + # But we can't just return True here, because symtable doesn't know about symbols + # that come from `from module import *` + if symbol.is_assigned(): + # symtable knows we assigned this symbol in the module + return True + + # The __module__ attribute is unreliable for anything except functions and classes, + # but it's our best guess at this point + try: + obj_mod = obj.__module__ + except Exception: + pass + else: + if isinstance(obj_mod, str): + return bool(obj_mod == r.__name__) + return True + + runtime_public_contents = ( + runtime_all_as_set + if runtime_all_as_set is not None + else { + m + for m in dir(runtime) + if not is_probably_private(m) + # Filter out objects that originate from other modules (best effort). Note that in the + # absence of __all__, we don't have a way to detect explicit / intentional re-exports + # at runtime + and _belongs_to_runtime(runtime, m) + } + ) + # Check all things declared in module's __all__, falling back to our best guess + to_check.update(runtime_public_contents) + to_check.difference_update(IGNORED_MODULE_DUNDERS) + + for entry in sorted(to_check): + stub_entry = stub.names[entry].node if entry in stub.names else MISSING + if entry in stub.names: + if xref := stub.names[entry].cross_ref: + orig_module = xref.rsplit(".", 1)[0] + elif isinstance(stub_entry, nodes.SymbolNode) and (name := stub_entry.fullname): + orig_module = name.rsplit(".", 1)[0] + else: + orig_module = None + + if orig_module and orig_module != stub.fullname and orig_module in _all_stubs: + # Skip re-exported names whose defining module will be checked separately. + continue + + if isinstance(stub_entry, nodes.MypyFile): + # Don't recursively check exported modules, since that leads to infinite recursion + continue + assert stub_entry is not None + if ( + is_probably_private(entry) + and not hasattr(runtime, entry) + and not isinstance(stub_entry, Missing) + and not _is_decoratable(stub_entry) + ): + # Skip private names that don't exist at runtime and which cannot + # be marked with @type_check_only. + continue + try: + runtime_entry = getattr(runtime, entry, MISSING) + except Exception: + # Catch all exceptions in case the runtime raises an unexpected exception + # from __getattr__ or similar. + continue + yield from verify(stub_entry, runtime_entry, object_path + [entry]) + + +def _is_decoratable(stub: nodes.SymbolNode) -> bool: + if not isinstance(stub, nodes.TypeInfo): + return False + if stub.is_newtype: + return False + if stub.typeddict_type is not None: + return all( + name.isidentifier() and not keyword.iskeyword(name) + for name in stub.typeddict_type.items.keys() + ) + return True + + +def _verify_final( + stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str] +) -> Iterator[Error]: + try: + + class SubClass(runtime): # type: ignore[misc] + pass + + except TypeError: + # Enum classes are implicitly @final + if not stub.is_final and not issubclass(runtime, enum.Enum): + yield Error( + object_path, + "cannot be subclassed at runtime, but isn't marked with @final in the stub", + stub, + runtime, + stub_desc=repr(stub), + ) + except Exception: + # The class probably wants its subclasses to do something special. + # Examples: ctypes.Array, ctypes._SimpleCData + pass + + # Runtime class might be annotated with `@final`: + try: + runtime_final = getattr(runtime, "__final__", False) + except Exception: + runtime_final = False + + if runtime_final and not stub.is_final: + yield Error( + object_path, + "has `__final__` attribute, but isn't marked with @final in the stub", + stub, + runtime, + stub_desc=repr(stub), + ) + + +SIZEOF_PYOBJECT = struct.calcsize("P") + + +def _shape_differs(t1: type[object], t2: type[object]) -> bool: + """Check whether two types differ in shape. + + Mirrors the shape_differs() function in typeobject.c in CPython.""" + if sys.version_info >= (3, 12): + return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__ + else: + # CPython had more complicated logic before 3.12: + # https://github.com/python/cpython/blob/f3c6f882cddc8dc30320d2e73edf019e201394fc/Objects/typeobject.c#L2224 + # We attempt to mirror it here well enough to support the most common cases. + if t1.__itemsize__ or t2.__itemsize__: + return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__ + t_size = t1.__basicsize__ + if not t2.__weakrefoffset__ and t1.__weakrefoffset__ + SIZEOF_PYOBJECT == t_size: + t_size -= SIZEOF_PYOBJECT + if not t2.__dictoffset__ and t1.__dictoffset__ + SIZEOF_PYOBJECT == t_size: + t_size -= SIZEOF_PYOBJECT + if not t2.__weakrefoffset__ and t2.__weakrefoffset__ == t_size: + t_size -= SIZEOF_PYOBJECT + return t_size != t2.__basicsize__ + + +def _is_disjoint_base(typ: type[object]) -> bool: + """Return whether a type is a disjoint base at runtime, mirroring CPython's logic in typeobject.c. + + See PEP 800.""" + if typ is object: + return True + base = typ.__base__ + assert base is not None, f"Type {typ} has no base" + return _shape_differs(typ, base) + + +def _verify_disjoint_base( + stub: nodes.TypeInfo, runtime: type[object], object_path: list[str] +) -> Iterator[Error]: + is_disjoint_runtime = _is_disjoint_base(runtime) + # Don't complain about missing @disjoint_base if there are __slots__, because + # in that case we can infer that it's a disjoint base. + if ( + is_disjoint_runtime + and not stub.is_disjoint_base + and not runtime.__dict__.get("__slots__") + and not stub.is_final + and not (stub.is_enum and stub.enum_members) + ): + yield Error( + object_path, + "is a disjoint base at runtime, but isn't marked with @disjoint_base in the stub", + stub, + runtime, + stub_desc=repr(stub), + ) + elif stub.is_disjoint_base: + if not is_disjoint_runtime: + yield Error( + object_path, + "is marked with @disjoint_base in the stub, but isn't a disjoint base at runtime", + stub, + runtime, + stub_desc=repr(stub), + ) + if runtime.__dict__.get("__slots__"): + yield Error( + object_path, + "is marked as @disjoint_base, but also has slots; add __slots__ instead", + stub, + runtime, + stub_desc=repr(stub), + ) + elif stub.is_final: + yield Error( + object_path, + "is marked as @disjoint_base, but also marked as @final; remove @disjoint_base", + stub, + runtime, + stub_desc=repr(stub), + ) + elif stub.is_enum and stub.enum_members: + yield Error( + object_path, + "is marked as @disjoint_base, but is an enum with members, which is implicitly final; " + "remove @disjoint_base", + stub, + runtime, + stub_desc=repr(stub), + ) + + +def _verify_metaclass( + stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str], *, is_runtime_typeddict: bool +) -> Iterator[Error]: + # We exclude protocols, because of how complex their implementation is in different versions of + # python. Enums are also hard, as are runtime TypedDicts; ignoring. + # TODO: check that metaclasses are identical? + if not stub.is_protocol and not stub.is_enum and not is_runtime_typeddict: + runtime_metaclass = type(runtime) + if runtime_metaclass is not type and stub.metaclass_type is None: + # This means that runtime has a custom metaclass, but a stub does not. + yield Error( + object_path, + "is inconsistent, metaclass differs", + stub, + runtime, + stub_desc="N/A", + runtime_desc=f"{runtime_metaclass}", + ) + elif ( + runtime_metaclass is type + and stub.metaclass_type is not None + # We ignore extra `ABCMeta` metaclass on stubs, this might be typing hack. + # We also ignore `builtins.type` metaclass as an implementation detail in mypy. + and not mypy.types.is_named_instance( + stub.metaclass_type, ("abc.ABCMeta", "builtins.type") + ) + ): + # This means that our stub has a metaclass that is not present at runtime. + yield Error( + object_path, + "metaclass mismatch", + stub, + runtime, + stub_desc=f"{stub.metaclass_type.type.fullname}", + runtime_desc="N/A", + ) + + +@verify.register(nodes.TypeInfo) +def verify_typeinfo( + stub: nodes.TypeInfo, + runtime: MaybeMissing[type[Any]], + object_path: list[str], + *, + is_alias_target: bool = False, +) -> Iterator[Error]: + if stub.is_type_check_only and not is_alias_target: + # This type only exists in stubs, we only check that the runtime part + # is missing. Other checks are not required. + if not isinstance(runtime, Missing): + yield Error( + object_path, + 'is marked as "@type_check_only", but also exists at runtime', + stub, + runtime, + stub_desc=repr(stub), + ) + return + + if isinstance(runtime, Missing): + msg = "is not present at runtime" + if is_probably_private(stub.name): + msg += '. Maybe mark it as "@type_check_only"?' + yield Error(object_path, msg, stub, runtime, stub_desc=repr(stub)) + return + if not isinstance(runtime, type): + # Yes, some runtime objects can be not types, no way to tell mypy about that. + yield Error(object_path, "is not a type", stub, runtime, stub_desc=repr(stub)) # type: ignore[unreachable] + return + + yield from _verify_final(stub, runtime, object_path) + yield from _verify_disjoint_base(stub, runtime, object_path) + is_runtime_typeddict = stub.typeddict_type is not None and is_typeddict(runtime) + yield from _verify_metaclass( + stub, runtime, object_path, is_runtime_typeddict=is_runtime_typeddict + ) + + # Check everything already defined on the stub class itself (i.e. not inherited) + # + # Filter out non-identifier names, as these are (hopefully always?) whacky/fictional things + # (like __mypy-replace or __mypy-post_init, etc.) that don't exist at runtime, + # and exist purely for internal mypy reasons + to_check = {name for name in stub.names if name.isidentifier()} + # Check all public things on the runtime class + to_check.update( + m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS + ) + # Special-case the __init__ method for Protocols and the __new__ method for TypedDicts + # + # TODO: On Python <3.11, __init__ methods on Protocol classes + # are silently discarded and replaced. + # However, this is not the case on Python 3.11+. + # Ideally, we'd figure out a good way of validating Protocol __init__ methods on 3.11+. + if stub.is_protocol: + to_check.discard("__init__") + if is_runtime_typeddict: + to_check.discard("__new__") + + for entry in sorted(to_check): + mangled_entry = entry + if entry.startswith("__") and not entry.endswith("__"): + mangled_entry = f"_{stub.name.lstrip('_')}{entry}" + stub_to_verify = next((t.names[entry].node for t in stub.mro if entry in t.names), MISSING) + assert stub_to_verify is not None + try: + try: + runtime_attr = getattr(runtime, mangled_entry) + except AttributeError: + runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING) + except Exception: + # Catch all exceptions in case the runtime raises an unexpected exception + # from __getattr__ or similar. + continue + + # If it came from the metaclass, consider the runtime_attr to be MISSING + # for a more accurate message + if ( + runtime_attr is not MISSING + and type(runtime) is not runtime + and getattr(runtime_attr, "__objclass__", None) is type(runtime) + ): + runtime_attr = MISSING + + # __setattr__ and __delattr__ on object are a special case, + # so if we only have these methods inherited from there, pretend that + # we don't have them. See python/typeshed#7385. + if ( + entry in ("__setattr__", "__delattr__") + and runtime_attr is not MISSING + and runtime is not object + and getattr(runtime_attr, "__objclass__", None) is object + ): + runtime_attr = MISSING + + # Do not error for an object missing from the stub + # If the runtime object is a types.WrapperDescriptorType object + # and has a non-special dunder name. + # The vast majority of these are false positives. + if not ( + isinstance(stub_to_verify, Missing) + and isinstance(runtime_attr, types.WrapperDescriptorType) + and is_dunder(mangled_entry, exclude_special=True) + ): + yield from verify(stub_to_verify, runtime_attr, object_path + [entry]) + + +def _static_lookup_runtime(object_path: list[str]) -> MaybeMissing[Any]: + static_runtime = importlib.import_module(object_path[0]) + for entry in object_path[1:]: + try: + static_runtime = inspect.getattr_static(static_runtime, entry) + except AttributeError: + # This can happen with mangled names, ignore for now. + # TODO: pass more information about ancestors of nodes/objects to verify, so we don't + # have to do this hacky lookup. Would be useful in several places. + return MISSING + return static_runtime + + +def _verify_static_class_methods( + stub: nodes.FuncBase, runtime: Any, static_runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[str]: + if stub.name in ("__new__", "__init_subclass__", "__class_getitem__"): + # Special cased by Python, so don't bother checking + return + if inspect.isbuiltin(runtime): + # The isinstance checks don't work reliably for builtins, e.g. datetime.datetime.now, so do + # something a little hacky that seems to work well + probably_class_method = isinstance(getattr(runtime, "__self__", None), type) + if probably_class_method and not stub.is_class: + yield "runtime is a classmethod but stub is not" + if not probably_class_method and stub.is_class: + yield "stub is a classmethod but runtime is not" + return + + if static_runtime is MISSING: + return + + if isinstance(static_runtime, classmethod) and not stub.is_class: + yield "runtime is a classmethod but stub is not" + if not isinstance(static_runtime, classmethod) and stub.is_class: + yield "stub is a classmethod but runtime is not" + if isinstance(static_runtime, staticmethod) and not stub.is_static: + yield "runtime is a staticmethod but stub is not" + if not isinstance(static_runtime, staticmethod) and stub.is_static: + yield "stub is a staticmethod but runtime is not" + + +def _verify_arg_name( + stub_arg: nodes.Argument, runtime_arg: inspect.Parameter, function_name: str +) -> Iterator[str]: + """Checks whether argument names match.""" + # Ignore exact names for most dunder methods + if is_dunder(function_name, exclude_special=True): + return + + if ( + stub_arg.variable.name == runtime_arg.name + or stub_arg.variable.name.removeprefix("__") == runtime_arg.name + ): + return + + nonspecific_names = {"object", "args"} + if runtime_arg.name in nonspecific_names: + return + + def names_approx_match(a: str, b: str) -> bool: + a = a.strip("_") + b = b.strip("_") + return a.startswith(b) or b.startswith(a) or len(a) == 1 or len(b) == 1 + + # Be more permissive about names matching for positional-only arguments + if runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY and names_approx_match( + stub_arg.variable.name, runtime_arg.name + ): + return + # This comes up with namedtuples, so ignore + if stub_arg.variable.name == "_self": + return + yield ( + f'stub parameter "{stub_arg.variable.name}" ' + f'differs from runtime parameter "{runtime_arg.name}"' + ) + + +def _verify_arg_default_value( + stub_arg: nodes.Argument, runtime_arg: inspect.Parameter +) -> Iterator[str]: + """Checks whether argument default values are compatible.""" + if runtime_arg.default is not inspect.Parameter.empty: + if stub_arg.kind.is_required(): + yield ( + f'runtime parameter "{runtime_arg.name}" ' + "has a default value but stub parameter does not" + ) + else: + type_context = stub_arg.variable.type + runtime_type = get_mypy_type_of_runtime_value( + runtime_arg.default, type_context=type_context + ) + + # Fallback to the type annotation type if var type is missing. The type annotation + # is an UnboundType, but I don't know enough to know what the pros and cons here are. + # UnboundTypes have ugly question marks following them, so default to var type. + # Note we do this same fallback when constructing signatures in from_overloadedfuncdef + stub_type = stub_arg.variable.type or stub_arg.type_annotation + if isinstance(stub_type, mypy.types.TypeVarType): + stub_type = stub_type.upper_bound + if ( + runtime_type is not None + and stub_type is not None + # Avoid false positives for marker objects + and type(runtime_arg.default) is not object + # And ellipsis + and runtime_arg.default is not ... + and not is_subtype_helper(runtime_type, stub_type) + ): + yield ( + f'runtime parameter "{runtime_arg.name}" ' + f"has a default value of type {runtime_type}, " + f"which is incompatible with stub parameter type {stub_type}" + ) + if stub_arg.initializer is not None: + stub_default = evaluate_expression(stub_arg.initializer) + if ( + stub_default is not UNKNOWN + and stub_default is not ... + and runtime_arg.default is not UNREPRESENTABLE + ): + defaults_match = True + # We want the types to match exactly, e.g. in case the stub has + # True and the runtime has 1 (or vice versa). + if type(stub_default) is not type(runtime_arg.default): + defaults_match = False + else: + try: + defaults_match = bool(stub_default == runtime_arg.default) + except Exception: + # Exception can be raised in bool dunder method (e.g. numpy arrays) + # At this point, consider the default to be different, it is probably + # too complex to put in a stub anyway. + defaults_match = False + if not defaults_match: + yield ( + f'runtime parameter "{runtime_arg.name}" ' + f"has a default value of {runtime_arg.default!r}, " + f"which is different from stub parameter default {stub_default!r}" + ) + else: + if stub_arg.kind.is_optional(): + yield ( + f'stub parameter "{stub_arg.variable.name}" has a default value ' + f"but runtime parameter does not" + ) + + +def maybe_strip_cls(name: str, args: list[nodes.Argument]) -> list[nodes.Argument]: + if args and name in ("__init_subclass__", "__class_getitem__"): + # These are implicitly classmethods. If the stub chooses not to have @classmethod, we + # should remove the cls argument + if args[0].variable.name == "cls": + return args[1:] + return args + + +class Signature(Generic[T]): + def __init__(self) -> None: + self.pos: list[T] = [] + self.kwonly: dict[str, T] = {} + self.varpos: T | None = None + self.varkw: T | None = None + + def __str__(self) -> str: + def get_name(arg: Any) -> str: + if isinstance(arg, inspect.Parameter): + return arg.name + if isinstance(arg, nodes.Argument): + return arg.variable.name + raise AssertionError + + def get_type(arg: Any) -> str | None: + if isinstance(arg, inspect.Parameter): + return None + if isinstance(arg, nodes.Argument): + return str(arg.variable.type or arg.type_annotation) + raise AssertionError + + def has_default(arg: Any) -> bool: + if isinstance(arg, inspect.Parameter): + return arg.default is not inspect.Parameter.empty + if isinstance(arg, nodes.Argument): + return arg.kind.is_optional() + raise AssertionError + + def get_desc(arg: Any) -> str: + arg_type = get_type(arg) + return ( + get_name(arg) + + (f": {arg_type}" if arg_type else "") + + (" = ..." if has_default(arg) else "") + ) + + kw_only = sorted(self.kwonly.values(), key=lambda a: (has_default(a), get_name(a))) + ret = "def (" + ret += ", ".join( + [get_desc(arg) for arg in self.pos] + + (["*" + get_name(self.varpos)] if self.varpos else (["*"] if self.kwonly else [])) + + [get_desc(arg) for arg in kw_only] + + (["**" + get_name(self.varkw)] if self.varkw else []) + ) + ret += ")" + return ret + + @staticmethod + def from_funcitem(stub: nodes.FuncItem) -> Signature[nodes.Argument]: + stub_sig: Signature[nodes.Argument] = Signature() + stub_args = maybe_strip_cls(stub.name, stub.arguments) + for stub_arg in stub_args: + if stub_arg.kind.is_positional(): + stub_sig.pos.append(stub_arg) + elif stub_arg.kind.is_named(): + stub_sig.kwonly[stub_arg.variable.name] = stub_arg + elif stub_arg.kind == nodes.ARG_STAR: + stub_sig.varpos = stub_arg + elif stub_arg.kind == nodes.ARG_STAR2: + stub_sig.varkw = stub_arg + else: + raise AssertionError + return stub_sig + + @staticmethod + def from_inspect_signature(signature: inspect.Signature) -> Signature[inspect.Parameter]: + runtime_sig: Signature[inspect.Parameter] = Signature() + for runtime_arg in signature.parameters.values(): + if runtime_arg.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + runtime_sig.pos.append(runtime_arg) + elif runtime_arg.kind == inspect.Parameter.KEYWORD_ONLY: + runtime_sig.kwonly[runtime_arg.name] = runtime_arg + elif runtime_arg.kind == inspect.Parameter.VAR_POSITIONAL: + runtime_sig.varpos = runtime_arg + elif runtime_arg.kind == inspect.Parameter.VAR_KEYWORD: + runtime_sig.varkw = runtime_arg + else: + raise AssertionError + return runtime_sig + + @staticmethod + def from_overloadedfuncdef(stub: nodes.OverloadedFuncDef) -> Signature[nodes.Argument]: + """Returns a Signature from an OverloadedFuncDef. + + If life were simple, to verify_overloadedfuncdef, we'd just verify_funcitem for each of its + items. Unfortunately, life isn't simple and overloads are pretty deceitful. So instead, we + try and combine the overload's items into a single signature that is compatible with any + lies it might try to tell. + + """ + # For most dunder methods, just assume all args are positional-only + assume_positional_only = is_dunder(stub.name, exclude_special=True) + + is_arg_pos_only: defaultdict[str, set[bool]] = defaultdict(set) + for func in map(_resolve_funcitem_from_decorator, stub.items): + assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}" + args = maybe_strip_cls(stub.name, func.arguments) + for index, arg in enumerate(args): + if ( + arg.variable.name.startswith("__") + or arg.pos_only + or assume_positional_only + or arg.variable.name.strip("_") == "self" + or (index == 0 and arg.variable.name.strip("_") == "cls") + ): + is_arg_pos_only[arg.variable.name].add(True) + else: + is_arg_pos_only[arg.variable.name].add(False) + + all_args: dict[str, list[tuple[nodes.Argument, int]]] = {} + for func in map(_resolve_funcitem_from_decorator, stub.items): + assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}" + args = maybe_strip_cls(stub.name, func.arguments) + for index, arg in enumerate(args): + # For positional-only args, we allow overloads to have different names for the same + # argument. To accomplish this, we just make up a fake index-based name. + # We can only use the index-based name if the argument is always + # positional only. Sometimes overloads have an arg as positional-only + # in some but not all branches of the overload. + name = arg.variable.name + if is_arg_pos_only[name] == {True}: + name = f"__{index}" + + all_args.setdefault(name, []).append((arg, index)) + + def get_position(arg_name: str) -> int: + # We just need this to return the positional args in the correct order. + return max(index for _, index in all_args[arg_name]) + + def get_type(arg_name: str) -> mypy.types.ProperType: + with mypy.state.state.strict_optional_set(True): + all_types = [ + arg.variable.type or arg.type_annotation for arg, _ in all_args[arg_name] + ] + return mypy.typeops.make_simplified_union([t for t in all_types if t]) + + def get_kind(arg_name: str) -> nodes.ArgKind: + kinds = {arg.kind for arg, _ in all_args[arg_name]} + if nodes.ARG_STAR in kinds: + return nodes.ARG_STAR + if nodes.ARG_STAR2 in kinds: + return nodes.ARG_STAR2 + # The logic here is based on two tenets: + # 1) If an arg is ever optional (or unspecified), it is optional + # 2) If an arg is ever positional, it is positional + is_opt = ( + len(all_args[arg_name]) < len(stub.items) + or nodes.ARG_OPT in kinds + or nodes.ARG_NAMED_OPT in kinds + ) + is_pos = nodes.ARG_OPT in kinds or nodes.ARG_POS in kinds + if is_opt: + return nodes.ARG_OPT if is_pos else nodes.ARG_NAMED_OPT + return nodes.ARG_POS if is_pos else nodes.ARG_NAMED + + sig: Signature[nodes.Argument] = Signature() + for arg_name in sorted(all_args, key=get_position): + # example_arg_name gives us a real name (in case we had a fake index-based name) + example_arg_name = all_args[arg_name][0][0].variable.name + arg = nodes.Argument( + nodes.Var(example_arg_name, get_type(arg_name)), + type_annotation=None, + initializer=None, + kind=get_kind(arg_name), + pos_only=all(arg.pos_only for arg, _ in all_args[arg_name]), + ) + if arg.kind.is_positional(): + sig.pos.append(arg) + elif arg.kind.is_named(): + sig.kwonly[arg.variable.name] = arg + elif arg.kind == nodes.ARG_STAR: + sig.varpos = arg + elif arg.kind == nodes.ARG_STAR2: + sig.varkw = arg + else: + raise AssertionError + return sig + + +def _verify_signature( + stub: Signature[nodes.Argument], + runtime: Signature[inspect.Parameter], + function_name: str, + warn_runtime_is_object_init: bool = False, +) -> Iterator[str]: + # Check positional arguments match up + for stub_arg, runtime_arg in zip(stub.pos, runtime.pos): + yield from _verify_arg_name(stub_arg, runtime_arg, function_name) + yield from _verify_arg_default_value(stub_arg, runtime_arg) + if ( + runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY + and not stub_arg.pos_only + and not stub_arg.variable.name.startswith("__") + and stub_arg.variable.name.strip("_") != "self" + and stub_arg.variable.name.strip("_") != "cls" + ): + yield ( + f'stub parameter "{stub_arg.variable.name}" should be positional-only ' + f'(add "/", e.g. "{runtime_arg.name}, /")' + ) + if ( + runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY + and (stub_arg.pos_only or stub_arg.variable.name.startswith("__")) + and not runtime_arg.name.startswith("__") + and stub_arg.variable.name.strip("_") != "self" + and stub_arg.variable.name.strip("_") != "cls" + and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods + ): + yield ( + f'stub parameter "{stub_arg.variable.name}" should be positional or keyword ' + '(remove "/")' + ) + + # Check unmatched positional args + if len(stub.pos) > len(runtime.pos): + # There are cases where the stub exhaustively lists out the extra parameters the function + # would take through *args. Hence, a) if runtime accepts *args, we don't check whether the + # runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes + # *args, since runtime logic may prevent arbitrary arguments from actually being accepted. + if runtime.varpos is None: + for stub_arg in stub.pos[len(runtime.pos) :]: + # If the variable is in runtime.kwonly, it's just mislabelled as not a + # keyword-only argument + if stub_arg.variable.name not in runtime.kwonly: + msg = f'runtime does not have parameter "{stub_arg.variable.name}"' + if runtime.varkw is not None: + msg += ". Maybe you forgot to make it keyword-only in the stub?" + elif warn_runtime_is_object_init: + msg += ". You may need to write stubs for __new__ instead of __init__." + yield msg + else: + yield f'stub parameter "{stub_arg.variable.name}" is not keyword-only' + if stub.varpos is not None: + yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"' + elif len(stub.pos) < len(runtime.pos): + for runtime_arg in runtime.pos[len(stub.pos) :]: + if runtime_arg.name not in stub.kwonly: + if not _is_private_parameter(runtime_arg): + yield f'stub does not have parameter "{runtime_arg.name}"' + else: + yield f'runtime parameter "{runtime_arg.name}" is not keyword-only' + + # Checks involving *args + if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None: + if stub.varpos is None and runtime.varpos is not None: + yield f'stub does not have *args parameter "{runtime.varpos.name}"' + if stub.varpos is not None and runtime.varpos is None: + yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"' + + # Check keyword-only args + for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)): + stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg] + yield from _verify_arg_name(stub_arg, runtime_arg, function_name) + yield from _verify_arg_default_value(stub_arg, runtime_arg) + + # Check unmatched keyword-only args + if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)): + # There are cases where the stub exhaustively lists out the extra parameters the function + # would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't + # exhaustively listed out params), we don't check whether the runtime has all of the stub's + # parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic + # may prevent arbitrary keyword arguments from actually being accepted. + for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)): + if arg in {runtime_arg.name for runtime_arg in runtime.pos}: + # Don't report this if we've reported it before + if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}: + yield f'runtime parameter "{arg}" is not keyword-only' + else: + msg = f'runtime does not have parameter "{arg}"' + if warn_runtime_is_object_init: + msg += ". You may need to write stubs for __new__ instead of __init__." + yield msg + + for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)): + if arg in {stub_arg.variable.name for stub_arg in stub.pos}: + # Don't report this if we've reported it before + if not ( + runtime.varpos is None + and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]} + ): + yield f'stub parameter "{arg}" is not keyword-only' + else: + if not _is_private_parameter(runtime.kwonly[arg]): + yield f'stub does not have parameter "{arg}"' + + # Checks involving **kwargs + if stub.varkw is None and runtime.varkw is not None: + # As mentioned above, don't enforce that the stub takes **kwargs. + # Also check against positional parameters, to avoid a nitpicky message when an argument + # isn't marked as keyword-only + stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos} + # Ideally we'd do a strict subset check, but in practice the errors from that aren't useful + if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names): + yield f'stub does not have **kwargs parameter "{runtime.varkw.name}"' + if stub.varkw is not None and runtime.varkw is None: + yield f'runtime does not have **kwargs parameter "{stub.varkw.variable.name}"' + + +def _is_private_parameter(arg: inspect.Parameter) -> bool: + return ( + arg.name.startswith("_") + and not arg.name.startswith("__") + and arg.default is not inspect.Parameter.empty + ) + + +@verify.register(nodes.FuncItem) +def verify_funcitem( + stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + + if not is_probably_a_function(runtime): + yield Error(object_path, "is not a function", stub, runtime) + if not callable(runtime): + return + + # Look the object up statically, to avoid binding by the descriptor protocol + static_runtime = _static_lookup_runtime(object_path) + + if isinstance(stub, nodes.FuncDef): + for error_text in _verify_abstract_status(stub, runtime): + yield Error(object_path, error_text, stub, runtime) + for error_text in _verify_final_method(stub, runtime, static_runtime): + yield Error(object_path, error_text, stub, runtime) + + for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path): + yield Error(object_path, "is inconsistent, " + message, stub, runtime) + + signature = safe_inspect_signature(runtime) + runtime_is_coroutine = inspect.iscoroutinefunction(runtime) + + if signature: + stub_sig = Signature.from_funcitem(stub) + runtime_sig = Signature.from_inspect_signature(signature) + runtime_sig_desc = describe_runtime_callable(signature, is_async=runtime_is_coroutine) + stub_desc = str(stub_sig) + else: + runtime_sig_desc, stub_desc = None, None + + # Don't raise an error if the stub is a coroutine, but the runtime isn't. + # That results in false positives. + # See https://github.com/python/typeshed/issues/7344 + if runtime_is_coroutine and not stub.is_coroutine: + yield Error( + object_path, + 'is an "async def" function at runtime, but not in the stub', + stub, + runtime, + stub_desc=stub_desc, + runtime_desc=runtime_sig_desc, + ) + + if not signature: + return + + for message in _verify_signature( + stub_sig, + runtime_sig, + function_name=stub.name, + warn_runtime_is_object_init=runtime is object.__init__, + ): + yield Error( + object_path, + "is inconsistent, " + message, + stub, + runtime, + runtime_desc=runtime_sig_desc, + ) + + +@verify.register(Missing) +def verify_missing( + stub: Missing, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if runtime is MISSING: + return + yield Error(object_path, "is not present in stub", stub, runtime) + + +@verify.register(nodes.Var) +def verify_var( + stub: nodes.Var, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + # Don't always yield an error here, because we often can't find instance variables + if len(object_path) <= 2: + yield Error(object_path, "is not present at runtime", stub, runtime) + return + + if ( + stub.is_initialized_in_class + and is_read_only_property(runtime) + and (stub.is_settable_property or not stub.is_property) + ): + yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime) + + runtime_type = get_mypy_type_of_runtime_value(runtime, type_context=stub.type) + note = "" + if ( + runtime_type is not None + and stub.type is not None + and not is_subtype_helper(runtime_type, stub.type) + ): + should_error = True + # Avoid errors when defining enums, since runtime_type is the enum itself, but we'd + # annotate it with the type of runtime.value + if isinstance(runtime, enum.Enum): + runtime_type = get_mypy_type_of_runtime_value(runtime.value) + if runtime_type is not None and is_subtype_helper(runtime_type, stub.type): + should_error = False + # We always allow setting the stub value to Ellipsis (...), but use + # _value_ type as a fallback if given. If a member is ... and _value_ + # type is given, all runtime types should be assignable to _value_. + proper_type = mypy.types.get_proper_type(stub.type) + if ( + isinstance(proper_type, mypy.types.Instance) + and proper_type.type.fullname in mypy.types.ELLIPSIS_TYPE_NAMES + ): + value_t = stub.info.get("_value_") + if value_t is None or value_t.type is None or runtime_type is None: + should_error = False + elif is_subtype_helper(runtime_type, value_t.type): + should_error = False + else: + note = " (incompatible '_value_')" + + if should_error: + yield Error( + object_path, + f"variable differs from runtime type {runtime_type}{note}", + stub, + runtime, + ) + elif stub.final_value is not None and stub.final_value != runtime: + yield Error( + object_path, + "is inconsistent, stub value for Final var differs from runtime value", + stub, + runtime, + stub_desc=repr(stub.final_value), + ) + + +@verify.register(nodes.OverloadedFuncDef) +def verify_overloadedfuncdef( + stub: nodes.OverloadedFuncDef, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + # TODO: support `@type_check_only` decorator + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + + if stub.is_property: + # Any property with a setter is represented as an OverloadedFuncDef + if is_read_only_property(runtime): + yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime) + return + + if not is_probably_a_function(runtime): + yield Error(object_path, "is not a function", stub, runtime) + if not callable(runtime): + return + + # mypy doesn't allow overloads where one overload is abstract but another isn't, + # so it should be okay to just check whether the first overload is abstract or not. + # + # TODO: Mypy *does* allow properties where e.g. the getter is abstract but the setter is not; + # and any property with a setter is represented as an OverloadedFuncDef internally; + # not sure exactly what (if anything) we should do about that. + first_part = stub.items[0] + if isinstance(first_part, nodes.Decorator) and first_part.is_overload: + for msg in _verify_abstract_status(first_part.func, runtime): + yield Error(object_path, msg, stub, runtime) + + # Look the object up statically, to avoid binding by the descriptor protocol + static_runtime = _static_lookup_runtime(object_path) + + for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path): + yield Error(object_path, "is inconsistent, " + message, stub, runtime) + + # TODO: Should call _verify_final_method here, + # but overloaded final methods in stubs cause a stubtest crash: see #14950 + + signature = safe_inspect_signature(runtime) + if not signature: + return + + stub_sig = Signature.from_overloadedfuncdef(stub) + runtime_sig = Signature.from_inspect_signature(signature) + + for message in _verify_signature( + stub_sig, + runtime_sig, + function_name=stub.name, + warn_runtime_is_object_init=runtime is object.__init__, + ): + # TODO: This is a little hacky, but the addition here is super useful + if "has a default value of type" in message: + message += ( + ". This is often caused by overloads failing to account for explicitly passing " + "in the default value." + ) + yield Error( + object_path, + "is inconsistent, " + message, + stub, + runtime, + stub_desc=(str(stub.type)) + f"\nInferred signature: {stub_sig}", + runtime_desc="def " + str(signature), + ) + + +@verify.register(nodes.TypeVarExpr) +def verify_typevarexpr( + stub: nodes.TypeVarExpr, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + # We seem to insert these typevars into NamedTuple stubs, but they + # don't exist at runtime. Just ignore! + if stub.name == "_NT": + return + yield Error(object_path, "is not present at runtime", stub, runtime) + return + if not isinstance(runtime, TypeVar): + yield Error(object_path, "is not a TypeVar", stub, runtime) + return + + +@verify.register(nodes.ParamSpecExpr) +def verify_paramspecexpr( + stub: nodes.ParamSpecExpr, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + maybe_paramspec_types = ( + getattr(typing, "ParamSpec", None), + getattr(typing_extensions, "ParamSpec", None), + ) + paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None) + if not paramspec_types or not isinstance(runtime, paramspec_types): + yield Error(object_path, "is not a ParamSpec", stub, runtime) + return + + +def _is_django_cached_property(runtime: Any) -> bool: # pragma: no cover + # This is a special case for + # https://docs.djangoproject.com/en/5.2/ref/utils/#django.utils.functional.cached_property + # This is needed in `django-stubs` project: + # https://github.com/typeddjango/django-stubs + if type(runtime).__name__ != "cached_property": + return False + try: + return bool(runtime.func) + except Exception: + return False + + +def _verify_readonly_property(stub: nodes.Decorator, runtime: Any) -> Iterator[str]: + assert stub.func.is_property + if isinstance(runtime, property): + yield from _verify_final_method(stub.func, runtime.fget, MISSING) + return + if isinstance(runtime, functools.cached_property): + yield from _verify_final_method(stub.func, runtime.func, MISSING) + return + if _is_django_cached_property(runtime): + yield from _verify_final_method(stub.func, runtime.func, MISSING) + return + if inspect.isdatadescriptor(runtime): + # It's enough like a property... + return + # Sometimes attributes pretend to be properties, for instance, to express that they + # are read only. So allowlist if runtime_type matches the return type of stub. + runtime_type = get_mypy_type_of_runtime_value(runtime) + func_type = ( + stub.func.type.ret_type if isinstance(stub.func.type, mypy.types.CallableType) else None + ) + if ( + runtime_type is not None + and func_type is not None + and is_subtype_helper(runtime_type, func_type) + ): + return + yield "is inconsistent, cannot reconcile @property on stub with runtime object" + + +def _verify_abstract_status(stub: nodes.FuncDef, runtime: Any) -> Iterator[str]: + stub_abstract = stub.abstract_status == nodes.IS_ABSTRACT + runtime_abstract = getattr(runtime, "__isabstractmethod__", False) + # The opposite can exist: some implementations omit `@abstractmethod` decorators + if runtime_abstract and not stub_abstract: + item_type = "property" if stub.is_property else "method" + yield f"is inconsistent, runtime {item_type} is abstract but stub is not" + + +def _verify_final_method( + stub: nodes.FuncDef, runtime: Any, static_runtime: MaybeMissing[Any] +) -> Iterator[str]: + if stub.is_final: + return + if getattr(runtime, "__final__", False) or ( + static_runtime is not MISSING and getattr(static_runtime, "__final__", False) + ): + yield "is decorated with @final at runtime, but not in the stub" + + +def _resolve_funcitem_from_decorator(dec: nodes.OverloadPart) -> nodes.FuncItem | None: + """Returns a FuncItem that corresponds to the output of the decorator. + + Returns None if we can't figure out what that would be. For convenience, this function also + accepts FuncItems. + """ + if isinstance(dec, nodes.FuncItem): + return dec + if dec.func.is_property: + return None + + def apply_decorator_to_funcitem( + decorator: nodes.Expression, func: nodes.FuncItem + ) -> nodes.FuncItem | None: + if ( + isinstance(decorator, nodes.CallExpr) + and isinstance(decorator.callee, nodes.RefExpr) + and decorator.callee.fullname in mypy.types.DEPRECATED_TYPE_NAMES + ): + return func + if not isinstance(decorator, nodes.RefExpr): + return None + if not decorator.fullname: + # Happens with namedtuple + return None + if ( + decorator.fullname in ("builtins.staticmethod", "abc.abstractmethod") + or decorator.fullname in mypy.types.OVERLOAD_NAMES + or decorator.fullname in mypy.types.OVERRIDE_DECORATOR_NAMES + or decorator.fullname in mypy.types.FINAL_DECORATOR_NAMES + ): + return func + if decorator.fullname == "builtins.classmethod": + if func.arguments[0].variable.name not in ("_cls", "cls", "mcs", "metacls"): + raise StubtestFailure( + f"unexpected class parameter name {func.arguments[0].variable.name!r} " + f"in {dec.fullname}" + ) + # FuncItem is written so that copy.copy() actually works, even when compiled + ret = copy.copy(func) + # Remove the cls argument, since it's not present in inspect.signature of classmethods + ret.arguments = ret.arguments[1:] + return ret + # Just give up on any other decorators. After excluding properties, we don't run into + # anything else when running on typeshed's stdlib. + return None + + func: nodes.FuncItem = dec.func + for decorator in dec.original_decorators: + resulting_func = apply_decorator_to_funcitem(decorator, func) + if resulting_func is None: + # We couldn't figure out how to apply the decorator by transforming nodes, so try to + # reconstitute a FuncDef from the resulting type of the decorator + # This is worse because e.g. we lose the values of defaults + dec_type = mypy.types.get_proper_type(dec.type) + callable_type = None + if isinstance(dec_type, mypy.types.Instance): + callable_type = mypy.subtypes.find_member( + "__call__", dec_type, dec_type, is_operator=True + ) + elif isinstance(dec_type, mypy.types.CallableType): + callable_type = dec_type + + callable_type = mypy.types.get_proper_type(callable_type) + if isinstance(callable_type, mypy.types.CallableType): + return _resolve_funcitem_from_callable_type(dec, callable_type) + return None + + func = resulting_func + return func + + +def _resolve_funcitem_from_callable_type( + dec: nodes.Decorator, typ: mypy.types.CallableType +) -> nodes.FuncDef | None: + if ( + typ.arg_kinds == [nodes.ARG_STAR, nodes.ARG_STAR2] + and (var_arg := typ.var_arg()) is not None + and isinstance(mypy.types.get_proper_type(var_arg.typ), mypy.types.AnyType) + and (var_kwarg := typ.kw_arg()) is not None + and isinstance(mypy.types.get_proper_type(var_kwarg.typ), mypy.types.AnyType) + ): + # There isn't a FuncDef we can invent corresponding to a Callable[..., T] + return None + + args: list[nodes.Argument] = [] + for i, (arg_type, arg_kind, arg_name) in enumerate( + zip(typ.arg_types, typ.arg_kinds, typ.arg_names, strict=True) + ): + var_name = arg_name if arg_name is not None else f"__arg{i}" + var = nodes.Var(var_name, arg_type) + pos_only = arg_name is None and arg_kind == nodes.ARG_POS + args.append( + nodes.Argument( + variable=var, + type_annotation=arg_type, + initializer=None, # CallableType doesn't store the values of defaults + kind=arg_kind, + pos_only=pos_only, + ) + ) + + if dec.func.is_class: + if not args: + return None + # Munge classmethods, similar to logic in _resolve_funcitem_from_decorator + if args[0].variable.name not in ("_cls", "cls", "mcs", "metacls"): + return None + args.pop(0) + + ret = nodes.FuncDef(name=typ.name or "", arguments=args, body=nodes.Block([]), typ=typ) + ret.is_class = dec.func.is_class + return ret + + +@verify.register(nodes.Decorator) +def verify_decorator( + stub: nodes.Decorator, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if stub.func.is_type_check_only: + # This function only exists in stubs, we only check that the runtime part + # is missing. Other checks are not required. + if not isinstance(runtime, Missing): + yield Error( + object_path, + 'is marked as "@type_check_only", but also exists at runtime', + stub, + runtime, + stub_desc=repr(stub), + ) + return + + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + if stub.func.is_property: + for message in _verify_readonly_property(stub, runtime): + yield Error(object_path, message, stub, runtime) + for message in _verify_abstract_status(stub.func, runtime): + yield Error(object_path, message, stub, runtime) + return + + func = _resolve_funcitem_from_decorator(stub) + if func is not None: + yield from verify(func, runtime, object_path) + + +@verify.register(nodes.TypeAlias) +def verify_typealias( + stub: nodes.TypeAlias, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + stub_target = mypy.types.get_proper_type(stub.target) + stub_desc = f"Type alias for {stub_target}" + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime, stub_desc=stub_desc) + return + runtime_origin = get_origin(runtime) or runtime + if isinstance(stub_target, mypy.types.Instance): + if not isinstance(runtime_origin, type): + yield Error( + object_path, + "is inconsistent, runtime is not a type", + stub, + runtime, + stub_desc=stub_desc, + ) + return + + stub_origin = stub_target.type + # Do our best to figure out the fullname of the runtime object... + runtime_name: object + try: + runtime_name = runtime_origin.__qualname__ + except AttributeError: + runtime_name = getattr(runtime_origin, "__name__", MISSING) + if isinstance(runtime_name, str): + runtime_module: object = getattr(runtime_origin, "__module__", MISSING) + if isinstance(runtime_module, str): + if runtime_module == "collections.abc" or ( + runtime_module == "re" and runtime_name in {"Match", "Pattern"} + ): + runtime_module = "typing" + runtime_fullname = f"{runtime_module}.{runtime_name}" + if re.fullmatch(rf"_?{re.escape(stub_origin.fullname)}", runtime_fullname): + # Okay, we're probably fine. + return + + # Okay, either we couldn't construct a fullname + # or the fullname of the stub didn't match the fullname of the runtime. + # Fallback to a full structural check of the runtime vis-a-vis the stub. + yield from verify_typeinfo(stub_origin, runtime_origin, object_path, is_alias_target=True) + return + if isinstance(stub_target, mypy.types.UnionType): + # complain if runtime is not a Union or UnionType + if runtime_origin is not Union and ( + not (sys.version_info >= (3, 10) and isinstance(runtime, types.UnionType)) + ): + yield Error(object_path, "is not a Union", stub, runtime, stub_desc=str(stub_target)) + # could check Union contents here... + return + if isinstance(stub_target, mypy.types.TupleType): + if tuple not in getattr(runtime_origin, "__mro__", ()): + yield Error( + object_path, "is not a subclass of tuple", stub, runtime, stub_desc=stub_desc + ) + # could check Tuple contents here... + return + if isinstance(stub_target, mypy.types.CallableType): + if runtime_origin is not collections.abc.Callable: + yield Error( + object_path, "is not a type alias for Callable", stub, runtime, stub_desc=stub_desc + ) + # could check Callable contents here... + return + if isinstance(stub_target, mypy.types.AnyType): + return + yield Error(object_path, "is not a recognised type alias", stub, runtime, stub_desc=stub_desc) + + +# ==================== +# Helpers +# ==================== + + +IGNORED_MODULE_DUNDERS: Final = frozenset( + { + "__file__", + "__doc__", + "__name__", + "__builtins__", + "__package__", + "__cached__", + "__loader__", + "__spec__", + "__annotations__", + "__conditional_annotations__", # 3.14+ + "__annotate__", + "__path__", # mypy adds __path__ to packages, but C packages don't have it + "__getattr__", # resulting behaviour might be typed explicitly + # Created by `warnings.warn`, does not make much sense to have in stubs: + "__warningregistry__", + # TODO: remove the following from this list + "__author__", + "__version__", + "__copyright__", + } +) + +IGNORABLE_CLASS_DUNDERS: Final = frozenset( + { + # Special attributes + "__dict__", + "__annotations__", + "__annotate__", + "__annotations_cache__", + "__annotate_func__", + "__text_signature__", + "__weakref__", + "__hash__", + "__getattr__", # resulting behaviour might be typed explicitly + "__setattr__", # defining this on a class can cause worse type checking + "__vectorcalloffset__", # undocumented implementation detail of the vectorcall protocol + "__firstlineno__", + "__static_attributes__", + "__classdictcell__", + # isinstance/issubclass hooks that type-checkers don't usually care about + "__instancecheck__", + "__subclasshook__", + "__subclasscheck__", + # python2 only magic methods: + "__cmp__", + "__nonzero__", + "__unicode__", + "__div__", + # cython methods + "__pyx_vtable__", + # Pickle methods + "__setstate__", + "__getstate__", + "__getnewargs__", + "__getinitargs__", + "__reduce_ex__", + "__reduce__", + "__slotnames__", # Cached names of slots added by `copyreg` module. + # ctypes weirdness + "__ctype_be__", + "__ctype_le__", + "__ctypes_from_outparam__", + # mypy limitations + "__abstractmethods__", # Classes with metaclass=ABCMeta inherit this attribute + "__new_member__", # If an enum defines __new__, the method is renamed as __new_member__ + "__dataclass_fields__", # Generated by dataclasses + "__dataclass_params__", # Generated by dataclasses + "__doc__", # mypy's semanal for namedtuples assumes this is str, not Optional[str] + # Added to all protocol classes on 3.12+ (or if using typing_extensions.Protocol) + "__protocol_attrs__", + "__callable_proto_members_only__", + "__non_callable_proto_members__", + # typing implementation details, consider removing some of these: + "__parameters__", + "__origin__", + "__args__", + "__orig_bases__", + "__final__", # Has a specialized check + # Consider removing __slots__? + "__slots__", + } +) + + +def is_probably_private(name: str) -> bool: + return name.startswith("_") and not is_dunder(name) + + +def is_probably_a_function(runtime: Any) -> bool: + return ( + isinstance( + runtime, + ( + types.FunctionType, + types.BuiltinFunctionType, + types.MethodType, + types.BuiltinMethodType, + ), + ) + or (inspect.ismethoddescriptor(runtime) and callable(runtime)) + or (isinstance(runtime, types.MethodWrapperType) and callable(runtime)) + ) + + +def is_read_only_property(runtime: object) -> bool: + return isinstance(runtime, property) and runtime.fset is None + + +def safe_inspect_signature(runtime: Any) -> inspect.Signature | None: + if ( + hasattr(runtime, "__name__") + and runtime.__name__ == "__init__" + and hasattr(runtime, "__text_signature__") + and runtime.__text_signature__ == "($self, /, *args, **kwargs)" + and hasattr(runtime, "__objclass__") + and hasattr(runtime.__objclass__, "__text_signature__") + and runtime.__objclass__.__text_signature__ is not None + ): + # This is an __init__ method with the generic C-class signature. + # In this case, the underlying class often has a better signature, + # which we can convert into an __init__ signature by adding in the + # self parameter. + try: + s = inspect.signature(runtime.__objclass__) + + parameter_kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_OR_KEYWORD + if s.parameters: + first_parameter = next(iter(s.parameters.values())) + if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY: + parameter_kind = inspect.Parameter.POSITIONAL_ONLY + return s.replace( + parameters=[inspect.Parameter("self", parameter_kind), *s.parameters.values()] + ) + except Exception: + pass + + if ( + hasattr(runtime, "__name__") + and runtime.__name__ == "__new__" + and hasattr(runtime, "__text_signature__") + and runtime.__text_signature__ == "($type, *args, **kwargs)" + and hasattr(runtime, "__self__") + and hasattr(runtime.__self__, "__text_signature__") + and runtime.__self__.__text_signature__ is not None + ): + # This is a __new__ method with the generic C-class signature. + # In this case, the underlying class often has a better signature, + # which we can convert into a __new__ signature by adding in the + # cls parameter. + + # If the attached class has a valid __init__, skip recovering a + # signature for this __new__ method. + has_init = False + if ( + hasattr(runtime.__self__, "__init__") + and hasattr(runtime.__self__.__init__, "__objclass__") + and runtime.__self__.__init__.__objclass__ is runtime.__self__ + ): + has_init = True + + if not has_init: + try: + s = inspect.signature(runtime.__self__) + parameter_kind = inspect.Parameter.POSITIONAL_OR_KEYWORD + if s.parameters: + first_parameter = next(iter(s.parameters.values())) + if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY: + parameter_kind = inspect.Parameter.POSITIONAL_ONLY + return s.replace( + parameters=[inspect.Parameter("cls", parameter_kind), *s.parameters.values()] + ) + except Exception: + pass + + try: + try: + return inspect.signature(runtime) + except ValueError: + if ( + hasattr(runtime, "__text_signature__") + and "" in runtime.__text_signature__ + ): + # Try to fix up the signature. Workaround for + # https://github.com/python/cpython/issues/87233 + sig = runtime.__text_signature__.replace("", "...") + sig = inspect._signature_fromstr(inspect.Signature, runtime, sig) # type: ignore[attr-defined] + assert isinstance(sig, inspect.Signature) + new_params = [ + ( + parameter.replace(default=UNREPRESENTABLE) + if parameter.default is ... + else parameter + ) + for parameter in sig.parameters.values() + ] + return sig.replace(parameters=new_params) + else: + raise + except Exception: + # inspect.signature throws ValueError all the time + # catch RuntimeError because of https://bugs.python.org/issue39504 + # catch TypeError because of https://github.com/python/typeshed/pull/5762 + # catch AttributeError because of inspect.signature(_curses.window.border) + return None + + +def describe_runtime_callable(signature: inspect.Signature, *, is_async: bool) -> str: + return f'{"async " if is_async else ""}def {signature}' + + +class _TypeCheckOnlyBaseMapper(mypy.types.TypeTranslator): + """Rewrites @type_check_only instances to the nearest runtime-visible base class.""" + + def visit_instance(self, t: mypy.types.Instance, /) -> mypy.types.Type: + instance = mypy.types.get_proper_type(super().visit_instance(t)) + assert isinstance(instance, mypy.types.Instance) + + if instance.type.is_type_check_only: + # find the nearest non-@type_check_only base class + for base_info in instance.type.mro[1:]: + if not base_info.is_type_check_only: + return map_instance_to_supertype(instance, base_info) + + msg = f"all base classes of {instance.type.fullname!r} are @type_check_only" + assert False, msg + + return instance + + def visit_type_alias_type(self, t: mypy.types.TypeAliasType, /) -> mypy.types.Type: + return t + + +_TYPE_CHECK_ONLY_BASE_MAPPER = _TypeCheckOnlyBaseMapper() + + +def _relax_type_check_only_type(typ: mypy.types.ProperType) -> mypy.types.ProperType: + return mypy.types.get_proper_type(typ.accept(_TYPE_CHECK_ONLY_BASE_MAPPER)) + + +def is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool: + """Checks whether ``left`` is a subtype of ``right``.""" + left = _relax_type_check_only_type(mypy.types.get_proper_type(left)) + right = _relax_type_check_only_type(mypy.types.get_proper_type(right)) + if ( + isinstance(left, mypy.types.LiteralType) + and isinstance(left.value, int) + and left.value in (0, 1) + and mypy.types.is_named_instance(right, "builtins.bool") + ): + # Pretend Literal[0, 1] is a subtype of bool to avoid unhelpful errors. + return True + + if isinstance(right, mypy.types.TypedDictType) and mypy.types.is_named_instance( + left, "builtins.dict" + ): + # Special case checks against TypedDicts + return True + + with mypy.state.state.strict_optional_set(True): + return mypy.subtypes.is_subtype(left, right) + + +def get_mypy_node_for_name(module: str, type_name: str) -> mypy.nodes.SymbolNode | None: + stub = get_stub(module) + if stub is None: + return None + if type_name not in stub.names: + return None + return stub.names[type_name].node + + +def get_mypy_type_of_runtime_value( + runtime: Any, type_context: mypy.types.Type | None = None +) -> mypy.types.Type | None: + """Returns a mypy type object representing the type of ``runtime``. + + Returns None if we can't find something that works. + + """ + if runtime is None: + return mypy.types.NoneType() + if isinstance(runtime, property): + # Give up on properties to avoid issues with things that are typed as attributes. + return None + + def anytype() -> mypy.types.AnyType: + return mypy.types.AnyType(mypy.types.TypeOfAny.unannotated) + + if isinstance( + runtime, + (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType), + ): + builtins = get_stub("builtins") + assert builtins is not None + type_info = builtins.names["function"].node + assert isinstance(type_info, nodes.TypeInfo) + fallback = mypy.types.Instance(type_info, [anytype()]) + signature = safe_inspect_signature(runtime) + if signature: + arg_types = [] + arg_kinds = [] + arg_names = [] + for arg in signature.parameters.values(): + arg_types.append(anytype()) + arg_names.append( + None if arg.kind == inspect.Parameter.POSITIONAL_ONLY else arg.name + ) + no_default = arg.default is inspect.Parameter.empty + if arg.kind == inspect.Parameter.POSITIONAL_ONLY: + arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT) + elif arg.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD: + arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT) + elif arg.kind == inspect.Parameter.KEYWORD_ONLY: + arg_kinds.append(nodes.ARG_NAMED if no_default else nodes.ARG_NAMED_OPT) + elif arg.kind == inspect.Parameter.VAR_POSITIONAL: + arg_kinds.append(nodes.ARG_STAR) + elif arg.kind == inspect.Parameter.VAR_KEYWORD: + arg_kinds.append(nodes.ARG_STAR2) + else: + raise AssertionError + else: + arg_types = [anytype(), anytype()] + arg_kinds = [nodes.ARG_STAR, nodes.ARG_STAR2] + arg_names = [None, None] + + return mypy.types.CallableType( + arg_types, + arg_kinds, + arg_names, + ret_type=anytype(), + fallback=fallback, + is_ellipsis_args=True, + ) + + skip_type_object_type = False + if type_context: + # Don't attempt to process the type object when context is generic + # This is related to issue #3737 + type_context = mypy.types.get_proper_type(type_context) + # Callable types with a generic return value + if isinstance(type_context, mypy.types.CallableType): + if isinstance(type_context.ret_type, mypy.types.TypeVarType): + skip_type_object_type = True + # Type[x] where x is generic + if isinstance(type_context, mypy.types.TypeType): + if isinstance(type_context.item, mypy.types.TypeVarType): + skip_type_object_type = True + + if isinstance(runtime, type) and not skip_type_object_type: + + def _named_type(name: str) -> mypy.types.Instance: + parts = name.rsplit(".", maxsplit=1) + node = get_mypy_node_for_name(parts[0], parts[1]) + assert isinstance(node, nodes.TypeInfo) + any_type = mypy.types.AnyType(mypy.types.TypeOfAny.special_form) + return mypy.types.Instance(node, [any_type] * len(node.defn.type_vars)) + + # Try and look up a stub for the runtime object itself + # The logic here is similar to ExpressionChecker.analyze_ref_expr + type_info = get_mypy_node_for_name(runtime.__module__, runtime.__name__) + if isinstance(type_info, nodes.TypeInfo): + result: mypy.types.Type | None = None + result = mypy.typeops.type_object_type(type_info, _named_type) + if mypy.checkexpr.is_type_type_context(type_context): + # This is the type in a type[] expression, so substitute type + # variables with Any. + result = mypy.erasetype.erase_typevars(result) + return result + + # Try and look up a stub for the runtime object's type + type_info = get_mypy_node_for_name(type(runtime).__module__, type(runtime).__name__) + if type_info is None: + return None + if isinstance(type_info, nodes.Var): + return type_info.type + if not isinstance(type_info, nodes.TypeInfo): + return None + + if isinstance(runtime, tuple): + # Special case tuples so we construct a valid mypy.types.TupleType + optional_items = [get_mypy_type_of_runtime_value(v) for v in runtime] + items = [(i if i is not None else anytype()) for i in optional_items] + fallback = mypy.types.Instance(type_info, [anytype()]) + return mypy.types.TupleType(items, fallback) + + fallback = mypy.types.Instance(type_info, [anytype() for _ in type_info.type_vars]) + if type(runtime) != runtime.__class__: + # Since `__class__` is redefined for an instance, we can't trust + # its `isinstance` checks, it can be dynamic. See #20919 + return fallback + + value: bool | int | str + if isinstance(runtime, enum.Enum) and isinstance(runtime.name, str): + value = runtime.name + elif isinstance(runtime, bytes): + value = bytes_to_human_readable_repr(runtime) + elif isinstance(runtime, (bool, int, str)): + value = runtime + else: + return fallback + + return mypy.types.LiteralType(value=value, fallback=fallback) + + +# ==================== +# Build and entrypoint +# ==================== + + +_all_stubs: dict[str, nodes.MypyFile] = {} + + +def build_stubs(modules: list[str], options: Options, find_submodules: bool = False) -> list[str]: + """Uses mypy to construct stub objects for the given modules. + + This sets global state that ``get_stub`` can access. + + Returns all modules we might want to check. If ``find_submodules`` is False, this is equal + to ``modules``. + + :param modules: List of modules to build stubs for. + :param options: Mypy options for finding and building stubs. + :param find_submodules: Whether to attempt to find submodules of the given modules as well. + + """ + data_dir = mypy.build.default_data_dir() + search_path = mypy.modulefinder.compute_search_paths([], options, data_dir) + find_module_cache = mypy.modulefinder.FindModuleCache( + search_path, fscache=None, options=options + ) + + all_modules = [] + sources = [] + for module in modules: + all_modules.append(module) + if not find_submodules: + module_path = find_module_cache.find_module(module) + if not isinstance(module_path, str): + # test_module will yield an error later when it can't find stubs + continue + sources.append(mypy.modulefinder.BuildSource(module_path, module, None)) + else: + found_sources = find_module_cache.find_modules_recursive(module) + sources.extend(found_sources) + # find submodules via mypy + all_modules.extend(s.module for s in found_sources if s.module not in all_modules) + # find submodules via pkgutil + try: + runtime = silent_import_module(module) + all_modules.extend( + m.name + for m in pkgutil.walk_packages(runtime.__path__, runtime.__name__ + ".") + if m.name not in all_modules + ) + except KeyboardInterrupt: + raise + except BaseException: + pass + + if sources: + try: + res = mypy.build.build(sources=sources, options=options) + except mypy.errors.CompileError as e: + raise StubtestFailure(f"failed mypy compile:\n{e}") from e + if res.errors: + raise StubtestFailure("mypy build errors:\n" + "\n".join(res.errors)) + + global _all_stubs + _all_stubs = res.files + + return all_modules + + +def get_stub(module: str) -> nodes.MypyFile | None: + """Returns a stub object for the given module, if we've built one.""" + return _all_stubs.get(module) + + +def get_typeshed_stdlib_modules( + custom_typeshed_dir: str | None, version_info: tuple[int, int] | None = None +) -> set[str]: + """Returns a list of stdlib modules in typeshed (for current Python version).""" + stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir) + if version_info is None: + version_info = sys.version_info[0:2] + + def exists_in_version(module: str) -> bool: + assert version_info is not None + parts = module.split(".") + for i in range(len(parts), 0, -1): + current_module = ".".join(parts[:i]) + if current_module in stdlib_py_versions: + minver, maxver = stdlib_py_versions[current_module] + return version_info >= minver and (maxver is None or version_info <= maxver) + return False + + if custom_typeshed_dir: + typeshed_dir = Path(custom_typeshed_dir) + else: + typeshed_dir = Path(mypy.build.default_data_dir()) / "typeshed" + stdlib_dir = typeshed_dir / "stdlib" + + modules: set[str] = set() + for path in stdlib_dir.rglob("*.pyi"): + if path.stem == "__init__": + path = path.parent + module = ".".join(path.relative_to(stdlib_dir).parts[:-1] + (path.stem,)) + if exists_in_version(module): + modules.add(module) + return modules + + +def get_importable_stdlib_modules() -> set[str]: + """Return all importable stdlib modules at runtime.""" + importable_stdlib_modules: set[str] = set() + for module_name in sys.stdlib_module_names: + if module_name in ANNOYING_STDLIB_MODULES: + continue + + try: + runtime = silent_import_module(module_name) + except ImportError: + continue + else: + importable_stdlib_modules.add(module_name) + + try: + # some stdlib modules (e.g. `nt`) don't have __path__ set... + runtime_path = runtime.__path__ + runtime_name = runtime.__name__ + except AttributeError: + continue + + for submodule in pkgutil.walk_packages(runtime_path, runtime_name + "."): + submodule_name = submodule.name + + # There are many annoying *.__main__ stdlib modules, + # and including stubs for them isn't really that useful anyway: + # tkinter.__main__ opens a tkinter windows; unittest.__main__ raises SystemExit; etc. + # + # The idlelib.* submodules are similarly annoying in opening random tkinter windows, + # and we're unlikely to ever add stubs for idlelib in typeshed + # (see discussion in https://github.com/python/typeshed/pull/9193) + # + # test.* modules do weird things like raising exceptions in __del__ methods, + # leading to unraisable exceptions being logged to the terminal + # as a warning at the end of the stubtest run + if submodule_name.endswith(".__main__") or submodule_name.startswith( + ("idlelib.", "test.") + ): + continue + + try: + silent_import_module(submodule_name) + except KeyboardInterrupt: + raise + # importing multiprocessing.popen_forkserver on Windows raises AttributeError... + # some submodules also appear to raise SystemExit as well on some Python versions + # (not sure exactly which) + except BaseException: + continue + else: + importable_stdlib_modules.add(submodule_name) + + return importable_stdlib_modules + + +def get_allowlist_entries(allowlist_file: str) -> Iterator[str]: + def strip_comments(s: str) -> str: + try: + return s[: s.index("#")].strip() + except ValueError: + return s.strip() + + with open(allowlist_file) as f: + for line in f: + entry = strip_comments(line) + if entry: + yield entry + + +class _Arguments: + modules: list[str] + concise: bool + ignore_missing_stub: bool + ignore_positional_only: bool + ignore_disjoint_bases: bool + strict_type_check_only: bool + allowlist: list[str] + generate_allowlist: bool + ignore_unused_allowlist: bool + mypy_config_file: str | None + custom_typeshed_dir: str | None + check_typeshed: bool + version: str + show_traceback: bool + pdb: bool + + +# typeshed added a stub for __main__, but that causes stubtest to check itself +ANNOYING_STDLIB_MODULES: Final = frozenset({"antigravity", "this", "__main__", "_ios_support"}) + + +def test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int: + """This is stubtest! It's time to test the stubs!""" + # Load the allowlist. This is a series of strings corresponding to Error.object_desc + # Values in the dict will store whether we used the allowlist entry or not. + allowlist = { + entry: False + for allowlist_file in args.allowlist + for entry in get_allowlist_entries(allowlist_file) + } + allowlist_regexes = {entry: re.compile(entry) for entry in allowlist} + + # If we need to generate an allowlist, we store Error.object_desc for each error here. + generated_allowlist = set() + + modules = args.modules + if args.check_typeshed: + if args.modules: + print( + _style("error:", color="red", bold=True), + "cannot pass both --check-typeshed and a list of modules", + ) + return 1 + typeshed_modules = get_typeshed_stdlib_modules(args.custom_typeshed_dir) + runtime_modules = get_importable_stdlib_modules() + modules = sorted((typeshed_modules | runtime_modules) - ANNOYING_STDLIB_MODULES) + + if not modules: + print(_style("error:", color="red", bold=True), "no modules to check") + return 1 + + options = Options() + options.incremental = False + options.custom_typeshed_dir = args.custom_typeshed_dir + if options.custom_typeshed_dir: + options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir) + options.config_file = args.mypy_config_file + options.use_builtins_fixtures = use_builtins_fixtures + options.show_traceback = args.show_traceback + options.pdb = args.pdb + options.pos_only_special_methods = False + + if options.config_file: + + def set_strict_flags() -> None: # not needed yet + return + + parse_config_file(options, set_strict_flags, options.config_file, sys.stdout, sys.stderr) + + def error_callback(msg: str) -> typing.NoReturn: + print(_style("error:", color="red", bold=True), msg) + sys.exit(1) + + def warning_callback(msg: str) -> None: + print(_style("warning:", color="yellow", bold=True), msg) + + options.process_error_codes(error_callback=error_callback) + options.process_incomplete_features( + error_callback=error_callback, warning_callback=warning_callback + ) + options.process_strict_bytes() + + try: + modules = build_stubs(modules, options, find_submodules=not args.check_typeshed) + except StubtestFailure as stubtest_failure: + print( + _style("error:", color="red", bold=True), + f"not checking stubs due to {stubtest_failure}", + ) + return 1 + + exit_code = 0 + error_count = 0 + for module in modules: + for error in test_module(module): + # Filter errors + if args.ignore_missing_stub and error.is_missing_stub(): + continue + if args.ignore_positional_only and error.is_positional_only_related(): + continue + if args.ignore_disjoint_bases and error.is_disjoint_base_related(): + continue + if not args.strict_type_check_only and error.is_private_type_check_only_related(): + continue + if error.object_desc in allowlist: + allowlist[error.object_desc] = True + continue + is_allowlisted = False + for w in allowlist: + if allowlist_regexes[w].fullmatch(error.object_desc): + allowlist[w] = True + is_allowlisted = True + break + if is_allowlisted: + continue + + # We have errors, so change exit code, and output whatever necessary + exit_code = 1 + if args.generate_allowlist: + generated_allowlist.add(error.object_desc) + continue + safe_print(error.get_description(concise=args.concise)) + error_count += 1 + + # Print unused allowlist entries + if not args.ignore_unused_allowlist: + for w in allowlist: + # Don't consider an entry unused if it regex-matches the empty string + # This lets us allowlist errors that don't manifest at all on some systems + if not allowlist[w] and not allowlist_regexes[w].fullmatch(""): + exit_code = 1 + error_count += 1 + print(f"note: unused allowlist entry {w}") + + # Print the generated allowlist + if args.generate_allowlist: + for e in sorted(generated_allowlist): + print(e) + exit_code = 0 + elif not args.concise: + if error_count: + print( + _style( + f"Found {error_count} error{plural_s(error_count)}" + f" (checked {len(modules)} module{plural_s(modules)})", + color="red", + bold=True, + ) + ) + else: + print( + _style( + f"Success: no issues found in {len(modules)} module{plural_s(modules)}", + color="green", + bold=True, + ) + ) + + return exit_code + + +def safe_print(text: str) -> None: + """Print a text replacing chars not representable in stdout encoding.""" + # If `sys.stdout` encoding is not the same as out (usually UTF8) string, + # if may cause painful crashes. I don't want to reconfigure `sys.stdout` + # to do `errors = "replace"` as that sounds scary. + out_encoding = sys.stdout.encoding + if out_encoding is not None: + # Can be None if stdout is replaced (including our own tests). This should be + # safe to omit if the actual stream doesn't care about encoding. + text = text.encode(out_encoding, errors="replace").decode(out_encoding, errors="replace") + print(text) + + +def parse_options(args: list[str]) -> _Arguments: + parser = argparse.ArgumentParser( + description="Compares stubs to objects introspected from the runtime." + ) + parser.add_argument("modules", nargs="*", help="Modules to test") + parser.add_argument( + "--concise", + action="store_true", + help="Makes stubtest's output more concise, one line per error", + ) + parser.add_argument( + "--ignore-missing-stub", + action="store_true", + help="Ignore errors for stub missing things that are present at runtime", + ) + parser.add_argument( + "--ignore-positional-only", + action="store_true", + help="Ignore errors for whether an argument should or shouldn't be positional-only", + ) + # TODO: Remove once PEP 800 is accepted + parser.add_argument( + "--ignore-disjoint-bases", + action="store_true", + help="Disable checks for PEP 800 @disjoint_base classes", + ) + parser.add_argument( + "--strict-type-check-only", + action="store_true", + help="Require @type_check_only on private types that are not present at runtime", + ) + parser.add_argument( + "--allowlist", + "--whitelist", + action="append", + metavar="FILE", + default=[], + help=( + "Use file as an allowlist. Can be passed multiple times to combine multiple " + "allowlists. Allowlists can be created with --generate-allowlist. Allowlists " + "support regular expressions." + ), + ) + parser.add_argument( + "--generate-allowlist", + "--generate-whitelist", + action="store_true", + help="Print an allowlist (to stdout) to be used with --allowlist", + ) + parser.add_argument( + "--ignore-unused-allowlist", + "--ignore-unused-whitelist", + action="store_true", + help="Ignore unused allowlist entries", + ) + parser.add_argument( + "--mypy-config-file", + metavar="FILE", + help=("Use specified mypy config file to determine mypy plugins and mypy path"), + ) + parser.add_argument( + "--custom-typeshed-dir", metavar="DIR", help="Use the custom typeshed in DIR" + ) + parser.add_argument( + "--check-typeshed", action="store_true", help="Check all stdlib modules in typeshed" + ) + parser.add_argument( + "--version", action="version", version="%(prog)s " + mypy.version.__version__ + ) + parser.add_argument("--pdb", action="store_true", help="Invoke pdb on fatal error") + parser.add_argument( + "--show-traceback", "--tb", action="store_true", help="Show traceback on fatal error" + ) + + return parser.parse_args(args, namespace=_Arguments()) + + +def main() -> int: + mypy.util.check_python_version("stubtest") + return test_stubs(parse_options(sys.argv[1:])) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubutil.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubutil.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c77d77e51b0058518d66a44ab7b27d58221e70af Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubutil.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubutil.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubutil.py new file mode 100644 index 0000000000000000000000000000000000000000..e8fcc4fc1829d547a4ea6dc1eb1939ca984a39b9 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/stubutil.py @@ -0,0 +1,895 @@ +"""Utilities for mypy.stubgen, mypy.stubgenc, and mypy.stubdoc modules.""" + +from __future__ import annotations + +import os.path +import re +import sys +import traceback +from abc import abstractmethod +from collections import defaultdict +from collections.abc import Iterable, Iterator, Mapping +from contextlib import contextmanager +from typing import Final, overload + +from mypy_extensions import mypyc_attr + +import mypy.options +from mypy.modulefinder import ModuleNotFoundReason +from mypy.moduleinspect import InspectError, ModuleInspect +from mypy.nodes import PARAM_SPEC_KIND, TYPE_VAR_TUPLE_KIND, ClassDef, FuncDef, TypeAliasStmt +from mypy.stubdoc import ArgSig, FunctionSig +from mypy.types import ( + AnyType, + NoneType, + Type, + TypeList, + TypeStrVisitor, + UnboundType, + UnionType, + UnpackType, +) + +# Modules that may fail when imported, or that may have side effects (fully qualified). +NOT_IMPORTABLE_MODULES: tuple[str, ...] = () + +# Typing constructs to be replaced by their builtin equivalents. +TYPING_BUILTIN_REPLACEMENTS: Final = { + # From typing + "typing.Text": "builtins.str", + "typing.Tuple": "builtins.tuple", + "typing.List": "builtins.list", + "typing.Dict": "builtins.dict", + "typing.Set": "builtins.set", + "typing.FrozenSet": "builtins.frozenset", + "typing.Type": "builtins.type", + # From typing_extensions + "typing_extensions.Text": "builtins.str", + "typing_extensions.Tuple": "builtins.tuple", + "typing_extensions.List": "builtins.list", + "typing_extensions.Dict": "builtins.dict", + "typing_extensions.Set": "builtins.set", + "typing_extensions.FrozenSet": "builtins.frozenset", + "typing_extensions.Type": "builtins.type", +} + + +class CantImport(Exception): + def __init__(self, module: str, message: str) -> None: + self.module = module + self.message = message + + +def walk_packages( + inspect: ModuleInspect, packages: list[str], verbose: bool = False +) -> Iterator[str]: + """Iterates through all packages and sub-packages in the given list. + + This uses runtime imports (in another process) to find both Python and C modules. + For Python packages we simply pass the __path__ attribute to pkgutil.walk_packages() to + get the content of the package (all subpackages and modules). However, packages in C + extensions do not have this attribute, so we have to roll out our own logic: recursively + find all modules imported in the package that have matching names. + """ + for package_name in packages: + if package_name in NOT_IMPORTABLE_MODULES: + print(f"{package_name}: Skipped (blacklisted)") + continue + if verbose: + print(f"Trying to import {package_name!r} for runtime introspection") + try: + prop = inspect.get_package_properties(package_name) + except InspectError: + if verbose: + tb = traceback.format_exc() + sys.stderr.write(tb) + report_missing(package_name) + continue + yield prop.name + if prop.is_c_module: + # Recursively iterate through the subpackages + yield from walk_packages(inspect, prop.subpackages, verbose) + else: + yield from prop.subpackages + + +def find_module_path_using_sys_path(module: str, sys_path: list[str]) -> str | None: + relative_candidates = ( + module.replace(".", "/") + ".py", + os.path.join(module.replace(".", "/"), "__init__.py"), + ) + for base in sys_path: + for relative_path in relative_candidates: + path = os.path.join(base, relative_path) + if os.path.isfile(path): + return path + return None + + +def find_module_path_and_all_py3( + inspect: ModuleInspect, module: str, verbose: bool +) -> tuple[str | None, list[str] | None] | None: + """Find module and determine __all__ for a Python 3 module. + + Return None if the module is a C or pyc-only module. + Return (module_path, __all__) if it is a Python module. + Raise CantImport if import failed. + """ + if module in NOT_IMPORTABLE_MODULES: + raise CantImport(module, "") + + # TODO: Support custom interpreters. + if verbose: + print(f"Trying to import {module!r} for runtime introspection") + try: + mod = inspect.get_package_properties(module) + except InspectError as e: + # Fall back to finding the module using sys.path. + path = find_module_path_using_sys_path(module, sys.path) + if path is None: + raise CantImport(module, str(e)) from e + return path, None + if mod.is_c_module: + return None + return mod.file, mod.all + + +@contextmanager +def generate_guarded( + mod: str, target: str, ignore_errors: bool = True, verbose: bool = False +) -> Iterator[None]: + """Ignore or report errors during stub generation. + + Optionally report success. + """ + if verbose: + print(f"Processing {mod}") + try: + yield + except Exception as e: + if not ignore_errors: + raise e + else: + # --ignore-errors was passed + print("Stub generation failed for", mod, file=sys.stderr) + else: + if verbose: + print(f"Created {target}") + + +def report_missing(mod: str, message: str | None = "", traceback: str = "") -> None: + if message: + message = " with error: " + message + print(f"{mod}: Failed to import, skipping{message}") + + +def fail_missing(mod: str, reason: ModuleNotFoundReason) -> None: + if reason is ModuleNotFoundReason.NOT_FOUND: + clarification = "(consider using --search-path)" + elif reason is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + clarification = "(module likely exists, but is not PEP 561 compatible)" + else: + clarification = f"(unknown reason '{reason}')" + raise SystemExit(f"Can't find module '{mod}' {clarification}") + + +@overload +def remove_misplaced_type_comments(source: bytes) -> bytes: ... + + +@overload +def remove_misplaced_type_comments(source: str) -> str: ... + + +def remove_misplaced_type_comments(source: str | bytes) -> str | bytes: + """Remove comments from source that could be understood as misplaced type comments. + + Normal comments may look like misplaced type comments, and since they cause blocking + parse errors, we want to avoid them. + """ + if isinstance(source, bytes): + # This gives us a 1-1 character code mapping, so it's roundtrippable. + text = source.decode("latin1") + else: + text = source + + # Remove something that looks like a variable type comment but that's by itself + # on a line, as it will often generate a parse error (unless it's # type: ignore). + text = re.sub(r'^[ \t]*# +type: +["\'a-zA-Z_].*$', "", text, flags=re.MULTILINE) + + # Remove something that looks like a function type comment after docstring, + # which will result in a parse error. + text = re.sub(r'""" *\n[ \t\n]*# +type: +\(.*$', '"""\n', text, flags=re.MULTILINE) + text = re.sub(r"''' *\n[ \t\n]*# +type: +\(.*$", "'''\n", text, flags=re.MULTILINE) + + # Remove something that looks like a badly formed function type comment. + text = re.sub(r"^[ \t]*# +type: +\([^()]+(\)[ \t]*)?$", "", text, flags=re.MULTILINE) + + if isinstance(source, bytes): + return text.encode("latin1") + else: + return text + + +def common_dir_prefix(paths: list[str]) -> str: + if not paths: + return "." + cur = os.path.dirname(os.path.normpath(paths[0])) + for path in paths[1:]: + while True: + path = os.path.dirname(os.path.normpath(path)) + if (cur + os.sep).startswith(path + os.sep): + cur = path + break + return cur or "." + + +class AnnotationPrinter(TypeStrVisitor): + """Visitor used to print existing annotations in a file. + + The main difference from TypeStrVisitor is a better treatment of + unbound types. + + Notes: + * This visitor doesn't add imports necessary for annotations, this is done separately + by ImportTracker. + * It can print all kinds of types, but the generated strings may not be valid (notably + callable types) since it prints the same string that reveal_type() does. + * For Instance types it prints the fully qualified names. + """ + + # TODO: Generate valid string representation for callable types. + # TODO: Use short names for Instances. + def __init__( + self, + stubgen: BaseStubGenerator, + known_modules: list[str] | None = None, + local_modules: list[str] | None = None, + ) -> None: + super().__init__(options=mypy.options.Options()) + self.stubgen = stubgen + self.known_modules = known_modules + self.local_modules = local_modules or ["builtins"] + + def visit_any(self, t: AnyType) -> str: + s = super().visit_any(t) + self.stubgen.import_tracker.require_name(s) + return s + + def visit_unbound_type(self, t: UnboundType) -> str: + s = t.name + fullname = self.stubgen.resolve_name(s) + if fullname == "typing.Union": + return " | ".join([item.accept(self) for item in t.args]) + if fullname == "typing.Optional": + if len(t.args) == 1: + return f"{t.args[0].accept(self)} | None" + return self.stubgen.add_name("_typeshed.Incomplete") + if fullname in TYPING_BUILTIN_REPLACEMENTS: + s = self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=True) + if self.known_modules is not None and "." in s: + # see if this object is from any of the modules that we're currently processing. + # reverse sort so that subpackages come before parents: e.g. "foo.bar" before "foo". + for module_name in self.local_modules + sorted(self.known_modules, reverse=True): + if s.startswith(module_name + "."): + if module_name in self.local_modules: + s = s[len(module_name) + 1 :] + arg_module = module_name + break + else: + arg_module = s[: s.rindex(".")] + if arg_module not in self.local_modules: + self.stubgen.import_tracker.add_import(arg_module, require=True) + elif s == "NoneType": + # when called without analysis all types are unbound, so this won't hit + # visit_none_type(). + s = "None" + else: + self.stubgen.import_tracker.require_name(s) + if t.args: + s += f"[{self.args_str(t.args)}]" + elif t.empty_tuple_index: + s += "[()]" + return s + + def visit_none_type(self, t: NoneType) -> str: + return "None" + + def visit_type_list(self, t: TypeList) -> str: + return f"[{self.list_str(t.items)}]" + + def visit_union_type(self, t: UnionType) -> str: + return " | ".join([item.accept(self) for item in t.items]) + + def visit_unpack_type(self, t: UnpackType) -> str: + if self.options.python_version >= (3, 11): + return f"*{t.type.accept(self)}" + return super().visit_unpack_type(t) + + def args_str(self, args: Iterable[Type]) -> str: + """Convert an array of arguments to strings and join the results with commas. + + The main difference from list_str is the preservation of quotes for string + arguments + """ + types = ["builtins.bytes", "builtins.str"] + res = [] + for arg in args: + arg_str = arg.accept(self) + if isinstance(arg, UnboundType) and arg.original_str_fallback in types: + res.append(f"'{arg_str}'") + else: + res.append(arg_str) + return ", ".join(res) + + +class ClassInfo: + def __init__( + self, + name: str, + self_var: str, + docstring: str | None = None, + cls: type | None = None, + parent: ClassInfo | None = None, + ) -> None: + self.name = name + self.self_var = self_var + self.docstring = docstring + self.cls = cls + self.parent = parent + + +class FunctionContext: + def __init__( + self, + module_name: str, + name: str, + docstring: str | None = None, + is_abstract: bool = False, + class_info: ClassInfo | None = None, + ) -> None: + self.module_name = module_name + self.name = name + self.docstring = docstring + self.is_abstract = is_abstract + self.class_info = class_info + self._fullname: str | None = None + + @property + def fullname(self) -> str: + if self._fullname is None: + if self.class_info: + parents = [] + class_info: ClassInfo | None = self.class_info + while class_info is not None: + parents.append(class_info.name) + class_info = class_info.parent + namespace = ".".join(reversed(parents)) + self._fullname = f"{self.module_name}.{namespace}.{self.name}" + else: + self._fullname = f"{self.module_name}.{self.name}" + return self._fullname + + +def infer_method_ret_type(name: str) -> str | None: + """Infer return types for known special methods""" + if name.startswith("__") and name.endswith("__"): + name = name[2:-2] + if name in ("float", "bool", "bytes", "int", "complex", "str"): + return name + # Note: __eq__ and co may return arbitrary types, but bool is good enough for stubgen. + elif name in ("eq", "ne", "lt", "le", "gt", "ge", "contains"): + return "bool" + elif name in ("len", "length_hint", "index", "hash", "sizeof", "trunc", "floor", "ceil"): + return "int" + elif name in ("format", "repr"): + return "str" + elif name in ("init", "setitem", "del", "delitem"): + return "None" + return None + + +def infer_method_arg_types( + name: str, self_var: str = "self", arg_names: list[str] | None = None +) -> list[ArgSig] | None: + """Infer argument types for known special methods""" + args: list[ArgSig] | None = None + if name.startswith("__") and name.endswith("__"): + if arg_names and len(arg_names) >= 1 and arg_names[0] == "self": + arg_names = arg_names[1:] + + name = name[2:-2] + if name == "exit": + if arg_names is None: + arg_names = ["type", "value", "traceback"] + if len(arg_names) == 3: + arg_types = [ + "type[BaseException] | None", + "BaseException | None", + "types.TracebackType | None", + ] + args = [ + ArgSig(name=arg_name, type=arg_type) + for arg_name, arg_type in zip(arg_names, arg_types) + ] + if args is not None: + return [ArgSig(name=self_var)] + args + return None + + +@mypyc_attr(allow_interpreted_subclasses=True) +class SignatureGenerator: + """Abstract base class for extracting a list of FunctionSigs for each function.""" + + def remove_self_type( + self, inferred: list[FunctionSig] | None, self_var: str + ) -> list[FunctionSig] | None: + """Remove type annotation from self/cls argument""" + if inferred: + for signature in inferred: + if signature.args: + if signature.args[0].name == self_var: + signature.args[0].type = None + return inferred + + @abstractmethod + def get_function_sig( + self, default_sig: FunctionSig, ctx: FunctionContext + ) -> list[FunctionSig] | None: + """Return a list of signatures for the given function. + + If no signature can be found, return None. If all of the registered SignatureGenerators + for the stub generator return None, then the default_sig will be used. + """ + pass + + @abstractmethod + def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None: + """Return the type of the given property""" + pass + + +class ImportTracker: + """Record necessary imports during stub generation.""" + + def __init__(self) -> None: + # module_for['foo'] has the module name where 'foo' was imported from, or None if + # 'foo' is a module imported directly; + # direct_imports['foo'] is the module path used when the name 'foo' was added to the + # namespace. + # reverse_alias['foo'] is the name that 'foo' had originally when imported with an + # alias; examples + # 'from pkg import mod' ==> module_for['mod'] == 'pkg' + # 'from pkg import mod as m' ==> module_for['m'] == 'pkg' + # ==> reverse_alias['m'] == 'mod' + # 'import pkg.mod as m' ==> module_for['m'] == None + # ==> reverse_alias['m'] == 'pkg.mod' + # 'import pkg.mod' ==> module_for['pkg'] == None + # ==> module_for['pkg.mod'] == None + # ==> direct_imports['pkg'] == 'pkg.mod' + # ==> direct_imports['pkg.mod'] == 'pkg.mod' + self.module_for: dict[str, str | None] = {} + self.direct_imports: dict[str, str] = {} + self.reverse_alias: dict[str, str] = {} + + # required_names is the set of names that are actually used in a type annotation + self.required_names: set[str] = set() + + # Names that should be reexported if they come from another module + self.reexports: set[str] = set() + + def add_import_from( + self, module: str, names: list[tuple[str, str | None]], require: bool = False + ) -> None: + for name, alias in names: + if alias: + # 'from {module} import {name} as {alias}' + self.module_for[alias] = module + self.reverse_alias[alias] = name + else: + # 'from {module} import {name}' + self.module_for[name] = module + self.reverse_alias.pop(name, None) + if require: + self.require_name(alias or name) + self.direct_imports.pop(alias or name, None) + + def add_import(self, module: str, alias: str | None = None, require: bool = False) -> None: + if alias: + # 'import {module} as {alias}' + assert "." not in alias # invalid syntax + self.module_for[alias] = None + self.reverse_alias[alias] = module + if require: + self.required_names.add(alias) + else: + # 'import {module}' + name = module + if require: + self.required_names.add(name) + # add module and its parent packages + while name: + self.module_for[name] = None + self.direct_imports[name] = module + self.reverse_alias.pop(name, None) + name = name.rpartition(".")[0] + + def require_name(self, name: str) -> None: + while name not in self.direct_imports and "." in name: + name = name.rsplit(".", 1)[0] + self.required_names.add(name) + + def reexport(self, name: str) -> None: + """Mark a given non qualified name as needed in __all__. + + This means that in case it comes from a module, it should be + imported with an alias even if the alias is the same as the name. + """ + self.require_name(name) + self.reexports.add(name) + + def import_lines(self) -> list[str]: + """The list of required import lines (as strings with python code). + + In order for a module be included in this output, an identifier must be both + 'required' via require_name() and 'imported' via add_import_from() + or add_import() + """ + result = [] + + # To summarize multiple names imported from a same module, we collect those + # in the `module_map` dictionary, mapping a module path to the list of names that should + # be imported from it. the names can also be alias in the form 'original as alias' + module_map: Mapping[str, list[str]] = defaultdict(list) + + for name in sorted( + self.required_names, + key=lambda n: (self.reverse_alias[n], n) if n in self.reverse_alias else (n, ""), + ): + # If we haven't seen this name in an import statement, ignore it + if name not in self.module_for: + continue + + m = self.module_for[name] + if m is not None: + # This name was found in a from ... import ... + # Collect the name in the module_map + if name in self.reverse_alias: + name = f"{self.reverse_alias[name]} as {name}" + elif name in self.reexports: + name = f"{name} as {name}" + module_map[m].append(name) + else: + # This name was found in an import ... + # We can already generate the import line + if name in self.reverse_alias: + source = self.reverse_alias[name] + result.append(f"import {source} as {name}\n") + elif name in self.reexports: + assert "." not in name # Because reexports only has nonqualified names + result.append(f"import {name} as {name}\n") + else: + result.append(f"import {name}\n") + + # Now generate all the from ... import ... lines collected in module_map + for module, names in sorted(module_map.items()): + result.append(f"from {module} import {', '.join(sorted(names))}\n") + return result + + +@mypyc_attr(allow_interpreted_subclasses=True) +class BaseStubGenerator: + # These names should be omitted from generated stubs. + IGNORED_DUNDERS: Final = { + "__all__", + "__author__", + "__about__", + "__copyright__", + "__email__", + "__license__", + "__summary__", + "__title__", + "__uri__", + "__str__", + "__repr__", + "__getstate__", + "__setstate__", + "__slots__", + "__builtins__", + "__cached__", + "__file__", + "__name__", + "__package__", + "__path__", + "__spec__", + "__loader__", + } + TYPING_MODULE_NAMES: Final = ("typing", "typing_extensions") + # Special-cased names that are implicitly exported from the stub (from m import y as y). + EXTRA_EXPORTED: Final = { + "pyasn1_modules.rfc2437.univ", + "pyasn1_modules.rfc2459.char", + "pyasn1_modules.rfc2459.univ", + } + + def __init__( + self, + _all_: list[str] | None = None, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + ) -> None: + # Best known value of __all__. + self._all_ = _all_ + self._include_private = include_private + self._include_docstrings = include_docstrings + # Disable implicit exports of package-internal imports? + self.export_less = export_less + self._import_lines: list[str] = [] + self._output: list[str] = [] + # Current indent level (indent is hardcoded to 4 spaces). + self._indent = "" + self._toplevel_names: list[str] = [] + self.import_tracker = ImportTracker() + # Top-level members + self.defined_names: set[str] = set() + self.sig_generators = self.get_sig_generators() + # populated by visit_mypy_file + self.module_name: str = "" + # These are "soft" imports for objects which might appear in annotations but not have + # a corresponding import statement. + self.known_imports = { + "_typeshed": ["Incomplete"], + "typing": ["Any", "TypeVar", "NamedTuple", "TypedDict"], + "collections.abc": ["Generator"], + "typing_extensions": ["ParamSpec", "TypeVarTuple"], + } + + def get_sig_generators(self) -> list[SignatureGenerator]: + return [] + + def resolve_name(self, name: str) -> str: + """Return the full name resolving imports and import aliases.""" + if "." not in name: + real_module = self.import_tracker.module_for.get(name) + real_short = self.import_tracker.reverse_alias.get(name, name) + if real_module is None and real_short not in self.defined_names: + real_module = "builtins" # not imported and not defined, must be a builtin + else: + name_module, real_short = name.split(".", 1) + real_module = self.import_tracker.reverse_alias.get(name_module, name_module) + resolved_name = real_short if real_module is None else f"{real_module}.{real_short}" + return resolved_name + + def add_name(self, fullname: str, require: bool = True) -> str: + """Add a name to be imported and return the name reference. + + The import will be internal to the stub (i.e don't reexport). + """ + module, name = fullname.rsplit(".", 1) + alias = "_" + name if name in self.defined_names else None + while alias in self.defined_names: + alias = "_" + alias + if module != "builtins" or alias: # don't import from builtins unless needed + self.import_tracker.add_import_from(module, [(name, alias)], require=require) + return alias or name + + def add_import_line(self, line: str) -> None: + """Add a line of text to the import section, unless it's already there.""" + if line not in self._import_lines: + self._import_lines.append(line) + + def get_imports(self) -> str: + """Return the import statements for the stub.""" + imports = "" + if self._import_lines: + imports += "".join(self._import_lines) + imports += "".join(self.import_tracker.import_lines()) + return imports + + def output(self) -> str: + """Return the text for the stub.""" + pieces: list[str] = [] + if imports := self.get_imports(): + pieces.append(imports) + if dunder_all := self.get_dunder_all(): + pieces.append(dunder_all) + if self._output: + pieces.append("".join(self._output)) + return "\n".join(pieces) + + def get_dunder_all(self) -> str: + """Return the __all__ list for the stub.""" + if self._all_: + # Note we emit all names in the runtime __all__ here, even if they + # don't actually exist. If that happens, the runtime has a bug, and + # it's not obvious what the correct behavior should be. We choose + # to reflect the runtime __all__ as closely as possible. + return f"__all__ = {self._all_!r}\n" + return "" + + def add(self, string: str) -> None: + """Add text to generated stub.""" + self._output.append(string) + + def is_top_level(self) -> bool: + """Are we processing the top level of a file?""" + return self._indent == "" + + def indent(self) -> None: + """Add one level of indentation.""" + self._indent += " " + + def dedent(self) -> None: + """Remove one level of indentation.""" + self._indent = self._indent[:-4] + + def record_name(self, name: str) -> None: + """Mark a name as defined. + + This only does anything if at the top level of a module. + """ + if self.is_top_level(): + self._toplevel_names.append(name) + + def is_recorded_name(self, name: str) -> bool: + """Has this name been recorded previously?""" + return self.is_top_level() and name in self._toplevel_names + + def set_defined_names(self, defined_names: set[str]) -> None: + self.defined_names = defined_names + # Names in __all__ are required + for name in self._all_ or (): + self.import_tracker.reexport(name) + + for pkg, imports in self.known_imports.items(): + for t in imports: + # require=False means that the import won't be added unless require_name() is called + # for the object during generation. + self.add_name(f"{pkg}.{t}", require=False) + + def check_undefined_names(self) -> None: + undefined_names = [name for name in self._all_ or [] if name not in self._toplevel_names] + if undefined_names: + if self._output: + self.add("\n") + self.add("# Names in __all__ with no definition:\n") + for name in sorted(undefined_names): + self.add(f"# {name}\n") + + def get_signatures( + self, + default_signature: FunctionSig, + sig_generators: list[SignatureGenerator], + func_ctx: FunctionContext, + ) -> list[FunctionSig]: + for sig_gen in sig_generators: + inferred = sig_gen.get_function_sig(default_signature, func_ctx) + if inferred: + return inferred + + return [default_signature] + + def get_property_type( + self, + default_type: str | None, + sig_generators: list[SignatureGenerator], + func_ctx: FunctionContext, + ) -> str | None: + for sig_gen in sig_generators: + inferred = sig_gen.get_property_type(default_type, func_ctx) + if inferred: + return inferred + + return default_type + + def format_func_def( + self, + sigs: list[FunctionSig], + is_coroutine: bool = False, + decorators: list[str] | None = None, + docstring: str | None = None, + ) -> list[str]: + lines: list[str] = [] + if decorators is None: + decorators = [] + + for signature in sigs: + # dump decorators, just before "def ..." + for deco in decorators: + lines.append(f"{self._indent}{deco}") + + lines.append( + signature.format_sig( + indent=self._indent, + is_async=is_coroutine, + docstring=docstring, + include_docstrings=self._include_docstrings, + ) + ) + return lines + + def format_type_args(self, o: TypeAliasStmt | FuncDef | ClassDef) -> str: + if not o.type_args: + return "" + p = AnnotationPrinter(self) + type_args_list: list[str] = [] + for type_arg in o.type_args: + if type_arg.kind == PARAM_SPEC_KIND: + prefix = "**" + elif type_arg.kind == TYPE_VAR_TUPLE_KIND: + prefix = "*" + else: + prefix = "" + if type_arg.upper_bound: + bound_or_values = f": {type_arg.upper_bound.accept(p)}" + elif type_arg.values: + bound_or_values = f": ({', '.join(v.accept(p) for v in type_arg.values)})" + else: + bound_or_values = "" + if type_arg.default: + default = f" = {type_arg.default.accept(p)}" + else: + default = "" + type_args_list.append(f"{prefix}{type_arg.name}{bound_or_values}{default}") + return "[" + ", ".join(type_args_list) + "]" + + def print_annotation( + self, + t: Type, + known_modules: list[str] | None = None, + local_modules: list[str] | None = None, + ) -> str: + printer = AnnotationPrinter(self, known_modules, local_modules) + return t.accept(printer) + + def is_not_in_all(self, name: str) -> bool: + if self.is_private_name(name): + return False + if self._all_: + return self.is_top_level() and name not in self._all_ + return False + + def is_private_name(self, name: str, fullname: str | None = None) -> bool: + if "__mypy-" in name: + return True # Never include mypy generated symbols + if self._include_private: + return False + if fullname in self.EXTRA_EXPORTED: + return False + if name == "_": + return False + if not name.startswith("_"): + return False + if self._all_ and name in self._all_: + return False + if name.startswith("__") and name.endswith("__"): + return name in self.IGNORED_DUNDERS + return True + + def should_reexport(self, name: str, full_module: str, name_is_alias: bool) -> bool: + if ( + not name_is_alias + and self.module_name + and (self.module_name + "." + name) in self.EXTRA_EXPORTED + ): + # Special case certain names that should be exported, against our general rules. + return True + if name_is_alias: + return False + if self.export_less: + return False + if not self.module_name: + return False + is_private = self.is_private_name(name, full_module + "." + name) + if is_private: + return False + top_level = full_module.split(".")[0] + self_top_level = self.module_name.split(".", 1)[0] + if top_level not in (self_top_level, "_" + self_top_level): + # Export imports from the same package, since we can't reliably tell whether they + # are part of the public API. + return False + if self._all_: + return name in self._all_ + return True diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/subtypes.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/subtypes.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e87225bd9c26686ee35f377995aa5f2a09f24976 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/subtypes.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/subtypes.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/subtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..66d7a95eb42525b1be163ab2fbfdc547b3bd4280 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/subtypes.py @@ -0,0 +1,2318 @@ +from __future__ import annotations + +from collections.abc import Callable, Iterable, Iterator +from contextlib import contextmanager +from typing import Any, Final, TypeAlias as _TypeAlias, TypeVar, cast + +import mypy.applytype +import mypy.constraints +import mypy.typeops +from mypy.checker_state import checker_state +from mypy.erasetype import erase_type +from mypy.expandtype import ( + expand_self_type, + expand_type, + expand_type_by_instance, + freshen_function_type_vars, +) +from mypy.maptype import map_instance_to_supertype + +# Circular import; done in the function instead. +# import mypy.solve +from mypy.nodes import ( + ARG_STAR, + ARG_STAR2, + CONTRAVARIANT, + COVARIANT, + INVARIANT, + VARIANCE_NOT_READY, + Context, + Decorator, + FuncBase, + OverloadedFuncDef, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.state import state +from mypy.types import ( + MYPYC_NATIVE_INT_NAMES, + TUPLE_LIKE_INSTANCE_NAMES, + TYPED_NAMEDTUPLE_NAMES, + AnyType, + CallableType, + DeletedType, + ErasedType, + FormalArgument, + FunctionLike, + Instance, + LiteralType, + NoneType, + NormalizedCallableType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + flatten_nested_unions, + get_proper_type, + is_named_instance, + split_with_prefix_and_suffix, +) +from mypy.types_utils import flatten_types +from mypy.typestate import SubtypeKind, type_state +from mypy.typevars import fill_typevars, fill_typevars_with_any + +# Flags for detected protocol members +IS_SETTABLE: Final = 1 +IS_CLASSVAR: Final = 2 +IS_CLASS_OR_STATIC: Final = 3 +IS_VAR: Final = 4 +IS_EXPLICIT_SETTER: Final = 5 + +TypeParameterChecker: _TypeAlias = Callable[[Type, Type, int, bool, "SubtypeContext"], bool] + + +class SubtypeContext: + def __init__( + self, + *, + # Non-proper subtype flags + ignore_type_params: bool = False, + ignore_pos_arg_names: bool = False, + ignore_declared_variance: bool = False, + # Supported for both proper and non-proper + always_covariant: bool = False, + ignore_promotions: bool = False, + # Proper subtype flags + erase_instances: bool = False, + keep_erased_types: bool = False, + options: Options | None = None, + ) -> None: + self.ignore_type_params = ignore_type_params + self.ignore_pos_arg_names = ignore_pos_arg_names + self.ignore_declared_variance = ignore_declared_variance + self.always_covariant = always_covariant + self.ignore_promotions = ignore_promotions + self.erase_instances = erase_instances + self.keep_erased_types = keep_erased_types + self.options = options + + def check_context(self, proper_subtype: bool) -> None: + # Historically proper and non-proper subtypes were defined using different helpers + # and different visitors. Check if flag values are such that we definitely support. + if proper_subtype: + assert not self.ignore_pos_arg_names and not self.ignore_declared_variance + else: + assert not self.erase_instances and not self.keep_erased_types + + +def is_subtype( + left: Type, + right: Type, + *, + subtype_context: SubtypeContext | None = None, + ignore_type_params: bool = False, + ignore_pos_arg_names: bool = False, + ignore_declared_variance: bool = False, + always_covariant: bool = False, + ignore_promotions: bool = False, + options: Options | None = None, +) -> bool: + """Is 'left' subtype of 'right'? + + Also consider Any to be a subtype of any type, and vice versa. This + recursively applies to components of composite types (List[int] is subtype + of List[Any], for example). + + type_parameter_checker is used to check the type parameters (for example, + A with B in is_subtype(C[A], C[B]). The default checks for subtype relation + between the type arguments (e.g., A and B), taking the variance of the + type var into account. + """ + if left == right: + return True + if subtype_context is None: + subtype_context = SubtypeContext( + ignore_type_params=ignore_type_params, + ignore_pos_arg_names=ignore_pos_arg_names, + ignore_declared_variance=ignore_declared_variance, + always_covariant=always_covariant, + ignore_promotions=ignore_promotions, + options=options, + ) + else: + assert ( + not ignore_type_params + and not ignore_pos_arg_names + and not ignore_declared_variance + and not always_covariant + and not ignore_promotions + and options is None + ), "Don't pass both context and individual flags" + if type_state.is_assumed_subtype(left, right): + return True + if mypy.typeops.is_recursive_pair(left, right): + # This case requires special care because it may cause infinite recursion. + # Our view on recursive types is known under a fancy name of iso-recursive mu-types. + # Roughly this means that a recursive type is defined as an alias where right hand side + # can refer to the type as a whole, for example: + # A = Union[int, Tuple[A, ...]] + # and an alias unrolled once represents the *same type*, in our case all these represent + # the same type: + # A + # Union[int, Tuple[A, ...]] + # Union[int, Tuple[Union[int, Tuple[A, ...]], ...]] + # The algorithm for subtyping is then essentially under the assumption that left <: right, + # check that get_proper_type(left) <: get_proper_type(right). On the example above, + # If we start with: + # A = Union[int, Tuple[A, ...]] + # B = Union[int, Tuple[B, ...]] + # When checking if A <: B we push pair (A, B) onto 'assuming' stack, then when after few + # steps we come back to initial call is_subtype(A, B) and immediately return True. + with pop_on_exit(type_state.get_assumptions(is_proper=False), left, right): + return _is_subtype(left, right, subtype_context, proper_subtype=False) + return _is_subtype(left, right, subtype_context, proper_subtype=False) + + +def is_proper_subtype( + left: Type, + right: Type, + *, + subtype_context: SubtypeContext | None = None, + ignore_promotions: bool = False, + erase_instances: bool = False, + keep_erased_types: bool = False, +) -> bool: + """Is left a proper subtype of right? + + For proper subtypes, there's no need to rely on compatibility due to + Any types. Every usable type is a proper subtype of itself. + + If erase_instances is True, erase left instance *after* mapping it to supertype + (this is useful for runtime isinstance() checks). If keep_erased_types is True, + do not consider ErasedType a subtype of all types (used by type inference against unions). + """ + if left == right: + return True + if subtype_context is None: + subtype_context = SubtypeContext( + ignore_promotions=ignore_promotions, + erase_instances=erase_instances, + keep_erased_types=keep_erased_types, + ) + else: + assert ( + not ignore_promotions and not erase_instances and not keep_erased_types + ), "Don't pass both context and individual flags" + if type_state.is_assumed_proper_subtype(left, right): + return True + if mypy.typeops.is_recursive_pair(left, right): + # Same as for non-proper subtype, see detailed comment there for explanation. + with pop_on_exit(type_state.get_assumptions(is_proper=True), left, right): + return _is_subtype(left, right, subtype_context, proper_subtype=True) + return _is_subtype(left, right, subtype_context, proper_subtype=True) + + +def is_equivalent( + a: Type, + b: Type, + *, + ignore_type_params: bool = False, + ignore_pos_arg_names: bool = False, + options: Options | None = None, + subtype_context: SubtypeContext | None = None, +) -> bool: + return is_subtype( + a, + b, + ignore_type_params=ignore_type_params, + ignore_pos_arg_names=ignore_pos_arg_names, + options=options, + subtype_context=subtype_context, + ) and is_subtype( + b, + a, + ignore_type_params=ignore_type_params, + ignore_pos_arg_names=ignore_pos_arg_names, + options=options, + subtype_context=subtype_context, + ) + + +def is_same_type( + a: Type, b: Type, ignore_promotions: bool = True, subtype_context: SubtypeContext | None = None +) -> bool: + """Are these types proper subtypes of each other? + + This means types may have different representation (e.g. an alias, or + a non-simplified union) but are semantically exchangeable in all contexts. + """ + # First, use fast path for some common types. This is performance-critical. + if ( + type(a) is Instance + and type(b) is Instance + and a.type == b.type + and len(a.args) == len(b.args) + and a.last_known_value is b.last_known_value + ): + return all(is_same_type(x, y) for x, y in zip(a.args, b.args)) + elif ( + isinstance(a, TypeVarType) + and isinstance(b, TypeVarType) + and a.id == b.id + and a.upper_bound == b.upper_bound + ): + return True + + # Note that using ignore_promotions=True (default) makes types like int and int64 + # considered not the same type (which is the case at runtime). + # Also Union[bool, int] (if it wasn't simplified before) will be different + # from plain int, etc. + return is_proper_subtype( + a, b, ignore_promotions=ignore_promotions, subtype_context=subtype_context + ) and is_proper_subtype( + b, a, ignore_promotions=ignore_promotions, subtype_context=subtype_context + ) + + +# This is a common entry point for subtyping checks (both proper and non-proper). +# Never call this private function directly, use the public versions. +def _is_subtype( + left: Type, right: Type, subtype_context: SubtypeContext, proper_subtype: bool +) -> bool: + subtype_context.check_context(proper_subtype) + orig_right = right + orig_left = left + left = get_proper_type(left) + right = get_proper_type(right) + + # Note: Unpack type should not be a subtype of Any, since it may represent + # multiple types. This should always go through the visitor, to check arity. + if ( + not proper_subtype + and isinstance(right, (AnyType, UnboundType, ErasedType)) + and not isinstance(left, UnpackType) + ): + # TODO: should we consider all types proper subtypes of UnboundType and/or + # ErasedType as we do for non-proper subtyping. + return True + + if isinstance(right, UnionType) and not isinstance(left, UnionType): + # Normally, when 'left' is not itself a union, the only way + # 'left' can be a subtype of the union 'right' is if it is a + # subtype of one of the items making up the union. + if proper_subtype: + is_subtype_of_item = any( + is_proper_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + else: + is_subtype_of_item = any( + is_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + # Recombine rhs literal types, to make an enum type a subtype + # of a union of all enum items as literal types. Only do it if + # the previous check didn't succeed, since recombining can be + # expensive. + # `bool` is a special case, because `bool` is `Literal[True, False]`. + if ( + not is_subtype_of_item + and isinstance(left, Instance) + and (left.type.is_enum or left.type.fullname == "builtins.bool") + ): + right = UnionType( + mypy.typeops.try_contracting_literals_in_union(flatten_nested_unions(right.items)) + ) + if proper_subtype: + is_subtype_of_item = any( + is_proper_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + else: + is_subtype_of_item = any( + is_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + # However, if 'left' is a type variable T, T might also have + # an upper bound which is itself a union. This case will be + # handled below by the SubtypeVisitor. We have to check both + # possibilities, to handle both cases like T <: Union[T, U] + # and cases like T <: B where B is the upper bound of T and is + # a union. (See #2314.) + if not isinstance(left, TypeVarType): + return is_subtype_of_item + elif is_subtype_of_item: + return True + # otherwise, fall through + return left.accept(SubtypeVisitor(orig_right, subtype_context, proper_subtype)) + + +def check_type_parameter( + left: Type, right: Type, variance: int, proper_subtype: bool, subtype_context: SubtypeContext +) -> bool: + # It is safe to consider empty collection literals and similar as covariant, since + # such type can't be stored in a variable, see checker.is_valid_inferred_type(). + if variance == INVARIANT: + p_left = get_proper_type(left) + if isinstance(p_left, UninhabitedType) and p_left.ambiguous: + variance = COVARIANT + # If variance hasn't been inferred yet, we are lenient and default to + # covariance. This shouldn't happen often, but it's very difficult to + # avoid these cases altogether. + if variance == COVARIANT or variance == VARIANCE_NOT_READY: + if proper_subtype: + return is_proper_subtype(left, right, subtype_context=subtype_context) + else: + return is_subtype(left, right, subtype_context=subtype_context) + elif variance == CONTRAVARIANT: + if proper_subtype: + return is_proper_subtype(right, left, subtype_context=subtype_context) + else: + return is_subtype(right, left, subtype_context=subtype_context) + else: + if proper_subtype: + # We pass ignore_promotions=False because it is a default for subtype checks. + # The actual value will be taken from the subtype_context, and it is whatever + # the original caller passed. + return is_same_type( + left, right, ignore_promotions=False, subtype_context=subtype_context + ) + else: + return is_equivalent(left, right, subtype_context=subtype_context) + + +class SubtypeVisitor(TypeVisitor[bool]): + __slots__ = ( + "right", + "orig_right", + "proper_subtype", + "subtype_context", + "options", + "_subtype_kind", + ) + + def __init__(self, right: Type, subtype_context: SubtypeContext, proper_subtype: bool) -> None: + self.right = get_proper_type(right) + self.orig_right = right + self.proper_subtype = proper_subtype + self.subtype_context = subtype_context + self.options = subtype_context.options + self._subtype_kind = SubtypeVisitor.build_subtype_kind(subtype_context, proper_subtype) + + @staticmethod + def build_subtype_kind(subtype_context: SubtypeContext, proper_subtype: bool) -> SubtypeKind: + return ( + state.strict_optional, + proper_subtype, + subtype_context.ignore_type_params, + subtype_context.ignore_pos_arg_names, + subtype_context.ignore_declared_variance, + subtype_context.always_covariant, + subtype_context.ignore_promotions, + subtype_context.erase_instances, + subtype_context.keep_erased_types, + ) + + def _is_subtype(self, left: Type, right: Type) -> bool: + if self.proper_subtype: + return is_proper_subtype(left, right, subtype_context=self.subtype_context) + return is_subtype(left, right, subtype_context=self.subtype_context) + + def _all_subtypes(self, lefts: Iterable[Type], rights: Iterable[Type]) -> bool: + return all(self._is_subtype(li, ri) for (li, ri) in zip(lefts, rights)) + + # visit_x(left) means: is left (which is an instance of X) a subtype of right? + + def visit_unbound_type(self, left: UnboundType) -> bool: + # This can be called if there is a bad type annotation. The result probably + # doesn't matter much but by returning True we simplify these bad types away + # from unions, which could filter out some bogus messages. + return True + + def visit_any(self, left: AnyType) -> bool: + return isinstance(self.right, AnyType) if self.proper_subtype else True + + def visit_none_type(self, left: NoneType) -> bool: + if state.strict_optional: + if isinstance(self.right, NoneType) or is_named_instance( + self.right, "builtins.object" + ): + return True + if isinstance(self.right, Instance) and self.right.type.is_protocol: + members = self.right.type.protocol_members + # None is compatible with Hashable (and other similar protocols). This is + # slightly sloppy since we don't check the signature of "__hash__". + # None is also compatible with `SupportsStr` protocol. + return not members or all(member in ("__hash__", "__str__") for member in members) + return False + else: + return True + + def visit_uninhabited_type(self, left: UninhabitedType) -> bool: + return True + + def visit_erased_type(self, left: ErasedType) -> bool: + # This may be encountered during type inference. The result probably doesn't + # matter much. + # TODO: it actually does matter, figure out more principled logic about this. + return not self.subtype_context.keep_erased_types + + def visit_deleted_type(self, left: DeletedType) -> bool: + return True + + def visit_instance(self, left: Instance) -> bool: + if left.type.fallback_to_any and not self.proper_subtype: + # NOTE: `None` is a *non-subclassable* singleton, therefore no class + # can by a subtype of it, even with an `Any` fallback. + # This special case is needed to treat descriptors in classes with + # dynamic base classes correctly, see #5456. + return not isinstance(self.right, NoneType) + right = self.right + if isinstance(right, TupleType) and right.partial_fallback.type.is_enum: + return self._is_subtype(left, mypy.typeops.tuple_fallback(right)) + if isinstance(right, TupleType): + if len(right.items) == 1: + # Non-normalized Tuple type (may be left after semantic analysis + # because semanal_typearg visitor is not a type translator). + item = right.items[0] + if isinstance(item, UnpackType): + unpacked = get_proper_type(item.type) + if isinstance(unpacked, Instance): + return self._is_subtype(left, unpacked) + if left.type.has_base(right.partial_fallback.type.fullname): + if not self.proper_subtype: + # Special cases to consider: + # * Plain tuple[Any, ...] instance is a subtype of all tuple types. + # * Foo[*tuple[Any, ...]] (normalized) instance is a subtype of all + # tuples with fallback to Foo (e.g. for variadic NamedTuples). + mapped = map_instance_to_supertype(left, right.partial_fallback.type) + if is_erased_instance(mapped): + if ( + mapped.type.fullname == "builtins.tuple" + or mapped.type.has_type_var_tuple_type + ): + return True + return False + if isinstance(right, TypeVarTupleType): + # tuple[Any, ...] is like Any in the world of tuples (see special case above). + if left.type.has_base("builtins.tuple"): + mapped = map_instance_to_supertype(left, right.tuple_fallback.type) + if isinstance(get_proper_type(mapped.args[0]), AnyType): + return not self.proper_subtype + if isinstance(right, Instance): + if type_state.is_cached_subtype_check(self._subtype_kind, left, right): + return True + if type_state.is_cached_negative_subtype_check(self._subtype_kind, left, right): + return False + if not self.subtype_context.ignore_promotions and not right.type.is_protocol: + for base in left.type.mro: + if base._promote and any( + self._is_subtype(p, self.right) for p in base._promote + ): + type_state.record_subtype_cache_entry(self._subtype_kind, left, right) + return True + # Special case: Low-level integer types are compatible with 'int'. We can't + # use promotions, since 'int' is already promoted to low-level integer types, + # and we can't have circular promotions. + if left.type.alt_promote and left.type.alt_promote.type is right.type: + return True + rname = right.type.fullname + # Always try a nominal check if possible, + # there might be errors that a user wants to silence *once*. + # NamedTuples are a special case, because `NamedTuple` is not listed + # in `TypeInfo.mro`, so when `(a: NamedTuple) -> None` is used, + # we need to check for `is_named_tuple` property + if ( + left.type.has_base(rname) + or rname == "builtins.object" + or ( + rname in TYPED_NAMEDTUPLE_NAMES + and any(l.is_named_tuple for l in left.type.mro) + ) + ) and not self.subtype_context.ignore_declared_variance: + # Map left type to corresponding right instances. + t = map_instance_to_supertype(left, right.type) + if self.subtype_context.erase_instances: + erased = erase_type(t) + assert isinstance(erased, Instance) + t = erased + nominal = True + if right.type.has_type_var_tuple_type: + # For variadic instances we simply find the correct type argument mappings, + # all the heavy lifting is done by the tuple subtyping. + assert right.type.type_var_tuple_prefix is not None + assert right.type.type_var_tuple_suffix is not None + prefix = right.type.type_var_tuple_prefix + suffix = right.type.type_var_tuple_suffix + tvt = right.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix( + t.args, prefix, suffix + ) + right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix( + right.args, prefix, suffix + ) + left_args = ( + left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix + ) + right_args = ( + right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix + ) + if not self.proper_subtype and is_erased_instance(t): + return True + if len(left_args) != len(right_args): + return False + type_params = zip(left_args, right_args, right.type.defn.type_vars) + else: + type_params = zip(t.args, right.args, right.type.defn.type_vars) + if not self.subtype_context.ignore_type_params: + tried_infer = False + for lefta, righta, tvar in type_params: + if isinstance(tvar, TypeVarType): + if tvar.variance == VARIANCE_NOT_READY and not tried_infer: + infer_class_variances(right.type) + tried_infer = True + if ( + self.subtype_context.always_covariant + and tvar.variance == INVARIANT + ): + variance = COVARIANT + else: + variance = tvar.variance + if not check_type_parameter( + lefta, righta, variance, self.proper_subtype, self.subtype_context + ): + nominal = False + else: + # TODO: everywhere else ParamSpecs are handled as invariant. + if not check_type_parameter( + lefta, righta, COVARIANT, self.proper_subtype, self.subtype_context + ): + nominal = False + if nominal: + type_state.record_subtype_cache_entry(self._subtype_kind, left, right) + else: + type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right) + return nominal + if right.type.is_protocol and is_protocol_implementation( + left, right, proper_subtype=self.proper_subtype, options=self.options + ): + return True + # We record negative cache entry here, and not in the protocol check like we do for + # positive cache, to avoid accidentally adding a type that is not a structural + # subtype, but is a nominal subtype (involving type: ignore override). + type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right) + return False + if isinstance(right, TypeType): + item = right.item + if isinstance(item, TupleType): + item = mypy.typeops.tuple_fallback(item) + # TODO: this is a bit arbitrary, we should only skip Any-related cases. + if not self.proper_subtype: + if is_named_instance(left, "builtins.type"): + return self._is_subtype(TypeType(AnyType(TypeOfAny.special_form)), right) + if left.type.is_metaclass(): + if isinstance(item, AnyType): + return True + if isinstance(item, Instance): + return is_named_instance(item, "builtins.object") + if isinstance(right, LiteralType) and left.last_known_value is not None: + return self._is_subtype(left.last_known_value, right) + if isinstance(right, FunctionLike): + # Special case: Instance can be a subtype of Callable / Overloaded. + call = find_member("__call__", left, left, is_operator=True) + if call: + return self._is_subtype(call, right) + return False + else: + return False + + def visit_type_var(self, left: TypeVarType) -> bool: + right = self.right + if isinstance(right, TypeVarType) and left.id == right.id: + # Fast path for most common case. + if left.upper_bound == right.upper_bound: + return True + # Corner case for self-types in classes generic in type vars + # with value restrictions. + if left.id.is_self(): + return True + return self._is_subtype(left.upper_bound, right.upper_bound) + if left.values and self._is_subtype(UnionType.make_union(left.values), right): + return True + return self._is_subtype(left.upper_bound, self.right) + + def visit_param_spec(self, left: ParamSpecType) -> bool: + right = self.right + if ( + isinstance(right, ParamSpecType) + and right.id == left.id + and right.flavor == left.flavor + ): + return self._is_subtype(left.prefix, right.prefix) + if isinstance(right, Parameters) and are_trivial_parameters(right): + return True + return self._is_subtype(left.upper_bound, self.right) + + def visit_type_var_tuple(self, left: TypeVarTupleType) -> bool: + right = self.right + if isinstance(right, TypeVarTupleType) and right.id == left.id: + return left.min_len >= right.min_len + return self._is_subtype(left.upper_bound, self.right) + + def visit_unpack_type(self, left: UnpackType) -> bool: + # TODO: Ideally we should not need this (since it is not a real type). + # Instead callers (upper level types) should handle it when it appears in type list. + if isinstance(self.right, UnpackType): + return self._is_subtype(left.type, self.right.type) + if isinstance(self.right, Instance) and self.right.type.fullname == "builtins.object": + return True + return False + + def visit_parameters(self, left: Parameters) -> bool: + if isinstance(self.right, Parameters): + return are_parameters_compatible( + left, + self.right, + is_compat=self._is_subtype, + # TODO: this should pass the current value, but then couple tests fail. + is_proper_subtype=False, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + ) + elif isinstance(self.right, Instance): + return self.right.type.fullname == "builtins.object" + else: + return False + + def visit_callable_type(self, left: CallableType) -> bool: + right = self.right + if isinstance(right, CallableType): + if left.type_guard is not None and right.type_guard is not None: + if not self._is_subtype(left.type_guard, right.type_guard): + return False + elif left.type_is is not None and right.type_is is not None: + # For TypeIs we have to check both ways; it is unsafe to pass + # a TypeIs[Child] when a TypeIs[Parent] is expected, because + # if the narrower returns False, we assume that the narrowed value is + # *not* a Parent. + if not self._is_subtype(left.type_is, right.type_is) or not self._is_subtype( + right.type_is, left.type_is + ): + return False + elif right.type_guard is not None and left.type_guard is None: + # This means that one function has `TypeGuard` and other does not. + # They are not compatible. See https://github.com/python/mypy/issues/11307 + return False + elif right.type_is is not None and left.type_is is None: + # Similarly, if one function has `TypeIs` and the other does not, + # they are not compatible. + return False + return is_callable_compatible( + left, + right, + is_compat=self._is_subtype, + is_proper_subtype=self.proper_subtype, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + strict_concatenate=( + (self.options.extra_checks or self.options.strict_concatenate) + if self.options + else False + ), + ) + elif isinstance(right, Overloaded): + return all(self._is_subtype(left, item) for item in right.items) + elif isinstance(right, Instance): + if right.type.is_protocol and "__call__" in right.type.protocol_members: + # OK, a callable can implement a protocol with a `__call__` member. + call = find_member("__call__", right, right, is_operator=True) + assert call is not None + if self._is_subtype(left, call): + if len(right.type.protocol_members) == 1: + return True + if is_protocol_implementation(left.fallback, right, skip=["__call__"]): + return True + if right.type.is_protocol and left.is_type_obj(): + ret_type = get_proper_type(left.ret_type) + if isinstance(ret_type, TupleType): + ret_type = mypy.typeops.tuple_fallback(ret_type) + if isinstance(ret_type, Instance) and is_protocol_implementation( + ret_type, right, proper_subtype=self.proper_subtype, class_obj=True + ): + return True + return self._is_subtype(left.fallback, right) + elif isinstance(right, TypeType): + # This is unsound, we don't check the __init__ signature. + return left.is_type_obj() and self._is_subtype(left.ret_type, right.item) + else: + return False + + def visit_tuple_type(self, left: TupleType) -> bool: + right = self.right + if isinstance(right, Instance): + if is_named_instance(right, "typing.Sized"): + return True + elif is_named_instance(right, TUPLE_LIKE_INSTANCE_NAMES): + if right.args: + iter_type = right.args[0] + else: + if self.proper_subtype: + return False + iter_type = AnyType(TypeOfAny.special_form) + if is_named_instance(right, "builtins.tuple") and isinstance( + get_proper_type(iter_type), AnyType + ): + # TODO: We shouldn't need this special case. This is currently needed + # for isinstance(x, tuple), though it's unclear why. + return True + for li in left.items: + if isinstance(li, UnpackType): + unpack = get_proper_type(li.type) + if isinstance(unpack, TypeVarTupleType): + unpack = get_proper_type(unpack.upper_bound) + assert ( + isinstance(unpack, Instance) + and unpack.type.fullname == "builtins.tuple" + ) + li = unpack.args[0] + if not self._is_subtype(li, iter_type): + return False + return True + elif self._is_subtype(left.partial_fallback, right) and self._is_subtype( + mypy.typeops.tuple_fallback(left), right + ): + return True + return False + elif isinstance(right, TupleType): + # If right has a variadic unpack this needs special handling. If there is a TypeVarTuple + # unpack, item count must coincide. If the left has variadic unpack but right + # doesn't have one, we will fall through to False down the line. + if self.variadic_tuple_subtype(left, right): + return True + if len(left.items) != len(right.items): + return False + if any(not self._is_subtype(l, r) for l, r in zip(left.items, right.items)): + return False + if is_named_instance(right.partial_fallback, "builtins.tuple"): + # No need to verify fallback. This is useful since the calculated fallback + # may be inconsistent due to how we calculate joins between unions vs. + # non-unions. For example, join(int, str) == object, whereas + # join(Union[int, C], Union[str, C]) == Union[int, str, C]. + return True + if is_named_instance(left.partial_fallback, "builtins.tuple"): + # Again, no need to verify. At this point we know the right fallback + # is a subclass of tuple, so if left is plain tuple, it cannot be a subtype. + return False + # At this point we know both fallbacks are non-tuple. + return self._is_subtype(left.partial_fallback, right.partial_fallback) + else: + return False + + def variadic_tuple_subtype(self, left: TupleType, right: TupleType) -> bool: + """Check subtyping between two potentially variadic tuples. + + Most non-trivial cases here are due to variadic unpacks like *tuple[X, ...], + we handle such unpacks as infinite unions Tuple[()] | Tuple[X] | Tuple[X, X] | ... + + Note: the cases where right is fixed or has *Ts unpack should be handled + by the caller. + """ + right_unpack_index = find_unpack_in_list(right.items) + if right_unpack_index is None: + # This case should be handled by the caller. + return False + right_unpack = right.items[right_unpack_index] + assert isinstance(right_unpack, UnpackType) + right_unpacked = get_proper_type(right_unpack.type) + if not isinstance(right_unpacked, Instance): + # This case should be handled by the caller. + return False + assert right_unpacked.type.fullname == "builtins.tuple" + right_item = right_unpacked.args[0] + right_prefix = right_unpack_index + right_suffix = len(right.items) - right_prefix - 1 + left_unpack_index = find_unpack_in_list(left.items) + if left_unpack_index is None: + # Simple case: left is fixed, simply find correct mapping to the right + # (effectively selecting item with matching length from an infinite union). + if len(left.items) < right_prefix + right_suffix: + return False + prefix, middle, suffix = split_with_prefix_and_suffix( + tuple(left.items), right_prefix, right_suffix + ) + if not all( + self._is_subtype(li, ri) for li, ri in zip(prefix, right.items[:right_prefix]) + ): + return False + if right_suffix and not all( + self._is_subtype(li, ri) for li, ri in zip(suffix, right.items[-right_suffix:]) + ): + return False + return all(self._is_subtype(li, right_item) for li in middle) + else: + if len(left.items) < len(right.items): + # There are some items on the left that will never have a matching length + # on the right. + return False + left_prefix = left_unpack_index + left_suffix = len(left.items) - left_prefix - 1 + left_unpack = left.items[left_unpack_index] + assert isinstance(left_unpack, UnpackType) + left_unpacked = get_proper_type(left_unpack.type) + if not isinstance(left_unpacked, Instance): + # *Ts unpack can't be split, except if it is all mapped to Anys or objects. + if self.is_top_type(right_item): + right_prefix_types, middle, right_suffix_types = split_with_prefix_and_suffix( + tuple(right.items), left_prefix, left_suffix + ) + if not all( + self.is_top_type(ri) or isinstance(ri, UnpackType) for ri in middle + ): + return False + # Also check the tails match as well. + return self._all_subtypes( + left.items[:left_prefix], right_prefix_types + ) and self._all_subtypes(left.items[-left_suffix:], right_suffix_types) + return False + assert left_unpacked.type.fullname == "builtins.tuple" + left_item = left_unpacked.args[0] + + # The most tricky case with two variadic unpacks we handle similar to union + # subtyping: *each* item on the left, must be a subtype of *some* item on the right. + # For this we first check the "asymptotic case", i.e. that both unpacks a subtypes, + # and then check subtyping for all finite overlaps. + if not self._is_subtype(left_item, right_item): + return False + max_overlap = max(0, right_prefix - left_prefix, right_suffix - left_suffix) + for overlap in range(max_overlap + 1): + repr_items = left.items[:left_prefix] + [left_item] * overlap + if left_suffix: + repr_items += left.items[-left_suffix:] + left_repr = left.copy_modified(items=repr_items) + if not self._is_subtype(left_repr, right): + return False + return True + + def is_top_type(self, typ: Type) -> bool: + if not self.proper_subtype and isinstance(get_proper_type(typ), AnyType): + return True + return is_named_instance(typ, "builtins.object") + + def visit_typeddict_type(self, left: TypedDictType) -> bool: + right = self.right + if isinstance(right, Instance): + return self._is_subtype(left.fallback, right) + elif isinstance(right, TypedDictType): + if left == right: + return True # Fast path + if not left.names_are_wider_than(right): + return False + for name, l, r in left.zip(right): + # TODO: should we pass on the full subtype_context here and below? + right_readonly = name in right.readonly_keys + if not right_readonly: + if self.proper_subtype: + check = is_same_type(l, r) + else: + check = is_equivalent( + l, + r, + ignore_type_params=self.subtype_context.ignore_type_params, + options=self.options, + ) + else: + # Read-only items behave covariantly + check = self._is_subtype(l, r) + if not check: + return False + # Non-required key is not compatible with a required key since + # indexing may fail unexpectedly if a required key is missing. + # Required key is not compatible with a non-read-only non-required + # key since the prior doesn't support 'del' but the latter should + # support it. + # Required key is compatible with a read-only non-required key. + required_differ = (name in left.required_keys) != (name in right.required_keys) + if not right_readonly and required_differ: + return False + # Readonly fields check: + # + # A = TypedDict('A', {'x': ReadOnly[int]}) + # B = TypedDict('B', {'x': int}) + # def reset_x(b: B) -> None: + # b['x'] = 0 + # + # So, `A` cannot be a subtype of `B`, while `B` can be a subtype of `A`, + # because you can use `B` everywhere you use `A`, but not the other way around. + if name in left.readonly_keys and name not in right.readonly_keys: + return False + # (NOTE: Fallbacks don't matter.) + return True + else: + return False + + def visit_literal_type(self, left: LiteralType) -> bool: + if isinstance(self.right, LiteralType): + return left == self.right + else: + return self._is_subtype(left.fallback, self.right) + + def visit_overloaded(self, left: Overloaded) -> bool: + right = self.right + if isinstance(right, Instance): + if right.type.is_protocol and "__call__" in right.type.protocol_members: + # same as for CallableType + call = find_member("__call__", right, right, is_operator=True) + assert call is not None + if self._is_subtype(left, call): + if len(right.type.protocol_members) == 1: + return True + if is_protocol_implementation(left.fallback, right, skip=["__call__"]): + return True + return self._is_subtype(left.fallback, right) + elif isinstance(right, CallableType): + for item in left.items: + if self._is_subtype(item, right): + return True + return False + elif isinstance(right, Overloaded): + if left == self.right: + # When it is the same overload, then the types are equal. + return True + + # Ensure each overload on the right side (the supertype) is accounted for. + previous_match_left_index = -1 + matched_overloads = set() + + for right_item in right.items: + found_match = False + + for left_index, left_item in enumerate(left.items): + subtype_match = self._is_subtype(left_item, right_item) + + # Order matters: we need to make sure that the index of + # this item is at least the index of the previous one. + if subtype_match and previous_match_left_index <= left_index: + previous_match_left_index = left_index + found_match = True + matched_overloads.add(left_index) + break + else: + # If this one overlaps with the supertype in any way, but it wasn't + # an exact match, then it's a potential error. + strict_concat = ( + (self.options.extra_checks or self.options.strict_concatenate) + if self.options + else False + ) + if left_index not in matched_overloads and ( + is_callable_compatible( + left_item, + right_item, + is_compat=self._is_subtype, + is_proper_subtype=self.proper_subtype, + ignore_return=True, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + strict_concatenate=strict_concat, + ) + or is_callable_compatible( + right_item, + left_item, + is_compat=self._is_subtype, + is_proper_subtype=self.proper_subtype, + ignore_return=True, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + strict_concatenate=strict_concat, + ) + ): + return False + + if not found_match: + return False + return True + elif isinstance(right, UnboundType): + return True + elif isinstance(right, TypeType): + # All the items must have the same type object status, so + # it's sufficient to query only (any) one of them. + # This is unsound, we don't check all the __init__ signatures. + return left.is_type_obj() and self._is_subtype(left.items[0], right) + else: + return False + + def visit_union_type(self, left: UnionType) -> bool: + if isinstance(self.right, Instance): + literal_types: set[Instance] = set() + # avoid redundant check for union of literals + for item in left.relevant_items(): + p_item = get_proper_type(item) + lit_type = mypy.typeops.simple_literal_type(p_item) + if lit_type is not None: + if lit_type in literal_types: + continue + literal_types.add(lit_type) + item = lit_type + if not self._is_subtype(item, self.orig_right): + return False + return True + + elif isinstance(self.right, UnionType): + # prune literals early to avoid nasty quadratic behavior which would otherwise arise when checking + # subtype relationships between slightly different narrowings of an Enum + # we achieve O(N+M) instead of O(N*M) + + fast_check: set[ProperType] = set() + + for item in flatten_types(self.right.relevant_items()): + p_item = get_proper_type(item) + fast_check.add(p_item) + if isinstance(p_item, Instance) and p_item.last_known_value is not None: + fast_check.add(p_item.last_known_value) + + for item in left.relevant_items(): + p_item = get_proper_type(item) + if p_item in fast_check: + continue + lit_type = mypy.typeops.simple_literal_type(p_item) + if lit_type in fast_check: + continue + if not self._is_subtype(item, self.orig_right): + return False + return True + + return all(self._is_subtype(item, self.orig_right) for item in left.items) + + def visit_partial_type(self, left: PartialType) -> bool: + # This is indeterminate as we don't really know the complete type yet. + if self.proper_subtype: + # TODO: What's the right thing to do here? + return False + if left.type is None: + # Special case, partial `None`. This might happen when defining + # class-level attributes with explicit `None`. + # We can still recover from this. + # https://github.com/python/mypy/issues/11105 + return self.visit_none_type(NoneType()) + raise RuntimeError(f'Partial type "{left}" cannot be checked with "issubtype()"') + + def visit_type_type(self, left: TypeType) -> bool: + right = self.right + if left.is_type_form: + if isinstance(right, TypeType): + if not right.is_type_form: + return False + return self._is_subtype(left.item, right.item) + if isinstance(right, Instance): + if right.type.fullname == "builtins.object": + return True + return False + return False + else: # not left.is_type_form + if isinstance(right, TypeType): + return self._is_subtype(left.item, right.item) + if isinstance(right, Overloaded) and right.is_type_obj(): + # Same as in other direction: if it's a constructor callable, all + # items should belong to the same class' constructor, so it's enough + # to check one of them. + return self._is_subtype(left, right.items[0]) + if isinstance(right, CallableType): + if self.proper_subtype and not right.is_type_obj(): + # We can't accept `Type[X]` as a *proper* subtype of Callable[P, X] + # since this will break transitivity of subtyping. + return False + # This is unsound, we don't check the __init__ signature. + return self._is_subtype(left.item, right.ret_type) + + if isinstance(right, Instance): + if right.type.fullname in ["builtins.object", "builtins.type"]: + # TODO: Strictly speaking, the type builtins.type is considered equivalent to + # Type[Any]. However, this would break the is_proper_subtype check in + # conditional_types for cases like isinstance(x, type) when the type + # of x is Type[int]. It's unclear what's the right way to address this. + return True + item = left.item + if isinstance(item, TypeVarType): + item = get_proper_type(item.upper_bound) + if isinstance(item, Instance): + if right.type.is_protocol and is_protocol_implementation( + item, right, proper_subtype=self.proper_subtype, class_obj=True + ): + return True + metaclass = item.type.metaclass_type + return metaclass is not None and self._is_subtype(metaclass, right) + return False + + def visit_type_alias_type(self, left: TypeAliasType) -> bool: + assert False, f"This should be never called, got {left}" + + +T = TypeVar("T", bound=Type) + + +@contextmanager +def pop_on_exit(stack: list[tuple[T, T]], left: T, right: T) -> Iterator[None]: + stack.append((left, right)) + yield + stack.pop() + + +def is_protocol_implementation( + left: Instance, + right: Instance, + proper_subtype: bool = False, + class_obj: bool = False, + skip: list[str] | None = None, + options: Options | None = None, +) -> bool: + """Check whether 'left' implements the protocol 'right'. + + If 'proper_subtype' is True, then check for a proper subtype. + Treat recursive protocols by using the 'assuming' structural subtype matrix + (in sparse representation, i.e. as a list of pairs (subtype, supertype)), + see also comment in nodes.TypeInfo. When we enter a check for classes + (A, P), defined as following:: + + class P(Protocol): + def f(self) -> P: ... + class A: + def f(self) -> A: ... + + this results in A being a subtype of P without infinite recursion. + On every false result, we pop the assumption, thus avoiding an infinite recursion + as well. + """ + assert right.type.is_protocol + if skip is None: + skip = [] + # We need to record this check to generate protocol fine-grained dependencies. + type_state.record_protocol_subtype_check(left.type, right.type) + # nominal subtyping currently ignores '__init__' and '__new__' signatures + members_not_to_check = {"__init__", "__new__"} + members_not_to_check.update(skip) + # Trivial check that circumvents the bug described in issue 9771: + if left.type.is_protocol: + members_right = set(right.type.protocol_members) - members_not_to_check + members_left = set(left.type.protocol_members) - members_not_to_check + if not members_right.issubset(members_left): + return False + assuming = right.type.assuming_proper if proper_subtype else right.type.assuming + for l, r in reversed(assuming): + if l == left and r == right: + return True + with pop_on_exit(assuming, left, right): + for member in right.type.protocol_members: + if member in members_not_to_check: + continue + ignore_names = member != "__call__" # __call__ can be passed kwargs + # The third argument below indicates to what self type is bound. + # We always bind self to the subtype. (Similarly to nominal types). + supertype = find_member(member, right, left) + assert supertype is not None + + subtype = mypy.typeops.get_protocol_member(left, member, class_obj) + # Useful for debugging: + # print(member, 'of', left, 'has type', subtype) + # print(member, 'of', right, 'has type', supertype) + if not subtype: + return False + if not proper_subtype: + # Nominal check currently ignores arg names + # NOTE: If we ever change this, be sure to also change the call to + # SubtypeVisitor.build_subtype_kind(...) down below. + is_compat = is_subtype( + subtype, supertype, ignore_pos_arg_names=ignore_names, options=options + ) + else: + is_compat = is_proper_subtype(subtype, supertype) + if not is_compat: + return False + if isinstance(get_proper_type(subtype), NoneType) and isinstance( + get_proper_type(supertype), CallableType + ): + # We want __hash__ = None idiom to work even without --strict-optional + return False + subflags = get_member_flags(member, left, class_obj=class_obj) + superflags = get_member_flags(member, right) + if IS_SETTABLE in superflags: + # Check opposite direction for settable attributes. + if IS_EXPLICIT_SETTER in superflags: + supertype = find_member(member, right, left, is_lvalue=True) + if IS_EXPLICIT_SETTER in subflags: + subtype = mypy.typeops.get_protocol_member( + left, member, class_obj, is_lvalue=True + ) + # At this point we know attribute is present on subtype, otherwise we + # would return False above. + assert supertype is not None and subtype is not None + if not is_subtype(supertype, subtype, options=options): + return False + if IS_SETTABLE in superflags and IS_SETTABLE not in subflags: + return False + if not class_obj: + if IS_SETTABLE not in superflags: + if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags: + return False + elif (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags): + return False + else: + if IS_VAR in superflags and IS_CLASSVAR not in subflags: + # Only class variables are allowed for class object access. + return False + if IS_CLASSVAR in superflags: + # This can be never matched by a class object. + return False + # This rule is copied from nominal check in checker.py + if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags: + return False + + if not proper_subtype: + # Nominal check currently ignores arg names, but __call__ is special for protocols + ignore_names = right.type.protocol_members != ["__call__"] + else: + ignore_names = False + subtype_kind = SubtypeVisitor.build_subtype_kind( + subtype_context=SubtypeContext(ignore_pos_arg_names=ignore_names), + proper_subtype=proper_subtype, + ) + type_state.record_subtype_cache_entry(subtype_kind, left, right) + return True + + +def find_member( + name: str, + itype: Instance, + subtype: Type, + *, + is_operator: bool = False, + class_obj: bool = False, + is_lvalue: bool = False, +) -> Type | None: + type_checker = checker_state.type_checker + if type_checker is None: + # Unfortunately, there are many scenarios where someone calls is_subtype() before + # type checking phase. In this case we fallback to old (incomplete) logic. + # TODO: reduce number of such cases (e.g. semanal_typeargs, post-semanal plugins). + return find_member_simple( + name, itype, subtype, is_operator=is_operator, class_obj=class_obj, is_lvalue=is_lvalue + ) + + # We don't use ATTR_DEFINED error code below (since missing attributes can cause various + # other error codes), instead we perform quick node lookup with all the fallbacks. + info = itype.type + sym = info.get(name) + node = sym.node if sym else None + if not node: + name_not_found = True + if ( + name not in ["__getattr__", "__setattr__", "__getattribute__"] + and not is_operator + and not class_obj + and itype.extra_attrs is None # skip ModuleType.__getattr__ + ): + for method_name in ("__getattribute__", "__getattr__"): + method = info.get_method(method_name) + if method and method.info.fullname != "builtins.object": + name_not_found = False + break + if name_not_found: + if info.fallback_to_any or class_obj and info.meta_fallback_to_any: + return AnyType(TypeOfAny.special_form) + if itype.extra_attrs and name in itype.extra_attrs.attrs: + return itype.extra_attrs.attrs[name] + return None + + from mypy.checkmember import ( + MemberContext, + analyze_class_attribute_access, + analyze_instance_member_access, + ) + + mx = MemberContext( + is_lvalue=is_lvalue, + is_super=False, + is_operator=is_operator, + original_type=TypeType.make_normalized(itype) if class_obj else itype, + self_type=TypeType.make_normalized(subtype) if class_obj else subtype, + context=Context(), # all errors are filtered, but this is a required argument + chk=type_checker, + suppress_errors=True, + # This is needed to avoid infinite recursion in situations involving protocols like + # class P(Protocol[T]): + # def combine(self, other: P[S]) -> P[Tuple[T, S]]: ... + # Normally we call freshen_all_functions_type_vars() during attribute access, + # to avoid type variable id collisions, but for protocols this means we can't + # use the assumption stack, that will grow indefinitely. + # TODO: find a cleaner solution that doesn't involve massive perf impact. + preserve_type_var_ids=True, + ) + with type_checker.msg.filter_errors(filter_deprecated=True): + if class_obj: + fallback = itype.type.metaclass_type or mx.named_type("builtins.type") + return analyze_class_attribute_access(itype, name, mx, mcs_fallback=fallback) + else: + return analyze_instance_member_access(name, itype, mx, info) + + +def find_member_simple( + name: str, + itype: Instance, + subtype: Type, + *, + is_operator: bool = False, + class_obj: bool = False, + is_lvalue: bool = False, +) -> Type | None: + """Find the type of member by 'name' in 'itype's TypeInfo. + + Find the member type after applying type arguments from 'itype', and binding + 'self' to 'subtype'. Return None if member was not found. + """ + info = itype.type + method = info.get_method(name) + if method: + if isinstance(method, Decorator): + return find_node_type(method.var, itype, subtype, class_obj=class_obj) + if method.is_property: + assert isinstance(method, OverloadedFuncDef) + dec = method.items[0] + assert isinstance(dec, Decorator) + # Pass on is_lvalue flag as this may be a property with different setter type. + return find_node_type( + dec.var, itype, subtype, class_obj=class_obj, is_lvalue=is_lvalue + ) + return find_node_type(method, itype, subtype, class_obj=class_obj) + else: + # don't have such method, maybe variable or decorator? + node = info.get(name) + v = node.node if node else None + if isinstance(v, Var): + return find_node_type(v, itype, subtype, class_obj=class_obj) + if ( + not v + and name not in ["__getattr__", "__setattr__", "__getattribute__"] + and not is_operator + and not class_obj + and itype.extra_attrs is None # skip ModuleType.__getattr__ + ): + for method_name in ("__getattribute__", "__getattr__"): + # Normally, mypy assumes that instances that define __getattr__ have all + # attributes with the corresponding return type. If this will produce + # many false negatives, then this could be prohibited for + # structural subtyping. + method = info.get_method(method_name) + if method and method.info.fullname != "builtins.object": + if isinstance(method, Decorator): + getattr_type = get_proper_type(find_node_type(method.var, itype, subtype)) + else: + getattr_type = get_proper_type(find_node_type(method, itype, subtype)) + if isinstance(getattr_type, CallableType): + return getattr_type.ret_type + return getattr_type + if itype.type.fallback_to_any or class_obj and itype.type.meta_fallback_to_any: + return AnyType(TypeOfAny.special_form) + if isinstance(v, TypeInfo): + # PEP 544 doesn't specify anything about such use cases. So we just try + # to do something meaningful (at least we should not crash). + return TypeType(fill_typevars_with_any(v)) + if itype.extra_attrs and name in itype.extra_attrs.attrs: + return itype.extra_attrs.attrs[name] + return None + + +def get_member_flags(name: str, itype: Instance, class_obj: bool = False) -> set[int]: + """Detect whether a member 'name' is settable, whether it is an + instance or class variable, and whether it is class or static method. + + The flags are defined as following: + * IS_SETTABLE: whether this attribute can be set, not set for methods and + non-settable properties; + * IS_CLASSVAR: set if the variable is annotated as 'x: ClassVar[t]'; + * IS_CLASS_OR_STATIC: set for methods decorated with @classmethod or + with @staticmethod. + """ + info = itype.type + method = info.get_method(name) + setattr_meth = info.get_method("__setattr__") + if method: + if isinstance(method, Decorator): + if method.var.is_staticmethod or method.var.is_classmethod: + return {IS_CLASS_OR_STATIC} + elif method.var.is_property: + return {IS_VAR} + elif method.is_property: # this could be settable property + assert isinstance(method, OverloadedFuncDef) + dec = method.items[0] + assert isinstance(dec, Decorator) + if dec.var.is_settable_property or setattr_meth: + flags = {IS_VAR, IS_SETTABLE} + if dec.var.setter_type is not None: + flags.add(IS_EXPLICIT_SETTER) + return flags + else: + return {IS_VAR} + return set() # Just a regular method + node = info.get(name) + if not node: + if setattr_meth: + return {IS_SETTABLE} + if itype.extra_attrs and name in itype.extra_attrs.attrs: + flags = set() + if name not in itype.extra_attrs.immutable: + flags.add(IS_SETTABLE) + return flags + return set() + v = node.node + # just a variable + if isinstance(v, Var): + if v.is_property: + return {IS_VAR} + flags = {IS_VAR} + if not v.is_final: + flags.add(IS_SETTABLE) + # TODO: define cleaner rules for class vs instance variables. + if v.is_classvar and not is_descriptor(v.type): + flags.add(IS_CLASSVAR) + if class_obj and v.is_inferred: + flags.add(IS_CLASSVAR) + return flags + return set() + + +def is_descriptor(typ: Type | None) -> bool: + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return typ.type.get("__get__") is not None + if isinstance(typ, UnionType): + return all(is_descriptor(item) for item in typ.relevant_items()) + return False + + +def find_node_type( + node: Var | FuncBase, + itype: Instance, + subtype: Type, + class_obj: bool = False, + is_lvalue: bool = False, +) -> Type: + """Find type of a variable or method 'node' (maybe also a decorated method). + Apply type arguments from 'itype', and bind 'self' to 'subtype'. + """ + from mypy.typeops import bind_self + + if isinstance(node, FuncBase): + typ: Type | None = mypy.typeops.function_type( + node, fallback=Instance(itype.type.mro[-1], []) + ) + else: + # This part and the one below are simply copies of the logic from checkmember.py. + if node.is_settable_property and is_lvalue: + typ = node.setter_type + if typ is None and node.is_ready: + typ = node.type + else: + typ = node.type + if typ is not None: + typ = expand_self_type(node, typ, subtype) + p_typ = get_proper_type(typ) + if typ is None: + return AnyType(TypeOfAny.from_error) + # We don't need to bind 'self' for static methods, since there is no 'self'. + if isinstance(node, FuncBase) or ( + isinstance(p_typ, FunctionLike) + and node.is_initialized_in_class + and not node.is_staticmethod + ): + assert isinstance(p_typ, FunctionLike) + if class_obj and not ( + node.is_class if isinstance(node, FuncBase) else node.is_classmethod + ): + # Don't bind instance methods on class objects. + signature = p_typ + else: + signature = bind_self( + p_typ, subtype, is_classmethod=isinstance(node, Var) and node.is_classmethod + ) + if node.is_property and not class_obj: + assert isinstance(signature, CallableType) + if ( + isinstance(node, Var) + and node.is_settable_property + and is_lvalue + and node.setter_type is not None + ): + typ = signature.arg_types[0] + else: + typ = signature.ret_type + else: + typ = signature + itype = map_instance_to_supertype(itype, node.info) + typ = expand_type_by_instance(typ, itype) + return typ + + +def non_method_protocol_members(tp: TypeInfo) -> list[str]: + """Find all non-callable members of a protocol.""" + + assert tp.is_protocol + result: list[str] = [] + anytype = AnyType(TypeOfAny.special_form) + instance = Instance(tp, [anytype] * len(tp.defn.type_vars)) + + for member in tp.protocol_members: + typ = get_proper_type(find_member(member, instance, instance)) + if not isinstance(typ, (Overloaded, CallableType)): + result.append(member) + return result + + +def is_callable_compatible( + left: CallableType, + right: CallableType, + *, + is_compat: Callable[[Type, Type], bool], + is_proper_subtype: bool, + is_compat_return: Callable[[Type, Type], bool] | None = None, + ignore_return: bool = False, + ignore_pos_arg_names: bool = False, + check_args_covariantly: bool = False, + allow_partial_overlap: bool = False, + strict_concatenate: bool = False, +) -> bool: + """Is the left compatible with the right, using the provided compatibility check? + + is_compat: + The check we want to run against the parameters. + + is_compat_return: + The check we want to run against the return type. + If None, use the 'is_compat' check. + + check_args_covariantly: + If true, check if the left's args is compatible with the right's + instead of the other way around (contravariantly). + + This function is mostly used to check if the left is a subtype of the right which + is why the default is to check the args contravariantly. However, it's occasionally + useful to check the args using some other check, so we leave the variance + configurable. + + For example, when checking the validity of overloads, it's useful to see if + the first overload alternative has more precise arguments than the second. + We would want to check the arguments covariantly in that case. + + Note! The following two function calls are NOT equivalent: + + is_callable_compatible(f, g, is_compat=is_subtype, check_args_covariantly=False) + is_callable_compatible(g, f, is_compat=is_subtype, check_args_covariantly=True) + + The two calls are similar in that they both check the function arguments in + the same direction: they both run `is_subtype(argument_from_g, argument_from_f)`. + + However, the two calls differ in which direction they check things like + keyword arguments. For example, suppose f and g are defined like so: + + def f(x: int, *y: int) -> int: ... + def g(x: int) -> int: ... + + In this case, the first call will succeed and the second will fail: f is a + valid stand-in for g but not vice-versa. + + allow_partial_overlap: + By default this function returns True if and only if *all* calls to left are + also calls to right (with respect to the provided 'is_compat' function). + + If this parameter is set to 'True', we return True if *there exists at least one* + call to left that's also a call to right. + + In other words, we perform an existential check instead of a universal one; + we require left to only overlap with right instead of being a subset. + + For example, suppose we set 'is_compat' to some subtype check and compare following: + + f(x: float, y: str = "...", *args: bool) -> str + g(*args: int) -> str + + This function would normally return 'False': f is not a subtype of g. + However, we would return True if this parameter is set to 'True': the two + calls are compatible if the user runs "f_or_g(3)". In the context of that + specific call, the two functions effectively have signatures of: + + f2(float) -> str + g2(int) -> str + + Here, f2 is a valid subtype of g2 so we return True. + + Specifically, if this parameter is set this function will: + + - Ignore optional arguments on either the left or right that have no + corresponding match. + - No longer mandate optional arguments on either side are also optional + on the other. + - No longer mandate that if right has a *arg or **kwarg that left must also + have the same. + + Note: when this argument is set to True, this function becomes "symmetric" -- + the following calls are equivalent: + + is_callable_compatible(f, g, + is_compat=some_check, + check_args_covariantly=False, + allow_partial_overlap=True) + is_callable_compatible(g, f, + is_compat=some_check, + check_args_covariantly=True, + allow_partial_overlap=True) + + If the 'some_check' function is also symmetric, the two calls would be equivalent + whether or not we check the args covariantly. + """ + # Normalize both types before comparing them. + left = left.with_unpacked_kwargs().with_normalized_var_args() + right = right.with_unpacked_kwargs().with_normalized_var_args() + + if is_compat_return is None: + is_compat_return = is_compat + + # If either function is implicitly typed, ignore positional arg names too + if left.implicit or right.implicit: + ignore_pos_arg_names = True + + # Non-type cannot be a subtype of type. + if right.is_type_obj() and not left.is_type_obj() and not allow_partial_overlap: + return False + + # A callable L is a subtype of a generic callable R if L is a + # subtype of every type obtained from R by substituting types for + # the variables of R. We can check this by simply leaving the + # generic variables of R as type variables, effectively varying + # over all possible values. + + # It's okay even if these variables share ids with generic + # type variables of L, because generating and solving + # constraints for the variables of L to make L a subtype of R + # (below) treats type variables on the two sides as independent. + if left.variables: + # Apply generic type variables away in left via type inference. + unified = unify_generic_callable(left, right, ignore_return=ignore_return) + if unified is None: + return False + left = unified + + # Check return types. + if not ignore_return and not is_compat_return(left.ret_type, right.ret_type): + return False + + if check_args_covariantly: + is_compat = flip_compat_check(is_compat) + + if not strict_concatenate and (left.from_concatenate or right.from_concatenate): + strict_concatenate_check = False + else: + strict_concatenate_check = True + + return are_parameters_compatible( + left, + right, + is_compat=is_compat, + is_proper_subtype=is_proper_subtype, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + strict_concatenate_check=strict_concatenate_check, + ) + + +def are_trivial_parameters(param: Parameters | NormalizedCallableType) -> bool: + param_star = param.var_arg() + param_star2 = param.kw_arg() + return ( + param.arg_kinds == [ARG_STAR, ARG_STAR2] + and param_star is not None + and isinstance(get_proper_type(param_star.typ), AnyType) + and param_star2 is not None + and isinstance(get_proper_type(param_star2.typ), AnyType) + ) + + +def is_trivial_suffix(param: Parameters | NormalizedCallableType) -> bool: + param_star = param.var_arg() + param_star2 = param.kw_arg() + return ( + param.arg_kinds[-2:] == [ARG_STAR, ARG_STAR2] + and param_star is not None + and isinstance(get_proper_type(param_star.typ), AnyType) + and param_star2 is not None + and isinstance(get_proper_type(param_star2.typ), AnyType) + ) + + +def are_parameters_compatible( + left: Parameters | NormalizedCallableType, + right: Parameters | NormalizedCallableType, + *, + is_compat: Callable[[Type, Type], bool], + is_proper_subtype: bool, + ignore_pos_arg_names: bool = False, + allow_partial_overlap: bool = False, + strict_concatenate_check: bool = False, +) -> bool: + """Helper function for is_callable_compatible, used for Parameter compatibility""" + if right.is_ellipsis_args and not is_proper_subtype: + return True + + left_star = left.var_arg() + left_star2 = left.kw_arg() + right_star = right.var_arg() + right_star2 = right.kw_arg() + + # Treat "def _(*a: Any, **kw: Any) -> X" similarly to "Callable[..., X]" + if are_trivial_parameters(right) and not is_proper_subtype: + return True + trivial_suffix = is_trivial_suffix(right) and not is_proper_subtype + + trivial_vararg_suffix = False + if ( + right.arg_kinds[-1:] == [ARG_STAR] + and isinstance(get_proper_type(right.arg_types[-1]), AnyType) + and not is_proper_subtype + and all(k.is_positional(star=True) for k in left.arg_kinds) + ): + # Similar to how (*Any, **Any) is considered a supertype of all callables, we consider + # (*Any) a supertype of all callables with positional arguments. This is needed in + # particular because we often refuse to try type inference if actual type is not + # a subtype of erased template type. + trivial_vararg_suffix = True + + # Match up corresponding arguments and check them for compatibility. In + # every pair (argL, argR) of corresponding arguments from L and R, argL must + # be "more general" than argR if L is to be a subtype of R. + + # Arguments are corresponding if they either share a name, share a position, + # or both. If L's corresponding argument is ambiguous, L is not a subtype of R. + + # If left has one corresponding argument by name and another by position, + # consider them to be one "merged" argument (and not ambiguous) if they're + # both optional, they're name-only and position-only respectively, and they + # have the same type. This rule allows functions with (*args, **kwargs) to + # properly stand in for the full domain of formal arguments that they're + # used for in practice. + + # Every argument in R must have a corresponding argument in L, and every + # required argument in L must have a corresponding argument in R. + + # Phase 1: Confirm every argument in R has a corresponding argument in L. + + # Phase 1a: If left and right can both accept an infinite number of args, + # their types must be compatible. + # + # Furthermore, if we're checking for compatibility in all cases, + # we confirm that if R accepts an infinite number of arguments, + # L must accept the same. + def _incompatible(left_arg: FormalArgument | None, right_arg: FormalArgument | None) -> bool: + if right_arg is None: + return False + if left_arg is None: + return not allow_partial_overlap and not trivial_suffix + return not is_compat(right_arg.typ, left_arg.typ) + + if ( + _incompatible(left_star, right_star) + and not trivial_vararg_suffix + or _incompatible(left_star2, right_star2) + ): + return False + + # Phase 1b: Check non-star args: for every arg right can accept, left must + # also accept. The only exception is if we are allowing partial + # overlaps: in that case, we ignore optional args on the right. + for right_arg in right.formal_arguments(): + left_arg = mypy.typeops.callable_corresponding_argument(left, right_arg) + if left_arg is None: + if allow_partial_overlap and not right_arg.required: + continue + return False + if not are_args_compatible( + left_arg, + right_arg, + is_compat, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + allow_imprecise_kinds=right.imprecise_arg_kinds, + ): + return False + + if trivial_suffix: + # For trivial right suffix we *only* check that every non-star right argument + # has a valid match on the left. + return True + + # Phase 1c: Check var args. Right has an infinite series of optional positional + # arguments. Get all further positional args of left, and make sure + # they're more general than the corresponding member in right. + # TODO: handle suffix in UnpackType (i.e. *args: *Tuple[Ts, X, Y]). + if right_star is not None and not trivial_vararg_suffix: + # Synthesize an anonymous formal argument for the right + right_by_position = right.try_synthesizing_arg_from_vararg(None) + assert right_by_position is not None + + i = right_star.pos + assert i is not None + while i < len(left.arg_kinds) and left.arg_kinds[i].is_positional(): + if allow_partial_overlap and left.arg_kinds[i].is_optional(): + break + + left_by_position = left.argument_by_position(i) + assert left_by_position is not None + + if not are_args_compatible( + left_by_position, + right_by_position, + is_compat, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + ): + return False + i += 1 + + # Phase 1d: Check kw args. Right has an infinite series of optional named + # arguments. Get all further named args of left, and make sure + # they're more general than the corresponding member in right. + if right_star2 is not None: + right_names = {name for name in right.arg_names if name is not None} + left_only_names = set() + for name, kind in zip(left.arg_names, left.arg_kinds): + if ( + name is None + or kind.is_star() + or name in right_names + or not strict_concatenate_check + ): + continue + left_only_names.add(name) + + # Synthesize an anonymous formal argument for the right + right_by_name = right.try_synthesizing_arg_from_kwarg(None) + assert right_by_name is not None + + for name in left_only_names: + left_by_name = left.argument_by_name(name) + assert left_by_name is not None + + if allow_partial_overlap and not left_by_name.required: + continue + + if not are_args_compatible( + left_by_name, + right_by_name, + is_compat, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + ): + return False + + # Phase 2: Left must not impose additional restrictions. + # (Every required argument in L must have a corresponding argument in R) + # Note: we already checked the *arg and **kwarg arguments in phase 1a. + for left_arg in left.formal_arguments(): + right_by_name = ( + right.argument_by_name(left_arg.name) if left_arg.name is not None else None + ) + + right_by_pos = ( + right.argument_by_position(left_arg.pos) if left_arg.pos is not None else None + ) + + # If the left hand argument corresponds to two right-hand arguments, + # neither of them can be required. + if ( + right_by_name is not None + and right_by_pos is not None + and right_by_name != right_by_pos + and (right_by_pos.required or right_by_name.required) + and strict_concatenate_check + and not right.imprecise_arg_kinds + ): + return False + + # All *required* left-hand arguments must have a corresponding + # right-hand argument. Optional args do not matter. + if left_arg.required and right_by_pos is None and right_by_name is None: + return False + + return True + + +def are_args_compatible( + left: FormalArgument, + right: FormalArgument, + is_compat: Callable[[Type, Type], bool], + *, + ignore_pos_arg_names: bool, + allow_partial_overlap: bool, + allow_imprecise_kinds: bool = False, +) -> bool: + if left.required and right.required: + # If both arguments are required allow_partial_overlap has no effect. + allow_partial_overlap = False + + def is_different( + left_item: object | None, right_item: object | None, allow_overlap: bool + ) -> bool: + """Checks if the left and right items are different. + + If the right item is unspecified (e.g. if the right callable doesn't care + about what name or position its arg has), we default to returning False. + + If we're allowing partial overlap, we also default to returning False + if the left callable also doesn't care.""" + if right_item is None: + return False + if allow_overlap and left_item is None: + return False + return left_item != right_item + + # If right has a specific name it wants this argument to be, left must + # have the same. + if is_different(left.name, right.name, allow_partial_overlap): + # But pay attention to whether we're ignoring positional arg names + if not ignore_pos_arg_names or right.pos is None: + return False + + # If right is at a specific position, left must have the same. + # TODO: partial overlap logic is flawed for positions. + # We disable it to avoid false positives at a cost of few false negatives. + if is_different(left.pos, right.pos, allow_overlap=False) and not allow_imprecise_kinds: + return False + + # If right's argument is optional, left's must also be + # (unless we're relaxing the checks to allow potential + # rather than definite compatibility). + if not allow_partial_overlap and not right.required and left.required: + return False + + # If we're allowing partial overlaps and neither arg is required, + # the types don't actually need to be the same + if allow_partial_overlap and not left.required and not right.required: + return True + + # Left must have a more general type + return is_compat(right.typ, left.typ) + + +def flip_compat_check(is_compat: Callable[[Type, Type], bool]) -> Callable[[Type, Type], bool]: + def new_is_compat(left: Type, right: Type) -> bool: + return is_compat(right, left) + + return new_is_compat + + +def unify_generic_callable( + type: NormalizedCallableType, + target: NormalizedCallableType, + ignore_return: bool, + return_constraint_direction: int | None = None, +) -> NormalizedCallableType | None: + """Try to unify a generic callable type with another callable type. + + Return unified CallableType if successful; otherwise, return None. + """ + import mypy.solve + + if set(type.type_var_ids()) & {v.id for v in mypy.typeops.get_all_type_vars(target)}: + # Overload overlap check does nasty things like unifying in opposite direction. + # This can easily create type variable clashes, so we need to refresh. + type = freshen_function_type_vars(type) + + if return_constraint_direction is None: + return_constraint_direction = mypy.constraints.SUBTYPE_OF + + constraints: list[mypy.constraints.Constraint] = [] + # There is some special logic for inference in callables, so better use them + # as wholes instead of picking separate arguments. + cs = mypy.constraints.infer_constraints( + type.copy_modified(ret_type=UninhabitedType()), + target.copy_modified(ret_type=UninhabitedType()), + mypy.constraints.SUBTYPE_OF, + skip_neg_op=True, + ) + constraints.extend(cs) + if not ignore_return: + c = mypy.constraints.infer_constraints( + type.ret_type, target.ret_type, return_constraint_direction + ) + constraints.extend(c) + inferred_vars, _ = mypy.solve.solve_constraints( + type.variables, constraints, allow_polymorphic=True + ) + if None in inferred_vars: + return None + non_none_inferred_vars = cast(list[Type], inferred_vars) + had_errors = False + + def report(*args: Any) -> None: + nonlocal had_errors + had_errors = True + + # This function may be called by the solver, so we need to allow erased types here. + # We anyway allow checking subtyping between other types containing + # (probably also because solver needs subtyping). See also comment in + # ExpandTypeVisitor.visit_erased_type(). + applied = mypy.applytype.apply_generic_arguments( + type, non_none_inferred_vars, report, context=target + ) + if had_errors: + return None + return cast(NormalizedCallableType, applied) + + +def try_restrict_literal_union(t: UnionType, s: Type) -> list[Type] | None: + """Return the items of t, excluding any occurrence of s, if and only if + - t only contains simple literals + - s is a simple literal + + Otherwise, returns None + """ + ps = get_proper_type(s) + if not mypy.typeops.is_simple_literal(ps): + return None + + new_items: list[Type] = [] + for i in t.relevant_items(): + pi = get_proper_type(i) + if not mypy.typeops.is_simple_literal(pi): + return None + if pi != ps: + new_items.append(i) + return new_items + + +def restrict_subtype_away(t: Type, s: Type, *, consider_runtime_isinstance: bool = True) -> Type: + """Return t minus s for runtime type assertions. + + If we can't determine a precise result, return a supertype of the + ideal result (just t is a valid result). + + This is used for type inference of runtime type checks such as + isinstance(). Currently, this just removes elements of a union type. + """ + p_t = get_proper_type(t) + if isinstance(p_t, UnionType): + new_items = try_restrict_literal_union(p_t, s) + if new_items is None: + new_items = [ + restrict_subtype_away( + item, s, consider_runtime_isinstance=consider_runtime_isinstance + ) + for item in p_t.relevant_items() + ] + return UnionType.make_union( + [item for item in new_items if not isinstance(get_proper_type(item), UninhabitedType)] + ) + elif isinstance(p_t, TypeVarType): + return p_t.copy_modified(upper_bound=restrict_subtype_away(p_t.upper_bound, s)) + + if consider_runtime_isinstance: + if covers_at_runtime(t, s): + return UninhabitedType() + else: + return t + else: + if is_proper_subtype(t, s, ignore_promotions=True): + return UninhabitedType() + if is_proper_subtype(t, s, ignore_promotions=True, erase_instances=True): + return UninhabitedType() + return t + + +def covers_at_runtime(item: Type, supertype: Type) -> bool: + """Will isinstance(item, supertype) always return True at runtime?""" + item = get_proper_type(item) + supertype = get_proper_type(supertype) + + # Since runtime type checks will ignore type arguments, erase the types. + if not (isinstance(supertype, FunctionLike) and supertype.is_type_obj()): + supertype = erase_type(supertype) + if is_proper_subtype( + erase_type(item), supertype, ignore_promotions=True, erase_instances=True + ): + return True + if isinstance(supertype, Instance): + if supertype.type.is_protocol: + # TODO: Implement more robust support for runtime isinstance() checks, see issue #3827. + if is_proper_subtype(item, supertype, ignore_promotions=True): + return True + if isinstance(item, TypedDictType): + # Special case useful for selecting TypedDicts from unions using isinstance(x, dict). + if supertype.type.fullname == "builtins.dict": + return True + elif isinstance(item, TypeVarType): + if is_proper_subtype(item.upper_bound, supertype, ignore_promotions=True): + return True + elif isinstance(item, Instance) and supertype.type.fullname == "builtins.int": + # "int" covers all native int types + if item.type.fullname in MYPYC_NATIVE_INT_NAMES: + return True + # TODO: Add more special cases. + return False + + +def is_more_precise(left: Type, right: Type, *, ignore_promotions: bool = False) -> bool: + """Check if left is a more precise type than right. + + A left is a proper subtype of right, left is also more precise than + right. Also, if right is Any, left is more precise than right, for + any left. + """ + # TODO Should List[int] be more precise than List[Any]? + right = get_proper_type(right) + if isinstance(right, AnyType): + return True + return is_proper_subtype(left, right, ignore_promotions=ignore_promotions) + + +def all_non_object_members(info: TypeInfo) -> set[str]: + members = set(info.names) + for base in info.mro[1:-1]: + members.update(base.names) + return members + + +def infer_variance(info: TypeInfo, i: int) -> bool: + """Infer the variance of the ith type variable of a generic class. + + Return True if successful. This can fail if some inferred types aren't ready. + """ + object_type = Instance(info.mro[-1], []) + + for variance in COVARIANT, CONTRAVARIANT, INVARIANT: + tv = info.defn.type_vars[i] + assert isinstance(tv, TypeVarType) + if tv.variance != VARIANCE_NOT_READY: + continue + tv.variance = variance + co = True + contra = True + tvar = info.defn.type_vars[i] + self_type = fill_typevars(info) + for member in all_non_object_members(info): + # __mypy-replace is an implementation detail of the dataclass plugin + if member in ("__init__", "__new__", "__mypy-replace"): + continue + + if isinstance(self_type, TupleType): + self_type = mypy.typeops.tuple_fallback(self_type) + flags = get_member_flags(member, self_type) + settable = IS_SETTABLE in flags + + node = info[member].node + if isinstance(node, Var): + if node.type is None: + tv.variance = VARIANCE_NOT_READY + return False + if has_underscore_prefix(member): + # Special case to avoid false positives (and to pass conformance tests) + settable = False + + # TODO: handle settable properties with setter type different from getter. + typ = find_member(member, self_type, self_type) + if typ: + # It's okay for a method in a generic class with a contravariant type + # variable to return a generic instance of the class, if it doesn't involve + # variance (i.e. values of type variables are propagated). Our normal rules + # would disallow this. Replace such return types with 'Any' to allow this. + # + # This could probably be more lenient (e.g. allow self type be nested, don't + # require all type arguments to be identical to self_type), but this will + # hopefully cover the vast majority of such cases, including Self. + typ = erase_return_self_types(typ, self_type) + + typ2 = expand_type(typ, {tvar.id: object_type}) + if not is_subtype(typ, typ2): + co = False + if not is_subtype(typ2, typ): + contra = False + if settable: + co = False + + # Infer variance from base classes, in case they have explicit variances + for base in info.bases: + base2 = expand_type(base, {tvar.id: object_type}) + if not is_subtype(base, base2): + co = False + if not is_subtype(base2, base): + contra = False + + if co: + v = COVARIANT + elif contra: + v = CONTRAVARIANT + else: + v = INVARIANT + if v == variance: + break + tv.variance = VARIANCE_NOT_READY + return True + + +def has_underscore_prefix(name: str) -> bool: + return name.startswith("_") and not (name.startswith("__") and name.endswith("__")) + + +def infer_class_variances(info: TypeInfo) -> bool: + if not info.defn.type_args: + return True + tvs = info.defn.type_vars + success = True + for i, tv in enumerate(tvs): + if isinstance(tv, TypeVarType) and tv.variance == VARIANCE_NOT_READY: + if not infer_variance(info, i): + success = False + return success + + +def erase_return_self_types(typ: Type, self_type: Instance) -> Type: + """If a typ is function-like and returns self_type, replace return type with Any.""" + proper_type = get_proper_type(typ) + if isinstance(proper_type, CallableType): + ret = get_proper_type(proper_type.ret_type) + if isinstance(ret, Instance) and ret == self_type: + return proper_type.copy_modified(ret_type=AnyType(TypeOfAny.implementation_artifact)) + elif isinstance(proper_type, Overloaded): + return Overloaded( + [ + cast(CallableType, erase_return_self_types(it, self_type)) + for it in proper_type.items + ] + ) + return typ + + +def is_erased_instance(t: Instance) -> bool: + """Is this an instance where all args are Any types?""" + if not t.args: + return False + for arg in t.args: + if isinstance(arg, UnpackType): + unpacked = get_proper_type(arg.type) + if not isinstance(unpacked, Instance): + return False + assert unpacked.type.fullname == "builtins.tuple" + if not isinstance(get_proper_type(unpacked.args[0]), AnyType): + return False + elif not isinstance(get_proper_type(arg), AnyType): + return False + return True diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/suggestions.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/suggestions.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..14a69a4ad7389c2456381d6b82ee01edcd523859 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/suggestions.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/suggestions.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/suggestions.py new file mode 100644 index 0000000000000000000000000000000000000000..39a220e34091e91cadeaff6f3dcde13dd2345b94 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/suggestions.py @@ -0,0 +1,1068 @@ +"""Mechanisms for inferring function types based on callsites. + +Currently works by collecting all argument types at callsites, +synthesizing a list of possible function types from that, trying them +all, and picking the one with the fewest errors that we think is the +"best". + +Can return JSON that pyannotate can use to apply the annotations to code. + +There are a bunch of TODOs here: + * Maybe want a way to surface the choices not selected?? + * We can generate an exponential number of type suggestions, and probably want + a way to not always need to check them all. + * Our heuristics for what types to try are primitive and not yet + supported by real practice. + * More! + +Other things: + * This is super brute force. Could we integrate with the typechecker + more to understand more about what is going on? + * Like something with tracking constraints/unification variables? + * No understanding of type variables at *all* +""" + +from __future__ import annotations + +import itertools +import json +import os +import sys +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from typing import NamedTuple, TypedDict, TypeVar, cast + +from mypy.argmap import map_actuals_to_formals +from mypy.build import Graph, State +from mypy.checkexpr import has_any_type +from mypy.find_sources import InvalidSourceList, SourceFinder +from mypy.join import join_type_list +from mypy.meet import meet_type_list +from mypy.modulefinder import PYTHON_EXTENSIONS +from mypy.nodes import ( + ARG_STAR, + ARG_STAR2, + ArgKind, + CallExpr, + Decorator, + Expression, + FuncDef, + MypyFile, + RefExpr, + ReturnStmt, + SymbolNode, + SymbolTable, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.plugin import FunctionContext, MethodContext, Plugin +from mypy.server.update import FineGrainedBuildManager +from mypy.state import state +from mypy.traverser import TraverserVisitor +from mypy.typeops import bind_self, make_simplified_union +from mypy.types import ( + AnyType, + CallableType, + FunctionLike, + Instance, + NoneType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeStrVisitor, + TypeTranslator, + TypeVarType, + UninhabitedType, + UnionType, + get_proper_type, +) +from mypy.types_utils import is_overlapping_none, remove_optional +from mypy.util import split_target + + +class PyAnnotateSignature(TypedDict): + return_type: str + arg_types: list[str] + + +class Callsite(NamedTuple): + path: str + line: int + arg_kinds: list[list[ArgKind]] + callee_arg_names: list[str | None] + arg_names: list[list[str | None]] + arg_types: list[list[Type]] + + +class SuggestionPlugin(Plugin): + """Plugin that records all calls to a given target.""" + + def __init__(self, target: str) -> None: + if target.endswith((".__new__", ".__init__")): + target = target.rsplit(".", 1)[0] + + self.target = target + # List of call sites found by dmypy suggest: + # (path, line, , , ) + self.mystery_hits: list[Callsite] = [] + + def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: + if fullname == self.target: + return self.log + else: + return None + + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: + if fullname == self.target: + return self.log + else: + return None + + def log(self, ctx: FunctionContext | MethodContext) -> Type: + self.mystery_hits.append( + Callsite( + ctx.api.path, + ctx.context.line, + ctx.arg_kinds, + ctx.callee_arg_names, + ctx.arg_names, + ctx.arg_types, + ) + ) + return ctx.default_return_type + + +# NOTE: We could make this a bunch faster by implementing a StatementVisitor that skips +# traversing into expressions +class ReturnFinder(TraverserVisitor): + """Visitor for finding all types returned from a function.""" + + def __init__(self, typemap: dict[Expression, Type]) -> None: + self.typemap = typemap + self.return_types: list[Type] = [] + + def visit_return_stmt(self, o: ReturnStmt) -> None: + if o.expr is not None and o.expr in self.typemap: + self.return_types.append(self.typemap[o.expr]) + + def visit_func_def(self, o: FuncDef) -> None: + # Skip nested functions + pass + + +def get_return_types(typemap: dict[Expression, Type], func: FuncDef) -> list[Type]: + """Find all the types returned by return statements in func.""" + finder = ReturnFinder(typemap) + func.body.accept(finder) + return finder.return_types + + +class ArgUseFinder(TraverserVisitor): + """Visitor for finding all the types of arguments that each arg is passed to. + + This is extremely simple minded but might be effective anyways. + """ + + def __init__(self, func: FuncDef, typemap: dict[Expression, Type]) -> None: + self.typemap = typemap + self.arg_types: dict[SymbolNode, list[Type]] = {arg.variable: [] for arg in func.arguments} + + def visit_call_expr(self, o: CallExpr) -> None: + if not any(isinstance(e, RefExpr) and e.node in self.arg_types for e in o.args): + return + + typ = get_proper_type(self.typemap.get(o.callee)) + if not isinstance(typ, CallableType): + return + + formal_to_actual = map_actuals_to_formals( + o.arg_kinds, + o.arg_names, + typ.arg_kinds, + typ.arg_names, + lambda n: AnyType(TypeOfAny.special_form), + ) + + for i, args in enumerate(formal_to_actual): + for arg_idx in args: + arg = o.args[arg_idx] + if isinstance(arg, RefExpr) and arg.node in self.arg_types: + self.arg_types[arg.node].append(typ.arg_types[i]) + + +def get_arg_uses(typemap: dict[Expression, Type], func: FuncDef) -> list[list[Type]]: + """Find all the types of arguments that each arg is passed to. + + For example, given + def foo(x: int) -> None: ... + def bar(x: str) -> None: ... + def test(x, y): + foo(x) + bar(y) + + this will return [[int], [str]]. + """ + finder = ArgUseFinder(func, typemap) + func.body.accept(finder) + return [finder.arg_types[arg.variable] for arg in func.arguments] + + +class SuggestionFailure(Exception): + pass + + +def is_explicit_any(typ: AnyType) -> bool: + # Originally I wanted to count as explicit anything derived from an explicit any, but that + # seemed too strict in some testing. + # return (typ.type_of_any == TypeOfAny.explicit + # or (typ.source_any is not None and typ.source_any.type_of_any == TypeOfAny.explicit)) + # Important question: what should we do with source_any stuff? Does that count? + # And actually should explicit anys count at all?? Maybe not! + return typ.type_of_any == TypeOfAny.explicit + + +def is_implicit_any(typ: Type) -> bool: + typ = get_proper_type(typ) + return isinstance(typ, AnyType) and not is_explicit_any(typ) + + +def _arg_accepts_function(typ: ProperType) -> bool: + return ( + # TypeVar / Callable + isinstance(typ, (TypeVarType, CallableType)) + or + # Protocol with __call__ + isinstance(typ, Instance) + and typ.type.is_protocol + and typ.type.get_method("__call__") is not None + ) + + +class SuggestionEngine: + """Engine for finding call sites and suggesting signatures.""" + + def __init__( + self, + fgmanager: FineGrainedBuildManager, + *, + json: bool, + no_errors: bool = False, + no_any: bool = False, + flex_any: float | None = None, + use_fixme: str | None = None, + max_guesses: int | None = None, + ) -> None: + self.fgmanager = fgmanager + self.manager = fgmanager.manager + self.plugin = self.manager.plugin + self.graph = fgmanager.graph + self.finder = SourceFinder(self.manager.fscache, self.manager.options) + + self.give_json = json + self.no_errors = no_errors + self.flex_any = flex_any + if no_any: + self.flex_any = 1.0 + + self.max_guesses = max_guesses or 64 + self.use_fixme = use_fixme + + def suggest(self, function: str) -> str: + """Suggest an inferred type for function.""" + mod, func_name, node = self.find_node(function) + + with self.restore_after(mod): + with self.with_export_types(): + suggestion = self.get_suggestion(mod, node) + + if self.give_json: + return self.json_suggestion(mod, func_name, node, suggestion) + else: + return self.format_signature(suggestion) + + def suggest_callsites(self, function: str) -> str: + """Find a list of call sites of function.""" + mod, _, node = self.find_node(function) + with self.restore_after(mod): + callsites, _ = self.get_callsites(node) + + return "\n".join( + dedup( + [ + f"{path}:{line}: {self.format_args(arg_kinds, arg_names, arg_types)}" + for path, line, arg_kinds, _, arg_names, arg_types in callsites + ] + ) + ) + + @contextmanager + def restore_after(self, module: str) -> Iterator[None]: + """Context manager that reloads a module after executing the body. + + This should undo any damage done to the module state while mucking around. + """ + try: + yield + finally: + self.reload(self.graph[module]) + + @contextmanager + def with_export_types(self) -> Iterator[None]: + """Context manager that enables the export_types flag in the body. + + This causes type information to be exported into the manager's all_types variable. + """ + old = self.manager.options.export_types + self.manager.options.export_types = True + try: + yield + finally: + self.manager.options.export_types = old + + def get_trivial_type(self, fdef: FuncDef) -> CallableType: + """Generate a trivial callable type from a func def, with all Anys""" + # The Anys are marked as being from the suggestion engine + # since they need some special treatment (specifically, + # constraint generation ignores them.) + return CallableType( + [AnyType(TypeOfAny.suggestion_engine) for _ in fdef.arg_kinds], + fdef.arg_kinds, + fdef.arg_names, + AnyType(TypeOfAny.suggestion_engine), + self.named_type("builtins.function"), + ) + + def get_starting_type(self, fdef: FuncDef) -> CallableType: + if isinstance(fdef.type, CallableType): + return make_suggestion_anys(fdef.type) + else: + return self.get_trivial_type(fdef) + + def get_args( + self, + is_method: bool, + base: CallableType, + defaults: list[Type | None], + callsites: list[Callsite], + uses: list[list[Type]], + ) -> list[list[Type]]: + """Produce a list of type suggestions for each argument type.""" + types: list[list[Type]] = [] + for i in range(len(base.arg_kinds)): + # Make self args Any but this will get overridden somewhere in the checker + if i == 0 and is_method: + types.append([AnyType(TypeOfAny.suggestion_engine)]) + continue + + all_arg_types = [] + for call in callsites: + for typ in call.arg_types[i - is_method]: + # Collect all the types except for implicit anys + if not is_implicit_any(typ): + all_arg_types.append(typ) + all_use_types = [] + for typ in uses[i]: + # Collect all the types except for implicit anys + if not is_implicit_any(typ): + all_use_types.append(typ) + # Add in any default argument types + default = defaults[i] + if default: + all_arg_types.append(default) + if all_use_types: + all_use_types.append(default) + + arg_types = [] + + if all_arg_types and all( + isinstance(get_proper_type(tp), NoneType) for tp in all_arg_types + ): + arg_types.append( + UnionType.make_union([all_arg_types[0], AnyType(TypeOfAny.explicit)]) + ) + elif all_arg_types: + arg_types.extend(generate_type_combinations(all_arg_types)) + else: + arg_types.append(AnyType(TypeOfAny.explicit)) + + if all_use_types: + # This is a meet because the type needs to be compatible with all the uses + arg_types.append(meet_type_list(all_use_types)) + + types.append(arg_types) + return types + + def get_default_arg_types(self, fdef: FuncDef) -> list[Type | None]: + return [ + self.manager.all_types[arg.initializer] if arg.initializer else None + for arg in fdef.arguments + ] + + def get_guesses( + self, + is_method: bool, + base: CallableType, + defaults: list[Type | None], + callsites: list[Callsite], + uses: list[list[Type]], + ) -> list[CallableType]: + """Compute a list of guesses for a function's type. + + This focuses just on the argument types, and doesn't change the provided return type. + """ + options = self.get_args(is_method, base, defaults, callsites, uses) + + # Take the first `max_guesses` guesses. + product = itertools.islice(itertools.product(*options), 0, self.max_guesses) + return [refine_callable(base, base.copy_modified(arg_types=list(x))) for x in product] + + def get_callsites(self, func: FuncDef) -> tuple[list[Callsite], list[str]]: + """Find all call sites of a function.""" + new_type = self.get_starting_type(func) + + collector_plugin = SuggestionPlugin(func.fullname) + + self.plugin._plugins.insert(0, collector_plugin) + try: + errors = self.try_type(func, new_type) + finally: + self.plugin._plugins.pop(0) + + return collector_plugin.mystery_hits, errors + + def filter_options( + self, guesses: list[CallableType], is_method: bool, ignore_return: bool + ) -> list[CallableType]: + """Apply any configured filters to the possible guesses. + + Currently the only option is filtering based on Any prevalance.""" + return [ + t + for t in guesses + if self.flex_any is None + or any_score_callable(t, is_method, ignore_return) >= self.flex_any + ] + + def find_best(self, func: FuncDef, guesses: list[CallableType]) -> tuple[CallableType, int]: + """From a list of possible function types, find the best one. + + For best, we want the fewest errors, then the best "score" from score_callable. + """ + if not guesses: + raise SuggestionFailure("No guesses that match criteria!") + errors = {guess: self.try_type(func, guess) for guess in guesses} + best = min(guesses, key=lambda s: (count_errors(errors[s]), self.score_callable(s))) + return best, count_errors(errors[best]) + + def get_guesses_from_parent(self, node: FuncDef) -> list[CallableType]: + """Try to get a guess of a method type from a parent class.""" + if not node.info: + return [] + + for parent in node.info.mro[1:]: + pnode = parent.names.get(node.name) + if pnode and isinstance(pnode.node, (FuncDef, Decorator)): + typ = get_proper_type(pnode.node.type) + # FIXME: Doesn't work right with generic types + if isinstance(typ, CallableType) and len(typ.arg_types) == len(node.arguments): + # Return the first thing we find, since it probably doesn't make sense + # to grab things further up in the chain if an earlier parent has it. + return [typ] + + return [] + + def get_suggestion(self, mod: str, node: FuncDef) -> PyAnnotateSignature: + """Compute a suggestion for a function. + + Return the type and whether the first argument should be ignored. + """ + graph = self.graph + callsites, orig_errors = self.get_callsites(node) + uses = get_arg_uses(self.manager.all_types, node) + + if self.no_errors and orig_errors: + raise SuggestionFailure("Function does not typecheck.") + + is_method = bool(node.info) and node.has_self_or_cls_argument + + with state.strict_optional_set(graph[mod].options.strict_optional): + guesses = self.get_guesses( + is_method, + self.get_starting_type(node), + self.get_default_arg_types(node), + callsites, + uses, + ) + guesses += self.get_guesses_from_parent(node) + guesses = self.filter_options(guesses, is_method, ignore_return=True) + best, _ = self.find_best(node, guesses) + + # Now try to find the return type! + self.try_type(node, best) + returns = get_return_types(self.manager.all_types, node) + with state.strict_optional_set(graph[mod].options.strict_optional): + if returns: + ret_types = generate_type_combinations(returns) + else: + ret_types = [NoneType()] + + guesses = [best.copy_modified(ret_type=refine_type(best.ret_type, t)) for t in ret_types] + guesses = self.filter_options(guesses, is_method, ignore_return=False) + best, errors = self.find_best(node, guesses) + + if self.no_errors and errors: + raise SuggestionFailure("No annotation without errors") + + return self.pyannotate_signature(mod, is_method, best) + + def format_args( + self, + arg_kinds: list[list[ArgKind]], + arg_names: list[list[str | None]], + arg_types: list[list[Type]], + ) -> str: + args: list[str] = [] + for i in range(len(arg_types)): + for kind, name, typ in zip(arg_kinds[i], arg_names[i], arg_types[i]): + arg = self.format_type(None, typ) + if kind == ARG_STAR: + arg = "*" + arg + elif kind == ARG_STAR2: + arg = "**" + arg + elif kind.is_named(): + if name: + arg = f"{name}={arg}" + args.append(arg) + return f"({', '.join(args)})" + + def find_node(self, key: str) -> tuple[str, str, FuncDef]: + """From a target name, return module/target names and the func def. + + The 'key' argument can be in one of two formats: + * As the function full name, e.g., package.module.Cls.method + * As the function location as file and line separated by column, + e.g., path/to/file.py:42 + """ + # TODO: Also return OverloadedFuncDef -- currently these are ignored. + node: SymbolNode | None = None + if ":" in key: + # A colon might be part of a drive name on Windows (like `C:/foo/bar`) + # and is also used as a delimiter between file path and lineno. + # If a colon is there for any of those reasons, it must be a file+line + # reference. + platform_key_count = 2 if sys.platform == "win32" else 1 + if key.count(":") > platform_key_count: + raise SuggestionFailure( + "Malformed location for function: {}. Must be either" + " package.module.Class.method or path/to/file.py:line".format(key) + ) + file, line = key.rsplit(":", 1) + if not line.isdigit(): + raise SuggestionFailure(f"Line number must be a number. Got {line}") + line_number = int(line) + modname, node = self.find_node_by_file_and_line(file, line_number) + tail = node.fullname[len(modname) + 1 :] # add one to account for '.' + else: + target = split_target(self.fgmanager.graph, key) + if not target: + raise SuggestionFailure(f"Cannot find module for {key}") + modname, tail = target + node = self.find_node_by_module_and_name(modname, tail) + + if isinstance(node, Decorator): + node = self.extract_from_decorator(node) + if not node: + raise SuggestionFailure(f"Object {key} is a decorator we can't handle") + + if not isinstance(node, FuncDef): + raise SuggestionFailure(f"Object {key} is not a function") + + return modname, tail, node + + def find_node_by_module_and_name(self, modname: str, tail: str) -> SymbolNode | None: + """Find symbol node by module id and qualified name. + + Raise SuggestionFailure if can't find one. + """ + tree = self.ensure_loaded(self.fgmanager.graph[modname]) + + # N.B. This is reimplemented from update's lookup_target + # basically just to produce better error messages. + + names: SymbolTable = tree.names + + # Look through any classes + components = tail.split(".") + for i, component in enumerate(components[:-1]): + if component not in names: + raise SuggestionFailure( + "Unknown class {}.{}".format(modname, ".".join(components[: i + 1])) + ) + node: SymbolNode | None = names[component].node + if not isinstance(node, TypeInfo): + raise SuggestionFailure( + "Object {}.{} is not a class".format(modname, ".".join(components[: i + 1])) + ) + names = node.names + + # Look for the actual function/method + funcname = components[-1] + if funcname not in names: + key = modname + "." + tail + raise SuggestionFailure( + "Unknown {} {}".format("method" if len(components) > 1 else "function", key) + ) + return names[funcname].node + + def find_node_by_file_and_line(self, file: str, line: int) -> tuple[str, SymbolNode]: + """Find symbol node by path to file and line number. + + Find the first function declared *before or on* the line number. + + Return module id and the node found. Raise SuggestionFailure if can't find one. + """ + if not any(file.endswith(ext) for ext in PYTHON_EXTENSIONS): + raise SuggestionFailure("Source file is not a Python file") + try: + modname, _ = self.finder.crawl_up(os.path.normpath(file)) + except InvalidSourceList as e: + raise SuggestionFailure("Invalid source file name: " + file) from e + if modname not in self.graph: + raise SuggestionFailure("Unknown module: " + modname) + # We must be sure about any edits in this file as this might affect the line numbers. + tree = self.ensure_loaded(self.fgmanager.graph[modname], force=True) + node: SymbolNode | None = None + closest_line: int | None = None + # TODO: Handle nested functions. + for _, sym, _ in tree.local_definitions(): + if isinstance(sym.node, (FuncDef, Decorator)): + sym_line = sym.node.line + # TODO: add support for OverloadedFuncDef. + else: + continue + + # We want the closest function above the specified line + if sym_line <= line and (closest_line is None or sym_line > closest_line): + closest_line = sym_line + node = sym.node + if not node: + raise SuggestionFailure(f"Cannot find a function at line {line}") + return modname, node + + def extract_from_decorator(self, node: Decorator) -> FuncDef | None: + for dec in node.decorators: + typ = None + if isinstance(dec, RefExpr) and isinstance(dec.node, (Var, FuncDef)): + typ = get_proper_type(dec.node.type) + elif ( + isinstance(dec, CallExpr) + and isinstance(dec.callee, RefExpr) + and isinstance(dec.callee.node, (Decorator, FuncDef, Var)) + and isinstance((call_tp := get_proper_type(dec.callee.node.type)), CallableType) + ): + typ = get_proper_type(call_tp.ret_type) + + if isinstance(typ, Instance): + call_method = typ.type.get_method("__call__") + if isinstance(call_method, FuncDef) and isinstance(call_method.type, FunctionLike): + typ = bind_self(call_method.type, None) + + if not isinstance(typ, FunctionLike): + return None + for ct in typ.items: + if not ( + len(ct.arg_types) == 1 + and _arg_accepts_function(get_proper_type(ct.arg_types[0])) + and ct.arg_types[0] == ct.ret_type + ): + return None + + return node.func + + def try_type(self, func: FuncDef, typ: ProperType) -> list[str]: + """Recheck a function while assuming it has type typ. + + Return all error messages. + """ + old = func.unanalyzed_type + # During reprocessing, unanalyzed_type gets copied to type (by aststrip). + # We set type to None to ensure that the type always changes during + # reprocessing. + func.type = None + func.unanalyzed_type = typ + try: + res = self.fgmanager.trigger(func.fullname) + # if res: + # print('===', typ) + # print('\n'.join(res)) + return res + finally: + func.unanalyzed_type = old + + def reload(self, state: State) -> list[str]: + """Recheck the module given by state.""" + assert state.path is not None + self.fgmanager.flush_cache() + return self.fgmanager.update([(state.id, state.path)], []) + + def ensure_loaded(self, state: State, force: bool = False) -> MypyFile: + """Make sure that the module represented by state is fully loaded.""" + if not state.tree or state.tree.is_cache_skeleton or force: + self.reload(state) + assert state.tree is not None + return state.tree + + def named_type(self, s: str) -> Instance: + return self.manager.semantic_analyzer.named_type(s) + + def json_suggestion( + self, mod: str, func_name: str, node: FuncDef, suggestion: PyAnnotateSignature + ) -> str: + """Produce a json blob for a suggestion suitable for application by pyannotate.""" + # pyannotate irritatingly drops class names for class and static methods + if node.is_class or node.is_static: + func_name = func_name.split(".", 1)[-1] + + # pyannotate works with either paths relative to where the + # module is rooted or with absolute paths. We produce absolute + # paths because it is simpler. + path = os.path.abspath(self.graph[mod].xpath) + + obj = { + "signature": suggestion, + "line": node.line, + "path": path, + "func_name": func_name, + "samples": 0, + } + return json.dumps([obj], sort_keys=True) + + def pyannotate_signature( + self, cur_module: str | None, is_method: bool, typ: CallableType + ) -> PyAnnotateSignature: + """Format a callable type as a pyannotate dict""" + start = int(is_method) + return { + "arg_types": [self.format_type(cur_module, t) for t in typ.arg_types[start:]], + "return_type": self.format_type(cur_module, typ.ret_type), + } + + def format_signature(self, sig: PyAnnotateSignature) -> str: + """Format a callable type in a way suitable as an annotation... kind of""" + return f"({', '.join(sig['arg_types'])}) -> {sig['return_type']}" + + def format_type(self, cur_module: str | None, typ: Type) -> str: + if self.use_fixme and isinstance(get_proper_type(typ), AnyType): + return self.use_fixme + return typ.accept(TypeFormatter(cur_module, self.graph, self.manager.options)) + + def score_type(self, t: Type, arg_pos: bool) -> int: + """Generate a score for a type that we use to pick which type to use. + + Lower is better, prefer non-union/non-any types. Don't penalize optionals. + """ + t = get_proper_type(t) + if isinstance(t, AnyType): + return 20 + if arg_pos and isinstance(t, NoneType): + return 20 + if isinstance(t, UnionType): + if any(isinstance(get_proper_type(x), AnyType) for x in t.items): + return 20 + if any(has_any_type(x) for x in t.items): + return 15 + if not is_overlapping_none(t): + return 10 + if isinstance(t, CallableType) and (has_any_type(t) or is_tricky_callable(t)): + return 10 + return 0 + + def score_callable(self, t: CallableType) -> int: + return sum(self.score_type(x, arg_pos=True) for x in t.arg_types) + self.score_type( + t.ret_type, arg_pos=False + ) + + +def any_score_type(ut: Type, arg_pos: bool) -> float: + """Generate a very made up number representing the Anyness of a type. + + Higher is better, 1.0 is max + """ + t = get_proper_type(ut) + if isinstance(t, AnyType) and t.type_of_any != TypeOfAny.suggestion_engine: + return 0 + if isinstance(t, NoneType) and arg_pos: + return 0.5 + if isinstance(t, UnionType): + if any(isinstance(get_proper_type(x), AnyType) for x in t.items): + return 0.5 + if any(has_any_type(x) for x in t.items): + return 0.25 + if isinstance(t, CallableType) and is_tricky_callable(t): + return 0.5 + if has_any_type(t): + return 0.5 + + return 1.0 + + +def any_score_callable(t: CallableType, is_method: bool, ignore_return: bool) -> float: + # Ignore the first argument of methods + scores = [any_score_type(x, arg_pos=True) for x in t.arg_types[int(is_method) :]] + # Return type counts twice (since it spreads type information), unless it is + # None in which case it does not count at all. (Though it *does* still count + # if there are no arguments.) + if not isinstance(get_proper_type(t.ret_type), NoneType) or not scores: + ret = 1.0 if ignore_return else any_score_type(t.ret_type, arg_pos=False) + scores += [ret, ret] + + return sum(scores) / len(scores) + + +def is_tricky_callable(t: CallableType) -> bool: + """Is t a callable that we need to put a ... in for syntax reasons?""" + return t.is_ellipsis_args or any(k.is_star() or k.is_named() for k in t.arg_kinds) + + +class TypeFormatter(TypeStrVisitor): + """Visitor used to format types""" + + # TODO: Probably a lot + def __init__(self, module: str | None, graph: Graph, options: Options) -> None: + super().__init__(options=options) + self.module = module + self.graph = graph + + def visit_any(self, t: AnyType) -> str: + if t.missing_import_name: + return t.missing_import_name + else: + return "Any" + + def visit_instance(self, t: Instance) -> str: + s = t.type.fullname or t.type.name or None + if s is None: + return "" + + mod_obj = split_target(self.graph, s) + assert mod_obj + mod, obj = mod_obj + + # If a class is imported into the current module, rewrite the reference + # to point to the current module. This helps the annotation tool avoid + # inserting redundant imports when a type has been reexported. + if self.module: + parts = obj.split(".") # need to split the object part if it is a nested class + tree = self.graph[self.module].tree + if tree and parts[0] in tree.names and mod not in tree.names: + mod = self.module + + if (mod, obj) == ("builtins", "tuple"): + mod, obj = "typing", "Tuple[" + t.args[0].accept(self) + ", ...]" + elif t.args: + obj += f"[{self.list_str(t.args)}]" + + if mod_obj == ("builtins", "unicode"): + return "Text" + elif mod == "builtins": + return obj + else: + delim = "." if "." not in obj else ":" + return mod + delim + obj + + def visit_tuple_type(self, t: TupleType) -> str: + if t.partial_fallback and t.partial_fallback.type: + fallback_name = t.partial_fallback.type.fullname + if fallback_name != "builtins.tuple": + return t.partial_fallback.accept(self) + s = self.list_str(t.items) + return f"Tuple[{s}]" + + def visit_uninhabited_type(self, t: UninhabitedType) -> str: + return "Any" + + def visit_typeddict_type(self, t: TypedDictType) -> str: + return t.fallback.accept(self) + + def visit_union_type(self, t: UnionType) -> str: + if len(t.items) == 2 and is_overlapping_none(t): + s = remove_optional(t).accept(self) + return f"{s} | None" + else: + return super().visit_union_type(t) + + def visit_callable_type(self, t: CallableType) -> str: + # TODO: use extended callables? + if is_tricky_callable(t): + arg_str = "..." + else: + # Note: for default arguments, we just assume that they + # are required. This isn't right, but neither is the + # other thing, and I suspect this will produce more better + # results than falling back to `...` + args = [typ.accept(self) for typ in t.arg_types] + arg_str = f"[{', '.join(args)}]" + + return f"Callable[{arg_str}, {t.ret_type.accept(self)}]" + + +TType = TypeVar("TType", bound=Type) + + +def make_suggestion_anys(t: TType) -> TType: + """Make all anys in the type as coming from the suggestion engine. + + This keeps those Anys from influencing constraint generation, + which allows us to do better when refining types. + """ + return cast(TType, t.accept(MakeSuggestionAny())) + + +class MakeSuggestionAny(TypeTranslator): + def visit_any(self, t: AnyType) -> Type: + if not t.missing_import_name: + return t.copy_modified(type_of_any=TypeOfAny.suggestion_engine) + else: + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def generate_type_combinations(types: list[Type]) -> list[Type]: + """Generate possible combinations of a list of types. + + mypy essentially supports two different ways to do this: joining the types + and unioning the types. We try both. + """ + joined_type = join_type_list(types) + union_type = make_simplified_union(types) + if joined_type == union_type: + return [joined_type] + else: + return [joined_type, union_type] + + +def count_errors(msgs: list[str]) -> int: + return len([x for x in msgs if " error: " in x]) + + +def refine_type(ti: Type, si: Type) -> Type: + """Refine `ti` by replacing Anys in it with information taken from `si` + + This basically works by, when the types have the same structure, + traversing both of them in parallel and replacing Any on the left + with whatever the type on the right is. If the types don't have the + same structure (or aren't supported), the left type is chosen. + + For example: + refine(Any, T) = T, for all T + refine(float, int) = float + refine(List[Any], List[int]) = List[int] + refine(Dict[int, Any], Dict[Any, int]) = Dict[int, int] + refine(Tuple[int, Any], Tuple[Any, int]) = Tuple[int, int] + + refine(Callable[[Any], Any], Callable[[int], int]) = Callable[[int], int] + refine(Callable[..., int], Callable[[int, float], Any]) = Callable[[int, float], int] + + refine(Optional[Any], int) = Optional[int] + refine(Optional[Any], Optional[int]) = Optional[int] + refine(Optional[Any], Union[int, str]) = Optional[Union[int, str]] + refine(Optional[List[Any]], List[int]) = List[int] + + """ + t = get_proper_type(ti) + s = get_proper_type(si) + + if isinstance(t, AnyType): + # If s is also an Any, we return if it is a missing_import Any + return t if isinstance(s, AnyType) and t.missing_import_name else s + + if isinstance(t, Instance) and isinstance(s, Instance) and t.type == s.type: + return t.copy_modified(args=[refine_type(ta, sa) for ta, sa in zip(t.args, s.args)]) + + if ( + isinstance(t, TupleType) + and isinstance(s, TupleType) + and t.partial_fallback == s.partial_fallback + and len(t.items) == len(s.items) + ): + return t.copy_modified(items=[refine_type(ta, sa) for ta, sa in zip(t.items, s.items)]) + + if isinstance(t, CallableType) and isinstance(s, CallableType): + return refine_callable(t, s) + + if isinstance(t, UnionType): + return refine_union(t, s) + + # TODO: Refining of builtins.tuple, Type? + + return t + + +def refine_union(t: UnionType, s: ProperType) -> Type: + """Refine a union type based on another type. + + This is done by refining every component of the union against the + right hand side type (or every component of its union if it is + one). If an element of the union is successfully refined, we drop it + from the union in favor of the refined versions. + """ + # Don't try to do any union refining if the types are already the + # same. This prevents things like refining Optional[Any] against + # itself and producing None. + if t == s: + return t + + rhs_items = s.items if isinstance(s, UnionType) else [s] + + new_items = [] + for lhs in t.items: + refined = False + for rhs in rhs_items: + new = refine_type(lhs, rhs) + if new != lhs: + new_items.append(new) + refined = True + if not refined: + new_items.append(lhs) + + # Turn strict optional on when simplifying the union since we + # don't want to drop Nones. + with state.strict_optional_set(True): + return make_simplified_union(new_items) + + +def refine_callable(t: CallableType, s: CallableType) -> CallableType: + """Refine a callable based on another. + + See comments for refine_type. + """ + if t.fallback != s.fallback: + return t + + if t.is_ellipsis_args and not is_tricky_callable(s): + return s.copy_modified(ret_type=refine_type(t.ret_type, s.ret_type)) + + if is_tricky_callable(t) or t.arg_kinds != s.arg_kinds: + return t + + return t.copy_modified( + arg_types=[refine_type(ta, sa) for ta, sa in zip(t.arg_types, s.arg_types)], + ret_type=refine_type(t.ret_type, s.ret_type), + ) + + +T = TypeVar("T") + + +def dedup(old: list[T]) -> list[T]: + new: list[T] = [] + for x in old: + if x not in new: + new.append(x) + return new diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/traverser.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/traverser.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3ed8b14e6f53f2fdab5312cbcdb142f563577ca6 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/traverser.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/traverser.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/traverser.py new file mode 100644 index 0000000000000000000000000000000000000000..6fdb54298f85c42e872b1acf35e4981f717cc0f7 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/traverser.py @@ -0,0 +1,1105 @@ +"""Generic node traverser visitor""" + +from __future__ import annotations + +from mypy_extensions import mypyc_attr, trait + +from mypy.nodes import ( + REVEAL_TYPE, + AssertStmt, + AssertTypeExpr, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + ExpressionStmt, + FloatExpr, + ForStmt, + FuncBase, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + ParamSpecExpr, + PassStmt, + PromoteExpr, + RaiseStmt, + ReturnStmt, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAlias, + TypeAliasExpr, + TypeAliasStmt, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, +) +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.visitor import NodeVisitor + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class TraverserVisitor(NodeVisitor[None]): + """A parse tree visitor that traverses the parse tree during visiting. + + It does not perform any actions outside the traversal. Subclasses + should override visit methods to perform actions during + traversal. Calling the superclass method allows reusing the + traversal implementation. + + TODO: split this into more limited visitor (e.g. statements-only etc). + This will improve performance since in many cases we don't need to recurse + all the way down in various visitors that subclass this. + """ + + def __init__(self) -> None: + pass + + # Visit methods + + def visit_mypy_file(self, o: MypyFile, /) -> None: + for d in o.defs: + d.accept(self) + + def visit_block(self, block: Block, /) -> None: + for s in block.body: + s.accept(self) + + def visit_func(self, o: FuncItem, /) -> None: + if o.arguments is not None: + for arg in o.arguments: + init = arg.initializer + if init is not None: + init.accept(self) + + for arg in o.arguments: + self.visit_var(arg.variable) + + o.body.accept(self) + + def visit_func_def(self, o: FuncDef, /) -> None: + self.visit_func(o) + + def visit_overloaded_func_def(self, o: OverloadedFuncDef, /) -> None: + for item in o.items: + item.accept(self) + if o.impl: + o.impl.accept(self) + + def visit_class_def(self, o: ClassDef, /) -> None: + for d in o.decorators: + d.accept(self) + for base in o.base_type_exprs: + base.accept(self) + if o.metaclass: + o.metaclass.accept(self) + for v in o.keywords.values(): + v.accept(self) + o.defs.accept(self) + if o.analyzed: + o.analyzed.accept(self) + + def visit_decorator(self, o: Decorator, /) -> None: + o.func.accept(self) + o.var.accept(self) + for decorator in o.decorators: + decorator.accept(self) + + def visit_expression_stmt(self, o: ExpressionStmt, /) -> None: + o.expr.accept(self) + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + o.rvalue.accept(self) + for l in o.lvalues: + l.accept(self) + + def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt, /) -> None: + o.rvalue.accept(self) + o.lvalue.accept(self) + + def visit_while_stmt(self, o: WhileStmt, /) -> None: + o.expr.accept(self) + o.body.accept(self) + if o.else_body: + o.else_body.accept(self) + + def visit_for_stmt(self, o: ForStmt, /) -> None: + o.index.accept(self) + o.expr.accept(self) + o.body.accept(self) + if o.else_body: + o.else_body.accept(self) + + def visit_return_stmt(self, o: ReturnStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + + def visit_assert_stmt(self, o: AssertStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + if o.msg is not None: + o.msg.accept(self) + + def visit_del_stmt(self, o: DelStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + + def visit_if_stmt(self, o: IfStmt, /) -> None: + for e in o.expr: + e.accept(self) + for b in o.body: + b.accept(self) + if o.else_body: + o.else_body.accept(self) + + def visit_raise_stmt(self, o: RaiseStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + if o.from_expr is not None: + o.from_expr.accept(self) + + def visit_try_stmt(self, o: TryStmt, /) -> None: + o.body.accept(self) + for i in range(len(o.types)): + tp = o.types[i] + if tp is not None: + tp.accept(self) + o.handlers[i].accept(self) + for v in o.vars: + if v is not None: + v.accept(self) + if o.else_body is not None: + o.else_body.accept(self) + if o.finally_body is not None: + o.finally_body.accept(self) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + for i in range(len(o.expr)): + o.expr[i].accept(self) + targ = o.target[i] + if targ is not None: + targ.accept(self) + o.body.accept(self) + + def visit_match_stmt(self, o: MatchStmt, /) -> None: + o.subject.accept(self) + for i in range(len(o.patterns)): + o.patterns[i].accept(self) + guard = o.guards[i] + if guard is not None: + guard.accept(self) + o.bodies[i].accept(self) + + def visit_type_alias_stmt(self, o: TypeAliasStmt, /) -> None: + o.name.accept(self) + o.value.accept(self) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + o.expr.accept(self) + + def visit_yield_from_expr(self, o: YieldFromExpr, /) -> None: + o.expr.accept(self) + + def visit_yield_expr(self, o: YieldExpr, /) -> None: + if o.expr: + o.expr.accept(self) + + def visit_call_expr(self, o: CallExpr, /) -> None: + o.callee.accept(self) + for a in o.args: + a.accept(self) + if o.analyzed: + o.analyzed.accept(self) + + def visit_op_expr(self, o: OpExpr, /) -> None: + o.left.accept(self) + o.right.accept(self) + if o.analyzed is not None: + o.analyzed.accept(self) + + def visit_comparison_expr(self, o: ComparisonExpr, /) -> None: + for operand in o.operands: + operand.accept(self) + + def visit_slice_expr(self, o: SliceExpr, /) -> None: + if o.begin_index is not None: + o.begin_index.accept(self) + if o.end_index is not None: + o.end_index.accept(self) + if o.stride is not None: + o.stride.accept(self) + + def visit_cast_expr(self, o: CastExpr, /) -> None: + o.expr.accept(self) + + def visit_type_form_expr(self, o: TypeFormExpr, /) -> None: + pass + + def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None: + o.expr.accept(self) + + def visit_reveal_expr(self, o: RevealExpr, /) -> None: + if o.kind == REVEAL_TYPE: + assert o.expr is not None + o.expr.accept(self) + else: + # RevealLocalsExpr doesn't have an inner expression + pass + + def visit_assignment_expr(self, o: AssignmentExpr, /) -> None: + o.target.accept(self) + o.value.accept(self) + + def visit_unary_expr(self, o: UnaryExpr, /) -> None: + o.expr.accept(self) + + def visit_list_expr(self, o: ListExpr, /) -> None: + for item in o.items: + item.accept(self) + + def visit_tuple_expr(self, o: TupleExpr, /) -> None: + for item in o.items: + item.accept(self) + + def visit_dict_expr(self, o: DictExpr, /) -> None: + for k, v in o.items: + if k is not None: + k.accept(self) + v.accept(self) + + def visit_template_str_expr(self, o: TemplateStrExpr, /) -> None: + for item in o.items: + if isinstance(item, tuple): + item[0].accept(self) + if item[3] is not None: + item[3].accept(self) + else: + item.accept(self) + + def visit_set_expr(self, o: SetExpr, /) -> None: + for item in o.items: + item.accept(self) + + def visit_index_expr(self, o: IndexExpr, /) -> None: + o.base.accept(self) + o.index.accept(self) + if o.analyzed: + o.analyzed.accept(self) + + def visit_generator_expr(self, o: GeneratorExpr, /) -> None: + for index, sequence, conditions in zip(o.indices, o.sequences, o.condlists): + sequence.accept(self) + index.accept(self) + for cond in conditions: + cond.accept(self) + o.left_expr.accept(self) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None: + for index, sequence, conditions in zip(o.indices, o.sequences, o.condlists): + sequence.accept(self) + index.accept(self) + for cond in conditions: + cond.accept(self) + o.key.accept(self) + o.value.accept(self) + + def visit_list_comprehension(self, o: ListComprehension, /) -> None: + o.generator.accept(self) + + def visit_set_comprehension(self, o: SetComprehension, /) -> None: + o.generator.accept(self) + + def visit_conditional_expr(self, o: ConditionalExpr, /) -> None: + o.cond.accept(self) + o.if_expr.accept(self) + o.else_expr.accept(self) + + def visit_type_application(self, o: TypeApplication, /) -> None: + o.expr.accept(self) + + def visit_lambda_expr(self, o: LambdaExpr, /) -> None: + self.visit_func(o) + + def visit_star_expr(self, o: StarExpr, /) -> None: + o.expr.accept(self) + + def visit_await_expr(self, o: AwaitExpr, /) -> None: + o.expr.accept(self) + + def visit_super_expr(self, o: SuperExpr, /) -> None: + o.call.accept(self) + + def visit_as_pattern(self, o: AsPattern, /) -> None: + if o.pattern is not None: + o.pattern.accept(self) + if o.name is not None: + o.name.accept(self) + + def visit_or_pattern(self, o: OrPattern, /) -> None: + for p in o.patterns: + p.accept(self) + + def visit_value_pattern(self, o: ValuePattern, /) -> None: + o.expr.accept(self) + + def visit_sequence_pattern(self, o: SequencePattern, /) -> None: + for p in o.patterns: + p.accept(self) + + def visit_starred_pattern(self, o: StarredPattern, /) -> None: + if o.capture is not None: + o.capture.accept(self) + + def visit_mapping_pattern(self, o: MappingPattern, /) -> None: + for key in o.keys: + key.accept(self) + for value in o.values: + value.accept(self) + if o.rest is not None: + o.rest.accept(self) + + def visit_class_pattern(self, o: ClassPattern, /) -> None: + o.class_ref.accept(self) + for p in o.positionals: + p.accept(self) + for v in o.keyword_values: + v.accept(self) + + def visit_import(self, o: Import, /) -> None: + for a in o.assignments: + a.accept(self) + + def visit_import_from(self, o: ImportFrom, /) -> None: + for a in o.assignments: + a.accept(self) + + # leaf nodes + def visit_name_expr(self, o: NameExpr, /) -> None: + return None + + def visit_str_expr(self, o: StrExpr, /) -> None: + return None + + def visit_int_expr(self, o: IntExpr, /) -> None: + return None + + def visit_float_expr(self, o: FloatExpr, /) -> None: + return None + + def visit_bytes_expr(self, o: BytesExpr, /) -> None: + return None + + def visit_ellipsis(self, o: EllipsisExpr, /) -> None: + return None + + def visit_var(self, o: Var, /) -> None: + return None + + def visit_continue_stmt(self, o: ContinueStmt, /) -> None: + return None + + def visit_pass_stmt(self, o: PassStmt, /) -> None: + return None + + def visit_break_stmt(self, o: BreakStmt, /) -> None: + return None + + def visit_temp_node(self, o: TempNode, /) -> None: + return None + + def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None: + return None + + def visit_global_decl(self, o: GlobalDecl, /) -> None: + return None + + def visit_import_all(self, o: ImportAll, /) -> None: + return None + + def visit_type_var_expr(self, o: TypeVarExpr, /) -> None: + return None + + def visit_paramspec_expr(self, o: ParamSpecExpr, /) -> None: + return None + + def visit_type_var_tuple_expr(self, o: TypeVarTupleExpr, /) -> None: + return None + + def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None: + return None + + def visit_type_alias(self, o: TypeAlias, /) -> None: + return None + + def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None: + return None + + def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None: + return None + + def visit_newtype_expr(self, o: NewTypeExpr, /) -> None: + return None + + def visit__promote_expr(self, o: PromoteExpr, /) -> None: + return None + + def visit_complex_expr(self, o: ComplexExpr, /) -> None: + return None + + def visit_enum_call_expr(self, o: EnumCallExpr, /) -> None: + return None + + def visit_singleton_pattern(self, o: SingletonPattern, /) -> None: + return None + + +class ExtendedTraverserVisitor(TraverserVisitor): + """This is a more flexible traverser. + + In addition to the base traverser it: + * has visit_ methods for leaf nodes + * has common method that is called for all nodes + * allows skipping recursing into a node + + Note that this traverser still doesn't visit some internal + mypy constructs like _promote expression and Var. + """ + + def visit(self, o: Node) -> bool: + # If returns True, will continue to nested nodes. + return True + + def visit_mypy_file(self, o: MypyFile, /) -> None: + if not self.visit(o): + return + super().visit_mypy_file(o) + + # Module structure + + def visit_import(self, o: Import, /) -> None: + if not self.visit(o): + return + super().visit_import(o) + + def visit_import_from(self, o: ImportFrom, /) -> None: + if not self.visit(o): + return + super().visit_import_from(o) + + def visit_import_all(self, o: ImportAll, /) -> None: + if not self.visit(o): + return + super().visit_import_all(o) + + # Definitions + + def visit_func_def(self, o: FuncDef, /) -> None: + if not self.visit(o): + return + super().visit_func_def(o) + + def visit_overloaded_func_def(self, o: OverloadedFuncDef, /) -> None: + if not self.visit(o): + return + super().visit_overloaded_func_def(o) + + def visit_class_def(self, o: ClassDef, /) -> None: + if not self.visit(o): + return + super().visit_class_def(o) + + def visit_global_decl(self, o: GlobalDecl, /) -> None: + if not self.visit(o): + return + super().visit_global_decl(o) + + def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None: + if not self.visit(o): + return + super().visit_nonlocal_decl(o) + + def visit_decorator(self, o: Decorator, /) -> None: + if not self.visit(o): + return + super().visit_decorator(o) + + def visit_type_alias(self, o: TypeAlias, /) -> None: + if not self.visit(o): + return + super().visit_type_alias(o) + + # Statements + + def visit_block(self, block: Block, /) -> None: + if not self.visit(block): + return + super().visit_block(block) + + def visit_expression_stmt(self, o: ExpressionStmt, /) -> None: + if not self.visit(o): + return + super().visit_expression_stmt(o) + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + if not self.visit(o): + return + super().visit_assignment_stmt(o) + + def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt, /) -> None: + if not self.visit(o): + return + super().visit_operator_assignment_stmt(o) + + def visit_while_stmt(self, o: WhileStmt, /) -> None: + if not self.visit(o): + return + super().visit_while_stmt(o) + + def visit_for_stmt(self, o: ForStmt, /) -> None: + if not self.visit(o): + return + super().visit_for_stmt(o) + + def visit_return_stmt(self, o: ReturnStmt, /) -> None: + if not self.visit(o): + return + super().visit_return_stmt(o) + + def visit_assert_stmt(self, o: AssertStmt, /) -> None: + if not self.visit(o): + return + super().visit_assert_stmt(o) + + def visit_del_stmt(self, o: DelStmt, /) -> None: + if not self.visit(o): + return + super().visit_del_stmt(o) + + def visit_if_stmt(self, o: IfStmt, /) -> None: + if not self.visit(o): + return + super().visit_if_stmt(o) + + def visit_break_stmt(self, o: BreakStmt, /) -> None: + if not self.visit(o): + return + super().visit_break_stmt(o) + + def visit_continue_stmt(self, o: ContinueStmt, /) -> None: + if not self.visit(o): + return + super().visit_continue_stmt(o) + + def visit_pass_stmt(self, o: PassStmt, /) -> None: + if not self.visit(o): + return + super().visit_pass_stmt(o) + + def visit_raise_stmt(self, o: RaiseStmt, /) -> None: + if not self.visit(o): + return + super().visit_raise_stmt(o) + + def visit_try_stmt(self, o: TryStmt, /) -> None: + if not self.visit(o): + return + super().visit_try_stmt(o) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + if not self.visit(o): + return + super().visit_with_stmt(o) + + def visit_match_stmt(self, o: MatchStmt, /) -> None: + if not self.visit(o): + return + super().visit_match_stmt(o) + + # Expressions (default no-op implementation) + + def visit_int_expr(self, o: IntExpr, /) -> None: + if not self.visit(o): + return + super().visit_int_expr(o) + + def visit_str_expr(self, o: StrExpr, /) -> None: + if not self.visit(o): + return + super().visit_str_expr(o) + + def visit_bytes_expr(self, o: BytesExpr, /) -> None: + if not self.visit(o): + return + super().visit_bytes_expr(o) + + def visit_float_expr(self, o: FloatExpr, /) -> None: + if not self.visit(o): + return + super().visit_float_expr(o) + + def visit_complex_expr(self, o: ComplexExpr, /) -> None: + if not self.visit(o): + return + super().visit_complex_expr(o) + + def visit_ellipsis(self, o: EllipsisExpr, /) -> None: + if not self.visit(o): + return + super().visit_ellipsis(o) + + def visit_star_expr(self, o: StarExpr, /) -> None: + if not self.visit(o): + return + super().visit_star_expr(o) + + def visit_name_expr(self, o: NameExpr, /) -> None: + if not self.visit(o): + return + super().visit_name_expr(o) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + if not self.visit(o): + return + super().visit_member_expr(o) + + def visit_yield_from_expr(self, o: YieldFromExpr, /) -> None: + if not self.visit(o): + return + super().visit_yield_from_expr(o) + + def visit_yield_expr(self, o: YieldExpr, /) -> None: + if not self.visit(o): + return + super().visit_yield_expr(o) + + def visit_call_expr(self, o: CallExpr, /) -> None: + if not self.visit(o): + return + super().visit_call_expr(o) + + def visit_op_expr(self, o: OpExpr, /) -> None: + if not self.visit(o): + return + super().visit_op_expr(o) + + def visit_comparison_expr(self, o: ComparisonExpr, /) -> None: + if not self.visit(o): + return + super().visit_comparison_expr(o) + + def visit_cast_expr(self, o: CastExpr, /) -> None: + if not self.visit(o): + return + super().visit_cast_expr(o) + + def visit_type_form_expr(self, o: TypeFormExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_form_expr(o) + + def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None: + if not self.visit(o): + return + super().visit_assert_type_expr(o) + + def visit_reveal_expr(self, o: RevealExpr, /) -> None: + if not self.visit(o): + return + super().visit_reveal_expr(o) + + def visit_super_expr(self, o: SuperExpr, /) -> None: + if not self.visit(o): + return + super().visit_super_expr(o) + + def visit_assignment_expr(self, o: AssignmentExpr, /) -> None: + if not self.visit(o): + return + super().visit_assignment_expr(o) + + def visit_unary_expr(self, o: UnaryExpr, /) -> None: + if not self.visit(o): + return + super().visit_unary_expr(o) + + def visit_list_expr(self, o: ListExpr, /) -> None: + if not self.visit(o): + return + super().visit_list_expr(o) + + def visit_dict_expr(self, o: DictExpr, /) -> None: + if not self.visit(o): + return + super().visit_dict_expr(o) + + def visit_template_str_expr(self, o: TemplateStrExpr, /) -> None: + if not self.visit(o): + return + super().visit_template_str_expr(o) + + def visit_tuple_expr(self, o: TupleExpr, /) -> None: + if not self.visit(o): + return + super().visit_tuple_expr(o) + + def visit_set_expr(self, o: SetExpr, /) -> None: + if not self.visit(o): + return + super().visit_set_expr(o) + + def visit_index_expr(self, o: IndexExpr, /) -> None: + if not self.visit(o): + return + super().visit_index_expr(o) + + def visit_type_application(self, o: TypeApplication, /) -> None: + if not self.visit(o): + return + super().visit_type_application(o) + + def visit_lambda_expr(self, o: LambdaExpr, /) -> None: + if not self.visit(o): + return + super().visit_lambda_expr(o) + + def visit_list_comprehension(self, o: ListComprehension, /) -> None: + if not self.visit(o): + return + super().visit_list_comprehension(o) + + def visit_set_comprehension(self, o: SetComprehension, /) -> None: + if not self.visit(o): + return + super().visit_set_comprehension(o) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None: + if not self.visit(o): + return + super().visit_dictionary_comprehension(o) + + def visit_generator_expr(self, o: GeneratorExpr, /) -> None: + if not self.visit(o): + return + super().visit_generator_expr(o) + + def visit_slice_expr(self, o: SliceExpr, /) -> None: + if not self.visit(o): + return + super().visit_slice_expr(o) + + def visit_conditional_expr(self, o: ConditionalExpr, /) -> None: + if not self.visit(o): + return + super().visit_conditional_expr(o) + + def visit_type_var_expr(self, o: TypeVarExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_var_expr(o) + + def visit_paramspec_expr(self, o: ParamSpecExpr, /) -> None: + if not self.visit(o): + return + super().visit_paramspec_expr(o) + + def visit_type_var_tuple_expr(self, o: TypeVarTupleExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_var_tuple_expr(o) + + def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_alias_expr(o) + + def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None: + if not self.visit(o): + return + super().visit_namedtuple_expr(o) + + def visit_enum_call_expr(self, o: EnumCallExpr, /) -> None: + if not self.visit(o): + return + super().visit_enum_call_expr(o) + + def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None: + if not self.visit(o): + return + super().visit_typeddict_expr(o) + + def visit_newtype_expr(self, o: NewTypeExpr, /) -> None: + if not self.visit(o): + return + super().visit_newtype_expr(o) + + def visit_await_expr(self, o: AwaitExpr, /) -> None: + if not self.visit(o): + return + super().visit_await_expr(o) + + # Patterns + + def visit_as_pattern(self, o: AsPattern, /) -> None: + if not self.visit(o): + return + super().visit_as_pattern(o) + + def visit_or_pattern(self, o: OrPattern, /) -> None: + if not self.visit(o): + return + super().visit_or_pattern(o) + + def visit_value_pattern(self, o: ValuePattern, /) -> None: + if not self.visit(o): + return + super().visit_value_pattern(o) + + def visit_singleton_pattern(self, o: SingletonPattern, /) -> None: + if not self.visit(o): + return + super().visit_singleton_pattern(o) + + def visit_sequence_pattern(self, o: SequencePattern, /) -> None: + if not self.visit(o): + return + super().visit_sequence_pattern(o) + + def visit_starred_pattern(self, o: StarredPattern, /) -> None: + if not self.visit(o): + return + super().visit_starred_pattern(o) + + def visit_mapping_pattern(self, o: MappingPattern, /) -> None: + if not self.visit(o): + return + super().visit_mapping_pattern(o) + + def visit_class_pattern(self, o: ClassPattern, /) -> None: + if not self.visit(o): + return + super().visit_class_pattern(o) + + +class ReturnSeeker(TraverserVisitor): + def __init__(self) -> None: + self.found = False + + def visit_return_stmt(self, o: ReturnStmt) -> None: + if o.expr is None or isinstance(o.expr, NameExpr) and o.expr.name == "None": + return + self.found = True + + +def has_return_statement(fdef: FuncBase) -> bool: + """Find if a function has a non-trivial return statement. + + Plain 'return' and 'return None' don't count. + """ + seeker = ReturnSeeker() + fdef.accept(seeker) + return seeker.found + + +class NameAndMemberCollector(TraverserVisitor): + def __init__(self) -> None: + super().__init__() + self.name_exprs: list[NameExpr] = [] + self.member_exprs: list[MemberExpr] = [] + + def visit_name_expr(self, o: NameExpr, /) -> None: + self.name_exprs.append(o) + super().visit_name_expr(o) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + self.member_exprs.append(o) + super().visit_member_expr(o) + + +def all_name_and_member_expressions(node: Expression) -> tuple[list[NameExpr], list[MemberExpr]]: + v = NameAndMemberCollector() + node.accept(v) + return (v.name_exprs, v.member_exprs) + + +class StringSeeker(TraverserVisitor): + def __init__(self) -> None: + self.found = False + + def visit_str_expr(self, o: StrExpr, /) -> None: + self.found = True + + +def has_str_expression(node: Expression) -> bool: + v = StringSeeker() + node.accept(v) + return v.found + + +class FuncCollectorBase(TraverserVisitor): + def __init__(self) -> None: + self.inside_func = False + + def visit_func_def(self, defn: FuncDef) -> None: + if not self.inside_func: + self.inside_func = True + super().visit_func_def(defn) + self.inside_func = False + + +class YieldSeeker(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.found = False + + def visit_yield_expr(self, o: YieldExpr) -> None: + self.found = True + + +def has_yield_expression(fdef: FuncBase) -> bool: + seeker = YieldSeeker() + fdef.accept(seeker) + return seeker.found + + +class YieldFromSeeker(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.found = False + + def visit_yield_from_expr(self, o: YieldFromExpr) -> None: + self.found = True + + +def has_yield_from_expression(fdef: FuncBase) -> bool: + seeker = YieldFromSeeker() + fdef.accept(seeker) + return seeker.found + + +class AwaitSeeker(TraverserVisitor): + def __init__(self) -> None: + super().__init__() + self.found = False + + def visit_await_expr(self, o: AwaitExpr) -> None: + self.found = True + + +def has_await_expression(expr: Expression) -> bool: + seeker = AwaitSeeker() + expr.accept(seeker) + return seeker.found + + +class ReturnCollector(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.return_statements: list[ReturnStmt] = [] + + def visit_return_stmt(self, stmt: ReturnStmt) -> None: + self.return_statements.append(stmt) + + +def all_return_statements(node: Node) -> list[ReturnStmt]: + v = ReturnCollector() + node.accept(v) + return v.return_statements + + +class YieldCollector(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.in_assignment = False + self.yield_expressions: list[tuple[YieldExpr, bool]] = [] + + def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None: + self.in_assignment = True + super().visit_assignment_stmt(stmt) + self.in_assignment = False + + def visit_yield_expr(self, expr: YieldExpr) -> None: + self.yield_expressions.append((expr, self.in_assignment)) + + +def all_yield_expressions(node: Node) -> list[tuple[YieldExpr, bool]]: + v = YieldCollector() + node.accept(v) + return v.yield_expressions + + +class YieldFromCollector(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.in_assignment = False + self.yield_from_expressions: list[tuple[YieldFromExpr, bool]] = [] + + def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None: + self.in_assignment = True + super().visit_assignment_stmt(stmt) + self.in_assignment = False + + def visit_yield_from_expr(self, expr: YieldFromExpr) -> None: + self.yield_from_expressions.append((expr, self.in_assignment)) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/treetransform.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/treetransform.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..022721d182b9f5bd9a90aabb7adb95842fed94f0 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/treetransform.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/treetransform.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/treetransform.py new file mode 100644 index 0000000000000000000000000000000000000000..25092de66a149d143a96c92fbea58c6ad6664f3b --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/treetransform.py @@ -0,0 +1,820 @@ +"""Base visitor that implements an identity AST transform. + +Subclass TransformVisitor to perform non-trivial transformations. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import cast + +from mypy.nodes import ( + GDEF, + REVEAL_TYPE, + Argument, + AssertStmt, + AssertTypeExpr, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + ExpressionStmt, + FloatExpr, + ForStmt, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + ParamSpecExpr, + PassStmt, + PromoteExpr, + RaiseStmt, + RefExpr, + ReturnStmt, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + SuperExpr, + SymbolTable, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAliasExpr, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, +) +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + Pattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.traverser import TraverserVisitor +from mypy.types import FunctionLike, ProperType, Type +from mypy.util import replace_object_state +from mypy.visitor import NodeVisitor + + +class TransformVisitor(NodeVisitor[Node]): + """Transform a semantically analyzed AST (or subtree) to an identical copy. + + Use the node() method to transform an AST node. + + Subclass to perform a non-identity transform. + + Notes: + + * This can only be used to transform functions or classes, not top-level + statements, and/or modules as a whole. + * Do not duplicate TypeInfo nodes. This would generally not be desirable. + * Only update some name binding cross-references, but only those that + refer to Var, Decorator or FuncDef nodes, not those targeting ClassDef or + TypeInfo nodes. + * Types are not transformed, but you can override type() to also perform + type transformation. + + TODO nested classes and functions have not been tested well enough + """ + + def __init__(self) -> None: + # To simplify testing, set this flag to True if you want to transform + # all statements in a file (this is prohibited in normal mode). + self.test_only = False + # There may be multiple references to a Var node. Keep track of + # Var translations using a dictionary. + self.var_map: dict[Var, Var] = {} + # These are uninitialized placeholder nodes used temporarily for nested + # functions while we are transforming a top-level function. This maps an + # untransformed node to a placeholder (which will later become the + # transformed node). + self.func_placeholder_map: dict[FuncDef, FuncDef] = {} + + def visit_mypy_file(self, node: MypyFile) -> MypyFile: + assert self.test_only, "This visitor should not be used for whole files." + # NOTE: The 'names' and 'imports' instance variables will be empty! + ignored_lines = {line: codes.copy() for line, codes in node.ignored_lines.items()} + new = MypyFile(self.statements(node.defs), [], node.is_bom, ignored_lines=ignored_lines) + new._fullname = node._fullname + new.path = node.path + new.names = SymbolTable() + return new + + def visit_import(self, node: Import) -> Import: + return Import(node.ids.copy()) + + def visit_import_from(self, node: ImportFrom) -> ImportFrom: + return ImportFrom(node.id, node.relative, node.names.copy()) + + def visit_import_all(self, node: ImportAll) -> ImportAll: + return ImportAll(node.id, node.relative) + + def copy_argument(self, argument: Argument) -> Argument: + arg = Argument( + self.visit_var(argument.variable), + argument.type_annotation, + argument.initializer, + argument.kind, + ) + + # Refresh lines of the inner things + arg.set_line(argument) + + return arg + + def visit_func_def(self, node: FuncDef) -> FuncDef: + # Note that a FuncDef must be transformed to a FuncDef. + + # These contortions are needed to handle the case of recursive + # references inside the function being transformed. + # Set up placeholder nodes for references within this function + # to other functions defined inside it. + # Don't create an entry for this function itself though, + # since we want self-references to point to the original + # function if this is the top-level node we are transforming. + init = FuncMapInitializer(self) + for stmt in node.body.body: + stmt.accept(init) + + new = FuncDef( + node.name, + [self.copy_argument(arg) for arg in node.arguments], + self.block(node.body), + cast(FunctionLike | None, self.optional_type(node.type)), + ) + + self.copy_function_attributes(new, node) + + new._fullname = node._fullname + new.is_decorated = node.is_decorated + new.is_conditional = node.is_conditional + new.abstract_status = node.abstract_status + new.is_static = node.is_static + new.is_class = node.is_class + new.is_property = node.is_property + new.is_final = node.is_final + new.original_def = node.original_def + + if node in self.func_placeholder_map: + # There is a placeholder definition for this function. Replace + # the attributes of the placeholder with those form the transformed + # function. We know that the classes will be identical (otherwise + # this wouldn't work). + result = self.func_placeholder_map[node] + replace_object_state(result, new) + return result + else: + return new + + def visit_lambda_expr(self, node: LambdaExpr) -> LambdaExpr: + new = LambdaExpr( + [self.copy_argument(arg) for arg in node.arguments], + self.block(node.body), + cast(FunctionLike | None, self.optional_type(node.type)), + ) + self.copy_function_attributes(new, node) + return new + + def copy_function_attributes(self, new: FuncItem, original: FuncItem) -> None: + new.info = original.info + new.min_args = original.min_args + new.max_pos = original.max_pos + new.is_overload = original.is_overload + new.is_generator = original.is_generator + new.is_coroutine = original.is_coroutine + new.is_async_generator = original.is_async_generator + new.is_awaitable_coroutine = original.is_awaitable_coroutine + new.line = original.line + + def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> OverloadedFuncDef: + items = [cast(OverloadPart, item.accept(self)) for item in node.items] + for newitem, olditem in zip(items, node.items): + newitem.line = olditem.line + new = OverloadedFuncDef(items) + new._fullname = node._fullname + new_type = self.optional_type(node.type) + assert isinstance(new_type, ProperType) + new.type = new_type + new.info = node.info + new.is_static = node.is_static + new.is_class = node.is_class + new.is_property = node.is_property + new.is_final = node.is_final + if node.impl: + new.impl = cast(OverloadPart, node.impl.accept(self)) + return new + + def visit_class_def(self, node: ClassDef) -> ClassDef: + keywords = [(key, self.expr(value)) for key, value in node.keywords.items()] + new = ClassDef( + node.name, + self.block(node.defs), + node.type_vars, + self.expressions(node.base_type_exprs), + self.optional_expr(node.metaclass), + keywords, + ) + new.fullname = node.fullname + new.info = node.info + new.decorators = [self.expr(decorator) for decorator in node.decorators] + return new + + def visit_global_decl(self, node: GlobalDecl) -> GlobalDecl: + return GlobalDecl(node.names.copy()) + + def visit_nonlocal_decl(self, node: NonlocalDecl) -> NonlocalDecl: + return NonlocalDecl(node.names.copy()) + + def visit_block(self, node: Block) -> Block: + return Block(self.statements(node.body), is_unreachable=node.is_unreachable) + + def visit_decorator(self, node: Decorator) -> Decorator: + # Note that a Decorator must be transformed to a Decorator. + func = self.visit_func_def(node.func) + func.line = node.func.line + new = Decorator(func, self.expressions(node.decorators), self.visit_var(node.var)) + new.is_overload = node.is_overload + return new + + def visit_var(self, node: Var) -> Var: + # Note that a Var must be transformed to a Var. + if node in self.var_map: + return self.var_map[node] + new = Var(node.name, self.optional_type(node.type)) + new.line = node.line + new._fullname = node._fullname + new.info = node.info + new.is_self = node.is_self + new.is_ready = node.is_ready + new.is_initialized_in_class = node.is_initialized_in_class + new.is_staticmethod = node.is_staticmethod + new.is_classmethod = node.is_classmethod + new.is_property = node.is_property + new.is_final = node.is_final + new.final_value = node.final_value + new.final_unset_in_class = node.final_unset_in_class + new.final_set_in_init = node.final_set_in_init + new.set_line(node) + self.var_map[node] = new + return new + + def visit_expression_stmt(self, node: ExpressionStmt) -> ExpressionStmt: + return ExpressionStmt(self.expr(node.expr)) + + def visit_assignment_stmt(self, node: AssignmentStmt) -> AssignmentStmt: + return self.duplicate_assignment(node) + + def duplicate_assignment(self, node: AssignmentStmt) -> AssignmentStmt: + new = AssignmentStmt( + self.expressions(node.lvalues), + self.expr(node.rvalue), + self.optional_type(node.unanalyzed_type), + ) + new.line = node.line + new.is_final_def = node.is_final_def + new.type = self.optional_type(node.type) + return new + + def visit_operator_assignment_stmt( + self, node: OperatorAssignmentStmt + ) -> OperatorAssignmentStmt: + return OperatorAssignmentStmt(node.op, self.expr(node.lvalue), self.expr(node.rvalue)) + + def visit_while_stmt(self, node: WhileStmt) -> WhileStmt: + return WhileStmt( + self.expr(node.expr), self.block(node.body), self.optional_block(node.else_body) + ) + + def visit_for_stmt(self, node: ForStmt) -> ForStmt: + new = ForStmt( + self.expr(node.index), + self.expr(node.expr), + self.block(node.body), + self.optional_block(node.else_body), + self.optional_type(node.unanalyzed_index_type), + ) + new.is_async = node.is_async + new.index_type = self.optional_type(node.index_type) + return new + + def visit_return_stmt(self, node: ReturnStmt) -> ReturnStmt: + return ReturnStmt(self.optional_expr(node.expr)) + + def visit_assert_stmt(self, node: AssertStmt) -> AssertStmt: + return AssertStmt(self.expr(node.expr), self.optional_expr(node.msg)) + + def visit_del_stmt(self, node: DelStmt) -> DelStmt: + return DelStmt(self.expr(node.expr)) + + def visit_if_stmt(self, node: IfStmt) -> IfStmt: + return IfStmt( + self.expressions(node.expr), + self.blocks(node.body), + self.optional_block(node.else_body), + ) + + def visit_break_stmt(self, node: BreakStmt) -> BreakStmt: + return BreakStmt() + + def visit_continue_stmt(self, node: ContinueStmt) -> ContinueStmt: + return ContinueStmt() + + def visit_pass_stmt(self, node: PassStmt) -> PassStmt: + return PassStmt() + + def visit_raise_stmt(self, node: RaiseStmt) -> RaiseStmt: + return RaiseStmt(self.optional_expr(node.expr), self.optional_expr(node.from_expr)) + + def visit_try_stmt(self, node: TryStmt) -> TryStmt: + new = TryStmt( + self.block(node.body), + self.optional_names(node.vars), + self.optional_expressions(node.types), + self.blocks(node.handlers), + self.optional_block(node.else_body), + self.optional_block(node.finally_body), + ) + new.is_star = node.is_star + return new + + def visit_with_stmt(self, node: WithStmt) -> WithStmt: + new = WithStmt( + self.expressions(node.expr), + self.optional_expressions(node.target), + self.block(node.body), + self.optional_type(node.unanalyzed_type), + ) + new.is_async = node.is_async + new.analyzed_types = [self.type(typ) for typ in node.analyzed_types] + return new + + def visit_as_pattern(self, p: AsPattern) -> AsPattern: + return AsPattern( + pattern=self.pattern(p.pattern) if p.pattern is not None else None, + name=self.duplicate_name(p.name) if p.name is not None else None, + ) + + def visit_or_pattern(self, p: OrPattern) -> OrPattern: + return OrPattern([self.pattern(pat) for pat in p.patterns]) + + def visit_value_pattern(self, p: ValuePattern) -> ValuePattern: + return ValuePattern(self.expr(p.expr)) + + def visit_singleton_pattern(self, p: SingletonPattern) -> SingletonPattern: + return SingletonPattern(p.value) + + def visit_sequence_pattern(self, p: SequencePattern) -> SequencePattern: + return SequencePattern([self.pattern(pat) for pat in p.patterns]) + + def visit_starred_pattern(self, p: StarredPattern) -> StarredPattern: + return StarredPattern(self.duplicate_name(p.capture) if p.capture is not None else None) + + def visit_mapping_pattern(self, p: MappingPattern) -> MappingPattern: + return MappingPattern( + keys=[self.expr(expr) for expr in p.keys], + values=[self.pattern(pat) for pat in p.values], + rest=self.duplicate_name(p.rest) if p.rest is not None else None, + ) + + def visit_class_pattern(self, p: ClassPattern) -> ClassPattern: + class_ref = p.class_ref.accept(self) + assert isinstance(class_ref, RefExpr) + return ClassPattern( + class_ref=class_ref, + positionals=[self.pattern(pat) for pat in p.positionals], + keyword_keys=list(p.keyword_keys), + keyword_values=[self.pattern(pat) for pat in p.keyword_values], + ) + + def visit_match_stmt(self, o: MatchStmt) -> MatchStmt: + return MatchStmt( + subject=self.expr(o.subject), + patterns=[self.pattern(p) for p in o.patterns], + guards=self.optional_expressions(o.guards), + bodies=self.blocks(o.bodies), + ) + + def visit_star_expr(self, node: StarExpr) -> StarExpr: + return StarExpr(node.expr) + + def visit_int_expr(self, node: IntExpr) -> IntExpr: + return IntExpr(node.value) + + def visit_str_expr(self, node: StrExpr) -> StrExpr: + return StrExpr(node.value) + + def visit_bytes_expr(self, node: BytesExpr) -> BytesExpr: + return BytesExpr(node.value) + + def visit_float_expr(self, node: FloatExpr) -> FloatExpr: + return FloatExpr(node.value) + + def visit_complex_expr(self, node: ComplexExpr) -> ComplexExpr: + return ComplexExpr(node.value) + + def visit_ellipsis(self, node: EllipsisExpr) -> EllipsisExpr: + return EllipsisExpr() + + def visit_name_expr(self, node: NameExpr) -> NameExpr: + return self.duplicate_name(node) + + def duplicate_name(self, node: NameExpr) -> NameExpr: + # This method is used when the transform result must be a NameExpr. + # visit_name_expr() is used when there is no such restriction. + new = NameExpr(node.name) + self.copy_ref(new, node) + new.is_special_form = node.is_special_form + return new + + def visit_member_expr(self, node: MemberExpr) -> MemberExpr: + member = MemberExpr(self.expr(node.expr), node.name) + if node.def_var: + # This refers to an attribute and we don't transform attributes by default, + # just normal variables. + member.def_var = node.def_var + self.copy_ref(member, node) + return member + + def copy_ref(self, new: RefExpr, original: RefExpr) -> None: + new.kind = original.kind + new.fullname = original.fullname + target = original.node + if isinstance(target, Var): + # Do not transform references to global variables. See + # testGenericFunctionAliasExpand for an example where this is important. + if original.kind != GDEF: + target = self.visit_var(target) + elif isinstance(target, Decorator): + target = self.visit_var(target.var) + elif isinstance(target, FuncDef): + # Use a placeholder node for the function if it exists. + target = self.func_placeholder_map.get(target, target) + new.node = target + new.is_new_def = original.is_new_def + new.is_inferred_def = original.is_inferred_def + + def visit_yield_from_expr(self, node: YieldFromExpr) -> YieldFromExpr: + return YieldFromExpr(self.expr(node.expr)) + + def visit_yield_expr(self, node: YieldExpr) -> YieldExpr: + return YieldExpr(self.optional_expr(node.expr)) + + def visit_await_expr(self, node: AwaitExpr) -> AwaitExpr: + return AwaitExpr(self.expr(node.expr)) + + def visit_call_expr(self, node: CallExpr) -> CallExpr: + return CallExpr( + self.expr(node.callee), + self.expressions(node.args), + node.arg_kinds.copy(), + node.arg_names.copy(), + self.optional_expr(node.analyzed), + ) + + def visit_op_expr(self, node: OpExpr) -> OpExpr: + new = OpExpr( + node.op, + self.expr(node.left), + self.expr(node.right), + cast(TypeAliasExpr | None, self.optional_expr(node.analyzed)), + ) + new.method_type = self.optional_type(node.method_type) + return new + + def visit_comparison_expr(self, node: ComparisonExpr) -> ComparisonExpr: + new = ComparisonExpr(node.operators, self.expressions(node.operands)) + new.method_types = [self.optional_type(t) for t in node.method_types] + return new + + def visit_cast_expr(self, node: CastExpr) -> CastExpr: + return CastExpr(self.expr(node.expr), self.type(node.type)) + + def visit_type_form_expr(self, node: TypeFormExpr) -> TypeFormExpr: + return TypeFormExpr(self.type(node.type)) + + def visit_assert_type_expr(self, node: AssertTypeExpr) -> AssertTypeExpr: + return AssertTypeExpr(self.expr(node.expr), self.type(node.type)) + + def visit_reveal_expr(self, node: RevealExpr) -> RevealExpr: + if node.kind == REVEAL_TYPE: + assert node.expr is not None + return RevealExpr(kind=REVEAL_TYPE, expr=self.expr(node.expr)) + else: + # Reveal locals expressions don't have any sub expressions + return node + + def visit_super_expr(self, node: SuperExpr) -> SuperExpr: + call = self.expr(node.call) + assert isinstance(call, CallExpr) + new = SuperExpr(node.name, call) + new.info = node.info + return new + + def visit_assignment_expr(self, node: AssignmentExpr) -> AssignmentExpr: + return AssignmentExpr(self.duplicate_name(node.target), self.expr(node.value)) + + def visit_unary_expr(self, node: UnaryExpr) -> UnaryExpr: + new = UnaryExpr(node.op, self.expr(node.expr)) + new.method_type = self.optional_type(node.method_type) + return new + + def visit_list_expr(self, node: ListExpr) -> ListExpr: + return ListExpr(self.expressions(node.items)) + + def visit_dict_expr(self, node: DictExpr) -> DictExpr: + return DictExpr( + [(self.expr(key) if key else None, self.expr(value)) for key, value in node.items] + ) + + def visit_template_str_expr(self, node: TemplateStrExpr) -> TemplateStrExpr: + items: list[Expression | tuple[Expression, str, str | None, Expression | None]] = [] + for item in node.items: + if isinstance(item, tuple): + value, source, conversion, format_spec = item + items.append( + (self.expr(value), source, conversion, self.optional_expr(format_spec)) + ) + else: + items.append(self.expr(item)) + return TemplateStrExpr(items) + + def visit_tuple_expr(self, node: TupleExpr) -> TupleExpr: + return TupleExpr(self.expressions(node.items)) + + def visit_set_expr(self, node: SetExpr) -> SetExpr: + return SetExpr(self.expressions(node.items)) + + def visit_index_expr(self, node: IndexExpr) -> IndexExpr: + new = IndexExpr(self.expr(node.base), self.expr(node.index)) + if node.method_type: + new.method_type = self.type(node.method_type) + if node.analyzed: + if isinstance(node.analyzed, TypeApplication): + new.analyzed = self.visit_type_application(node.analyzed) + else: + new.analyzed = self.visit_type_alias_expr(node.analyzed) + new.analyzed.set_line(node.analyzed) + return new + + def visit_type_application(self, node: TypeApplication) -> TypeApplication: + return TypeApplication(self.expr(node.expr), self.types(node.types)) + + def visit_list_comprehension(self, node: ListComprehension) -> ListComprehension: + generator = self.duplicate_generator(node.generator) + generator.set_line(node.generator) + return ListComprehension(generator) + + def visit_set_comprehension(self, node: SetComprehension) -> SetComprehension: + generator = self.duplicate_generator(node.generator) + generator.set_line(node.generator) + return SetComprehension(generator) + + def visit_dictionary_comprehension( + self, node: DictionaryComprehension + ) -> DictionaryComprehension: + return DictionaryComprehension( + self.expr(node.key), + self.expr(node.value), + [self.expr(index) for index in node.indices], + [self.expr(s) for s in node.sequences], + [[self.expr(cond) for cond in conditions] for conditions in node.condlists], + node.is_async, + ) + + def visit_generator_expr(self, node: GeneratorExpr) -> GeneratorExpr: + return self.duplicate_generator(node) + + def duplicate_generator(self, node: GeneratorExpr) -> GeneratorExpr: + return GeneratorExpr( + self.expr(node.left_expr), + [self.expr(index) for index in node.indices], + [self.expr(s) for s in node.sequences], + [[self.expr(cond) for cond in conditions] for conditions in node.condlists], + node.is_async, + ) + + def visit_slice_expr(self, node: SliceExpr) -> SliceExpr: + return SliceExpr( + self.optional_expr(node.begin_index), + self.optional_expr(node.end_index), + self.optional_expr(node.stride), + ) + + def visit_conditional_expr(self, node: ConditionalExpr) -> ConditionalExpr: + return ConditionalExpr( + self.expr(node.cond), self.expr(node.if_expr), self.expr(node.else_expr) + ) + + def visit_type_var_expr(self, node: TypeVarExpr) -> TypeVarExpr: + return TypeVarExpr( + node.name, + node.fullname, + self.types(node.values), + self.type(node.upper_bound), + self.type(node.default), + variance=node.variance, + ) + + def visit_paramspec_expr(self, node: ParamSpecExpr) -> ParamSpecExpr: + return ParamSpecExpr( + node.name, + node.fullname, + self.type(node.upper_bound), + self.type(node.default), + variance=node.variance, + ) + + def visit_type_var_tuple_expr(self, node: TypeVarTupleExpr) -> TypeVarTupleExpr: + return TypeVarTupleExpr( + node.name, + node.fullname, + self.type(node.upper_bound), + node.tuple_fallback, + self.type(node.default), + variance=node.variance, + ) + + def visit_type_alias_expr(self, node: TypeAliasExpr) -> TypeAliasExpr: + return TypeAliasExpr(node.node) + + def visit_newtype_expr(self, node: NewTypeExpr) -> NewTypeExpr: + res = NewTypeExpr(node.name, node.old_type, line=node.line, column=node.column) + res.info = node.info + return res + + def visit_namedtuple_expr(self, node: NamedTupleExpr) -> NamedTupleExpr: + return NamedTupleExpr(node.info) + + def visit_enum_call_expr(self, node: EnumCallExpr) -> EnumCallExpr: + return EnumCallExpr(node.info, node.items, node.values) + + def visit_typeddict_expr(self, node: TypedDictExpr) -> Node: + return TypedDictExpr(node.info) + + def visit__promote_expr(self, node: PromoteExpr) -> PromoteExpr: + return PromoteExpr(node.type) + + def visit_temp_node(self, node: TempNode) -> TempNode: + return TempNode(self.type(node.type)) + + def node(self, node: Node) -> Node: + new = node.accept(self) + new.set_line(node) + return new + + def mypyfile(self, node: MypyFile) -> MypyFile: + new = node.accept(self) + assert isinstance(new, MypyFile) + new.set_line(node) + return new + + def expr(self, expr: Expression) -> Expression: + new = expr.accept(self) + assert isinstance(new, Expression) + new.set_line(expr) + return new + + def stmt(self, stmt: Statement) -> Statement: + new = stmt.accept(self) + assert isinstance(new, Statement) + new.set_line(stmt) + return new + + def pattern(self, pattern: Pattern) -> Pattern: + new = pattern.accept(self) + assert isinstance(new, Pattern) + new.set_line(pattern) + return new + + # Helpers + # + # All the node helpers also propagate line numbers. + + def optional_expr(self, expr: Expression | None) -> Expression | None: + if expr: + return self.expr(expr) + else: + return None + + def block(self, block: Block) -> Block: + new = self.visit_block(block) + new.line = block.line + return new + + def optional_block(self, block: Block | None) -> Block | None: + if block: + return self.block(block) + else: + return None + + def statements(self, statements: list[Statement]) -> list[Statement]: + return [self.stmt(stmt) for stmt in statements] + + def expressions(self, expressions: list[Expression]) -> list[Expression]: + return [self.expr(expr) for expr in expressions] + + def optional_expressions( + self, expressions: Iterable[Expression | None] + ) -> list[Expression | None]: + return [self.optional_expr(expr) for expr in expressions] + + def blocks(self, blocks: list[Block]) -> list[Block]: + return [self.block(block) for block in blocks] + + def names(self, names: list[NameExpr]) -> list[NameExpr]: + return [self.duplicate_name(name) for name in names] + + def optional_names(self, names: Iterable[NameExpr | None]) -> list[NameExpr | None]: + result: list[NameExpr | None] = [] + for name in names: + if name: + result.append(self.duplicate_name(name)) + else: + result.append(None) + return result + + def type(self, type: Type) -> Type: + # Override this method to transform types. + return type + + def optional_type(self, type: Type | None) -> Type | None: + if type: + return self.type(type) + else: + return None + + def types(self, types: list[Type]) -> list[Type]: + return [self.type(type) for type in types] + + +class FuncMapInitializer(TraverserVisitor): + """This traverser creates mappings from nested FuncDefs to placeholder FuncDefs. + + The placeholders will later be replaced with transformed nodes. + """ + + def __init__(self, transformer: TransformVisitor) -> None: + self.transformer = transformer + + def visit_func_def(self, node: FuncDef) -> None: + if node not in self.transformer.func_placeholder_map: + # Haven't seen this FuncDef before, so create a placeholder node. + self.transformer.func_placeholder_map[node] = FuncDef( + node.name, node.arguments, node.body, None + ) + super().visit_func_def(node) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/tvar_scope.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/tvar_scope.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..26e321941c70ce617c6725d469e7e9e701f203c1 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/tvar_scope.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/tvar_scope.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/tvar_scope.py new file mode 100644 index 0000000000000000000000000000000000000000..e65f9f5ee3a429b6e4385fc5d2f715114db6bd92 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/tvar_scope.py @@ -0,0 +1,216 @@ +from __future__ import annotations + +from collections.abc import Callable +from typing import TypeAlias as _TypeAlias + +from mypy.nodes import ( + Context, + ParamSpecExpr, + SymbolTableNode, + TypeVarExpr, + TypeVarLikeExpr, + TypeVarTupleExpr, +) +from mypy.types import ( + AnyType, + ParamSpecFlavor, + ParamSpecType, + TrivialSyntheticTypeTranslator, + Type, + TypeAliasType, + TypeOfAny, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, +) + +FailFunc: _TypeAlias = Callable[[str, Context], None] + + +class TypeVarLikeDefaultFixer(TrivialSyntheticTypeTranslator): + """Set namespace for all TypeVarLikeTypes types.""" + + def __init__( + self, + scope: TypeVarLikeScope, + fail_func: FailFunc, + source_tv: TypeVarLikeExpr, + context: Context, + ) -> None: + self.scope = scope + self.fail_func = fail_func + self.source_tv = source_tv + self.context = context + super().__init__() + + def visit_type_var(self, t: TypeVarType) -> Type: + existing = self.scope.get_binding(t.fullname) + if existing is None: + self._report_unbound_tvar(t) + return AnyType(TypeOfAny.from_error) + return existing + + def visit_param_spec(self, t: ParamSpecType) -> Type: + existing = self.scope.get_binding(t.fullname) + if existing is None: + self._report_unbound_tvar(t) + return AnyType(TypeOfAny.from_error) + return existing + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + existing = self.scope.get_binding(t.fullname) + if existing is None: + self._report_unbound_tvar(t) + return AnyType(TypeOfAny.from_error) + return existing + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t + + def _report_unbound_tvar(self, tvar: TypeVarLikeType) -> None: + self.fail_func( + f"Type variable {tvar.name} referenced in the default" + f" of {self.source_tv.name} is unbound", + self.context, + ) + + +class TypeVarLikeScope: + """Scope that holds bindings for type variables and parameter specifications. + + Node fullname -> TypeVarLikeType. + """ + + def __init__( + self, + parent: TypeVarLikeScope | None = None, + is_class_scope: bool = False, + prohibited: TypeVarLikeScope | None = None, + namespace: str = "", + ) -> None: + """Initializer for TypeVarLikeScope + + Parameters: + parent: the outer scope for this scope + is_class_scope: True if this represents a generic class + prohibited: Type variables that aren't strictly in scope exactly, + but can't be bound because they're part of an outer class's scope. + """ + self.scope: dict[str, TypeVarLikeType] = {} + self.parent = parent + self.func_id = 0 + self.class_id = 0 + self.is_class_scope = is_class_scope + self.prohibited = prohibited + self.namespace = namespace + if parent is not None: + self.func_id = parent.func_id + self.class_id = parent.class_id + + def get_function_scope(self) -> TypeVarLikeScope | None: + """Get the nearest parent that's a function scope, not a class scope""" + it: TypeVarLikeScope | None = self + while it is not None and it.is_class_scope: + it = it.parent + return it + + def allow_binding(self, fullname: str) -> bool: + if fullname in self.scope: + return False + elif self.parent and not self.parent.allow_binding(fullname): + return False + elif self.prohibited and not self.prohibited.allow_binding(fullname): + return False + return True + + def method_frame(self, namespace: str) -> TypeVarLikeScope: + """A new scope frame for binding a method""" + return TypeVarLikeScope(self, False, None, namespace=namespace) + + def class_frame(self, namespace: str) -> TypeVarLikeScope: + """A new scope frame for binding a class. Prohibits *this* class's tvars""" + return TypeVarLikeScope(self.get_function_scope(), True, self, namespace=namespace) + + def new_unique_func_id(self) -> TypeVarId: + """Used by plugin-like code that needs to make synthetic generic functions.""" + self.func_id -= 1 + return TypeVarId(self.func_id) + + def bind_new( + self, name: str, tvar_expr: TypeVarLikeExpr, fail_func: FailFunc, context: Context + ) -> TypeVarLikeType: + if self.is_class_scope: + self.class_id += 1 + i = self.class_id + else: + self.func_id -= 1 + i = self.func_id + namespace = self.namespace + + # Defaults may reference other type variables. That is only valid when the + # referenced variable is already in scope (textually precedes the definition we're + # processing now). + default = tvar_expr.default.accept( + TypeVarLikeDefaultFixer( + self, fail_func=fail_func, source_tv=tvar_expr, context=context + ) + ) + + if isinstance(tvar_expr, TypeVarExpr): + tvar_def: TypeVarLikeType = TypeVarType( + name=name, + fullname=tvar_expr.fullname, + id=TypeVarId(i, namespace=namespace), + values=tvar_expr.values, + upper_bound=tvar_expr.upper_bound, + default=default, + variance=tvar_expr.variance, + line=tvar_expr.line, + column=tvar_expr.column, + ) + elif isinstance(tvar_expr, ParamSpecExpr): + tvar_def = ParamSpecType( + name=name, + fullname=tvar_expr.fullname, + id=TypeVarId(i, namespace=namespace), + flavor=ParamSpecFlavor.BARE, + upper_bound=tvar_expr.upper_bound, + default=default, + line=tvar_expr.line, + column=tvar_expr.column, + ) + elif isinstance(tvar_expr, TypeVarTupleExpr): + tvar_def = TypeVarTupleType( + name=name, + fullname=tvar_expr.fullname, + id=TypeVarId(i, namespace=namespace), + upper_bound=tvar_expr.upper_bound, + tuple_fallback=tvar_expr.tuple_fallback, + default=default, + line=tvar_expr.line, + column=tvar_expr.column, + ) + else: + assert False + self.scope[tvar_expr.fullname] = tvar_def + return tvar_def + + def bind_existing(self, tvar_def: TypeVarLikeType) -> None: + self.scope[tvar_def.fullname] = tvar_def + + def get_binding(self, item: str | SymbolTableNode) -> TypeVarLikeType | None: + fullname = item.fullname if isinstance(item, SymbolTableNode) else item + assert fullname + if fullname in self.scope: + return self.scope[fullname] + elif self.parent is not None: + return self.parent.get_binding(fullname) + else: + return None + + def __str__(self) -> str: + me = ", ".join(f"{k}: {v.name}`{v.id}" for k, v in self.scope.items()) + if self.parent is None: + return me + return f"{self.parent} <- {me}" diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/type_visitor.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/type_visitor.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a7f9ccb07476121945256f55827cd28ac8e74072 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/type_visitor.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/type_visitor.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/type_visitor.py new file mode 100644 index 0000000000000000000000000000000000000000..1b38481ba000479a071973a8e56eeecffceb362c --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/type_visitor.py @@ -0,0 +1,612 @@ +"""Type visitor classes. + +This module defines the type visitors that are intended to be +subclassed by other code. They have been separated out into their own +module to ease converting mypy to run under mypyc, since currently +mypyc-extension classes can extend interpreted classes but not the +other way around. Separating them out, then, allows us to compile +types before we can compile everything that uses a TypeVisitor. + +The visitors are all re-exported from mypy.types and that is how +other modules refer to them. +""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Iterable, Sequence +from typing import Any, Final, Generic, TypeVar, cast + +from mypy_extensions import mypyc_attr, trait + +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + DeletedType, + EllipsisType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + PlaceholderType, + RawExpressionType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeList, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + get_proper_type, +) + +T = TypeVar("T", covariant=True) + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class TypeVisitor(Generic[T]): + """Visitor class for types (Type subclasses). + + The parameter T is the return type of the visit methods. + """ + + @abstractmethod + def visit_unbound_type(self, t: UnboundType, /) -> T: + pass + + @abstractmethod + def visit_any(self, t: AnyType, /) -> T: + pass + + @abstractmethod + def visit_none_type(self, t: NoneType, /) -> T: + pass + + @abstractmethod + def visit_uninhabited_type(self, t: UninhabitedType, /) -> T: + pass + + @abstractmethod + def visit_erased_type(self, t: ErasedType, /) -> T: + pass + + @abstractmethod + def visit_deleted_type(self, t: DeletedType, /) -> T: + pass + + @abstractmethod + def visit_type_var(self, t: TypeVarType, /) -> T: + pass + + @abstractmethod + def visit_param_spec(self, t: ParamSpecType, /) -> T: + pass + + @abstractmethod + def visit_parameters(self, t: Parameters, /) -> T: + pass + + @abstractmethod + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> T: + pass + + @abstractmethod + def visit_instance(self, t: Instance, /) -> T: + pass + + @abstractmethod + def visit_callable_type(self, t: CallableType, /) -> T: + pass + + @abstractmethod + def visit_overloaded(self, t: Overloaded, /) -> T: + pass + + @abstractmethod + def visit_tuple_type(self, t: TupleType, /) -> T: + pass + + @abstractmethod + def visit_typeddict_type(self, t: TypedDictType, /) -> T: + pass + + @abstractmethod + def visit_literal_type(self, t: LiteralType, /) -> T: + pass + + @abstractmethod + def visit_union_type(self, t: UnionType, /) -> T: + pass + + @abstractmethod + def visit_partial_type(self, t: PartialType, /) -> T: + pass + + @abstractmethod + def visit_type_type(self, t: TypeType, /) -> T: + pass + + @abstractmethod + def visit_type_alias_type(self, t: TypeAliasType, /) -> T: + pass + + @abstractmethod + def visit_unpack_type(self, t: UnpackType, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class SyntheticTypeVisitor(TypeVisitor[T]): + """A TypeVisitor that also knows how to visit synthetic AST constructs. + + Not just real types. + """ + + @abstractmethod + def visit_type_list(self, t: TypeList, /) -> T: + pass + + @abstractmethod + def visit_callable_argument(self, t: CallableArgument, /) -> T: + pass + + @abstractmethod + def visit_ellipsis_type(self, t: EllipsisType, /) -> T: + pass + + @abstractmethod + def visit_raw_expression_type(self, t: RawExpressionType, /) -> T: + pass + + @abstractmethod + def visit_placeholder_type(self, t: PlaceholderType, /) -> T: + pass + + +@mypyc_attr(allow_interpreted_subclasses=True) +class TypeTranslator(TypeVisitor[Type]): + """Identity type transformation. + + Subclass this and override some methods to implement a non-trivial + transformation. + + We cache the results of certain translations to avoid + massively expanding the sizes of types. + """ + + def __init__(self, cache: dict[Type, Type] | None = None) -> None: + # For deduplication of results + self.cache = cache + + def get_cached(self, t: Type) -> Type | None: + if self.cache is None: + return None + return self.cache.get(t) + + def set_cached(self, orig: Type, new: Type) -> None: + if self.cache is None: + # Minor optimization: construct lazily + self.cache = {} + self.cache[orig] = new + + def visit_unbound_type(self, t: UnboundType, /) -> Type: + return t + + def visit_any(self, t: AnyType, /) -> Type: + return t + + def visit_none_type(self, t: NoneType, /) -> Type: + return t + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> Type: + return t + + def visit_erased_type(self, t: ErasedType, /) -> Type: + return t + + def visit_deleted_type(self, t: DeletedType, /) -> Type: + return t + + def visit_instance(self, t: Instance, /) -> Type: + last_known_value: LiteralType | None = None + if t.last_known_value is not None: + raw_last_known_value = t.last_known_value.accept(self) + assert isinstance(raw_last_known_value, LiteralType) # type: ignore[misc] + last_known_value = raw_last_known_value + return Instance( + typ=t.type, + args=self.translate_type_tuple(t.args), + line=t.line, + column=t.column, + last_known_value=last_known_value, + extra_attrs=t.extra_attrs, + ) + + def visit_type_var(self, t: TypeVarType, /) -> Type: + return t + + def visit_param_spec(self, t: ParamSpecType, /) -> Type: + return t + + def visit_parameters(self, t: Parameters, /) -> Type: + return t.copy_modified(arg_types=self.translate_type_list(t.arg_types)) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> Type: + return t + + def visit_partial_type(self, t: PartialType, /) -> Type: + return t + + def visit_unpack_type(self, t: UnpackType, /) -> Type: + return UnpackType(t.type.accept(self)) + + def visit_callable_type(self, t: CallableType, /) -> Type: + return t.copy_modified( + arg_types=self.translate_type_list(t.arg_types), + ret_type=t.ret_type.accept(self), + variables=self.translate_variables(t.variables), + ) + + def visit_tuple_type(self, t: TupleType, /) -> Type: + return TupleType( + self.translate_type_list(t.items), + # TODO: This appears to be unsafe. + cast(Any, t.partial_fallback.accept(self)), + t.line, + t.column, + ) + + def visit_typeddict_type(self, t: TypedDictType, /) -> Type: + # Use cache to avoid O(n**2) or worse expansion of types during translation + if cached := self.get_cached(t): + return cached + items = {item_name: item_type.accept(self) for (item_name, item_type) in t.items.items()} + result = TypedDictType( + items, + t.required_keys, + t.readonly_keys, + # TODO: This appears to be unsafe. + cast(Any, t.fallback.accept(self)), + t.line, + t.column, + ) + self.set_cached(t, result) + return result + + def visit_literal_type(self, t: LiteralType, /) -> Type: + fallback = t.fallback.accept(self) + assert isinstance(fallback, Instance) # type: ignore[misc] + return LiteralType(value=t.value, fallback=fallback, line=t.line, column=t.column) + + def visit_union_type(self, t: UnionType, /) -> Type: + # Use cache to avoid O(n**2) or worse expansion of types during translation + # (only for large unions, since caching adds overhead) + use_cache = len(t.items) > 3 + if use_cache and (cached := self.get_cached(t)): + return cached + + result = UnionType( + self.translate_type_list(t.items), + t.line, + t.column, + uses_pep604_syntax=t.uses_pep604_syntax, + ) + if use_cache: + self.set_cached(t, result) + return result + + def translate_type_list(self, types: list[Type]) -> list[Type]: + return [t.accept(self) for t in types] + + def translate_type_tuple(self, types: tuple[Type, ...]) -> tuple[Type, ...]: + return tuple(t.accept(self) for t in types) + + def translate_variables( + self, variables: Sequence[TypeVarLikeType] + ) -> Sequence[TypeVarLikeType]: + return variables + + def visit_overloaded(self, t: Overloaded, /) -> Type: + items: list[CallableType] = [] + for item in t.items: + new = item.accept(self) + assert isinstance(new, CallableType) # type: ignore[misc] + items.append(new) + return Overloaded(items=items) + + def visit_type_type(self, t: TypeType, /) -> Type: + return TypeType.make_normalized( + t.item.accept(self), line=t.line, column=t.column, is_type_form=t.is_type_form + ) + + @abstractmethod + def visit_type_alias_type(self, t: TypeAliasType, /) -> Type: + # This method doesn't have a default implementation for type translators, + # because type aliases are special: some information is contained in the + # TypeAlias node, and we normally don't generate new nodes. Every subclass + # must implement this depending on its semantics. + pass + + +@mypyc_attr(allow_interpreted_subclasses=True) +class TypeQuery(SyntheticTypeVisitor[T]): + """Visitor for performing queries of types. + + strategy is used to combine results for a series of types, + common use cases involve a boolean query using `any` or `all`. + + Note: this visitor keeps an internal state (tracks type aliases to avoid + recursion), so it should *never* be reused for querying different types, + create a new visitor instance instead. + + # TODO: check that we don't have existing violations of this rule. + """ + + def __init__(self) -> None: + # Keep track of the type aliases already visited. This is needed to avoid + # infinite recursion on types like A = Union[int, List[A]]. + self.seen_aliases: set[TypeAliasType] | None = None + # By default, we eagerly expand type aliases, and query also types in the + # alias target. In most cases this is a desired behavior, but we may want + # to skip targets in some cases (e.g. when collecting type variables). + self.skip_alias_target = False + + @abstractmethod + def strategy(self, items: list[T]) -> T: + raise NotImplementedError + + def visit_unbound_type(self, t: UnboundType, /) -> T: + return self.query_types(t.args) + + def visit_type_list(self, t: TypeList, /) -> T: + return self.query_types(t.items) + + def visit_callable_argument(self, t: CallableArgument, /) -> T: + return t.typ.accept(self) + + def visit_any(self, t: AnyType, /) -> T: + return self.strategy([]) + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> T: + return self.strategy([]) + + def visit_none_type(self, t: NoneType, /) -> T: + return self.strategy([]) + + def visit_erased_type(self, t: ErasedType, /) -> T: + return self.strategy([]) + + def visit_deleted_type(self, t: DeletedType, /) -> T: + return self.strategy([]) + + def visit_type_var(self, t: TypeVarType, /) -> T: + return self.query_types([t.upper_bound, t.default] + t.values) + + def visit_param_spec(self, t: ParamSpecType, /) -> T: + return self.query_types([t.upper_bound, t.default, t.prefix]) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> T: + return self.query_types([t.upper_bound, t.default]) + + def visit_unpack_type(self, t: UnpackType, /) -> T: + return self.query_types([t.type]) + + def visit_parameters(self, t: Parameters, /) -> T: + return self.query_types(t.arg_types) + + def visit_partial_type(self, t: PartialType, /) -> T: + return self.strategy([]) + + def visit_instance(self, t: Instance, /) -> T: + return self.query_types(t.args) + + def visit_callable_type(self, t: CallableType, /) -> T: + # FIX generics + return self.query_types(t.arg_types + [t.ret_type]) + + def visit_tuple_type(self, t: TupleType, /) -> T: + return self.query_types([t.partial_fallback] + t.items) + + def visit_typeddict_type(self, t: TypedDictType, /) -> T: + return self.query_types(t.items.values()) + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> T: + return self.strategy([]) + + def visit_literal_type(self, t: LiteralType, /) -> T: + return self.strategy([]) + + def visit_union_type(self, t: UnionType, /) -> T: + return self.query_types(t.items) + + def visit_overloaded(self, t: Overloaded, /) -> T: + return self.query_types(t.items) + + def visit_type_type(self, t: TypeType, /) -> T: + return t.item.accept(self) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> T: + return self.strategy([]) + + def visit_placeholder_type(self, t: PlaceholderType, /) -> T: + return self.query_types(t.args) + + def visit_type_alias_type(self, t: TypeAliasType, /) -> T: + if self.skip_alias_target: + return self.query_types(t.args) + # Skip type aliases already visited types to avoid infinite recursion + # (also use this as a simple-minded cache). + if self.seen_aliases is None: + self.seen_aliases = set() + elif t in self.seen_aliases: + return self.strategy([]) + self.seen_aliases.add(t) + return get_proper_type(t).accept(self) + + def query_types(self, types: Iterable[Type]) -> T: + """Perform a query for a list of types using the strategy to combine the results.""" + return self.strategy([t.accept(self) for t in types]) + + +# Return True if at least one type component returns True +ANY_STRATEGY: Final = 0 +# Return True if no type component returns False +ALL_STRATEGY: Final = 1 + + +class BoolTypeQuery(SyntheticTypeVisitor[bool]): + """Visitor for performing recursive queries of types with a bool result. + + Use TypeQuery if you need non-bool results. + + 'strategy' is used to combine results for a series of types. It must + be ANY_STRATEGY or ALL_STRATEGY. + + Note: This visitor keeps an internal state (tracks type aliases to avoid + recursion), so it should *never* be reused for querying different types + unless you call reset() first. + """ + + def __init__(self, strategy: int) -> None: + self.strategy = strategy + if strategy == ANY_STRATEGY: + self.default = False + else: + assert strategy == ALL_STRATEGY + self.default = True + # Keep track of the type aliases already visited. This is needed to avoid + # infinite recursion on types like A = Union[int, List[A]]. An empty set is + # represented as None as a micro-optimization. + self.seen_aliases: set[TypeAliasType] | None = None + # By default, we eagerly expand type aliases, and query also types in the + # alias target. In most cases this is a desired behavior, but we may want + # to skip targets in some cases (e.g. when collecting type variables). + self.skip_alias_target = False + + def reset(self) -> None: + """Clear mutable state (but preserve strategy). + + This *must* be called if you want to reuse the visitor. + """ + self.seen_aliases = None + + def visit_unbound_type(self, t: UnboundType, /) -> bool: + return self.query_types(t.args) + + def visit_type_list(self, t: TypeList, /) -> bool: + return self.query_types(t.items) + + def visit_callable_argument(self, t: CallableArgument, /) -> bool: + return t.typ.accept(self) + + def visit_any(self, t: AnyType, /) -> bool: + return self.default + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> bool: + return self.default + + def visit_none_type(self, t: NoneType, /) -> bool: + return self.default + + def visit_erased_type(self, t: ErasedType, /) -> bool: + return self.default + + def visit_deleted_type(self, t: DeletedType, /) -> bool: + return self.default + + def visit_type_var(self, t: TypeVarType, /) -> bool: + return self.query_types([t.upper_bound, t.default] + t.values) + + def visit_param_spec(self, t: ParamSpecType, /) -> bool: + return self.query_types([t.upper_bound, t.default, t.prefix]) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> bool: + return self.query_types([t.upper_bound, t.default]) + + def visit_unpack_type(self, t: UnpackType, /) -> bool: + return self.query_types([t.type]) + + def visit_parameters(self, t: Parameters, /) -> bool: + return self.query_types(t.arg_types) + + def visit_partial_type(self, t: PartialType, /) -> bool: + return self.default + + def visit_instance(self, t: Instance, /) -> bool: + return self.query_types(t.args) + + def visit_callable_type(self, t: CallableType, /) -> bool: + # FIX generics + # Avoid allocating any objects here as an optimization. + args = self.query_types(t.arg_types) + ret = t.ret_type.accept(self) + if self.strategy == ANY_STRATEGY: + return args or ret + else: + return args and ret + + def visit_tuple_type(self, t: TupleType, /) -> bool: + return self.query_types([t.partial_fallback] + t.items) + + def visit_typeddict_type(self, t: TypedDictType, /) -> bool: + return self.query_types(list(t.items.values())) + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> bool: + return self.default + + def visit_literal_type(self, t: LiteralType, /) -> bool: + return self.default + + def visit_union_type(self, t: UnionType, /) -> bool: + return self.query_types(t.items) + + def visit_overloaded(self, t: Overloaded, /) -> bool: + return self.query_types(t.items) # type: ignore[arg-type] + + def visit_type_type(self, t: TypeType, /) -> bool: + return t.item.accept(self) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> bool: + return self.default + + def visit_placeholder_type(self, t: PlaceholderType, /) -> bool: + return self.query_types(t.args) + + def visit_type_alias_type(self, t: TypeAliasType, /) -> bool: + if self.skip_alias_target: + return self.query_types(t.args) + # Skip type aliases already visited types to avoid infinite recursion + # (also use this as a simple-minded cache). + if self.seen_aliases is None: + self.seen_aliases = set() + elif t in self.seen_aliases: + return self.default + self.seen_aliases.add(t) + return get_proper_type(t).accept(self) + + def query_types(self, types: list[Type] | tuple[Type, ...]) -> bool: + """Perform a query for a sequence of types using the strategy to combine the results.""" + # Special-case for lists and tuples to allow mypyc to produce better code. + if isinstance(types, list): + if self.strategy == ANY_STRATEGY: + return any(t.accept(self) for t in types) + else: + return all(t.accept(self) for t in types) + else: + if self.strategy == ANY_STRATEGY: + return any(t.accept(self) for t in types) + else: + return all(t.accept(self) for t in types) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeanal.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeanal.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..27255754a54aee8950fc4883bd19e23bcb420d41 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeanal.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeanal.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeanal.py new file mode 100644 index 0000000000000000000000000000000000000000..941310ae86a34de2beba70a45dcde99d9e61fb31 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeanal.py @@ -0,0 +1,2803 @@ +"""Semantic analysis of types""" + +from __future__ import annotations + +import itertools +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager +from typing import Final, Protocol, TypeVar + +from mypy import errorcodes as codes, message_registry, nodes +from mypy.errorcodes import ErrorCode +from mypy.errors import ErrorInfo +from mypy.expandtype import expand_type +from mypy.message_registry import ( + INVALID_PARAM_SPEC_LOCATION, + INVALID_PARAM_SPEC_LOCATION_NOTE, + TYPEDDICT_OVERRIDE_MERGE, +) +from mypy.messages import ( + MessageBuilder, + format_type, + format_type_bare, + quote_type_string, + wrong_type_arg_count, +) +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR, + ARG_STAR2, + MISSING_FALLBACK, + SYMBOL_FUNCBASE_TYPES, + ArgKind, + Context, + Decorator, + ImportFrom, + MypyFile, + ParamSpecExpr, + PlaceholderNode, + SymbolTableNode, + TypeAlias, + TypeInfo, + TypeVarExpr, + TypeVarLikeExpr, + TypeVarTupleExpr, + Var, + check_arg_kinds, + check_param_names, +) +from mypy.options import INLINE_TYPEDDICT, TYPE_FORM, Options +from mypy.plugin import AnalyzeTypeContext, Plugin, TypeAnalyzerPluginInterface +from mypy.semanal_shared import ( + SemanticAnalyzerCoreInterface, + SemanticAnalyzerInterface, + paramspec_args, + paramspec_kwargs, +) +from mypy.state import state +from mypy.tvar_scope import TypeVarLikeScope +from mypy.types import ( + ANNOTATED_TYPE_NAMES, + ANY_STRATEGY, + CONCATENATE_TYPE_NAMES, + FINAL_TYPE_NAMES, + LITERAL_TYPE_NAMES, + MYPYC_NATIVE_INT_NAMES, + NEVER_NAMES, + TUPLE_NAMES, + TYPE_ALIAS_NAMES, + TYPE_NAMES, + UNPACK_TYPE_NAMES, + AnyType, + BoolTypeQuery, + CallableArgument, + CallableType, + DeletedType, + EllipsisType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PartialType, + PlaceholderType, + ProperType, + RawExpressionType, + ReadOnlyType, + RequiredType, + SyntheticTypeVisitor, + TrivialSyntheticTypeTranslator, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeList, + TypeOfAny, + TypeQuery, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + callable_with_ellipsis, + find_unpack_in_list, + flatten_nested_tuples, + get_proper_type, + has_type_vars, +) +from mypy.types_utils import get_bad_type_type_item +from mypy.typevars import fill_typevars + +T = TypeVar("T") + +type_constructors: Final = { + "typing.Callable", + "typing.Optional", + "typing.Tuple", + "typing.Type", + "typing.Union", + *LITERAL_TYPE_NAMES, + *ANNOTATED_TYPE_NAMES, +} + +ARG_KINDS_BY_CONSTRUCTOR: Final = { + "mypy_extensions.Arg": ARG_POS, + "mypy_extensions.DefaultArg": ARG_OPT, + "mypy_extensions.NamedArg": ARG_NAMED, + "mypy_extensions.DefaultNamedArg": ARG_NAMED_OPT, + "mypy_extensions.VarArg": ARG_STAR, + "mypy_extensions.KwArg": ARG_STAR2, +} + +SELF_TYPE_NAMES: Final = {"typing.Self", "typing_extensions.Self"} + + +def analyze_type_alias( + type: Type, + api: SemanticAnalyzerCoreInterface, + tvar_scope: TypeVarLikeScope, + plugin: Plugin, + options: Options, + cur_mod_node: MypyFile, + is_typeshed_stub: bool, + allow_placeholder: bool = False, + in_dynamic_func: bool = False, + global_scope: bool = True, + allowed_alias_tvars: list[TypeVarLikeType] | None = None, + alias_type_params_names: list[str] | None = None, + python_3_12_type_alias: bool = False, +) -> tuple[Type, set[str]]: + """Analyze r.h.s. of a (potential) type alias definition. + + If `node` is valid as a type alias rvalue, return the resulting type and a set of + full names of type aliases it depends on (directly or indirectly). + 'node' must have been semantically analyzed. + """ + analyzer = TypeAnalyser( + api, + tvar_scope, + plugin, + options, + cur_mod_node, + is_typeshed_stub, + defining_alias=True, + allow_placeholder=allow_placeholder, + prohibit_self_type="type alias target", + allowed_alias_tvars=allowed_alias_tvars, + alias_type_params_names=alias_type_params_names, + python_3_12_type_alias=python_3_12_type_alias, + ) + analyzer.in_dynamic_func = in_dynamic_func + analyzer.global_scope = global_scope + res = analyzer.anal_type(type, nested=False) + return res, analyzer.aliases_used + + +class TypeAnalyser(SyntheticTypeVisitor[Type], TypeAnalyzerPluginInterface): + """Semantic analyzer for types. + + Converts unbound types into bound types. This is a no-op for already + bound types. + + If an incomplete reference is encountered, this does a defer. The + caller never needs to defer. + """ + + # Is this called from an untyped function definition? + in_dynamic_func: bool = False + # Is this called from global scope? + global_scope: bool = True + + def __init__( + self, + api: SemanticAnalyzerCoreInterface, + tvar_scope: TypeVarLikeScope, + plugin: Plugin, + options: Options, + cur_mod_node: MypyFile, + is_typeshed_stub: bool, + *, + defining_alias: bool = False, + python_3_12_type_alias: bool = False, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_placeholder: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = True, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + allowed_alias_tvars: list[TypeVarLikeType] | None = None, + allow_type_any: bool = False, + alias_type_params_names: list[str] | None = None, + ) -> None: + self.api = api + self.fail_func = api.fail + self.note_func = api.note + self.tvar_scope = tvar_scope + # Are we analysing a type alias definition rvalue? + self.defining_alias = defining_alias + self.python_3_12_type_alias = python_3_12_type_alias + self.allow_tuple_literal = allow_tuple_literal + # Positive if we are analyzing arguments of another (outer) type + self.nesting_level = 0 + # Should we allow new type syntax when targeting older Python versions + # like 'list[int]' or 'X | Y' (allowed in stubs and with `__future__` import)? + self.always_allow_new_syntax = self.api.is_stub_file or self.api.is_future_flag_set( + "annotations" + ) + # Should we accept unbound type variables? This is currently used for class bases, + # and alias right hand sides (before they are analyzed as type aliases). + self.allow_unbound_tvars = allow_unbound_tvars + if allowed_alias_tvars is None: + allowed_alias_tvars = [] + self.allowed_alias_tvars = allowed_alias_tvars + self.alias_type_params_names = alias_type_params_names + # If false, record incomplete ref if we generate PlaceholderType. + self.allow_placeholder = allow_placeholder + # Are we in a context where Required[] is allowed? + self.allow_typed_dict_special_forms = allow_typed_dict_special_forms + # Set True when we analyze ClassVar else False + self.allow_final = allow_final + # Are we in a context where ParamSpec literals are allowed? + self.allow_param_spec_literals = allow_param_spec_literals + # Are we in context where literal "..." specifically is allowed? + self.allow_ellipsis = False + # Should we report an error whenever we encounter a RawExpressionType outside + # of a Literal context: e.g. whenever we encounter an invalid type? Normally, + # we want to report an error, but the caller may want to do more specialized + # error handling. + self.report_invalid_types = report_invalid_types + self.plugin = plugin + self.options = options + self.cur_mod_node = cur_mod_node + self.is_typeshed_stub = is_typeshed_stub + # Names of type aliases encountered while analysing a type will be collected here. + self.aliases_used: set[str] = set() + self.prohibit_self_type = prohibit_self_type + # Set when we analyze TypedDicts or NamedTuples, since they are special: + self.prohibit_special_class_field_types = prohibit_special_class_field_types + # Allow variables typed as Type[Any] and type (useful for base classes). + self.allow_type_any = allow_type_any + self.allow_type_var_tuple = False + self.allow_unpack = allow_unpack + + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + return self.api.lookup_qualified(name, ctx, suppress_errors) + + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode: + return self.api.lookup_fully_qualified(fullname) + + def visit_unbound_type(self, t: UnboundType, defining_literal: bool = False) -> Type: + typ = self.visit_unbound_type_nonoptional(t, defining_literal) + if t.optional: + # We don't need to worry about double-wrapping Optionals or + # wrapping Anys: Union simplification will take care of that. + return make_optional_type(typ) + return typ + + def not_declared_in_type_params(self, tvar_name: str) -> bool: + return ( + self.alias_type_params_names is not None + and tvar_name not in self.alias_type_params_names + ) + + def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) -> Type: + sym = self.lookup_qualified(t.name, t) + param_spec_name = None + if t.name.endswith((".args", ".kwargs")): + param_spec_name = t.name.rsplit(".", 1)[0] + maybe_param_spec = self.lookup_qualified(param_spec_name, t) + if maybe_param_spec and isinstance(maybe_param_spec.node, ParamSpecExpr): + sym = maybe_param_spec + else: + param_spec_name = None + + if sym is not None: + node = sym.node + if isinstance(node, PlaceholderNode): + if node.becomes_typeinfo: + # Reference to placeholder type. + if self.api.final_iteration: + self.cannot_resolve_type(t) + return AnyType(TypeOfAny.from_error) + elif self.allow_placeholder: + self.api.defer() + else: + self.api.record_incomplete_ref() + # Always allow ParamSpec for placeholders, if they are actually not valid, + # they will be reported later, after we resolve placeholders. + return PlaceholderType( + node.fullname, + self.anal_array( + t.args, + allow_param_spec=True, + allow_param_spec_literals=True, + allow_unpack=True, + ), + t.line, + ) + else: + if self.api.final_iteration: + self.cannot_resolve_type(t) + return AnyType(TypeOfAny.from_error) + else: + # Reference to an unknown placeholder node. + self.api.record_incomplete_ref() + return AnyType(TypeOfAny.special_form) + if node is None: + self.fail(f"Internal error (node is None, kind={sym.kind})", t) + return AnyType(TypeOfAny.special_form) + fullname = node.fullname + hook = self.plugin.get_type_analyze_hook(fullname) + if hook is not None: + return hook(AnalyzeTypeContext(t, t, self)) + tvar_def = self.tvar_scope.get_binding(sym) + if tvar_def is not None: + # We need to cover special-case explained in get_typevarlike_argument() here, + # since otherwise the deferral will not be triggered if the type variable is + # used in a different module. Using isinstance() should be safe for this purpose. + tvar_params = [tvar_def.upper_bound, tvar_def.default] + if isinstance(tvar_def, TypeVarType): + tvar_params += tvar_def.values + if any(isinstance(tp, PlaceholderType) for tp in tvar_params): + self.api.defer() + if isinstance(sym.node, ParamSpecExpr): + if tvar_def is None: + if self.allow_unbound_tvars: + return t + name = param_spec_name or t.name + if self.defining_alias and self.not_declared_in_type_params(t.name): + msg = f'ParamSpec "{name}" is not included in type_params' + else: + msg = f'ParamSpec "{name}" is unbound' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + assert isinstance(tvar_def, ParamSpecType) + if len(t.args) > 0: + self.fail( + f'ParamSpec "{t.name}" used with arguments', t, code=codes.VALID_TYPE + ) + if param_spec_name is not None and not self.allow_param_spec_literals: + self.fail( + "ParamSpec components are not allowed here", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + # Change the line number + return ParamSpecType( + tvar_def.name, + tvar_def.fullname, + tvar_def.id, + tvar_def.flavor, + tvar_def.upper_bound, + tvar_def.default, + line=t.line, + column=t.column, + ) + if ( + isinstance(sym.node, TypeVarExpr) + and self.defining_alias + and not defining_literal + and (tvar_def is None or tvar_def not in self.allowed_alias_tvars) + ): + if self.not_declared_in_type_params(t.name): + if self.python_3_12_type_alias: + msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format( + f'"{t.name}"' + ) + else: + msg = f'Type variable "{t.name}" is not included in type_params' + else: + msg = f'Can\'t use bound type variable "{t.name}" to define generic alias' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + if isinstance(sym.node, TypeVarExpr) and tvar_def is not None: + assert isinstance(tvar_def, TypeVarType) + if len(t.args) > 0: + self.fail( + f'Type variable "{t.name}" used with arguments', t, code=codes.VALID_TYPE + ) + # Change the line number + return tvar_def.copy_modified(line=t.line, column=t.column) + if isinstance(sym.node, TypeVarTupleExpr) and ( + tvar_def is not None + and self.defining_alias + and tvar_def not in self.allowed_alias_tvars + ): + if self.not_declared_in_type_params(t.name): + msg = f'Type variable "{t.name}" is not included in type_params' + else: + msg = f'Can\'t use bound type variable "{t.name}" to define generic alias' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + if isinstance(sym.node, TypeVarTupleExpr): + if tvar_def is None: + if self.allow_unbound_tvars: + return t + if self.defining_alias and self.not_declared_in_type_params(t.name): + if self.python_3_12_type_alias: + msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format( + f'"{t.name}"' + ) + else: + msg = f'TypeVarTuple "{t.name}" is not included in type_params' + else: + msg = f'TypeVarTuple "{t.name}" is unbound' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + assert isinstance(tvar_def, TypeVarTupleType) + if not self.allow_type_var_tuple: + self.fail( + f'TypeVarTuple "{t.name}" is only valid with an unpack', + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) > 0: + self.fail( + f'Type variable "{t.name}" used with arguments', t, code=codes.VALID_TYPE + ) + + # Change the line number + return TypeVarTupleType( + tvar_def.name, + tvar_def.fullname, + tvar_def.id, + tvar_def.upper_bound, + sym.node.tuple_fallback, + tvar_def.default, + line=t.line, + column=t.column, + ) + special = self.try_analyze_special_unbound_type(t, fullname) + if special is not None: + return special + if isinstance(node, TypeAlias): + self.aliases_used.add(fullname) + an_args = self.anal_array( + t.args, + allow_param_spec=True, + allow_param_spec_literals=node.has_param_spec_type, + allow_unpack=True, # Fixed length unpacks can be used for non-variadic aliases. + ) + if node.has_param_spec_type and len(node.alias_tvars) == 1: + an_args = self.pack_paramspec_args(an_args, t.empty_tuple_index) + + disallow_any = self.options.disallow_any_generics and not self.is_typeshed_stub + res = instantiate_type_alias( + node, + an_args, + self.fail, + node.no_args, + t, + self.options, + unexpanded_type=t, + disallow_any=disallow_any, + empty_tuple_index=t.empty_tuple_index, + ) + # The only case where instantiate_type_alias() can return an incorrect instance is + # when it is top-level instance, so no need to recurse. + if ( + isinstance(res, ProperType) + and isinstance(res, Instance) + and not (self.defining_alias and self.nesting_level == 0) + and not validate_instance(res, self.fail, t.empty_tuple_index) + ): + fix_instance( + res, + self.fail, + self.note, + disallow_any=disallow_any, + options=self.options, + use_generic_error=True, + unexpanded_type=t, + ) + if node.eager: + res = get_proper_type(res) + return res + elif isinstance(node, TypeInfo): + return self.analyze_type_with_type_info(node, t.args, t, t.empty_tuple_index) + elif node.fullname in TYPE_ALIAS_NAMES: + return AnyType(TypeOfAny.special_form) + # Concatenate is an operator, no need for a proper type + elif node.fullname in CONCATENATE_TYPE_NAMES: + # We check the return type further up the stack for valid use locations + return self.apply_concatenate_operator(t) + else: + return self.analyze_unbound_type_without_type_info(t, sym, defining_literal) + else: # sym is None + return AnyType(TypeOfAny.special_form) + + def pack_paramspec_args(self, an_args: Sequence[Type], empty_tuple_index: bool) -> list[Type]: + # "Aesthetic" ParamSpec literals for single ParamSpec: C[int, str] -> C[[int, str]]. + # These do not support mypy_extensions VarArgs, etc. as they were already analyzed + # TODO: should these be re-analyzed to get rid of this inconsistency? + count = len(an_args) + if count == 0 and empty_tuple_index: + return [Parameters([], [], [])] + elif count == 0: + return [] + + if count == 1 and isinstance(get_proper_type(an_args[0]), AnyType): + # Single Any is interpreted as ..., rather that a single argument with Any type. + # I didn't find this in the PEP, but it sounds reasonable. + return list(an_args) + if any(isinstance(a, (Parameters, ParamSpecType)) for a in an_args): + if len(an_args) > 1: + first_wrong = next( + arg for arg in an_args if isinstance(arg, (Parameters, ParamSpecType)) + ) + self.fail( + "Nested parameter specifications are not allowed", + first_wrong, + code=codes.VALID_TYPE, + ) + return [AnyType(TypeOfAny.from_error)] + return list(an_args) + first = an_args[0] + return [ + Parameters( + an_args, [ARG_POS] * count, [None] * count, line=first.line, column=first.column + ) + ] + + def cannot_resolve_type(self, t: UnboundType) -> None: + # TODO: Move error message generation to messages.py. We'd first + # need access to MessageBuilder here. Also move the similar + # message generation logic in semanal.py. + self.api.fail(f'Cannot resolve name "{t.name}" (possible cyclic definition)', t) + if self.api.is_func_scope(): + self.note("Recursive types are not allowed at function scope", t) + + def apply_concatenate_operator(self, t: UnboundType) -> Type: + if len(t.args) == 0: + self.api.fail("Concatenate needs type arguments", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + + # Last argument has to be ParamSpec or Ellipsis. + ps = self.anal_type(t.args[-1], allow_param_spec=True, allow_ellipsis=True) + if not isinstance(ps, (ParamSpecType, Parameters)): + if isinstance(ps, UnboundType) and self.allow_unbound_tvars: + sym = self.lookup_qualified(ps.name, t) + if sym is not None and isinstance(sym.node, ParamSpecExpr): + return ps + self.api.fail( + "The last parameter to Concatenate needs to be a ParamSpec", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + elif isinstance(ps, ParamSpecType) and ps.prefix.arg_types: + self.api.fail("Nested Concatenates are invalid", t, code=codes.VALID_TYPE) + + args = self.anal_array(t.args[:-1]) + pre = ps.prefix if isinstance(ps, ParamSpecType) else ps + + # mypy can't infer this :( + names: list[str | None] = [None] * len(args) + + pre = Parameters( + args + pre.arg_types, + [ARG_POS] * len(args) + pre.arg_kinds, + names + pre.arg_names, + line=t.line, + column=t.column, + ) + return ps.copy_modified(prefix=pre) if isinstance(ps, ParamSpecType) else pre + + def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Type | None: + """Bind special type that is recognized through magic name such as 'typing.Any'. + + Return the bound type if successful, and return None if the type is a normal type. + """ + if fullname == "builtins.None": + return NoneType() + elif fullname == "typing.Any": + return AnyType(TypeOfAny.explicit, line=t.line, column=t.column) + elif fullname in FINAL_TYPE_NAMES: + if self.prohibit_special_class_field_types: + self.fail( + f"Final[...] can't be used inside a {self.prohibit_special_class_field_types}", + t, + code=codes.VALID_TYPE, + ) + else: + if not self.allow_final: + self.fail( + "Final can be only used as an outermost qualifier in a variable annotation", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + elif fullname in TUPLE_NAMES: + # Tuple is special because it is involved in builtin import cycle + # and may be not ready when used. + sym = self.api.lookup_fully_qualified_or_none("builtins.tuple") + if not sym or isinstance(sym.node, PlaceholderNode): + if self.api.is_incomplete_namespace("builtins"): + self.api.record_incomplete_ref() + else: + self.fail('Name "tuple" is not defined', t) + return AnyType(TypeOfAny.special_form) + if len(t.args) == 0 and not t.empty_tuple_index: + # Bare 'Tuple' is same as 'tuple' + any_type = self.get_omitted_any(t) + return self.named_type("builtins.tuple", [any_type], line=t.line, column=t.column) + if len(t.args) == 2 and isinstance(t.args[1], EllipsisType): + # Tuple[T, ...] (uniform, variable-length tuple) + instance = self.named_type("builtins.tuple", [self.anal_type(t.args[0])]) + instance.line = t.line + return instance + return self.tuple_type( + self.anal_array(t.args, allow_unpack=True), line=t.line, column=t.column + ) + elif fullname == "typing.Union": + items = self.anal_array(t.args) + return UnionType.make_union(items, line=t.line, column=t.column) + elif fullname == "typing.Optional": + if len(t.args) != 1: + self.fail( + "Optional[...] must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + item = self.anal_type(t.args[0]) + return make_optional_type(item) + elif fullname == "typing.Callable": + return self.analyze_callable_type(t) + elif fullname in TYPE_NAMES: + if len(t.args) == 0: + if fullname == "typing.Type": + any_type = self.get_omitted_any(t) + return TypeType(any_type, line=t.line, column=t.column) + else: + # To prevent assignment of 'builtins.type' inferred as 'builtins.object' + # See https://github.com/python/mypy/issues/9476 for more information + return None + type_str = "Type[...]" if fullname == "typing.Type" else "type[...]" + if len(t.args) != 1: + self.fail( + f"{type_str} must have exactly one type argument", t, code=codes.VALID_TYPE + ) + item = self.anal_type(t.args[0]) + bad_item_name = get_bad_type_type_item(item) + if bad_item_name: + self.fail(f'{type_str} can\'t contain "{bad_item_name}"', t, code=codes.VALID_TYPE) + item = AnyType(TypeOfAny.from_error) + return TypeType.make_normalized(item, line=t.line, column=t.column) + elif fullname in ("typing_extensions.TypeForm", "typing.TypeForm"): + if TYPE_FORM not in self.options.enable_incomplete_feature: + self.fail( + "TypeForm is experimental," + " must be enabled with --enable-incomplete-feature=TypeForm", + t, + ) + if len(t.args) == 0: + any_type = self.get_omitted_any(t) + return TypeType(any_type, line=t.line, column=t.column, is_type_form=True) + if len(t.args) != 1: + type_str = "TypeForm[...]" + self.fail( + type_str + " must have exactly one type argument", t, code=codes.VALID_TYPE + ) + item = self.anal_type(t.args[0]) + return TypeType.make_normalized(item, line=t.line, column=t.column, is_type_form=True) + elif fullname == "typing.ClassVar": + if self.nesting_level > 0: + self.fail( + "Invalid type: ClassVar nested inside other type", t, code=codes.VALID_TYPE + ) + if self.prohibit_special_class_field_types: + self.fail( + f"ClassVar[...] can't be used inside a {self.prohibit_special_class_field_types}", + t, + code=codes.VALID_TYPE, + ) + if self.defining_alias: + self.fail( + "ClassVar[...] can't be used inside a type alias", t, code=codes.VALID_TYPE + ) + if len(t.args) == 0: + return AnyType(TypeOfAny.from_omitted_generics, line=t.line, column=t.column) + if len(t.args) != 1: + self.fail( + "ClassVar[...] must have at most one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0], allow_final=self.options.python_version >= (3, 13)) + elif fullname in NEVER_NAMES: + return UninhabitedType() + elif fullname in LITERAL_TYPE_NAMES: + return self.analyze_literal_type(t) + elif fullname in ANNOTATED_TYPE_NAMES: + if len(t.args) < 2: + self.fail( + "Annotated[...] must have exactly one type argument" + " and at least one annotation", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + return self.anal_type( + t.args[0], allow_typed_dict_special_forms=self.allow_typed_dict_special_forms + ) + elif fullname in ("typing_extensions.Required", "typing.Required"): + if not self.allow_typed_dict_special_forms: + self.fail( + "Required[] can be only used in a TypedDict definition", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) != 1: + self.fail( + "Required[] must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return RequiredType( + self.anal_type(t.args[0], allow_typed_dict_special_forms=True), required=True + ) + elif fullname in ("typing_extensions.NotRequired", "typing.NotRequired"): + if not self.allow_typed_dict_special_forms: + self.fail( + "NotRequired[] can be only used in a TypedDict definition", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) != 1: + self.fail( + "NotRequired[] must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return RequiredType( + self.anal_type(t.args[0], allow_typed_dict_special_forms=True), required=False + ) + elif fullname in ("typing_extensions.ReadOnly", "typing.ReadOnly"): + if not self.allow_typed_dict_special_forms: + self.fail( + "ReadOnly[] can be only used in a TypedDict definition", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) != 1: + self.fail( + '"ReadOnly[]" must have exactly one type argument', t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return ReadOnlyType(self.anal_type(t.args[0], allow_typed_dict_special_forms=True)) + elif ( + self.anal_type_guard_arg(t, fullname) is not None + or self.anal_type_is_arg(t, fullname) is not None + ): + # In most contexts, TypeGuard[...] acts as an alias for bool (ignoring its args) + return self.named_type("builtins.bool") + elif fullname in UNPACK_TYPE_NAMES: + if len(t.args) != 1: + self.fail("Unpack[...] requires exactly one type argument", t) + return AnyType(TypeOfAny.from_error) + if not self.allow_unpack: + self.fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + self.allow_type_var_tuple = True + result = UnpackType(self.anal_type(t.args[0]), line=t.line, column=t.column) + self.allow_type_var_tuple = False + return result + elif fullname in SELF_TYPE_NAMES: + if t.args: + self.fail("Self type cannot have type arguments", t) + if self.prohibit_self_type is not None: + self.fail(f"Self type cannot be used in {self.prohibit_self_type}", t) + return AnyType(TypeOfAny.from_error) + if self.api.type is None: + self.fail("Self type is only allowed in annotations within class definition", t) + return AnyType(TypeOfAny.from_error) + if self.api.type.has_base("builtins.type"): + self.fail("Self type cannot be used in a metaclass", t) + if self.api.type.self_type is not None: + if self.api.type.is_final or self.api.type.is_enum and self.api.type.enum_members: + return fill_typevars(self.api.type) + return self.api.type.self_type.copy_modified(line=t.line, column=t.column) + # TODO: verify this is unreachable and replace with an assert? + self.fail("Unexpected Self type", t) + return AnyType(TypeOfAny.from_error) + return None + + def get_omitted_any(self, typ: Type, fullname: str | None = None) -> AnyType: + disallow_any = not self.is_typeshed_stub and self.options.disallow_any_generics + return get_omitted_any(disallow_any, self.fail, self.note, typ, self.options, fullname) + + def check_and_warn_deprecated(self, info: TypeInfo, ctx: Context) -> None: + """Similar logic to `TypeChecker.check_deprecated` and `TypeChecker.warn_deprecated.""" + + if ( + (deprecated := info.deprecated) + and not self.is_typeshed_stub + and not (self.api.type and (self.api.type.fullname == info.fullname)) + and not any( + info.fullname == p or info.fullname.startswith(f"{p}.") + for p in self.options.deprecated_calls_exclude + ) + ): + for imp in self.cur_mod_node.imports: + if isinstance(imp, ImportFrom) and any(info.name == n[0] for n in imp.names): + break + else: + warn = self.note if self.options.report_deprecated_as_note else self.fail + warn(deprecated, ctx, code=codes.DEPRECATED) + + def analyze_type_with_type_info( + self, info: TypeInfo, args: Sequence[Type], ctx: Context, empty_tuple_index: bool + ) -> Type: + """Bind unbound type when were able to find target TypeInfo. + + This handles simple cases like 'int', 'modname.UserClass[str]', etc. + """ + + self.check_and_warn_deprecated(info, ctx) + + if len(args) > 0 and info.fullname == "builtins.tuple": + fallback = Instance(info, [AnyType(TypeOfAny.special_form)], ctx.line) + return TupleType(self.anal_array(args, allow_unpack=True), fallback, ctx.line) + + # Analyze arguments and (usually) construct Instance type. The + # number of type arguments and their values are + # checked only later, since we do not always know the + # valid count at this point. Thus we may construct an + # Instance with an invalid number of type arguments. + # + # We allow ParamSpec literals based on a heuristic: it will be + # checked later anyways but the error message may be worse. + instance = Instance( + info, + self.anal_array( + args, + allow_param_spec=True, + allow_param_spec_literals=info.has_param_spec_type, + allow_unpack=True, # Fixed length tuples can be used for non-variadic types. + ), + ctx.line, + ctx.column, + ) + instance.end_line = ctx.end_line + instance.end_column = ctx.end_column + if len(info.type_vars) == 1 and info.has_param_spec_type: + instance.args = tuple(self.pack_paramspec_args(instance.args, empty_tuple_index)) + + if info.fullname == "librt.vecs.vec" and not check_vec_type_args( + instance.args, ctx, self.api + ): + return AnyType(TypeOfAny.from_error) + + # Check type argument count. + instance.args = tuple(flatten_nested_tuples(instance.args)) + if not (self.defining_alias and self.nesting_level == 0) and not validate_instance( + instance, self.fail, empty_tuple_index + ): + fix_instance( + instance, + self.fail, + self.note, + disallow_any=self.options.disallow_any_generics and not self.is_typeshed_stub, + options=self.options, + ) + + tup = info.tuple_type + if tup is not None: + # The class has a Tuple[...] base class so it will be + # represented as a tuple type. + if info.special_alias: + return instantiate_type_alias( + info.special_alias, + # TODO: should we allow NamedTuples generic in ParamSpec? + self.anal_array(args, allow_unpack=True), + self.fail, + False, + ctx, + self.options, + use_standard_error=True, + ) + return tup.copy_modified( + items=self.anal_array(tup.items, allow_unpack=True), fallback=instance + ) + td = info.typeddict_type + if td is not None: + # The class has a TypedDict[...] base class so it will be + # represented as a typeddict type. + if info.special_alias: + return instantiate_type_alias( + info.special_alias, + # TODO: should we allow TypedDicts generic in ParamSpec? + self.anal_array(args, allow_unpack=True), + self.fail, + False, + ctx, + self.options, + use_standard_error=True, + ) + # Create a named TypedDictType + return td.copy_modified( + item_types=self.anal_array(list(td.items.values())), fallback=instance + ) + + if info.fullname == "types.NoneType": + self.fail( + "NoneType should not be used as a type, please use None instead", + ctx, + code=codes.NONETYPE_TYPE, + ) + return NoneType(ctx.line, ctx.column) + + return instance + + def analyze_unbound_type_without_type_info( + self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool + ) -> Type: + """Figure out what an unbound type that doesn't refer to a TypeInfo node means. + + This is something unusual. We try our best to find out what it is. + """ + name = sym.fullname + if name is None: + assert sym.node is not None + name = sym.node.name + # Option 1: + # Something with an Any type -- make it an alias for Any in a type + # context. This is slightly problematic as it allows using the type 'Any' + # as a base class -- however, this will fail soon at runtime so the problem + # is pretty minor. + if isinstance(sym.node, Var): + typ = get_proper_type(sym.node.type) + if isinstance(typ, AnyType): + return AnyType( + TypeOfAny.from_unimported_type, missing_import_name=typ.missing_import_name + ) + elif self.allow_type_any: + if isinstance(typ, Instance) and typ.type.fullname == "builtins.type": + return AnyType(TypeOfAny.special_form) + if isinstance(typ, TypeType) and isinstance(typ.item, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=typ.item) + # Option 2: + # Unbound type variable. Currently these may be still valid, + # for example when defining a generic type alias. + unbound_tvar = ( + isinstance(sym.node, (TypeVarExpr, TypeVarTupleExpr)) + and self.tvar_scope.get_binding(sym) is None + ) + if self.allow_unbound_tvars and unbound_tvar: + return t + + # Option 3: + # Enum value. Note: we only want to return a LiteralType when + # we're using this enum value specifically within context of + # a "Literal[...]" type. So, if `defining_literal` is not set, + # we bail out early with an error. + # + # If, in the distant future, we decide to permit things like + # `def foo(x: Color.RED) -> None: ...`, we can remove that + # check entirely. + if ( + isinstance(sym.node, Var) + and sym.node.info + and sym.node.info.is_enum + and sym.node.name in sym.node.info.enum_members + ): + value = sym.node.name + base_enum_short_name = sym.node.info.name + if not defining_literal: + msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format( + base_enum_short_name, value + ) + self.fail(msg.value, t, code=msg.code) + return AnyType(TypeOfAny.from_error) + return LiteralType( + value=value, + fallback=Instance(sym.node.info, [], line=t.line, column=t.column), + line=t.line, + column=t.column, + ) + + # None of the above options worked. We parse the args (if there are any) + # to make sure there are no remaining semanal-only types, then give up. + t = t.copy_modified(args=self.anal_array(t.args)) + # TODO: Move this message building logic to messages.py. + notes: list[str] = [] + error_code = codes.VALID_TYPE + if isinstance(sym.node, Var): + notes.append( + "See https://mypy.readthedocs.io/en/" + "stable/common_issues.html#variables-vs-type-aliases" + ) + message = 'Variable "{}" is not valid as a type' + elif isinstance(sym.node, (SYMBOL_FUNCBASE_TYPES, Decorator)): + message = 'Function "{}" is not valid as a type' + if name == "builtins.any": + notes.append('Perhaps you meant "typing.Any" instead of "any"?') + elif name == "builtins.callable": + notes.append('Perhaps you meant "typing.Callable" instead of "callable"?') + else: + notes.append('Perhaps you need "Callable[...]" or a callback protocol?') + elif isinstance(sym.node, MypyFile): + message = 'Module "{}" is not valid as a type' + notes.append("Perhaps you meant to use a protocol matching the module structure?") + elif unbound_tvar: + assert isinstance(sym.node, TypeVarLikeExpr) + if sym.node.is_new_style: + # PEP 695 type parameters are never considered unbound -- they are undefined + # in contexts where they aren't valid, such as in argument default values. + message = 'Name "{}" is not defined' + name = name.split(".")[-1] + error_code = codes.NAME_DEFINED + else: + message = 'Type variable "{}" is unbound' + short = name.split(".")[-1] + notes.append( + f'(Hint: Use "Generic[{short}]" or "Protocol[{short}]" base class' + f' to bind "{short}" inside a class)' + ) + notes.append( + f'(Hint: Use "{short}" in function signature ' + f'to bind "{short}" inside a function)' + ) + else: + message = 'Cannot interpret reference "{}" as a type' + if not defining_literal: + # Literal check already gives a custom error. Avoid duplicating errors. + self.fail(message.format(name), t, code=error_code) + for note in notes: + self.note(note, t, code=error_code) + + # TODO: Would it be better to always return Any instead of UnboundType + # in case of an error? On one hand, UnboundType has a name so error messages + # are more detailed, on the other hand, some of them may be bogus, + # see https://github.com/python/mypy/issues/4987. + return t + + def visit_any(self, t: AnyType) -> Type: + return t + + def visit_none_type(self, t: NoneType) -> Type: + return t + + def visit_uninhabited_type(self, t: UninhabitedType) -> Type: + return t + + def visit_erased_type(self, t: ErasedType) -> Type: + # This type should exist only temporarily during type inference + assert False, "Internal error: Unexpected erased type" + + def visit_deleted_type(self, t: DeletedType) -> Type: + return t + + def visit_type_list(self, t: TypeList) -> Type: + # Parameters literal (Z[[int, str, Whatever]]) + if self.allow_param_spec_literals: + params = self.analyze_callable_args(t) + if params: + ts, kinds, names = params + # bind these types + return Parameters(self.anal_array(ts), kinds, names, line=t.line, column=t.column) + else: + return AnyType(TypeOfAny.from_error) + else: + self.fail( + 'Bracketed expression "[...]" is not valid as a type', t, code=codes.VALID_TYPE + ) + if len(t.items) == 1: + self.note('Did you mean "List[...]"?', t) + return AnyType(TypeOfAny.from_error) + + def visit_callable_argument(self, t: CallableArgument) -> Type: + self.fail("Invalid type", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + + def visit_instance(self, t: Instance) -> Type: + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # TODO: should we do something here? + return t + + def visit_type_var(self, t: TypeVarType) -> Type: + return t + + def visit_param_spec(self, t: ParamSpecType) -> Type: + return t + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + return t + + def visit_unpack_type(self, t: UnpackType) -> Type: + if not self.allow_unpack: + self.fail(message_registry.INVALID_UNPACK_POSITION, t.type, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + self.allow_type_var_tuple = True + result = UnpackType(self.anal_type(t.type), from_star_syntax=t.from_star_syntax) + self.allow_type_var_tuple = False + return result + + def visit_parameters(self, t: Parameters) -> Type: + raise NotImplementedError("ParamSpec literals cannot have unbound TypeVars") + + def visit_callable_type( + self, t: CallableType, nested: bool = True, namespace: str = "" + ) -> Type: + # Every Callable can bind its own type variables, if they're not in the outer scope + # TODO: attach namespace for nested free type variables (these appear in return type only). + with self.tvar_scope_frame(namespace=namespace): + unpacked_kwargs = t.unpack_kwargs + if self.defining_alias: + variables = t.variables + else: + variables, _ = self.bind_function_type_variables(t, t) + type_guard = self.anal_type_guard(t.ret_type) if t.type_guard is None else t.type_guard + type_is = self.anal_type_is(t.ret_type) if t.type_is is None else t.type_is + + arg_kinds = t.arg_kinds + arg_types = [] + param_spec_with_args = param_spec_with_kwargs = None + param_spec_invalid = False + for kind, ut in zip(arg_kinds, t.arg_types): + if kind == ARG_STAR: + param_spec_with_args, at = self.anal_star_arg_type(ut, kind, nested=nested) + elif kind == ARG_STAR2: + param_spec_with_kwargs, at = self.anal_star_arg_type(ut, kind, nested=nested) + else: + if param_spec_with_args: + param_spec_invalid = True + self.fail( + "Arguments not allowed after ParamSpec.args", t, code=codes.VALID_TYPE + ) + at = self.anal_type(ut, nested=nested, allow_unpack=False) + arg_types.append(at) + + if nested and arg_types: + # If we've got a Callable[[Unpack[SomeTypedDict]], None], make sure + # Unpack is interpreted as `**` and not as `*`. + last = arg_types[-1] + if isinstance(last, UnpackType): + # TODO: it would be better to avoid this get_proper_type() call. + p_at = get_proper_type(last.type) + if isinstance(p_at, TypedDictType) and not last.from_star_syntax: + # Automatically detect Unpack[Foo] in Callable as backwards + # compatible syntax for **Foo, if Foo is a TypedDict. + arg_kinds[-1] = ARG_STAR2 + arg_types[-1] = p_at + unpacked_kwargs = True + arg_types = self.check_unpacks_in_list(arg_types) + + if not param_spec_invalid and param_spec_with_args != param_spec_with_kwargs: + # If already invalid, do not report more errors - definition has + # to be fixed anyway + name = param_spec_with_args or param_spec_with_kwargs + self.fail( + f'ParamSpec must have "*args" typed as "{name}.args" and "**kwargs" typed as "{name}.kwargs"', + t, + code=codes.VALID_TYPE, + ) + param_spec_invalid = True + + if param_spec_invalid: + if ARG_STAR in arg_kinds: + arg_types[arg_kinds.index(ARG_STAR)] = AnyType(TypeOfAny.from_error) + if ARG_STAR2 in arg_kinds: + arg_types[arg_kinds.index(ARG_STAR2)] = AnyType(TypeOfAny.from_error) + + # If there were multiple (invalid) unpacks, the arg types list will become shorter, + # we need to trim the kinds/names as well to avoid crashes. + arg_kinds = t.arg_kinds[: len(arg_types)] + arg_names = t.arg_names[: len(arg_types)] + + ret = t.copy_modified( + arg_types=arg_types, + arg_kinds=arg_kinds, + arg_names=arg_names, + ret_type=self.anal_type(t.ret_type, nested=nested), + # If the fallback isn't filled in yet, + # its type will be the falsey FakeInfo + fallback=(t.fallback if t.fallback.type else self.named_type("builtins.function")), + variables=self.anal_var_defs(variables), + type_guard=type_guard, + type_is=type_is, + unpack_kwargs=unpacked_kwargs, + ) + return ret + + def anal_type_guard(self, t: Type) -> Type | None: + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym is not None and sym.node is not None: + return self.anal_type_guard_arg(t, sym.node.fullname) + # TODO: What if it's an Instance? Then use t.type.fullname? + return None + + def anal_type_guard_arg(self, t: UnboundType, fullname: str) -> Type | None: + if fullname in ("typing_extensions.TypeGuard", "typing.TypeGuard"): + if len(t.args) != 1: + self.fail( + "TypeGuard must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0]) + return None + + def anal_type_is(self, t: Type) -> Type | None: + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym is not None and sym.node is not None: + return self.anal_type_is_arg(t, sym.node.fullname) + # TODO: What if it's an Instance? Then use t.type.fullname? + return None + + def anal_type_is_arg(self, t: UnboundType, fullname: str) -> Type | None: + if fullname in ("typing_extensions.TypeIs", "typing.TypeIs"): + if len(t.args) != 1: + self.fail("TypeIs must have exactly one type argument", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0]) + return None + + def anal_star_arg_type(self, t: Type, kind: ArgKind, nested: bool) -> tuple[str | None, Type]: + """Analyze signature argument type for *args and **kwargs argument.""" + if isinstance(t, UnboundType) and t.name and "." in t.name and not t.args: + components = t.name.split(".") + tvar_name = ".".join(components[:-1]) + sym = self.lookup_qualified(tvar_name, t) + if sym is not None and isinstance(sym.node, ParamSpecExpr): + tvar_def = self.tvar_scope.get_binding(sym) + if isinstance(tvar_def, ParamSpecType): + if kind == ARG_STAR: + make_paramspec = paramspec_args + if components[-1] != "args": + self.fail( + f'Use "{tvar_name}.args" for variadic "*" parameter', + t, + code=codes.VALID_TYPE, + ) + elif kind == ARG_STAR2: + make_paramspec = paramspec_kwargs + if components[-1] != "kwargs": + self.fail( + f'Use "{tvar_name}.kwargs" for variadic "**" parameter', + t, + code=codes.VALID_TYPE, + ) + else: + assert False, kind + return tvar_name, make_paramspec( + tvar_def.name, + tvar_def.fullname, + tvar_def.id, + named_type_func=self.named_type, + line=t.line, + column=t.column, + ) + return None, self.anal_type(t, nested=nested, allow_unpack=True) + + def visit_overloaded(self, t: Overloaded) -> Type: + # Overloaded types are manually constructed in semanal.py by analyzing the + # AST and combining together the Callable types this visitor converts. + # + # So if we're ever asked to reanalyze an Overloaded type, we know it's + # fine to just return it as-is. + return t + + def visit_tuple_type(self, t: TupleType) -> Type: + # Types such as (t1, t2, ...) only allowed in assignment statements. They'll + # generate errors elsewhere, and Tuple[t1, t2, ...] must be used instead. + if t.implicit and not self.allow_tuple_literal: + self.fail("Syntax error in type annotation", t, code=codes.SYNTAX) + if len(t.items) == 0: + self.note( + "Suggestion: Use Tuple[()] instead of () for an empty tuple, or " + "None for a function without a return value", + t, + code=codes.SYNTAX, + ) + elif len(t.items) == 1: + self.note("Suggestion: Is there a spurious trailing comma?", t, code=codes.SYNTAX) + else: + self.note( + "Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)", + t, + code=codes.SYNTAX, + ) + return AnyType(TypeOfAny.from_error) + + any_type = AnyType(TypeOfAny.special_form) + # If the fallback isn't filled in yet, its type will be the falsey FakeInfo + fallback = ( + t.partial_fallback + if t.partial_fallback.type + else self.named_type("builtins.tuple", [any_type]) + ) + return TupleType(self.anal_array(t.items, allow_unpack=True), fallback, t.line) + + def visit_typeddict_type(self, t: TypedDictType) -> Type: + req_keys = set() + readonly_keys = set() + items = {} + for item_name, item_type in t.items.items(): + # TODO: rework + analyzed = self.anal_type(item_type, allow_typed_dict_special_forms=True) + if isinstance(analyzed, RequiredType): + if analyzed.required: + req_keys.add(item_name) + analyzed = analyzed.item + else: + # Keys are required by default. + req_keys.add(item_name) + if isinstance(analyzed, ReadOnlyType): + readonly_keys.add(item_name) + analyzed = analyzed.item + items[item_name] = analyzed + if t.fallback.type is MISSING_FALLBACK: # anonymous/inline TypedDict + if INLINE_TYPEDDICT not in self.options.enable_incomplete_feature: + self.fail( + "Inline TypedDict is experimental," + " must be enabled with --enable-incomplete-feature=InlineTypedDict", + t, + ) + required_keys = req_keys + fallback = self.named_type("typing._TypedDict") + for typ in t.extra_items_from: + analyzed = self.analyze_type(typ) + p_analyzed = get_proper_type(analyzed) + if not isinstance(p_analyzed, TypedDictType): + if not isinstance(p_analyzed, (AnyType, PlaceholderType)): + self.fail("Can only merge-in other TypedDict", t, code=codes.VALID_TYPE) + continue + for sub_item_name, sub_item_type in p_analyzed.items.items(): + if sub_item_name in items: + self.fail(TYPEDDICT_OVERRIDE_MERGE.format(sub_item_name), t) + continue + items[sub_item_name] = sub_item_type + if sub_item_name in p_analyzed.required_keys: + req_keys.add(sub_item_name) + if sub_item_name in p_analyzed.readonly_keys: + readonly_keys.add(sub_item_name) + else: + required_keys = t.required_keys + fallback = t.fallback + return TypedDictType(items, required_keys, readonly_keys, fallback, t.line, t.column) + + def visit_raw_expression_type(self, t: RawExpressionType) -> Type: + # We should never see a bare Literal. We synthesize these raw literals + # in the earlier stages of semantic analysis, but those + # "fake literals" should always be wrapped in an UnboundType + # corresponding to 'Literal'. + # + # Note: if at some point in the distant future, we decide to + # make signatures like "foo(x: 20) -> None" legal, we can change + # this method so it generates and returns an actual LiteralType + # instead. + + if self.report_invalid_types: + if t.base_type_name in ("builtins.int", "builtins.bool"): + # The only time it makes sense to use an int or bool is inside of + # a literal type. + msg = f"Invalid type: try using Literal[{repr(t.literal_value)}] instead?" + elif t.base_type_name in ("builtins.float", "builtins.complex"): + # We special-case warnings for floats and complex numbers. + msg = f"Invalid type: {t.simple_name()} literals cannot be used as a type" + else: + # And in all other cases, we default to a generic error message. + # Note: the reason why we use a generic error message for strings + # but not ints or bools is because whenever we see an out-of-place + # string, it's unclear if the user meant to construct a literal type + # or just misspelled a regular type. So we avoid guessing. + msg = "Invalid type comment or annotation" + + self.fail(msg, t, code=codes.VALID_TYPE) + if t.note is not None: + self.note(t.note, t, code=codes.VALID_TYPE) + + return AnyType(TypeOfAny.from_error, line=t.line, column=t.column) + + def visit_literal_type(self, t: LiteralType) -> Type: + return t + + def visit_union_type(self, t: UnionType) -> Type: + if ( + t.uses_pep604_syntax is True + and t.is_evaluated is True + and not self.always_allow_new_syntax + and not self.options.python_version >= (3, 10) + ): + self.fail("X | Y syntax for unions requires Python 3.10", t, code=codes.SYNTAX) + return UnionType(self.anal_array(t.items), t.line, uses_pep604_syntax=t.uses_pep604_syntax) + + def visit_partial_type(self, t: PartialType) -> Type: + assert False, "Internal error: Unexpected partial type" + + def visit_ellipsis_type(self, t: EllipsisType) -> Type: + if self.allow_ellipsis or self.allow_param_spec_literals: + any_type = AnyType(TypeOfAny.explicit) + return Parameters( + [any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None], is_ellipsis_args=True + ) + else: + self.fail('Unexpected "..."', t) + return AnyType(TypeOfAny.from_error) + + def visit_type_type(self, t: TypeType) -> Type: + return TypeType.make_normalized( + self.anal_type(t.item), line=t.line, is_type_form=t.is_type_form + ) + + def visit_placeholder_type(self, t: PlaceholderType) -> Type: + n = ( + None + # No dot in fullname indicates we are at function scope, and recursive + # types are not supported there anyway, so we just give up. + if not t.fullname or "." not in t.fullname + else self.api.lookup_fully_qualified(t.fullname) + ) + if not n or isinstance(n.node, PlaceholderNode): + self.api.defer() # Still incomplete + return t + else: + # TODO: Handle non-TypeInfo + assert isinstance(n.node, TypeInfo) + return self.analyze_type_with_type_info(n.node, t.args, t, False) + + def analyze_callable_args_for_paramspec( + self, callable_args: Type, ret_type: Type, fallback: Instance + ) -> CallableType | None: + """Construct a 'Callable[P, RET]', where P is ParamSpec, return None if we cannot.""" + if not isinstance(callable_args, UnboundType): + return None + sym = self.lookup_qualified(callable_args.name, callable_args) + if sym is None: + return None + tvar_def = self.tvar_scope.get_binding(sym) + if not isinstance(tvar_def, ParamSpecType): + if ( + tvar_def is None + and self.allow_unbound_tvars + and isinstance(sym.node, ParamSpecExpr) + ): + # We are analyzing this type in runtime context (e.g. as type application). + # If it is not valid as a type in this position an error will be given later. + return callable_with_ellipsis( + AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback + ) + return None + elif ( + self.defining_alias + and self.not_declared_in_type_params(tvar_def.name) + and tvar_def not in self.allowed_alias_tvars + ): + if self.python_3_12_type_alias: + msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format( + f'"{tvar_def.name}"' + ) + else: + msg = f'ParamSpec "{tvar_def.name}" is not included in type_params' + self.fail(msg, callable_args, code=codes.VALID_TYPE) + return callable_with_ellipsis( + AnyType(TypeOfAny.special_form), ret_type=ret_type, fallback=fallback + ) + + return CallableType( + [ + paramspec_args( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + paramspec_kwargs( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + ], + [nodes.ARG_STAR, nodes.ARG_STAR2], + [None, None], + ret_type=ret_type, + fallback=fallback, + ) + + def analyze_callable_args_for_concatenate( + self, callable_args: Type, ret_type: Type, fallback: Instance + ) -> CallableType | AnyType | None: + """Construct a 'Callable[C, RET]', where C is Concatenate[..., P], returning None if we + cannot. + """ + if not isinstance(callable_args, UnboundType): + return None + sym = self.lookup_qualified(callable_args.name, callable_args) + if sym is None: + return None + if sym.node is None: + return None + if sym.node.fullname not in CONCATENATE_TYPE_NAMES: + return None + + tvar_def = self.anal_type(callable_args, allow_param_spec=True) + if not isinstance(tvar_def, (ParamSpecType, Parameters)): + if self.allow_unbound_tvars and isinstance(tvar_def, UnboundType): + sym = self.lookup_qualified(tvar_def.name, callable_args) + if sym is not None and isinstance(sym.node, ParamSpecExpr): + # We are analyzing this type in runtime context (e.g. as type application). + # If it is not valid as a type in this position an error will be given later. + return callable_with_ellipsis( + AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback + ) + # Error was already given, so prevent further errors. + return AnyType(TypeOfAny.from_error) + if isinstance(tvar_def, Parameters): + # This comes from Concatenate[int, ...] + return CallableType( + arg_types=tvar_def.arg_types, + arg_names=tvar_def.arg_names, + arg_kinds=tvar_def.arg_kinds, + ret_type=ret_type, + fallback=fallback, + from_concatenate=True, + ) + + # ick, CallableType should take ParamSpecType + prefix = tvar_def.prefix + # we don't set the prefix here as generic arguments will get updated at some point + # in the future. CallableType.param_spec() accounts for this. + return CallableType( + [ + *prefix.arg_types, + paramspec_args( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + paramspec_kwargs( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + ], + [*prefix.arg_kinds, nodes.ARG_STAR, nodes.ARG_STAR2], + [*prefix.arg_names, None, None], + ret_type=ret_type, + fallback=fallback, + from_concatenate=True, + ) + + def analyze_callable_type(self, t: UnboundType) -> Type: + fallback = self.named_type("builtins.function") + if len(t.args) == 0: + # Callable (bare). Treat as Callable[..., Any]. + any_type = self.get_omitted_any(t) + ret = callable_with_ellipsis(any_type, any_type, fallback) + elif len(t.args) == 2: + callable_args = t.args[0] + ret_type = t.args[1] + if isinstance(callable_args, TypeList): + # Callable[[ARG, ...], RET] (ordinary callable type) + analyzed_args = self.analyze_callable_args(callable_args) + if analyzed_args is None: + return AnyType(TypeOfAny.from_error) + args, kinds, names = analyzed_args + ret = CallableType(args, kinds, names, ret_type=ret_type, fallback=fallback) + elif isinstance(callable_args, EllipsisType): + # Callable[..., RET] (with literal ellipsis; accept arbitrary arguments) + ret = callable_with_ellipsis( + AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback + ) + else: + # Callable[P, RET] (where P is ParamSpec) + with self.tvar_scope_frame(namespace=""): + # Temporarily bind ParamSpecs to allow code like this: + # my_fun: Callable[Q, Foo[Q]] + # We usually do this later in visit_callable_type(), but the analysis + # below happens at very early stage. + variables = [] + for name, tvar_expr in self.find_type_var_likes(callable_args): + variables.append( + self.tvar_scope.bind_new(name, tvar_expr, self.fail_func, t) + ) + maybe_ret = self.analyze_callable_args_for_paramspec( + callable_args, ret_type, fallback + ) or self.analyze_callable_args_for_concatenate( + callable_args, ret_type, fallback + ) + if isinstance(maybe_ret, CallableType): + maybe_ret = maybe_ret.copy_modified(variables=variables) + if maybe_ret is None: + # Callable[?, RET] (where ? is something invalid) + self.fail( + "The first argument to Callable must be a " + 'list of types, parameter specification, or "..."', + t, + code=codes.VALID_TYPE, + ) + self.note( + "See https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas", + t, + ) + return AnyType(TypeOfAny.from_error) + elif isinstance(maybe_ret, AnyType): + return maybe_ret + ret = maybe_ret + else: + if self.options.disallow_any_generics: + self.fail('Please use "Callable[[], ]"', t) + else: + self.fail('Please use "Callable[[], ]" or "Callable"', t) + return AnyType(TypeOfAny.from_error) + assert isinstance(ret, CallableType) + return ret.accept(self) + + def refers_to_full_names(self, arg: UnboundType, names: Sequence[str]) -> bool: + sym = self.lookup_qualified(arg.name, arg) + if sym is not None: + if sym.fullname in names: + return True + return False + + def analyze_callable_args( + self, arglist: TypeList + ) -> tuple[list[Type], list[ArgKind], list[str | None]] | None: + args: list[Type] = [] + kinds: list[ArgKind] = [] + names: list[str | None] = [] + seen_unpack = False + unpack_types: list[Type] = [] + invalid_unpacks: list[Type] = [] + second_unpack_last = False + for i, arg in enumerate(arglist.items): + if isinstance(arg, CallableArgument): + args.append(arg.typ) + names.append(arg.name) + if arg.constructor is None: + return None + found = self.lookup_qualified(arg.constructor, arg) + if found is None: + # Looking it up already put an error message in + return None + elif found.fullname not in ARG_KINDS_BY_CONSTRUCTOR: + self.fail(f'Invalid argument constructor "{found.fullname}"', arg) + return None + else: + assert found.fullname is not None + kind = ARG_KINDS_BY_CONSTRUCTOR[found.fullname] + kinds.append(kind) + if arg.name is not None and kind.is_star(): + self.fail(f"{arg.constructor} arguments should not have names", arg) + return None + elif ( + isinstance(arg, UnboundType) + and self.refers_to_full_names(arg, UNPACK_TYPE_NAMES) + or isinstance(arg, UnpackType) + ): + if seen_unpack: + # Multiple unpacks, preserve them, so we can give an error later. + if i == len(arglist.items) - 1 and not invalid_unpacks: + # Special case: if there are just two unpacks, and the second one appears + # as last type argument, it can be still valid, if the second unpacked type + # is a TypedDict. This should be checked by the caller. + second_unpack_last = True + invalid_unpacks.append(arg) + continue + seen_unpack = True + unpack_types.append(arg) + else: + if seen_unpack: + unpack_types.append(arg) + else: + args.append(arg) + kinds.append(ARG_POS) + names.append(None) + if seen_unpack: + if len(unpack_types) == 1: + args.append(unpack_types[0]) + else: + first = unpack_types[0] + if isinstance(first, UnpackType): + # UnpackType doesn't have its own line/column numbers, + # so use the unpacked type for error messages. + first = first.type + args.append( + UnpackType(self.tuple_type(unpack_types, line=first.line, column=first.column)) + ) + kinds.append(ARG_STAR) + names.append(None) + for arg in invalid_unpacks: + args.append(arg) + kinds.append(ARG_STAR2 if second_unpack_last else ARG_STAR) + names.append(None) + # Note that arglist below is only used for error context. + check_param_names(names, [arglist] * len(args), self.fail, "Callable") + check_arg_kinds(kinds, [arglist] * len(args), self.fail) + return args, kinds, names + + def analyze_literal_type(self, t: UnboundType) -> Type: + if len(t.args) == 0: + self.fail("Literal[...] must have at least one parameter", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + + output: list[Type] = [] + for i, arg in enumerate(t.args): + analyzed_types = self.analyze_literal_param(i + 1, arg, t) + if analyzed_types is None: + return AnyType(TypeOfAny.from_error) + else: + output.extend(analyzed_types) + return UnionType.make_union(output, line=t.line) + + def analyze_literal_param(self, idx: int, arg: Type, ctx: Context) -> list[Type] | None: + # This UnboundType was originally defined as a string. + if ( + isinstance(arg, ProperType) + and isinstance(arg, (UnboundType, UnionType)) + and arg.original_str_expr is not None + ): + assert arg.original_str_fallback is not None + return [ + LiteralType( + value=arg.original_str_expr, + fallback=self.named_type(arg.original_str_fallback), + line=arg.line, + column=arg.column, + ) + ] + + # If arg is an UnboundType that was *not* originally defined as + # a string, try expanding it in case it's a type alias or something. + if isinstance(arg, UnboundType): + self.nesting_level += 1 + try: + arg = self.visit_unbound_type(arg, defining_literal=True) + finally: + self.nesting_level -= 1 + + # Literal[...] cannot contain Any. Give up and add an error message + # (if we haven't already). + arg = get_proper_type(arg) + if isinstance(arg, AnyType): + # Note: We can encounter Literals containing 'Any' under three circumstances: + # + # 1. If the user attempts use an explicit Any as a parameter + # 2. If the user is trying to use an enum value imported from a module with + # no type hints, giving it an implicit type of 'Any' + # 3. If there's some other underlying problem with the parameter. + # + # We report an error in only the first two cases. In the third case, we assume + # some other region of the code has already reported a more relevant error. + # + # TODO: Once we start adding support for enums, make sure we report a custom + # error for case 2 as well. + if arg.type_of_any not in (TypeOfAny.from_error, TypeOfAny.special_form): + self.fail( + f'Parameter {idx} of Literal[...] cannot be of type "Any"', + ctx, + code=codes.VALID_TYPE, + ) + return None + elif isinstance(arg, RawExpressionType): + # A raw literal. Convert it directly into a literal if we can. + if arg.literal_value is None: + name = arg.simple_name() + if name in ("float", "complex"): + msg = f'Parameter {idx} of Literal[...] cannot be of type "{name}"' + else: + msg = "Invalid type: Literal[...] cannot contain arbitrary expressions" + self.fail(msg, ctx, code=codes.VALID_TYPE) + # Note: we deliberately ignore arg.note here: the extra info might normally be + # helpful, but it generally won't make sense in the context of a Literal[...]. + return None + + # Remap bytes and unicode into the appropriate type for the correct Python version + fallback = self.named_type(arg.base_type_name) + assert isinstance(fallback, Instance) + return [LiteralType(arg.literal_value, fallback, line=arg.line, column=arg.column)] + elif isinstance(arg, (NoneType, LiteralType)): + # Types that we can just add directly to the literal/potential union of literals. + return [arg] + elif isinstance(arg, Instance) and arg.last_known_value is not None: + # Types generated from declarations like "var: Final = 4". + return [arg.last_known_value] + elif isinstance(arg, UnionType): + out = [] + for union_arg in arg.items: + union_result = self.analyze_literal_param(idx, union_arg, ctx) + if union_result is None: + return None + out.extend(union_result) + return out + else: + self.fail(f"Parameter {idx} of Literal[...] is invalid", ctx, code=codes.VALID_TYPE) + return None + + def analyze_type(self, typ: Type) -> Type: + return typ.accept(self) + + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.fail_func(msg, ctx, code=code) + + def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.note_func(msg, ctx, code=code) + + @contextmanager + def tvar_scope_frame(self, namespace: str) -> Iterator[None]: + old_scope = self.tvar_scope + self.tvar_scope = self.tvar_scope.method_frame(namespace) + yield + self.tvar_scope = old_scope + + def find_type_var_likes(self, t: Type) -> TypeVarLikeList: + visitor = FindTypeVarVisitor(self.api, self.tvar_scope) + t.accept(visitor) + return visitor.type_var_likes + + def infer_type_variables( + self, type: CallableType + ) -> tuple[list[tuple[str, TypeVarLikeExpr]], bool]: + """Infer type variables from a callable. + + Return tuple with these items: + - list of unique type variables referred to in a callable + - whether there is a reference to the Self type + """ + visitor = FindTypeVarVisitor(self.api, self.tvar_scope) + for arg in type.arg_types: + arg.accept(visitor) + + # When finding type variables in the return type of a function, don't + # look inside Callable types. Type variables only appearing in + # functions in the return type belong to those functions, not the + # function we're currently analyzing. + visitor.include_callables = False + type.ret_type.accept(visitor) + + return visitor.type_var_likes, visitor.has_self_type + + def bind_function_type_variables( + self, fun_type: CallableType, defn: Context + ) -> tuple[tuple[TypeVarLikeType, ...], bool]: + """Find the type variables of the function type and bind them in our tvar_scope""" + has_self_type = False + if fun_type.variables: + defs = [] + for var in fun_type.variables: + if self.api.type and self.api.type.self_type and var == self.api.type.self_type: + has_self_type = True + continue + var_node = self.lookup_qualified(var.name, defn) + assert var_node, "Binding for function type variable not found within function" + var_expr = var_node.node + assert isinstance(var_expr, TypeVarLikeExpr) + binding = self.tvar_scope.bind_new(var.name, var_expr, self.fail_func, fun_type) + defs.append(binding) + return tuple(defs), has_self_type + typevars, has_self_type = self.infer_type_variables(fun_type) + # Do not define a new type variable if already defined in scope. + typevars = [ + (name, tvar) for name, tvar in typevars if not self.is_defined_type_var(name, defn) + ] + defs = [] + for name, tvar in typevars: + if not self.tvar_scope.allow_binding(tvar.fullname): + err_msg = message_registry.TYPE_VAR_REDECLARED_IN_NESTED_CLASS.format(name) + self.fail(err_msg.value, defn, code=err_msg.code) + binding = self.tvar_scope.bind_new(name, tvar, self.fail_func, fun_type) + defs.append(binding) + + return tuple(defs), has_self_type + + def is_defined_type_var(self, tvar: str, context: Context) -> bool: + tvar_node = self.lookup_qualified(tvar, context) + if not tvar_node: + return False + return self.tvar_scope.get_binding(tvar_node) is not None + + def anal_array( + self, + a: Iterable[Type], + nested: bool = True, + *, + allow_param_spec: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + ) -> list[Type]: + old_allow_param_spec_literals = self.allow_param_spec_literals + self.allow_param_spec_literals = allow_param_spec_literals + res: list[Type] = [] + for t in a: + res.append( + self.anal_type( + t, nested, allow_param_spec=allow_param_spec, allow_unpack=allow_unpack + ) + ) + self.allow_param_spec_literals = old_allow_param_spec_literals + return self.check_unpacks_in_list(res) + + def anal_type( + self, + t: Type, + nested: bool = True, + *, + allow_param_spec: bool = False, + allow_unpack: bool = False, + allow_ellipsis: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = False, + ) -> Type: + if nested: + self.nesting_level += 1 + old_allow_typed_dict_special_forms = self.allow_typed_dict_special_forms + self.allow_typed_dict_special_forms = allow_typed_dict_special_forms + self.allow_final = allow_final + old_allow_ellipsis = self.allow_ellipsis + self.allow_ellipsis = allow_ellipsis + old_allow_unpack = self.allow_unpack + self.allow_unpack = allow_unpack + try: + analyzed = t.accept(self) + finally: + if nested: + self.nesting_level -= 1 + self.allow_typed_dict_special_forms = old_allow_typed_dict_special_forms + self.allow_ellipsis = old_allow_ellipsis + self.allow_unpack = old_allow_unpack + if ( + not allow_param_spec + and isinstance(analyzed, ParamSpecType) + and analyzed.flavor == ParamSpecFlavor.BARE + ): + if analyzed.prefix.arg_types: + self.fail("Invalid location for Concatenate", t, code=codes.VALID_TYPE) + self.note("You can use Concatenate as the first argument to Callable", t) + analyzed = AnyType(TypeOfAny.from_error) + else: + self.fail( + INVALID_PARAM_SPEC_LOCATION.format(format_type(analyzed, self.options)), + t, + code=codes.VALID_TYPE, + ) + self.note( + INVALID_PARAM_SPEC_LOCATION_NOTE.format(analyzed.name), + t, + code=codes.VALID_TYPE, + ) + analyzed = AnyType(TypeOfAny.from_error) + return analyzed + + def anal_var_def(self, var_def: TypeVarLikeType) -> TypeVarLikeType: + if isinstance(var_def, TypeVarType): + return TypeVarType( + name=var_def.name, + fullname=var_def.fullname, + id=var_def.id, + values=self.anal_array(var_def.values), + upper_bound=var_def.upper_bound.accept(self), + default=var_def.default.accept(self), + variance=var_def.variance, + line=var_def.line, + column=var_def.column, + ) + else: + return var_def + + def anal_var_defs(self, var_defs: Sequence[TypeVarLikeType]) -> list[TypeVarLikeType]: + return [self.anal_var_def(vd) for vd in var_defs] + + def named_type( + self, fullname: str, args: list[Type] | None = None, line: int = -1, column: int = -1 + ) -> Instance: + node = self.lookup_fully_qualified(fullname) + assert isinstance(node.node, TypeInfo) + any_type = AnyType(TypeOfAny.special_form) + if args is not None: + args = self.check_unpacks_in_list(args) + return Instance( + node.node, args or [any_type] * len(node.node.defn.type_vars), line=line, column=column + ) + + def check_unpacks_in_list(self, items: list[Type]) -> list[Type]: + new_items: list[Type] = [] + num_unpacks = 0 + final_unpack = None + for item in items: + # TODO: handle forward references here, they appear as Unpack[Any]. + if isinstance(item, UnpackType) and not isinstance( + get_proper_type(item.type), TupleType + ): + if not num_unpacks: + new_items.append(item) + num_unpacks += 1 + final_unpack = item + else: + new_items.append(item) + + if num_unpacks > 1: + assert final_unpack is not None + self.fail("More than one variadic Unpack in a type is not allowed", final_unpack.type) + return new_items + + def tuple_type(self, items: list[Type], line: int, column: int) -> TupleType: + any_type = AnyType(TypeOfAny.special_form) + return TupleType( + items, fallback=self.named_type("builtins.tuple", [any_type]), line=line, column=column + ) + + +TypeVarLikeList = list[tuple[str, TypeVarLikeExpr]] + + +class MsgCallback(Protocol): + def __call__( + self, __msg: str, __ctx: Context, *, code: ErrorCode | None = None + ) -> ErrorInfo | None: ... + + +def get_omitted_any( + disallow_any: bool, + fail: MsgCallback, + note: MsgCallback, + orig_type: Type, + options: Options, + fullname: str | None = None, + unexpanded_type: Type | None = None, +) -> AnyType: + if disallow_any: + typ = unexpanded_type or orig_type + type_str = typ.name if isinstance(typ, UnboundType) else format_type_bare(typ, options) + + fail( + message_registry.BARE_GENERIC.format(quote_type_string(type_str)), + typ, + code=codes.TYPE_ARG, + ) + + any_type = AnyType(TypeOfAny.from_error, line=typ.line, column=typ.column) + else: + any_type = AnyType( + TypeOfAny.from_omitted_generics, line=orig_type.line, column=orig_type.column + ) + return any_type + + +def fix_type_var_tuple_argument(t: Instance) -> None: + if t.type.has_type_var_tuple_type: + args = list(t.args) + assert t.type.type_var_tuple_prefix is not None + tvt = t.type.defn.type_vars[t.type.type_var_tuple_prefix] + assert isinstance(tvt, TypeVarTupleType) + args[t.type.type_var_tuple_prefix] = UnpackType( + Instance(tvt.tuple_fallback.type, [args[t.type.type_var_tuple_prefix]]) + ) + t.args = tuple(args) + + +def fix_instance( + t: Instance, + fail: MsgCallback, + note: MsgCallback, + disallow_any: bool, + options: Options, + use_generic_error: bool = False, + unexpanded_type: Type | None = None, +) -> None: + """Fix a malformed instance by replacing all type arguments with TypeVar default or Any. + + Also emit a suitable error if this is not due to implicit Any's. + """ + arg_count = len(t.args) + min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars) + max_tv_count = len(t.type.type_vars) + if arg_count < min_tv_count or arg_count > max_tv_count: + # Don't use existing args if arg_count doesn't match + if arg_count > max_tv_count: + # Already wrong arg count error, don't emit missing type parameters error as well. + disallow_any = False + t.args = () + + args: list[Type] = [*(t.args[:max_tv_count])] + any_type: AnyType | None = None + env: dict[TypeVarId, Type] = {} + + for tv, arg in itertools.zip_longest(t.type.defn.type_vars, t.args, fillvalue=None): + if tv is None: + continue + if arg is None: + if tv.has_default(): + arg = tv.default + else: + if any_type is None: + fullname = None if use_generic_error else t.type.fullname + any_type = get_omitted_any( + disallow_any, fail, note, t, options, fullname, unexpanded_type + ) + arg = any_type + args.append(arg) + env[tv.id] = arg + t.args = tuple(args) + fix_type_var_tuple_argument(t) + if not t.type.has_type_var_tuple_type: + with state.strict_optional_set(True): + fixed = expand_type(t, env) + assert isinstance(fixed, Instance) + t.args = fixed.args + + +def instantiate_type_alias( + node: TypeAlias, + args: list[Type], + fail: MsgCallback, + no_args: bool, + ctx: Context, + options: Options, + *, + unexpanded_type: Type | None = None, + disallow_any: bool = False, + use_standard_error: bool = False, + empty_tuple_index: bool = False, +) -> Type: + """Create an instance of a (generic) type alias from alias node and type arguments. + + We are following the rules outlined in TypeAlias docstring. + Here: + node: type alias node (definition) + args: type arguments (types to be substituted in place of type variables + when expanding the alias) + fail: error reporter callback + no_args: whether original definition used a bare generic `A = List` + ctx: context where expansion happens + unexpanded_type, disallow_any, use_standard_error: used to customize error messages + """ + # Type aliases are special, since they can be expanded during semantic analysis, + # so we need to normalize them as soon as possible. + # TODO: can this cause an infinite recursion? + args = flatten_nested_tuples(args) + if any(unknown_unpack(a) for a in args): + # This type is not ready to be validated, because of unknown total count. + # Note that we keep the kind of Any for consistency. + return set_any_tvars(node, [], ctx.line, ctx.column, options, special_form=True) + + if ( + no_args + and isinstance(node.target, ProperType) + and isinstance(node.target, Instance) + and node.target.type.fullname == "builtins.tuple" + and len(args) + ): + no_args = False + + max_tv_count = len(node.alias_tvars) + act_len = len(args) + if ( + max_tv_count > 0 + and act_len == 0 + and not (empty_tuple_index and node.tvar_tuple_index is not None) + ): + # Interpret bare Alias same as normal generic, i.e., Alias[Any, Any, ...] + return set_any_tvars( + node, + args, + ctx.line, + ctx.column, + options, + disallow_any=disallow_any, + fail=fail, + unexpanded_type=unexpanded_type, + ) + if max_tv_count == 0 and act_len == 0: + if no_args: + assert isinstance(node.target, Instance) # type: ignore[misc] + # Note: this is the only case where we use an eager expansion. See more info about + # no_args aliases like L = List in the docstring for TypeAlias class. + return Instance(node.target.type, [], line=ctx.line, column=ctx.column) + return TypeAliasType(node, [], line=ctx.line, column=ctx.column) + if ( + max_tv_count == 0 + and act_len > 0 + and isinstance(node.target, Instance) # type: ignore[misc] + and no_args + ): + tp = Instance(node.target.type, args) + tp.line = ctx.line + tp.column = ctx.column + tp.end_line = ctx.end_line + tp.end_column = ctx.end_column + return tp + if node.tvar_tuple_index is None: + if any(isinstance(a, UnpackType) for a in args): + # A variadic unpack in fixed size alias (fixed unpacks must be flattened by the caller) + fail(message_registry.INVALID_UNPACK_POSITION, ctx, code=codes.VALID_TYPE) + return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True) + min_tv_count = sum(not tv.has_default() for tv in node.alias_tvars) + fill_typevars = act_len != max_tv_count + correct = min_tv_count <= act_len <= max_tv_count + else: + min_tv_count = sum( + not tv.has_default() and not isinstance(tv, TypeVarTupleType) + for tv in node.alias_tvars + ) + correct = act_len >= min_tv_count + for a in args: + if isinstance(a, UnpackType): + unpacked = get_proper_type(a.type) + if isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple": + # Variadic tuple is always correct. + correct = True + fill_typevars = not correct + if fill_typevars: + if not correct: + if use_standard_error: + # This is used if type alias is an internal representation of another type, + # for example a generic TypedDict or NamedTuple. + msg = wrong_type_arg_count(max_tv_count, max_tv_count, str(act_len), node.name) + else: + if node.tvar_tuple_index is not None: + msg = ( + "Bad number of arguments for type alias," + f" expected at least {min_tv_count}, given {act_len}" + ) + elif min_tv_count != max_tv_count: + msg = ( + "Bad number of arguments for type alias," + f" expected between {min_tv_count} and {max_tv_count}, given {act_len}" + ) + else: + msg = ( + "Bad number of arguments for type alias," + f" expected {min_tv_count}, given {act_len}" + ) + fail(msg, ctx, code=codes.TYPE_ARG) + args = [] + return set_any_tvars(node, args, ctx.line, ctx.column, options, from_error=True) + elif node.tvar_tuple_index is not None: + # We also need to check if we are not performing a type variable tuple split. + unpack = find_unpack_in_list(args) + if unpack is not None: + unpack_arg = args[unpack] + assert isinstance(unpack_arg, UnpackType) + if isinstance(unpack_arg.type, TypeVarTupleType): + exp_prefix = node.tvar_tuple_index + act_prefix = unpack + exp_suffix = len(node.alias_tvars) - node.tvar_tuple_index - 1 + act_suffix = len(args) - unpack - 1 + if act_prefix < exp_prefix or act_suffix < exp_suffix: + fail("TypeVarTuple cannot be split", ctx, code=codes.TYPE_ARG) + return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True) + # TODO: we need to check args validity w.r.t alias.alias_tvars. + # Otherwise invalid instantiations will be allowed in runtime context. + # Note: in type context, these will be still caught by semanal_typeargs. + typ = TypeAliasType(node, args, ctx.line, ctx.column) + assert typ.alias is not None + # HACK: Implement FlexibleAlias[T, typ] by expanding it to typ here. + if ( + isinstance(typ.alias.target, Instance) # type: ignore[misc] + and typ.alias.target.type.fullname == "mypy_extensions.FlexibleAlias" + ): + exp = get_proper_type(typ) + assert isinstance(exp, Instance) + return exp.args[-1] + return typ + + +def set_any_tvars( + node: TypeAlias, + args: list[Type], + newline: int, + newcolumn: int, + options: Options, + *, + from_error: bool = False, + disallow_any: bool = False, + special_form: bool = False, + fail: MsgCallback | None = None, + unexpanded_type: Type | None = None, +) -> TypeAliasType: + if from_error or disallow_any: + type_of_any = TypeOfAny.from_error + elif special_form: + type_of_any = TypeOfAny.special_form + else: + type_of_any = TypeOfAny.from_omitted_generics + any_type = AnyType(type_of_any, line=newline, column=newcolumn) + + env: dict[TypeVarId, Type] = {} + used_any_type = False + has_type_var_tuple_type = False + for tv, arg in itertools.zip_longest(node.alias_tvars, args, fillvalue=None): + if tv is None: + continue + if arg is None: + if tv.has_default(): + arg = tv.default + else: + arg = any_type + used_any_type = True + if isinstance(tv, TypeVarTupleType): + # TODO Handle TypeVarTuple defaults + has_type_var_tuple_type = True + arg = UnpackType(Instance(tv.tuple_fallback.type, [any_type])) + args.append(arg) + env[tv.id] = arg + t = TypeAliasType(node, args, newline, newcolumn) + if not has_type_var_tuple_type: + with state.strict_optional_set(options.strict_optional): + fixed = expand_type(t, env) + assert isinstance(fixed, TypeAliasType) + t.args = fixed.args + + if used_any_type and disallow_any and node.alias_tvars: + assert fail is not None + if unexpanded_type: + type_str = ( + unexpanded_type.name + if isinstance(unexpanded_type, UnboundType) + else format_type_bare(unexpanded_type, options) + ) + else: + type_str = node.name + + fail( + message_registry.BARE_GENERIC.format(quote_type_string(type_str)), + Context(newline, newcolumn), + code=codes.TYPE_ARG, + ) + return t + + +class DivergingAliasDetector(TrivialSyntheticTypeTranslator): + """See docstring of detect_diverging_alias() for details.""" + + # TODO: this doesn't really need to be a translator, but we don't have a trivial visitor. + def __init__( + self, + seen_nodes: set[TypeAlias], + lookup: Callable[[str, Context], SymbolTableNode | None], + scope: TypeVarLikeScope, + ) -> None: + super().__init__() + self.seen_nodes = seen_nodes + self.lookup = lookup + self.scope = scope + self.diverging = False + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + assert t.alias is not None, f"Unfixed type alias {t.type_ref}" + if t.alias in self.seen_nodes: + for arg in t.args: + if not ( + isinstance(arg, TypeVarLikeType) + or isinstance(arg, UnpackType) + and isinstance(arg.type, TypeVarLikeType) + ) and has_type_vars(arg): + self.diverging = True + return t + # All clear for this expansion chain. + return t + new_nodes = self.seen_nodes | {t.alias} + visitor = DivergingAliasDetector(new_nodes, self.lookup, self.scope) + _ = get_proper_type(t).accept(visitor) + if visitor.diverging: + self.diverging = True + return t + + +def detect_diverging_alias( + node: TypeAlias, + target: Type, + lookup: Callable[[str, Context], SymbolTableNode | None], + scope: TypeVarLikeScope, +) -> bool: + """This detects type aliases that will diverge during type checking. + + For example F = Something[..., F[List[T]]]. At each expansion step this will produce + *new* type aliases: e.g. F[List[int]], F[List[List[int]]], etc. So we can't detect + recursion. It is a known problem in the literature, recursive aliases and generic types + don't always go well together. It looks like there is no known systematic solution yet. + + # TODO: should we handle such aliases using type_recursion counter and some large limit? + They may be handy in rare cases, e.g. to express a union of non-mixed nested lists: + Nested = Union[T, Nested[List[T]]] ~> Union[T, List[T], List[List[T]], ...] + """ + visitor = DivergingAliasDetector({node}, lookup, scope) + _ = target.accept(visitor) + return visitor.diverging + + +def check_for_explicit_any( + typ: Type | None, + options: Options, + is_typeshed_stub: bool, + msg: MessageBuilder, + context: Context, +) -> None: + if options.disallow_any_explicit and not is_typeshed_stub and typ and has_explicit_any(typ): + msg.explicit_any(context) + + +def has_explicit_any(t: Type) -> bool: + """ + Whether this type is or type it contains is an Any coming from explicit type annotation + """ + return t.accept(HasExplicitAny()) + + +class HasExplicitAny(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_any(self, t: AnyType) -> bool: + return t.type_of_any == TypeOfAny.explicit + + def visit_typeddict_type(self, t: TypedDictType) -> bool: + # typeddict is checked during TypedDict declaration, so don't typecheck it here. + return False + + +def has_any_from_unimported_type(t: Type) -> bool: + """Return true if this type is Any because an import was not followed. + + If type t is such Any type or has type arguments that contain such Any type + this function will return true. + """ + return t.accept(HasAnyFromUnimportedType()) + + +class HasAnyFromUnimportedType(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_any(self, t: AnyType) -> bool: + return t.type_of_any == TypeOfAny.from_unimported_type + + def visit_typeddict_type(self, t: TypedDictType) -> bool: + # typeddict is checked during TypedDict declaration, so don't typecheck it here + return False + + +def collect_all_inner_types(t: Type) -> list[Type]: + """ + Return all types that `t` contains + """ + return t.accept(CollectAllInnerTypesQuery()) + + +class CollectAllInnerTypesQuery(TypeQuery[list[Type]]): + def query_types(self, types: Iterable[Type]) -> list[Type]: + return self.strategy([t.accept(self) for t in types]) + list(types) + + def strategy(self, items: Iterable[list[Type]]) -> list[Type]: + return list(itertools.chain.from_iterable(items)) + + +def make_optional_type(t: Type) -> Type: + """Return the type corresponding to Optional[t]. + + Note that we can't use normal union simplification, since this function + is called during semantic analysis and simplification only works during + type checking. + """ + if isinstance(t, ProperType) and isinstance(t, NoneType): + return t + elif isinstance(t, ProperType) and isinstance(t, UnionType): + # Eagerly expanding aliases is not safe during semantic analysis. + items = [item for item in t.items if not isinstance(get_proper_type(item), NoneType)] + return UnionType(items + [NoneType()], t.line, t.column) + else: + return UnionType([t, NoneType()], t.line, t.column) + + +def validate_instance(t: Instance, fail: MsgCallback, indexed: bool) -> bool: + """Check if this is a well-formed instance with respect to argument count/positions.""" + # TODO: combine logic with instantiate_type_alias(). + if any(unknown_unpack(a) for a in t.args): + # This type is not ready to be validated, because of unknown total count. + # TODO: is it OK to fill with TypeOfAny.from_error instead of special form? + return False + empty_tuple_index = indexed and not t.args + if t.type.has_type_var_tuple_type: + min_tv_count = sum( + not tv.has_default() and not isinstance(tv, TypeVarTupleType) + for tv in t.type.defn.type_vars + ) + correct = len(t.args) >= min_tv_count + if any( + isinstance(a, UnpackType) and isinstance(get_proper_type(a.type), Instance) + for a in t.args + ): + correct = True + if not t.args: + if not (empty_tuple_index and len(t.type.type_vars) == 1): + # The Any arguments should be set by the caller. + if empty_tuple_index and min_tv_count: + fail( + f"At least {min_tv_count} type argument(s) expected, none given", + t, + code=codes.TYPE_ARG, + ) + return False + elif not correct: + fail( + f"Bad number of arguments, expected: at least {min_tv_count}, given: {len(t.args)}", + t, + code=codes.TYPE_ARG, + ) + return False + else: + # We also need to check if we are not performing a type variable tuple split. + unpack = find_unpack_in_list(t.args) + if unpack is not None: + unpack_arg = t.args[unpack] + assert isinstance(unpack_arg, UnpackType) + if isinstance(unpack_arg.type, TypeVarTupleType): + assert t.type.type_var_tuple_prefix is not None + assert t.type.type_var_tuple_suffix is not None + exp_prefix = t.type.type_var_tuple_prefix + act_prefix = unpack + exp_suffix = t.type.type_var_tuple_suffix + act_suffix = len(t.args) - unpack - 1 + if act_prefix < exp_prefix or act_suffix < exp_suffix: + fail("TypeVarTuple cannot be split", t, code=codes.TYPE_ARG) + return False + elif any(isinstance(a, UnpackType) for a in t.args): + # A variadic unpack in fixed size instance (fixed unpacks must be flattened by the caller) + fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE) + t.args = () + return False + elif len(t.args) != len(t.type.type_vars): + # Invalid number of type parameters. + arg_count = len(t.args) + min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars) + max_tv_count = len(t.type.type_vars) + if (arg_count or empty_tuple_index) and ( + arg_count < min_tv_count or arg_count > max_tv_count + ): + fail( + wrong_type_arg_count(min_tv_count, max_tv_count, str(arg_count), t.type.name), + t, + code=codes.TYPE_ARG, + ) + return False + return True + + +def find_self_type(typ: Type, lookup: Callable[[str], SymbolTableNode | None]) -> bool: + return typ.accept(HasSelfType(lookup)) + + +class HasSelfType(BoolTypeQuery): + def __init__(self, lookup: Callable[[str], SymbolTableNode | None]) -> None: + self.lookup = lookup + super().__init__(ANY_STRATEGY) + + def visit_unbound_type(self, t: UnboundType) -> bool: + sym = self.lookup(t.name) + if sym and sym.fullname in SELF_TYPE_NAMES: + return True + return super().visit_unbound_type(t) + + +def unknown_unpack(t: Type) -> bool: + """Check if a given type is an unpack of an unknown type. + + Unfortunately, there is no robust way to distinguish forward references from + genuine undefined names here. But this worked well so far, although it looks + quite fragile. + """ + if isinstance(t, UnpackType): + unpacked = get_proper_type(t.type) + if isinstance(unpacked, AnyType) and unpacked.type_of_any == TypeOfAny.special_form: + return True + return False + + +class FindTypeVarVisitor(SyntheticTypeVisitor[None]): + """Type visitor that looks for type variable types and self types.""" + + def __init__(self, api: SemanticAnalyzerCoreInterface, scope: TypeVarLikeScope) -> None: + self.api = api + self.scope = scope + self.type_var_likes: list[tuple[str, TypeVarLikeExpr]] = [] + self.has_self_type = False + self.include_callables = True + + def _seems_like_callable(self, type: UnboundType) -> bool: + if not type.args: + return False + return isinstance(type.args[0], (EllipsisType, TypeList, ParamSpecType)) + + def visit_unbound_type(self, t: UnboundType) -> None: + name = t.name + node = self.api.lookup_qualified(name, t) + if node and node.fullname in SELF_TYPE_NAMES: + self.has_self_type = True + if ( + node + and isinstance(node.node, TypeVarLikeExpr) + and self.scope.get_binding(node) is None + ): + if (name, node.node) not in self.type_var_likes: + self.type_var_likes.append((name, node.node)) + elif not self.include_callables and self._seems_like_callable(t): + if find_self_type( + t, lambda name: self.api.lookup_qualified(name, t, suppress_errors=True) + ): + self.has_self_type = True + return + elif node and node.fullname in LITERAL_TYPE_NAMES: + return + elif node and node.fullname in ANNOTATED_TYPE_NAMES and t.args: + # Don't query the second argument to Annotated for TypeVars + self.process_types([t.args[0]]) + elif t.args: + self.process_types(t.args) + + def visit_type_list(self, t: TypeList) -> None: + self.process_types(t.items) + + def visit_callable_argument(self, t: CallableArgument) -> None: + t.typ.accept(self) + + def visit_any(self, t: AnyType) -> None: + pass + + def visit_uninhabited_type(self, t: UninhabitedType) -> None: + pass + + def visit_none_type(self, t: NoneType) -> None: + pass + + def visit_erased_type(self, t: ErasedType) -> None: + pass + + def visit_deleted_type(self, t: DeletedType) -> None: + pass + + def visit_type_var(self, t: TypeVarType) -> None: + self.process_types([t.upper_bound, t.default] + t.values) + + def visit_param_spec(self, t: ParamSpecType) -> None: + self.process_types([t.upper_bound, t.default, t.prefix]) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: + self.process_types([t.upper_bound, t.default]) + + def visit_unpack_type(self, t: UnpackType) -> None: + self.process_types([t.type]) + + def visit_parameters(self, t: Parameters) -> None: + self.process_types(t.arg_types) + + def visit_partial_type(self, t: PartialType) -> None: + pass + + def visit_instance(self, t: Instance) -> None: + self.process_types(t.args) + + def visit_callable_type(self, t: CallableType) -> None: + # FIX generics + self.process_types(t.arg_types) + t.ret_type.accept(self) + + def visit_tuple_type(self, t: TupleType) -> None: + self.process_types(t.items) + + def visit_typeddict_type(self, t: TypedDictType) -> None: + self.process_types(list(t.items.values())) + + def visit_raw_expression_type(self, t: RawExpressionType) -> None: + pass + + def visit_literal_type(self, t: LiteralType) -> None: + pass + + def visit_union_type(self, t: UnionType) -> None: + self.process_types(t.items) + + def visit_overloaded(self, t: Overloaded) -> None: + for it in t.items: + it.accept(self) + + def visit_type_type(self, t: TypeType) -> None: + t.item.accept(self) + + def visit_ellipsis_type(self, t: EllipsisType) -> None: + pass + + def visit_placeholder_type(self, t: PlaceholderType) -> None: + return self.process_types(t.args) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + self.process_types(t.args) + + def process_types(self, types: list[Type] | tuple[Type, ...]) -> None: + # Redundant type check helps mypyc. + if isinstance(types, list): + for t in types: + t.accept(self) + else: + for t in types: + t.accept(self) + + +class TypeVarDefaultTranslator(TrivialSyntheticTypeTranslator): + """Type translate visitor that replaces UnboundTypes with in-scope TypeVars.""" + + def __init__( + self, api: SemanticAnalyzerInterface, tvar_expr_name: str, context: Context + ) -> None: + super().__init__() + self.api = api + self.tvar_expr_name = tvar_expr_name + self.context = context + + def visit_unbound_type(self, t: UnboundType) -> Type: + sym = self.api.lookup_qualified(t.name, t, suppress_errors=True) + if sym is not None: + if type_var := self.api.tvar_scope.get_binding(sym): + return type_var + if isinstance(sym.node, TypeVarLikeExpr): + self.api.fail( + f'Type parameter "{self.tvar_expr_name}" has a default type ' + "that refers to one or more type variables that are out of scope", + self.context, + ) + return AnyType(TypeOfAny.from_error) + return super().visit_unbound_type(t) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # TypeAliasTypes are analyzed separately already, just return it + return t + + +def check_vec_type_args( + args: tuple[Type, ...] | list[Type], ctx: Context, api: SemanticAnalyzerCoreInterface +) -> bool: + """Report an error if type args for 'vec' are invalid. + + Return False on error. + """ + ok = True + if len(args) != 1: + ok = False + else: + arg = get_proper_type(args[0]) + if isinstance(arg, Instance): + if arg.type.fullname == "builtins.int": + # A fixed-width integer such as 'i64' must be used instead of plain 'int' + ok = False + elif isinstance(arg, UnionType): + non_optional = None + items = [get_proper_type(item) for item in arg.items] + if len(items) != 2: + ok = False + elif isinstance(items[0], NoneType): + if not check_vec_type_args([items[1]], ctx, api): + # Error has already been reported so it's fine to return + return False + non_optional = items[1] + elif isinstance(items[1], NoneType): + if not check_vec_type_args([items[0]], ctx, api): + # Error has already been reported so it's fine to return + return False + non_optional = items[0] + else: + ok = False + if isinstance(non_optional, Instance) and ( + non_optional.type.fullname in MYPYC_NATIVE_INT_NAMES + or non_optional.type.fullname + in ("builtins.int", "builtins.float", "builtins.bool", "librt.vecs.vec") + ): + ok = False + elif isinstance(arg, TypeVarType): + # Generic vec types aren't supported in type checked Python code, but + # they can be provided in libraries implemented in C (e.g. append). + if not api.is_stub_file: + ok = False + else: + ok = False + if not ok: + api.fail('Invalid item type for "vec"', ctx) + return ok diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeops.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeops.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..fd89739c9987751be1cec36848220b0d96fe20df Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeops.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeops.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeops.py new file mode 100644 index 0000000000000000000000000000000000000000..839c6454ca28fcda460efe1d76d832895e295bb6 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typeops.py @@ -0,0 +1,1344 @@ +"""Miscellaneous type operations and helpers for use during type checking. + +NOTE: These must not be accessed from mypy.nodes or mypy.types to avoid import + cycles. These must not be called from the semantic analysis main pass + since these may assume that MROs are ready. +""" + +from __future__ import annotations + +import itertools +from collections.abc import Callable, Iterable, Sequence +from typing import Any, TypeVar, cast + +from mypy.checker_state import checker_state +from mypy.copytype import copy_type +from mypy.expandtype import expand_type, expand_type_by_instance +from mypy.maptype import map_instance_to_supertype +from mypy.nodes import ( + ARG_POS, + ARG_STAR, + ARG_STAR2, + SYMBOL_FUNCBASE_TYPES, + Decorator, + Expression, + FuncBase, + FuncDef, + FuncItem, + OverloadedFuncDef, + StrExpr, + SymbolNode, + TypeInfo, + Var, +) +from mypy.state import state +from mypy.types import ( + ELLIPSIS_TYPE_NAMES, + NOT_IMPLEMENTED_TYPE_NAMES, + AnyType, + CallableType, + ExtraAttrs, + FormalArgument, + FunctionLike, + Instance, + LiteralType, + NoneType, + NormalizedCallableType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeQuery, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + get_proper_types, + remove_dups, +) +from mypy.typetraverser import TypeTraverserVisitor +from mypy.typevars import fill_typevars + + +def is_recursive_pair(s: Type, t: Type) -> bool: + """Is this a pair of recursive types? + + There may be more cases, and we may be forced to use e.g. has_recursive_types() + here, but this function is called in very hot code, so we try to keep it simple + and return True only in cases we know may have problems. + """ + if isinstance(s, TypeAliasType) and s.is_recursive: + return ( + isinstance(get_proper_type(t), (Instance, UnionType)) + or isinstance(t, TypeAliasType) + and t.is_recursive + # Tuple types are special, they can cause an infinite recursion even if + # the other type is not recursive, because of the tuple fallback that is + # calculated "on the fly". + or isinstance(get_proper_type(s), TupleType) + ) + if isinstance(t, TypeAliasType) and t.is_recursive: + return ( + isinstance(get_proper_type(s), (Instance, UnionType)) + or isinstance(s, TypeAliasType) + and s.is_recursive + # Same as above. + or isinstance(get_proper_type(t), TupleType) + ) + return False + + +def tuple_fallback(typ: TupleType) -> Instance: + """Return fallback type for a tuple.""" + info = typ.partial_fallback.type + if info.fullname != "builtins.tuple": + return typ.partial_fallback + items = [] + for item in typ.items: + if isinstance(item, UnpackType): + unpacked_type = get_proper_type(item.type) + if isinstance(unpacked_type, TypeVarTupleType): + unpacked_type = get_proper_type(unpacked_type.upper_bound) + if ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ): + items.append(unpacked_type.args[0]) + else: + raise NotImplementedError + else: + items.append(item) + return Instance( + info, + # Note: flattening recursive unions is dangerous, since it can fool recursive + # types optimization in subtypes.py and go into infinite recursion. + [make_simplified_union(items, handle_recursive=False)], + extra_attrs=typ.partial_fallback.extra_attrs, + ) + + +def get_self_type(func: CallableType, def_info: TypeInfo) -> Type | None: + default_self = fill_typevars(def_info) + if isinstance(get_proper_type(func.ret_type), UninhabitedType): + return func.ret_type + elif func.arg_types and func.arg_types[0] != default_self and func.arg_kinds[0] == ARG_POS: + return func.arg_types[0] + else: + return None + + +def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> ProperType: + """Return the type of a type object. + + For a generic type G with type variables T and S the type is generally of form + + Callable[..., G[T, S]] + + where ... are argument types for the __init__/__new__ method (without the self + argument). Also, the fallback type will be 'type' instead of 'function'. + """ + allow_cache = ( + checker_state.type_checker is not None + and checker_state.type_checker.allow_constructor_cache + ) + + if info.type_object_type is not None: + if allow_cache: + return info.type_object_type + info.type_object_type = None + + # We take the type from whichever of __init__ and __new__ is first + # in the MRO, preferring __init__ if there is a tie. + init_method = info.get("__init__") + new_method = info.get("__new__") + if not init_method or not is_valid_constructor(init_method.node): + # Must be an invalid class definition. + return AnyType(TypeOfAny.from_error) + # There *should* always be a __new__ method except the test stubs + # lack it, so just copy init_method in that situation + new_method = new_method or init_method + if not is_valid_constructor(new_method.node): + # Must be an invalid class definition. + return AnyType(TypeOfAny.from_error) + + # The two is_valid_constructor() checks ensure this. + assert isinstance(new_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator)) + assert isinstance(init_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator)) + + init_index = info.mro.index(init_method.node.info) + new_index = info.mro.index(new_method.node.info) + + if info.metaclass_type is not None: + fallback = info.metaclass_type + elif checker_state.type_checker: + # Prefer direct call when it is available. It is faster, and, + # unfortunately, some callers provide bogus callback. + fallback = checker_state.type_checker.named_type("builtins.type") + else: + fallback = named_type("builtins.type") + + if init_index < new_index: + method: FuncBase | Decorator = init_method.node + is_new = False + elif init_index > new_index: + method = new_method.node + is_new = True + else: + if init_method.node.info.fullname == "builtins.object": + # Both are defined by object. But if we've got a bogus + # base class, we can't know for sure, so check for that. + if info.fallback_to_any: + # Construct a universal callable as the prototype. + any_type = AnyType(TypeOfAny.special_form) + sig = CallableType( + arg_types=[any_type, any_type], + arg_kinds=[ARG_STAR, ARG_STAR2], + arg_names=["_args", "_kwds"], + ret_type=any_type, + is_bound=True, + fallback=named_type("builtins.function"), + ) + result: FunctionLike = class_callable(sig, info, fallback, None, is_new=False) + if allow_cache and state.strict_optional: + info.type_object_type = result + return result + + # Otherwise prefer __init__ in a tie. It isn't clear that this + # is the right thing, but __new__ caused problems with + # typeshed (#5647). + method = init_method.node + is_new = False + # Construct callable type based on signature of __init__. Adjust + # return type and insert type arguments. + if isinstance(method, FuncBase): + if isinstance(method, OverloadedFuncDef) and not method.type: + # Do not cache if the type is not ready. Same logic for decorators is + # achieved in early return above because is_valid_constructor() is False. + allow_cache = False + t = function_type(method, fallback) + else: + assert isinstance(method.type, ProperType) + assert isinstance(method.type, FunctionLike) # is_valid_constructor() ensures this + t = method.type + result = type_object_type_from_function(t, info, method.info, fallback, is_new) + # Only write cached result is strict_optional=True, otherwise we may get + # inconsistent behaviour because of union simplification. + if allow_cache and state.strict_optional: + info.type_object_type = result + return result + + +def is_valid_constructor(n: SymbolNode | None) -> bool: + """Does this node represents a valid constructor method? + + This includes normal functions, overloaded functions, and decorators + that return a callable type. + """ + if isinstance(n, SYMBOL_FUNCBASE_TYPES): + return True + if isinstance(n, Decorator): + return isinstance(get_proper_type(n.type), FunctionLike) + return False + + +def type_object_type_from_function( + signature: FunctionLike, info: TypeInfo, def_info: TypeInfo, fallback: Instance, is_new: bool +) -> FunctionLike: + # We first need to record all non-trivial (explicit) self types in __init__, + # since they will not be available after we bind them. Note, we use explicit + # self-types only in the defining class, similar to __new__ (but not exactly the same, + # see comment in class_callable below). This is mostly useful for annotating library + # classes such as subprocess.Popen. + if not is_new and not info.is_newtype: + orig_self_types = [get_self_type(it, def_info) for it in signature.items] + else: + orig_self_types = [None] * len(signature.items) + + # The __init__ method might come from a generic superclass 'def_info' + # with type variables that do not map identically to the type variables of + # the class 'info' being constructed. For example: + # + # class A(Generic[T]): + # def __init__(self, x: T) -> None: ... + # class B(A[List[T]]): + # ... + # + # We need to map B's __init__ to the type (List[T]) -> None. + signature = bind_self( + signature, + original_type=fill_typevars(info), + is_classmethod=is_new, + # Explicit instance self annotations have special handling in class_callable(), + # we don't need to bind any type variables in them if they are generic. + ignore_instances=True, + ) + signature = cast(FunctionLike, map_type_from_supertype(signature, info, def_info)) + + special_sig: str | None = None + if def_info.fullname == "builtins.dict": + # Special signature! + special_sig = "dict" + + if isinstance(signature, CallableType): + return class_callable(signature, info, fallback, special_sig, is_new, orig_self_types[0]) + else: + # Overloaded __init__/__new__. + assert isinstance(signature, Overloaded) + items: list[CallableType] = [] + for item, orig_self in zip(signature.items, orig_self_types): + items.append(class_callable(item, info, fallback, special_sig, is_new, orig_self)) + return Overloaded(items) + + +def class_callable( + init_type: CallableType, + info: TypeInfo, + type_type: Instance, + special_sig: str | None, + is_new: bool, + orig_self_type: Type | None = None, +) -> CallableType: + """Create a type object type based on the signature of __init__.""" + variables: list[TypeVarLikeType] = [] + variables.extend(info.defn.type_vars) + variables.extend(init_type.variables) + + from mypy.subtypes import is_subtype + + init_ret_type = get_proper_type(init_type.ret_type) + orig_self_type = get_proper_type(orig_self_type) + default_ret_type = fill_typevars(info) + explicit_type = init_ret_type if is_new else orig_self_type + if ( + isinstance(explicit_type, (Instance, TupleType, UninhabitedType, LiteralType)) + # We have to skip protocols, because it can be a subtype of a return type + # by accident. Like `Hashable` is a subtype of `object`. See #11799 + and isinstance(default_ret_type, Instance) + and not default_ret_type.type.is_protocol + # Only use the declared return type from __new__ or declared self in __init__ + # if it is actually returning a subtype of what we would return otherwise. + and is_subtype(explicit_type, default_ret_type, ignore_type_params=True) + ): + ret_type: Type = explicit_type + else: + ret_type = default_ret_type + + callable_type = init_type.copy_modified( + ret_type=ret_type, + fallback=type_type, + name=None, + variables=variables, + special_sig=special_sig, + ) + c = callable_type.with_name(info.name) + return c + + +def map_type_from_supertype(typ: Type, sub_info: TypeInfo, super_info: TypeInfo) -> Type: + """Map type variables in a type defined in a supertype context to be valid + in the subtype context. Assume that the result is unique; if more than + one type is possible, return one of the alternatives. + + For example, assume + + class D(Generic[S]): ... + class C(D[E[T]], Generic[T]): ... + + Now S in the context of D would be mapped to E[T] in the context of C. + """ + # Create the type of self in subtype, of form t[a1, ...]. + inst_type = fill_typevars(sub_info) + if isinstance(inst_type, TupleType): + inst_type = tuple_fallback(inst_type) + # Map the type of self to supertype. This gets us a description of the + # supertype type variables in terms of subtype variables, i.e. t[t1, ...] + # so that any type variables in tN are to be interpreted in subtype + # context. + inst_type = map_instance_to_supertype(inst_type, super_info) + # Finally expand the type variables in type with those in the previously + # constructed type. Note that both type and inst_type may have type + # variables, but in type they are interpreted in supertype context while + # in inst_type they are interpreted in subtype context. This works even if + # the names of type variables in supertype and subtype overlap. + return expand_type_by_instance(typ, inst_type) + + +def supported_self_type( + typ: ProperType, allow_callable: bool = True, allow_instances: bool = True +) -> bool: + """Is this a supported kind of explicit self-types? + + Currently, this means an X or Type[X], where X is an instance or + a type variable with an instance upper bound. + """ + if isinstance(typ, TypeType): + return supported_self_type(typ.item) + if allow_callable and isinstance(typ, CallableType): + # Special case: allow class callable instead of Type[...] as cls annotation, + # as well as callable self for callback protocols. + return True + return isinstance(typ, TypeVarType) or ( + allow_instances and isinstance(typ, Instance) and typ != fill_typevars(typ.type) + ) + + +F = TypeVar("F", bound=FunctionLike) + + +def bind_self( + method: F, + original_type: Type | None = None, + is_classmethod: bool = False, + ignore_instances: bool = False, +) -> F: + """Return a copy of `method`, with the type of its first parameter (usually + self or cls) bound to original_type. + + If the type of `self` is a generic type (T, or Type[T] for classmethods), + instantiate every occurrence of type with original_type in the rest of the + signature and in the return type. + + original_type is the type of E in the expression E.copy(). It is None in + compatibility checks. In this case we treat it as the erasure of the + declared type of self. + + This way we can express "the type of self". For example: + + T = TypeVar('T', bound='A') + class A: + def copy(self: T) -> T: ... + + class B(A): pass + + b = B().copy() # type: B + + """ + if isinstance(method, Overloaded): + items = [ + bind_self(c, original_type, is_classmethod, ignore_instances) for c in method.items + ] + return cast(F, Overloaded(items)) + assert isinstance(method, CallableType) + func: CallableType = method + if not func.arg_types: + # Invalid method, return something. + return method + if func.arg_kinds[0] in (ARG_STAR, ARG_STAR2): + # The signature is of the form 'def foo(*args, ...)'. + # In this case we shouldn't drop the first arg, + # since func will be absorbed by the *args. + # TODO: infer bounds on the type of *args? + + # In the case of **kwargs we should probably emit an error, but + # for now we simply skip it, to avoid crashes down the line. + return method + self_param_type = get_proper_type(func.arg_types[0]) + + variables: Sequence[TypeVarLikeType] + # Having a def __call__(self: Callable[...], ...) can cause infinite recursion. Although + # this special-casing looks not very principled, there is nothing meaningful we can infer + # from such definition, since it is inherently indefinitely recursive. + allow_callable = func.name is None or not func.name.startswith("__call__ of") + if func.variables and supported_self_type( + self_param_type, allow_callable=allow_callable, allow_instances=not ignore_instances + ): + from mypy.infer import infer_type_arguments + + if original_type is None: + # TODO: type check method override (see #7861). + original_type = erase_to_bound(self_param_type) + original_type = get_proper_type(original_type) + + # Find which of method type variables appear in the type of "self". + self_ids = {tv.id for tv in get_all_type_vars(self_param_type)} + self_vars = [tv for tv in func.variables if tv.id in self_ids] + + # Solve for these type arguments using the actual class or instance type. + typeargs = infer_type_arguments( + self_vars, self_param_type, original_type, is_supertype=True + ) + if ( + is_classmethod + and any(isinstance(get_proper_type(t), UninhabitedType) for t in typeargs) + and isinstance(original_type, (Instance, TypeVarType, TupleType)) + ): + # In case we call a classmethod through an instance x, fallback to type(x). + typeargs = infer_type_arguments( + self_vars, self_param_type, TypeType(original_type), is_supertype=True + ) + + # Update the method signature with the solutions found. + # Technically, some constraints might be unsolvable, make them Never. + to_apply = [t if t is not None else UninhabitedType() for t in typeargs] + func = expand_type(func, {tv.id: arg for tv, arg in zip(self_vars, to_apply)}) + variables = [v for v in func.variables if v not in self_vars] + else: + variables = func.variables + + res = func.copy_modified( + arg_types=func.arg_types[1:], + arg_kinds=func.arg_kinds[1:], + arg_names=func.arg_names[1:], + variables=variables, + is_bound=True, + ) + return cast(F, res) + + +def erase_to_bound(t: Type) -> Type: + # TODO: use value restrictions to produce a union? + t = get_proper_type(t) + if isinstance(t, TypeVarType): + return t.upper_bound + if isinstance(t, TypeType): + if isinstance(t.item, TypeVarType): + return TypeType.make_normalized(t.item.upper_bound, is_type_form=t.is_type_form) + return t + + +def callable_corresponding_argument( + typ: NormalizedCallableType | Parameters, model: FormalArgument +) -> FormalArgument | None: + """Return the argument of a function that corresponds to `model`""" + + by_name = typ.argument_by_name(model.name) + by_pos = typ.argument_by_position(model.pos) + if by_name is None and by_pos is None: + return None + if by_name is not None and by_pos is not None: + if by_name == by_pos: + return by_name + # If we're dealing with an optional pos-only and an optional + # name-only arg, merge them. This is the case for all functions + # taking both *args and **args, or a pair of functions like so: + + # def right(a: int = ...) -> None: ... + # def left(x: int = ..., /, *, a: int = ...) -> None: ... + from mypy.meet import meet_types + + if ( + not (by_name.required or by_pos.required) + and by_pos.name is None + and by_name.pos is None + # This is not principled, but prevents a crash. It's weird to have a FormalArgument + # that has an UnpackType. + and not isinstance(by_name.typ, UnpackType) + and not isinstance(by_pos.typ, UnpackType) + ): + return FormalArgument( + by_name.name, by_pos.pos, meet_types(by_name.typ, by_pos.typ), False + ) + return by_name + + return by_name if by_name is not None else by_pos + + +def simple_literal_type(t: ProperType | None) -> Instance | None: + """Extract the underlying fallback Instance type for a simple Literal""" + if isinstance(t, Instance) and t.last_known_value is not None: + t = t.last_known_value + if isinstance(t, LiteralType): + return t.fallback + return None + + +def is_simple_literal(t: ProperType) -> bool: + if isinstance(t, LiteralType): + return t.fallback.type.is_enum or t.fallback.type.fullname == "builtins.str" + if isinstance(t, Instance): + return t.last_known_value is not None and isinstance(t.last_known_value.value, str) + return False + + +def make_simplified_union( + items: Sequence[Type], + line: int = -1, + column: int = -1, + *, + keep_erased: bool = False, + contract_literals: bool = True, + handle_recursive: bool = True, +) -> ProperType: + """Build union type with redundant union items removed. + + If only a single item remains, this may return a non-union type. + + Examples: + + * [int, str] -> Union[int, str] + * [int, object] -> object + * [int, int] -> int + * [int, Any] -> Union[int, Any] (Any types are not simplified away!) + * [Any, Any] -> Any + * [int, Union[bytes, str]] -> Union[int, bytes, str] + + Note: This must NOT be used during semantic analysis, since TypeInfos may not + be fully initialized. + + The keep_erased flag is used for type inference against union types + containing type variables. If set to True, keep all ErasedType items. + + The contract_literals flag indicates whether we need to contract literal types + back into a sum type. Set it to False when called by try_expanding_sum_type_ + to_union(). + """ + # Step 1: expand all nested unions + items = flatten_nested_unions(items, handle_recursive=handle_recursive) + + # Step 2: fast path for single item + if len(items) == 1: + return get_proper_type(items[0]) + + # Step 3: remove redundant unions + simplified_set: Sequence[Type] = _remove_redundant_union_items(items, keep_erased) + + # Step 4: If more than one literal exists in the union, try to simplify + if ( + contract_literals + and sum(isinstance(get_proper_type(item), LiteralType) for item in simplified_set) > 1 + ): + simplified_set = try_contracting_literals_in_union(simplified_set) + + result = get_proper_type(UnionType.make_union(simplified_set, line, column)) + + nitems = len(items) + if nitems > 1 and ( + nitems > 2 or not (type(items[0]) is NoneType or type(items[1]) is NoneType) + ): + # Step 5: At last, we erase any (inconsistent) extra attributes on instances. + + # Initialize with None instead of an empty set as a micro-optimization. The set + # is needed very rarely, so we try to avoid constructing it. + extra_attrs_set: set[ExtraAttrs] | None = None + for item in items: + instance = try_getting_instance_fallback(item) + if instance and instance.extra_attrs: + if extra_attrs_set is None: + extra_attrs_set = {instance.extra_attrs} + else: + extra_attrs_set.add(instance.extra_attrs) + + # Code below is awkward, because we don't want the extra checks to affect + # performance in the common case. + erase_extra = False + if extra_attrs_set is not None: + fallback = try_getting_instance_fallback(result) + if fallback is None: + return result + if len(extra_attrs_set) > 1: # This case is too tricky to handle. + erase_extra = True + else: + # Check that all relevant items have the extra attributes. + for item in items: + instance = try_getting_instance_fallback(item) + if instance and instance.type == fallback.type and not instance.extra_attrs: + erase_extra = True + break + if erase_extra: + fallback.extra_attrs = None + + return result + + +def _remove_redundant_union_items(items: list[Type], keep_erased: bool) -> list[Type]: + from mypy.subtypes import is_proper_subtype + + # The first pass through this loop, we check if later items are subtypes of earlier items. + # The second pass through this loop, we check if earlier items are subtypes of later items + # (by reversing the remaining items) + for _direction in range(2): + new_items: list[Type] = [] + # seen is a map from a type to its index in new_items + seen: dict[ProperType, int] = {} + unduplicated_literal_fallbacks: set[Instance] | None = None + for ti in items: + proper_ti = get_proper_type(ti) + + # UninhabitedType is always redundant + if isinstance(proper_ti, UninhabitedType): + continue + + duplicate_index = -1 + # Quickly check if we've seen this type + if proper_ti in seen: + duplicate_index = seen[proper_ti] + elif ( + isinstance(proper_ti, LiteralType) + and unduplicated_literal_fallbacks is not None + and proper_ti.fallback in unduplicated_literal_fallbacks + ): + # This is an optimisation for unions with many LiteralType + # We've already checked for exact duplicates. This means that any super type of + # the LiteralType must be a super type of its fallback. If we've gone through + # the expensive loop below and found no super type for a previous LiteralType + # with the same fallback, we can skip doing that work again and just add the type + # to new_items + pass + else: + # If not, check if we've seen a supertype of this type + for j, tj in enumerate(new_items): + proper_tj = get_proper_type(tj) + # If tj is an Instance with a last_known_value, do not remove proper_ti + # (unless it's an instance with the same last_known_value) + if ( + isinstance(proper_tj, Instance) + and proper_tj.last_known_value is not None + and not ( + isinstance(proper_ti, Instance) + and proper_tj.last_known_value == proper_ti.last_known_value + ) + ): + continue + + if is_proper_subtype( + ti, tj, keep_erased_types=keep_erased, ignore_promotions=True + ): + duplicate_index = j + break + if duplicate_index != -1: + # If deleted subtypes had more general truthiness, use that + orig_item = new_items[duplicate_index] + if not orig_item.can_be_true and ti.can_be_true: + new_items[duplicate_index] = true_or_false(orig_item) + elif not orig_item.can_be_false and ti.can_be_false: + new_items[duplicate_index] = true_or_false(orig_item) + else: + # We have a non-duplicate item, add it to new_items + seen[proper_ti] = len(new_items) + new_items.append(ti) + if isinstance(proper_ti, LiteralType): + if unduplicated_literal_fallbacks is None: + unduplicated_literal_fallbacks = set() + unduplicated_literal_fallbacks.add(proper_ti.fallback) + + items = new_items + if len(items) <= 1: + break + items.reverse() + + return items + + +def _get_type_method_ret_type(t: ProperType, *, name: str) -> Type | None: + # For Enum literals the ret_type can change based on the Enum + # we need to check the type of the enum rather than the literal + if isinstance(t, LiteralType) and t.is_enum_literal(): + t = t.fallback + + if isinstance(t, Instance): + sym = t.type.get(name) + if sym: + sym_type = get_proper_type(sym.type) + if isinstance(sym_type, CallableType): + return sym_type.ret_type + + return None + + +def true_only(t: Type) -> ProperType: + """ + Restricted version of t with only True-ish values + """ + t = get_proper_type(t) + + if not t.can_be_true: + # All values of t are False-ish, so there are no true values in it + return UninhabitedType(line=t.line, column=t.column) + elif not t.can_be_false: + # All values of t are already True-ish, so true_only is idempotent in this case + return t + elif isinstance(t, UnionType): + # The true version of a union type is the union of the true versions of its components + new_items = [true_only(item) for item in t.items] + can_be_true_items = [item for item in new_items if item.can_be_true] + return make_simplified_union(can_be_true_items, line=t.line, column=t.column) + else: + ret_type = _get_type_method_ret_type(t, name="__bool__") or _get_type_method_ret_type( + t, name="__len__" + ) + + if ret_type and not ret_type.can_be_true: + return UninhabitedType(line=t.line, column=t.column) + + new_t = copy_type(t) + new_t.can_be_false = False + return new_t + + +def false_only(t: Type) -> ProperType: + """ + Restricted version of t with only False-ish values + """ + t = get_proper_type(t) + + if not t.can_be_false: + if state.strict_optional: + # All values of t are True-ish, so there are no false values in it + return UninhabitedType(line=t.line) + else: + # When strict optional checking is disabled, everything can be + # False-ish since anything can be None + return NoneType(line=t.line) + elif not t.can_be_true: + # All values of t are already False-ish, so false_only is idempotent in this case + return t + elif isinstance(t, UnionType): + # The false version of a union type is the union of the false versions of its components + new_items = [false_only(item) for item in t.items] + can_be_false_items = [item for item in new_items if item.can_be_false] + return make_simplified_union(can_be_false_items, line=t.line, column=t.column) + elif isinstance(t, Instance) and t.type.fullname in ("builtins.str", "builtins.bytes"): + return LiteralType("", fallback=t) + elif isinstance(t, Instance) and t.type.fullname == "builtins.int": + return LiteralType(0, fallback=t) + else: + ret_type = _get_type_method_ret_type(t, name="__bool__") or _get_type_method_ret_type( + t, name="__len__" + ) + + if ret_type: + if not ret_type.can_be_false: + return UninhabitedType(line=t.line) + elif isinstance(t, Instance): + if (t.type.is_final or t.type.is_enum) and state.strict_optional: + return UninhabitedType(line=t.line) + elif isinstance(t, LiteralType) and t.is_enum_literal() and state.strict_optional: + return UninhabitedType(line=t.line) + + new_t = copy_type(t) + new_t.can_be_true = False + return new_t + + +def true_or_false(t: Type) -> ProperType: + """ + Unrestricted version of t with both True-ish and False-ish values + """ + t = get_proper_type(t) + + if isinstance(t, UnionType): + new_items = [true_or_false(item) for item in t.items] + return make_simplified_union(new_items, line=t.line, column=t.column) + + new_t = copy_type(t) + new_t.can_be_true = new_t.can_be_true_default() + new_t.can_be_false = new_t.can_be_false_default() + return new_t + + +def erase_def_to_union_or_bound(tdef: TypeVarLikeType) -> Type: + # TODO(PEP612): fix for ParamSpecType + if isinstance(tdef, ParamSpecType): + return AnyType(TypeOfAny.from_error) + if isinstance(tdef, TypeVarType) and tdef.values: + return make_simplified_union(tdef.values) + else: + return tdef.upper_bound + + +def erase_to_union_or_bound(typ: TypeVarType) -> ProperType: + if typ.values: + return make_simplified_union(typ.values) + else: + return get_proper_type(typ.upper_bound) + + +def function_type(func: FuncBase, fallback: Instance) -> FunctionLike: + if func.type: + assert isinstance(func.type, FunctionLike) + return func.type + else: + # Implicit type signature with dynamic types. + if isinstance(func, FuncItem): + return callable_type(func, fallback) + else: + # Either a broken overload, or decorated overload type is not ready. + # TODO: make sure the caller defers if possible. + assert isinstance(func, OverloadedFuncDef) + any_type = AnyType(TypeOfAny.from_error) + dummy = CallableType( + [any_type, any_type], + [ARG_STAR, ARG_STAR2], + [None, None], + any_type, + fallback, + line=func.line, + is_ellipsis_args=True, + ) + # Return an Overloaded, because some callers may expect that + # an OverloadedFuncDef has an Overloaded type. + return Overloaded([dummy]) + + +def callable_type( + fdef: FuncItem, fallback: Instance, ret_type: Type | None = None +) -> CallableType: + # TODO: somewhat unfortunate duplication with prepare_method_signature in semanal + if fdef.info and fdef.has_self_or_cls_argument and fdef.arg_names: + self_type: Type = fill_typevars(fdef.info) + if fdef.is_class or fdef.name == "__new__": + self_type = TypeType.make_normalized(self_type) + args = [self_type] + [AnyType(TypeOfAny.unannotated)] * (len(fdef.arg_names) - 1) + else: + args = [AnyType(TypeOfAny.unannotated)] * len(fdef.arg_names) + + return CallableType( + args, + fdef.arg_kinds, + fdef.arg_names, + ret_type or AnyType(TypeOfAny.unannotated), + fallback, + name=fdef.name, + line=fdef.line, + column=fdef.column, + implicit=True, + # We need this for better error messages, like missing `self` note: + definition=fdef if isinstance(fdef, FuncDef) else None, + ) + + +def try_getting_str_literals(expr: Expression, typ: Type) -> list[str] | None: + """If the given expression or type corresponds to a string literal + or a union of string literals, returns a list of the underlying strings. + Otherwise, returns None. + + Specifically, this function is guaranteed to return a list with + one or more strings if one of the following is true: + + 1. 'expr' is a StrExpr + 2. 'typ' is a LiteralType containing a string + 3. 'typ' is a UnionType containing only LiteralType of strings + """ + if isinstance(expr, StrExpr): + return [expr.value] + + # TODO: See if we can eliminate this function and call the below one directly + return try_getting_str_literals_from_type(typ) + + +def try_getting_str_literals_from_type(typ: Type) -> list[str] | None: + """If the given expression or type corresponds to a string Literal + or a union of string Literals, returns a list of the underlying strings. + Otherwise, returns None. + + For example, if we had the type 'Literal["foo", "bar"]' as input, this function + would return a list of strings ["foo", "bar"]. + """ + return try_getting_literals_from_type(typ, str, "builtins.str") + + +def try_getting_int_literals_from_type(typ: Type) -> list[int] | None: + """If the given expression or type corresponds to an int Literal + or a union of int Literals, returns a list of the underlying ints. + Otherwise, returns None. + + For example, if we had the type 'Literal[1, 2, 3]' as input, this function + would return a list of ints [1, 2, 3]. + """ + return try_getting_literals_from_type(typ, int, "builtins.int") + + +T = TypeVar("T") + + +def try_getting_literals_from_type( + typ: Type, target_literal_type: type[T], target_fullname: str +) -> list[T] | None: + """If the given expression or type corresponds to a Literal or + union of Literals where the underlying values correspond to the given + target type, returns a list of those underlying values. Otherwise, + returns None. + """ + typ = get_proper_type(typ) + + if isinstance(typ, Instance) and typ.last_known_value is not None: + possible_literals: list[Type] = [typ.last_known_value] + elif isinstance(typ, UnionType): + possible_literals = list(typ.items) + else: + possible_literals = [typ] + + literals: list[T] = [] + for lit in get_proper_types(possible_literals): + if isinstance(lit, LiteralType) and lit.fallback.type.fullname == target_fullname: + val = lit.value + if isinstance(val, target_literal_type): + literals.append(val) + else: + return None + else: + return None + return literals + + +def is_literal_type_like(t: Type | None) -> bool: + """Returns 'true' if the given type context is potentially either a LiteralType, + a Union of LiteralType, or something similar. + """ + t = get_proper_type(t) + if t is None: + return False + elif isinstance(t, LiteralType): + return True + elif isinstance(t, UnionType): + return any(is_literal_type_like(item) for item in t.items) + elif isinstance(t, TypeVarType): + return is_literal_type_like(t.upper_bound) or any( + is_literal_type_like(item) for item in t.values + ) + else: + return False + + +def is_singleton_identity_type(typ: ProperType) -> bool: + """ + Returns True if every value of this type is identical to every other value of this type, + as judged by the `is` operator. + + Note that this is not true of certain LiteralType, such as Literal[100001] or Literal["string"] + """ + if isinstance(typ, NoneType): + return True + if isinstance(typ, Instance): + return ( + (typ.type.is_enum and len(typ.type.enum_members) == 1) + or (typ.type.fullname in ELLIPSIS_TYPE_NAMES) + or (typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES) + ) + if isinstance(typ, LiteralType): + return typ.is_enum_literal() or isinstance(typ.value, bool) + if isinstance(typ, TypeType) and isinstance(typ.item, Instance) and typ.item.type.is_final: + return True + if isinstance(typ, FunctionLike) and typ.is_type_obj() and typ.type_object().is_final: + return True + return False + + +def is_singleton_equality_type(typ: ProperType) -> bool: + """ + Returns True if every value of this type compares equal to every other value of this type, + as judged by the `==` operator. + """ + return isinstance(typ, LiteralType) or is_singleton_identity_type(typ) + + +def try_expanding_sum_type_to_union(typ: Type, target_fullname: str | None) -> Type: + """Attempts to recursively expand any enum Instances with the given target_fullname + into a Union of all of its component LiteralTypes. + + For example, if we have: + + class Color(Enum): + RED = 1 + BLUE = 2 + YELLOW = 3 + + class Status(Enum): + SUCCESS = 1 + FAILURE = 2 + UNKNOWN = 3 + + ...and if we call `try_expanding_sum_type_to_union(Union[Color, Status], 'module.Color')`, + this function will return Literal[Color.RED, Color.BLUE, Color.YELLOW, Status]. + """ + typ = get_proper_type(typ) + + if isinstance(typ, UnionType): + # Non-empty enums cannot subclass each other so simply removing duplicates is enough. + items = [ + try_expanding_sum_type_to_union(item, target_fullname) + for item in remove_dups(flatten_nested_unions(typ.relevant_items())) + ] + return UnionType.make_union(items) + + if isinstance(typ, Instance) and ( + target_fullname is None or typ.type.fullname == target_fullname + ): + if typ.type.fullname == "builtins.bool": + return UnionType([LiteralType(True, typ), LiteralType(False, typ)]) + + if typ.type.is_enum: + items = [LiteralType(name, typ) for name in typ.type.enum_members] + if not items: + return typ + return UnionType.make_union(items) + + return typ + + +def try_contracting_literals_in_union(types: Sequence[Type]) -> list[ProperType]: + """Contracts any literal types back into a sum type if possible. + + Requires a flattened union and does not descend into children. + + Will replace the first instance of the literal with the sum type and + remove all others. + + If we call `try_contracting_union(Literal[Color.RED, Color.BLUE, Color.YELLOW])`, + this function will return Color. + + We also treat `Literal[True, False]` as `bool`. + """ + proper_types = [get_proper_type(typ) for typ in types] + sum_types: dict[str, tuple[set[Any], list[int]]] = {} + marked_for_deletion = set() + for idx, typ in enumerate(proper_types): + if isinstance(typ, LiteralType): + fullname = typ.fallback.type.fullname + if typ.fallback.type.is_enum or isinstance(typ.value, bool): + if fullname not in sum_types: + sum_types[fullname] = ( + ( + set(typ.fallback.type.enum_members) + if typ.fallback.type.is_enum + else {True, False} + ), + [], + ) + literals, indexes = sum_types[fullname] + literals.discard(typ.value) + indexes.append(idx) + if not literals: + first, *rest = indexes + proper_types[first] = typ.fallback + marked_for_deletion |= set(rest) + return list( + itertools.compress( + proper_types, [(i not in marked_for_deletion) for i in range(len(proper_types))] + ) + ) + + +def coerce_to_literal(typ: Type) -> Type: + """Recursively converts any Instances that have a last_known_value or are + instances of enum types with a single value into the corresponding LiteralType. + """ + original_type = typ + typ = get_proper_type(typ) + if isinstance(typ, UnionType): + new_items = [coerce_to_literal(item) for item in typ.items] + return UnionType.make_union(new_items) + elif isinstance(typ, Instance): + if typ.last_known_value: + return typ.last_known_value + elif typ.type.is_enum: + enum_values = typ.type.enum_members + if len(enum_values) == 1: + return LiteralType(value=enum_values[0], fallback=typ) + return original_type + + +def get_type_vars(tp: Type) -> list[TypeVarType]: + return cast("list[TypeVarType]", tp.accept(TypeVarExtractor())) + + +def get_all_type_vars(tp: Type) -> list[TypeVarLikeType]: + # TODO: should we always use this function instead of get_type_vars() above? + return tp.accept(TypeVarExtractor(include_all=True)) + + +class TypeVarExtractor(TypeQuery[list[TypeVarLikeType]]): + def __init__(self, include_all: bool = False) -> None: + super().__init__() + self.include_all = include_all + + def strategy(self, items: Iterable[list[TypeVarLikeType]]) -> list[TypeVarLikeType]: + out = [] + for item in items: + out.extend(item) + return out + + def visit_type_var(self, t: TypeVarType) -> list[TypeVarLikeType]: + return [t] + + def visit_param_spec(self, t: ParamSpecType) -> list[TypeVarLikeType]: + return [t] if self.include_all else [] + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> list[TypeVarLikeType]: + return [t] if self.include_all else [] + + +def freeze_all_type_vars(member_type: Type) -> None: + member_type.accept(FreezeTypeVarsVisitor()) + + +class FreezeTypeVarsVisitor(TypeTraverserVisitor): + def visit_callable_type(self, t: CallableType) -> None: + for v in t.variables: + v.id.meta_level = 0 + super().visit_callable_type(t) + + +def custom_special_method(typ: Type, name: str, check_all: bool = False) -> bool: + """Does this type have a custom special method such as __format__() or __eq__()? + + If check_all is True ensure all items of a union have a custom method, not just some. + """ + typ = get_proper_type(typ) + if isinstance(typ, Instance): + method = typ.type.get(name) + if method and isinstance(method.node, (SYMBOL_FUNCBASE_TYPES, Decorator, Var)): + if method.node.info: + return not method.node.info.fullname.startswith(("builtins.", "typing.")) + return False + if isinstance(typ, UnionType): + if check_all: + return all(custom_special_method(t, name, check_all) for t in typ.items) + return any(custom_special_method(t, name) for t in typ.items) + if isinstance(typ, TupleType): + return custom_special_method(tuple_fallback(typ), name, check_all) + if isinstance(typ, FunctionLike) and typ.is_type_obj(): + # Look up __method__ on the metaclass for class objects. + return custom_special_method(typ.fallback, name, check_all) + if isinstance(typ, TypeType) and isinstance(typ.item, Instance): + if typ.item.type.metaclass_type: + # Look up __method__ on the metaclass for class objects. + return custom_special_method(typ.item.type.metaclass_type, name, check_all) + if isinstance(typ, AnyType): + # Avoid false positives in uncertain cases. + return True + # TODO: support other types (see ExpressionChecker.has_member())? + return False + + +def separate_union_literals(t: UnionType) -> tuple[Sequence[LiteralType], Sequence[Type]]: + """Separate literals from other members in a union type.""" + literal_items = [] + union_items = [] + + for item in t.items: + proper = get_proper_type(item) + if isinstance(proper, LiteralType): + literal_items.append(proper) + else: + union_items.append(item) + + return literal_items, union_items + + +def try_getting_instance_fallback(typ: Type) -> Instance | None: + """Returns the Instance fallback for this type if one exists or None.""" + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return typ + elif isinstance(typ, LiteralType): + return typ.fallback + elif isinstance(typ, (NoneType, AnyType)): + return None # Fast path for None, which is common + elif isinstance(typ, FunctionLike): + return typ.fallback + elif isinstance(typ, TypeVarType): + return try_getting_instance_fallback(typ.upper_bound) + elif isinstance(typ, TupleType): + return typ.partial_fallback + elif isinstance(typ, TypedDictType): + return typ.fallback + return None + + +def fixup_partial_type(typ: Type) -> Type: + """Convert a partial type that we couldn't resolve into something concrete. + + This means, for None we make it Optional[Any], and for anything else we + fill in all of the type arguments with Any. + """ + if not isinstance(typ, PartialType): + return typ + if typ.type is None: + return UnionType.make_union([AnyType(TypeOfAny.unannotated), NoneType()]) + else: + return Instance(typ.type, [AnyType(TypeOfAny.unannotated)] * len(typ.type.type_vars)) + + +def get_protocol_member( + left: Instance, member: str, class_obj: bool, is_lvalue: bool = False +) -> Type | None: + if member == "__call__" and class_obj: + # Special case: class objects always have __call__ that is just the constructor. + + # TODO: this is wrong, it creates callables that are not recognized as type objects. + # Long-term, we should probably get rid of this callback argument altogether. + def named_type(fullname: str) -> Instance: + return Instance(left.type.mro[-1], []) + + return type_object_type(left.type, named_type) + + if member == "__call__" and left.type.is_metaclass(precise=True): + # Special case: we want to avoid falling back to metaclass __call__ + # if constructor signature didn't match, this can cause many false negatives. + return None + + from mypy.subtypes import find_member + + subtype = find_member(member, left, left, class_obj=class_obj, is_lvalue=is_lvalue) + if isinstance(subtype, PartialType): + subtype = ( + NoneType() + if subtype.type is None + else Instance( + subtype.type, [AnyType(TypeOfAny.unannotated)] * len(subtype.type.type_vars) + ) + ) + return subtype + + +def _is_disjoint_base(info: TypeInfo) -> bool: + # It either has the @disjoint_base decorator or defines nonempty __slots__. + if info.is_disjoint_base: + return True + if not info.slots: + return False + own_slots = { + slot + for slot in info.slots + if not any( + base_info.type.slots is not None and slot in base_info.type.slots + for base_info in info.bases + ) + } + return bool(own_slots) + + +def _get_disjoint_base_of(instance: Instance) -> TypeInfo | None: + """Returns the disjoint base of the given instance, if it exists.""" + if _is_disjoint_base(instance.type): + return instance.type + for base in instance.type.mro: + if _is_disjoint_base(base): + return base + return None + + +def can_have_shared_disjoint_base(instances: list[Instance]) -> bool: + """Returns whether the given instances can share a disjoint base. + + This means that a child class of these classes can exist at runtime. + """ + # Ignore None disjoint bases (which are `object`). + disjoint_bases = [ + base for instance in instances if (base := _get_disjoint_base_of(instance)) is not None + ] + if not disjoint_bases: + # All are `object`. + return True + + candidate = disjoint_bases[0] + for base in disjoint_bases[1:]: + if candidate.has_base(base.fullname): + continue + elif base.has_base(candidate.fullname): + candidate = base + else: + return False + return True diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..df9441387f88343653062427a235eb2c2e89d032 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ed728f4c9b8d003743dde0b1880232c28b2b8b --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types.py @@ -0,0 +1,4452 @@ +"""Classes for representing mypy types.""" + +from __future__ import annotations + +import sys +from abc import abstractmethod +from collections.abc import Iterable, Sequence +from typing import ( + Any, + ClassVar, + Final, + NewType, + TypeAlias as _TypeAlias, + TypeGuard, + TypeVar, + cast, + overload, +) +from typing_extensions import Self + +from librt.internal import ( + read_int as read_int_bare, + read_str as read_str_bare, + write_int as write_int_bare, + write_str as write_str_bare, +) + +import mypy.nodes +from mypy.bogus_type import Bogus +from mypy.cache import ( + DICT_STR_GEN, + END_TAG, + EXTRA_ATTRS, + LIST_GEN, + LITERAL_NONE, + ReadBuffer, + Tag, + WriteBuffer, + read_bool, + read_int, + read_int_list, + read_literal, + read_str, + read_str_list, + read_str_opt, + read_str_opt_list, + read_tag, + write_bool, + write_int, + write_int_list, + write_literal, + write_str, + write_str_list, + write_str_opt, + write_str_opt_list, + write_tag, +) +from mypy.nodes import ARG_KINDS, ARG_POS, ARG_STAR, ARG_STAR2, INVARIANT, ArgKind, SymbolNode +from mypy.options import Options +from mypy.state import state +from mypy.util import IdMapper + +T = TypeVar("T") + +JsonDict: _TypeAlias = dict[str, Any] + +# The set of all valid expressions that can currently be contained +# inside of a Literal[...]. +# +# Literals can contain bytes and enum-values: we special-case both of these +# and store the value as a string. We rely on the fallback type that's also +# stored with the Literal to determine how a string is being used. +# +# TODO: confirm that we're happy with representing enums (and the +# other types) in the manner described above. +# +# Note: if we change the set of types included below, we must also +# make sure to audit the following methods: +# +# 1. types.LiteralType's serialize and deserialize methods: this method +# needs to make sure it can convert the below types into JSON and back. +# +# 2. types.LiteralType's 'value_repr` method: this method is ultimately used +# by TypeStrVisitor's visit_literal_type to generate a reasonable +# repr-able output. +# +# 3. server.astdiff.SnapshotTypeVisitor's visit_literal_type_method: this +# method assumes that the following types supports equality checks and +# hashability. +# +# Note: Although "Literal[None]" is a valid type, we internally always convert +# such a type directly into "None". So, "None" is not a valid parameter of +# LiteralType and is omitted from this list. +# +# Note: Float values are only used internally. They are not accepted within +# Literal[...]. +LiteralValue: _TypeAlias = int | str | bool | float + + +TUPLE_NAMES: Final = ("builtins.tuple", "typing.Tuple") +TYPE_NAMES: Final = ("builtins.type", "typing.Type") + +TYPE_VAR_LIKE_NAMES: Final = ( + "typing.TypeVar", + "typing_extensions.TypeVar", + "typing.ParamSpec", + "typing_extensions.ParamSpec", + "typing.TypeVarTuple", + "typing_extensions.TypeVarTuple", +) + +TYPED_NAMEDTUPLE_NAMES: Final = ("typing.NamedTuple", "typing_extensions.NamedTuple") + +# Supported names of TypedDict type constructors. +TPDICT_NAMES: Final = ( + "typing.TypedDict", + "typing_extensions.TypedDict", + "mypy_extensions.TypedDict", +) + +# Supported fallback instance type names for TypedDict types. +TPDICT_FB_NAMES: Final = ( + "typing._TypedDict", + "typing_extensions._TypedDict", + "mypy_extensions._TypedDict", +) + +# Supported names of Protocol base class. +PROTOCOL_NAMES: Final = ("typing.Protocol", "typing_extensions.Protocol") + +# Supported TypeAlias names. +TYPE_ALIAS_NAMES: Final = ("typing.TypeAlias", "typing_extensions.TypeAlias") + +# Supported Final type names. +FINAL_TYPE_NAMES: Final = ("typing.Final", "typing_extensions.Final") + +# Supported @final decorator names. +FINAL_DECORATOR_NAMES: Final = ("typing.final", "typing_extensions.final") + +# Supported @type_check_only names. +TYPE_CHECK_ONLY_NAMES: Final = ("typing.type_check_only", "typing_extensions.type_check_only") + +# Supported Literal type names. +LITERAL_TYPE_NAMES: Final = ("typing.Literal", "typing_extensions.Literal") + +# Supported Annotated type names. +ANNOTATED_TYPE_NAMES: Final = ("typing.Annotated", "typing_extensions.Annotated") + +# Supported Concatenate type names. +CONCATENATE_TYPE_NAMES: Final = ("typing.Concatenate", "typing_extensions.Concatenate") + +# Supported Unpack type names. +UNPACK_TYPE_NAMES: Final = ("typing.Unpack", "typing_extensions.Unpack") + +# Supported @deprecated decorator names +DEPRECATED_TYPE_NAMES: Final = ("warnings.deprecated", "typing_extensions.deprecated") + +# Supported @disjoint_base decorator names +DISJOINT_BASE_DECORATOR_NAMES: Final = ("typing.disjoint_base", "typing_extensions.disjoint_base") + +# We use this constant in various places when checking `tuple` subtyping: +TUPLE_LIKE_INSTANCE_NAMES: Final = ( + "builtins.tuple", + "typing.Iterable", + "typing.Container", + "typing.Sequence", + "typing.Reversible", +) + +IMPORTED_REVEAL_TYPE_NAMES: Final = ("typing.reveal_type", "typing_extensions.reveal_type") +REVEAL_TYPE_NAMES: Final = ("builtins.reveal_type", *IMPORTED_REVEAL_TYPE_NAMES) + +ASSERT_TYPE_NAMES: Final = ("typing.assert_type", "typing_extensions.assert_type") + +OVERLOAD_NAMES: Final = ("typing.overload", "typing_extensions.overload") + +NEVER_NAMES: Final = ( + "typing.NoReturn", + "typing_extensions.NoReturn", + "mypy_extensions.NoReturn", + "typing.Never", + "typing_extensions.Never", +) + +# Mypyc fixed-width native int types (compatible with builtins.int) +MYPYC_NATIVE_INT_NAMES: Final = ( + "mypy_extensions.i64", + "mypy_extensions.i32", + "mypy_extensions.i16", + "mypy_extensions.u8", +) + +DATACLASS_TRANSFORM_NAMES: Final = ( + "typing.dataclass_transform", + "typing_extensions.dataclass_transform", +) +# Supported @override decorator names. +OVERRIDE_DECORATOR_NAMES: Final = ("typing.override", "typing_extensions.override") + +ELLIPSIS_TYPE_NAMES: Final = ("builtins.ellipsis", "types.EllipsisType") + +NOT_IMPLEMENTED_TYPE_NAMES: Final = ("builtins._NotImplementedType", "types.NotImplementedType") + +# A placeholder used for Bogus[...] parameters +_dummy: Final[Any] = object() + +# A placeholder for int parameters +_dummy_int: Final = -999999 + + +class TypeOfAny: + """ + This class describes different types of Any. Each 'Any' can be of only one type at a time. + """ + + __slots__ = () + + # Was this Any type inferred without a type annotation? + unannotated: Final = 1 + # Does this Any come from an explicit type annotation? + explicit: Final = 2 + # Does this come from an unfollowed import? See --disallow-any-unimported option + from_unimported_type: Final = 3 + # Does this Any type come from omitted generics? + from_omitted_generics: Final = 4 + # Does this Any come from an error? + from_error: Final = 5 + # Is this a type that can't be represented in mypy's type system? For instance, type of + # call to NewType(...). Even though these types aren't real Anys, we treat them as such. + # Also used for variables named '_'. + special_form: Final = 6 + # Does this Any come from interaction with another Any? + from_another_any: Final = 7 + # Does this Any come from an implementation limitation/bug? + implementation_artifact: Final = 8 + # Does this Any come from use in the suggestion engine? This is + # used to ignore Anys inserted by the suggestion engine when + # generating constraints. + suggestion_engine: Final = 9 + + +def deserialize_type(data: JsonDict | str) -> Type: + if isinstance(data, str): + return Instance.deserialize(data) + classname = data[".class"] + method = deserialize_map.get(classname) + if method is not None: + return method(data) + raise NotImplementedError(f"unexpected .class {classname}") + + +class Type(mypy.nodes.Context): + """Abstract base class for all types.""" + + __slots__ = ("_can_be_true", "_can_be_false") + # 'can_be_true' and 'can_be_false' mean whether the value of the + # expression can be true or false in a boolean context. They are useful + # when inferring the type of logic expressions like `x and y`. + # + # For example: + # * the literal `False` can't be true while `True` can. + # * a value with type `bool` can be true or false. + # * `None` can't be true + # * ... + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + # Value of these can be -1 (use the default, lazy init), 0 (false) or 1 (true) + self._can_be_true = -1 + self._can_be_false = -1 + + @property + def can_be_true(self) -> bool: + if self._can_be_true == -1: # Lazy init helps mypyc + self._can_be_true = self.can_be_true_default() + return bool(self._can_be_true) + + @can_be_true.setter + def can_be_true(self, v: bool) -> None: + self._can_be_true = v + + @property + def can_be_false(self) -> bool: + if self._can_be_false == -1: # Lazy init helps mypyc + self._can_be_false = self.can_be_false_default() + return bool(self._can_be_false) + + @can_be_false.setter + def can_be_false(self, v: bool) -> None: + self._can_be_false = v + + def can_be_true_default(self) -> bool: + return True + + def can_be_false_default(self) -> bool: + return True + + def accept(self, visitor: TypeVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + def __repr__(self) -> str: + return self.accept(TypeStrVisitor(options=Options())) + + def str_with_options(self, options: Options) -> str: + return self.accept(TypeStrVisitor(options=options)) + + def serialize(self) -> JsonDict | str: + raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance") + + @classmethod + def deserialize(cls, data: JsonDict) -> Type: + raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance") + + def write(self, data: WriteBuffer) -> None: + raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance") + + @classmethod + def read(cls, data: ReadBuffer) -> Type: + raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance") + + +class TypeAliasType(Type): + """A type alias to another type. + + To support recursive type aliases we don't immediately expand a type alias + during semantic analysis, but create an instance of this type that records the target alias + definition node (mypy.nodes.TypeAlias) and type arguments (for generic aliases). + + This is very similar to how TypeInfo vs Instance interact, where a recursive class-based + structure like + class Node: + value: int + children: List[Node] + can be represented in a tree-like manner. + """ + + __slots__ = ("alias", "args", "type_ref") + + def __init__( + self, + alias: mypy.nodes.TypeAlias | None, + args: list[Type], + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.alias = alias + self.args = args + self.type_ref: str | None = None + + def _expand_once(self) -> Type: + """Expand to the target type exactly once. + + This doesn't do full expansion, i.e. the result can contain another + (or even this same) type alias. Use this internal helper only when really needed, + its public wrapper mypy.types.get_proper_type() is preferred. + """ + assert self.alias is not None + if self.alias.no_args: + # We know that no_args=True aliases like L = List must have an instance + # as their target. + assert isinstance(self.alias.target, Instance) # type: ignore[misc] + return self.alias.target.copy_modified(args=self.args) + + # TODO: this logic duplicates the one in expand_type_by_instance(). + if self.alias.tvar_tuple_index is None: + mapping: dict[TypeVarId, Type] = { + v.id: s for (v, s) in zip(self.alias.alias_tvars, self.args) + } + else: + prefix = self.alias.tvar_tuple_index + suffix = len(self.alias.alias_tvars) - self.alias.tvar_tuple_index - 1 + start, middle, end = split_with_prefix_and_suffix(tuple(self.args), prefix, suffix) + tvar = self.alias.alias_tvars[prefix] + assert isinstance(tvar, TypeVarTupleType) + mapping = {tvar.id: TupleType(list(middle), tvar.tuple_fallback)} + for tvar, sub in zip( + self.alias.alias_tvars[:prefix] + self.alias.alias_tvars[prefix + 1 :], start + end + ): + mapping[tvar.id] = sub + + return self.alias.target.accept(InstantiateAliasVisitor(mapping)) + + @property + def is_recursive(self) -> bool: + """Whether this type alias is recursive. + + Note this doesn't check generic alias arguments, but only if this alias + *definition* is recursive. The property value thus can be cached on the + underlying TypeAlias node. If you want to include all nested types, use + has_recursive_types() function. + """ + assert self.alias is not None, "Unfixed type alias" + is_recursive = self.alias._is_recursive + if is_recursive is None: + is_recursive = self.alias in self.alias.target.accept(CollectAliasesVisitor()) + # We cache the value on the underlying TypeAlias node as an optimization, + # since the value is the same for all instances of the same alias. + self.alias._is_recursive = is_recursive + return is_recursive + + def can_be_true_default(self) -> bool: + if self.alias is not None: + return self.alias.target.can_be_true + return super().can_be_true_default() + + def can_be_false_default(self) -> bool: + if self.alias is not None: + return self.alias.target.can_be_false + return super().can_be_false_default() + + def copy_modified(self, *, args: list[Type] | None = None) -> TypeAliasType: + return TypeAliasType( + self.alias, args if args is not None else self.args.copy(), self.line, self.column + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_alias_type(self) + + def __hash__(self) -> int: + return hash((self.alias, tuple(self.args))) + + def __eq__(self, other: object) -> bool: + # Note: never use this to determine subtype relationships, use is_subtype(). + if not isinstance(other, TypeAliasType): + return NotImplemented + return self.alias == other.alias and self.args == other.args + + def serialize(self) -> JsonDict: + assert self.alias is not None + data: JsonDict = { + ".class": "TypeAliasType", + "type_ref": self.alias.fullname, + "args": [arg.serialize() for arg in self.args], + } + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeAliasType: + assert data[".class"] == "TypeAliasType" + args: list[Type] = [] + if "args" in data: + args_list = data["args"] + assert isinstance(args_list, list) + args = [deserialize_type(arg) for arg in args_list] + alias = TypeAliasType(None, args) + alias.type_ref = data["type_ref"] + return alias + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_ALIAS_TYPE) + write_type_list(data, self.args) + assert self.alias is not None + write_str(data, self.alias.fullname) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeAliasType: + alias = TypeAliasType(None, read_type_list(data)) + alias.type_ref = read_str(data) + assert read_tag(data) == END_TAG + return alias + + +class TypeGuardedType(Type): + """Only used by find_isinstance_check() etc.""" + + __slots__ = ("type_guard",) + + def __init__(self, type_guard: Type) -> None: + super().__init__(line=type_guard.line, column=type_guard.column) + self.type_guard = type_guard + + def __repr__(self) -> str: + return f"TypeGuard({self.type_guard})" + + # This may hide some real bugs, but it is convenient for various "synthetic" + # visitors, similar to RequiredType and ReadOnlyType below. + def accept(self, visitor: TypeVisitor[T]) -> T: + return self.type_guard.accept(visitor) + + +class RequiredType(Type): + """Required[T] or NotRequired[T]. Only usable at top-level of a TypedDict definition.""" + + def __init__(self, item: Type, *, required: bool) -> None: + super().__init__(line=item.line, column=item.column) + self.item = item + self.required = required + + def __repr__(self) -> str: + if self.required: + return f"Required[{self.item}]" + else: + return f"NotRequired[{self.item}]" + + def accept(self, visitor: TypeVisitor[T]) -> T: + return self.item.accept(visitor) + + +class ReadOnlyType(Type): + """ReadOnly[T] Only usable at top-level of a TypedDict definition.""" + + def __init__(self, item: Type) -> None: + super().__init__(line=item.line, column=item.column) + self.item = item + + def __repr__(self) -> str: + return f"ReadOnly[{self.item}]" + + def accept(self, visitor: TypeVisitor[T]) -> T: + return self.item.accept(visitor) + + +class ProperType(Type): + """Not a type alias. + + Every type except TypeAliasType must inherit from this type. + """ + + __slots__ = () + + +class TypeVarId: + # A type variable is uniquely identified by its raw id and meta level. + + # For plain variables (type parameters of generic classes and + # functions) raw ids are allocated by semantic analysis, using + # positive ids 1, 2, ... for generic class parameters and negative + # ids -1, ... for generic function type arguments. A special value 0 + # is reserved for Self type variable (autogenerated). This convention + # is only used to keep type variable ids distinct when allocating + # them; the type checker makes no distinction between class and + # function type variables. + + # Metavariables are allocated unique ids starting from 1. + raw_id: Final[int] + + # Level of the variable in type inference. Currently either 0 for + # declared types, or 1 for type inference metavariables. + meta_level: int = 0 + + # Class variable used for allocating fresh ids for metavariables. + next_raw_id: ClassVar[int] = 1 + + # Fullname of class or function/method which declares this type + # variable (not the fullname of the TypeVar definition!), or '' + namespace: str + + def __init__(self, raw_id: int, meta_level: int = 0, *, namespace: str = "") -> None: + self.raw_id = raw_id + self.meta_level = meta_level + self.namespace = namespace + + @staticmethod + def new(meta_level: int) -> TypeVarId: + raw_id = TypeVarId.next_raw_id + TypeVarId.next_raw_id += 1 + return TypeVarId(raw_id, meta_level) + + def __repr__(self) -> str: + return self.raw_id.__repr__() + + def __eq__(self, other: object) -> bool: + # Although this call is not expensive (like UnionType or TypedDictType), + # most of the time we get the same object here, so add a fast path. + if self is other: + return True + return ( + isinstance(other, TypeVarId) + and self.raw_id == other.raw_id + and self.meta_level == other.meta_level + and self.namespace == other.namespace + ) + + def __ne__(self, other: object) -> bool: + return not (self == other) + + def __hash__(self) -> int: + return self.raw_id ^ (self.meta_level << 8) ^ hash(self.namespace) + + def is_meta_var(self) -> bool: + return self.meta_level > 0 + + def is_self(self) -> bool: + # This is a special value indicating typing.Self variable. + return self.raw_id == 0 + + +class TypeVarLikeType(ProperType): + __slots__ = ("name", "fullname", "id", "upper_bound", "default") + + name: str # Name (may be qualified) + fullname: str # Fully qualified name + id: TypeVarId + upper_bound: Type + default: Type + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + upper_bound: Type, + default: Type, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.name = name + self.fullname = fullname + self.id = id + self.upper_bound = upper_bound + self.default = default + + def serialize(self) -> JsonDict: + raise NotImplementedError + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarLikeType: + raise NotImplementedError + + def copy_modified(self, *, id: TypeVarId, **kwargs: Any) -> Self: + raise NotImplementedError + + @classmethod + def new_unification_variable(cls, old: Self) -> Self: + new_id = TypeVarId.new(meta_level=1) + return old.copy_modified(id=new_id) + + def has_default(self) -> bool: + t = get_proper_type(self.default) + return not (isinstance(t, AnyType) and t.type_of_any == TypeOfAny.from_omitted_generics) + + def values_or_bound(self) -> ProperType: + if isinstance(self, TypeVarType) and self.values: + return UnionType(self.values) + return get_proper_type(self.upper_bound) + + +class TypeVarType(TypeVarLikeType): + """Type that refers to a type variable.""" + + __slots__ = ("values", "variance") + + values: list[Type] # Value restriction, empty list if no restriction + variance: int + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + values: list[Type], + upper_bound: Type, + default: Type, + variance: int = INVARIANT, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(name, fullname, id, upper_bound, default, line, column) + assert values is not None, "No restrictions must be represented by empty list" + self.values = values + self.variance = variance + + def copy_modified( + self, + *, + values: Bogus[list[Type]] = _dummy, + upper_bound: Bogus[Type] = _dummy, + default: Bogus[Type] = _dummy, + id: Bogus[TypeVarId] = _dummy, + line: int = _dummy_int, + column: int = _dummy_int, + **kwargs: Any, + ) -> TypeVarType: + return TypeVarType( + name=self.name, + fullname=self.fullname, + id=self.id if id is _dummy else id, + values=self.values if values is _dummy else values, + upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound, + default=self.default if default is _dummy else default, + variance=self.variance, + line=self.line if line == _dummy_int else line, + column=self.column if column == _dummy_int else column, + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_var(self) + + def __hash__(self) -> int: + return hash((self.id, self.upper_bound, tuple(self.values))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypeVarType): + return NotImplemented + return ( + self.id == other.id + and self.upper_bound == other.upper_bound + and self.values == other.values + ) + + def serialize(self) -> JsonDict: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "values": [v.serialize() for v in self.values], + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarType: + assert data[".class"] == "TypeVarType" + return TypeVarType( + name=data["name"], + fullname=data["fullname"], + id=TypeVarId(data["id"], namespace=data["namespace"]), + values=[deserialize_type(v) for v in data["values"]], + upper_bound=deserialize_type(data["upper_bound"]), + default=deserialize_type(data["default"]), + variance=data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_TYPE) + write_str(data, self.name) + write_str(data, self.fullname) + write_int(data, self.id.raw_id) + write_str(data, self.id.namespace) + write_type_list(data, self.values) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarType: + ret = TypeVarType( + read_str(data), + read_str(data), + TypeVarId(read_int(data), namespace=read_str(data)), + read_type_list(data), + read_type(data), + read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class ParamSpecFlavor: + # Simple ParamSpec reference such as "P" + BARE: Final = 0 + # P.args + ARGS: Final = 1 + # P.kwargs + KWARGS: Final = 2 + + +class ParamSpecType(TypeVarLikeType): + """Type that refers to a ParamSpec. + + A ParamSpec is a type variable that represents the parameter + types, names and kinds of a callable (i.e., the signature without + the return type). + + This can be one of these forms + * P (ParamSpecFlavor.BARE) + * P.args (ParamSpecFlavor.ARGS) + * P.kwargs (ParamSpecFLavor.KWARGS) + + The upper_bound is really used as a fallback type -- it's shared + with TypeVarType for simplicity. It can't be specified by the user + and the value is directly derived from the flavor (currently + always just 'object'). + """ + + __slots__ = ("flavor", "prefix") + + flavor: int + prefix: Parameters + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + flavor: int, + upper_bound: Type, + default: Type, + *, + line: int = -1, + column: int = -1, + prefix: Parameters | None = None, + ) -> None: + super().__init__(name, fullname, id, upper_bound, default, line=line, column=column) + self.flavor = flavor + self.prefix = prefix or Parameters([], [], []) + + def with_flavor(self, flavor: int) -> ParamSpecType: + return ParamSpecType( + self.name, + self.fullname, + self.id, + flavor, + upper_bound=self.upper_bound, + default=self.default, + prefix=self.prefix, + ) + + def copy_modified( + self, + *, + id: Bogus[TypeVarId] = _dummy, + flavor: int = _dummy_int, + prefix: Bogus[Parameters] = _dummy, + default: Bogus[Type] = _dummy, + **kwargs: Any, + ) -> ParamSpecType: + return ParamSpecType( + self.name, + self.fullname, + id if id is not _dummy else self.id, + flavor if flavor != _dummy_int else self.flavor, + self.upper_bound, + default=default if default is not _dummy else self.default, + line=self.line, + column=self.column, + prefix=prefix if prefix is not _dummy else self.prefix, + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_param_spec(self) + + def name_with_suffix(self) -> str: + n = self.name + if self.flavor == ParamSpecFlavor.ARGS: + return f"{n}.args" + elif self.flavor == ParamSpecFlavor.KWARGS: + return f"{n}.kwargs" + return n + + def __hash__(self) -> int: + return hash((self.id, self.flavor, self.prefix)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ParamSpecType): + return NotImplemented + # Upper bound can be ignored, since it's determined by flavor. + return self.id == other.id and self.flavor == other.flavor and self.prefix == other.prefix + + def serialize(self) -> JsonDict: + assert not self.id.is_meta_var() + return { + ".class": "ParamSpecType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "flavor": self.flavor, + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "prefix": self.prefix.serialize(), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ParamSpecType: + assert data[".class"] == "ParamSpecType" + return ParamSpecType( + data["name"], + data["fullname"], + TypeVarId(data["id"], namespace=data["namespace"]), + data["flavor"], + deserialize_type(data["upper_bound"]), + deserialize_type(data["default"]), + prefix=Parameters.deserialize(data["prefix"]), + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, PARAM_SPEC_TYPE) + self.prefix.write(data) + write_str(data, self.name) + write_str(data, self.fullname) + write_int(data, self.id.raw_id) + write_str(data, self.id.namespace) + write_int(data, self.flavor) + self.upper_bound.write(data) + self.default.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ParamSpecType: + assert read_tag(data) == PARAMETERS + prefix = Parameters.read(data) + ret = ParamSpecType( + read_str(data), + read_str(data), + TypeVarId(read_int(data), namespace=read_str(data)), + read_int(data), + read_type(data), + read_type(data), + prefix=prefix, + ) + assert read_tag(data) == END_TAG + return ret + + +class TypeVarTupleType(TypeVarLikeType): + """Type that refers to a TypeVarTuple. + + See PEP646 for more information. + """ + + __slots__ = ("tuple_fallback", "min_len") + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + upper_bound: Type, + tuple_fallback: Instance, + default: Type, + *, + line: int = -1, + column: int = -1, + min_len: int = 0, + ) -> None: + super().__init__(name, fullname, id, upper_bound, default, line=line, column=column) + self.tuple_fallback = tuple_fallback + # This value is not settable by a user. It is an internal-only thing to support + # len()-narrowing of variadic tuples. + self.min_len = min_len + + def serialize(self) -> JsonDict: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarTupleType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "upper_bound": self.upper_bound.serialize(), + "tuple_fallback": self.tuple_fallback.serialize(), + "default": self.default.serialize(), + "min_len": self.min_len, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarTupleType: + assert data[".class"] == "TypeVarTupleType" + return TypeVarTupleType( + data["name"], + data["fullname"], + TypeVarId(data["id"], namespace=data["namespace"]), + deserialize_type(data["upper_bound"]), + Instance.deserialize(data["tuple_fallback"]), + deserialize_type(data["default"]), + min_len=data["min_len"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_TUPLE_TYPE) + self.tuple_fallback.write(data) + write_str(data, self.name) + write_str(data, self.fullname) + write_int(data, self.id.raw_id) + write_str(data, self.id.namespace) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.min_len) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarTupleType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = TypeVarTupleType( + read_str(data), + read_str(data), + TypeVarId(read_int(data), namespace=read_str(data)), + read_type(data), + fallback, + read_type(data), + min_len=read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_var_tuple(self) + + def __hash__(self) -> int: + return hash((self.id, self.min_len)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypeVarTupleType): + return NotImplemented + return self.id == other.id and self.min_len == other.min_len + + def copy_modified( + self, + *, + id: Bogus[TypeVarId] = _dummy, + upper_bound: Bogus[Type] = _dummy, + default: Bogus[Type] = _dummy, + min_len: Bogus[int] = _dummy, + **kwargs: Any, + ) -> TypeVarTupleType: + return TypeVarTupleType( + self.name, + self.fullname, + self.id if id is _dummy else id, + self.upper_bound if upper_bound is _dummy else upper_bound, + self.tuple_fallback, + self.default if default is _dummy else default, + line=self.line, + column=self.column, + min_len=self.min_len if min_len is _dummy else min_len, + ) + + +class UnboundType(ProperType): + """Instance type that has not been bound during semantic analysis.""" + + __slots__ = ( + "name", + "args", + "optional", + "empty_tuple_index", + "original_str_expr", + "original_str_fallback", + ) + + def __init__( + self, + name: str, + args: Sequence[Type] | None = None, + *, + line: int = -1, + column: int = -1, + optional: bool = False, + empty_tuple_index: bool = False, + original_str_expr: str | None = None, + original_str_fallback: str | None = None, + ) -> None: + super().__init__(line, column) + if not args: + args = [] + self.name = name + self.args = tuple(args) + # Should this type be wrapped in an Optional? + self.optional = optional + # Special case for X[()] + self.empty_tuple_index = empty_tuple_index + # If this UnboundType was originally defined as a str or bytes, keep track of + # the original contents of that string-like thing. This way, if this UnboundExpr + # ever shows up inside of a LiteralType, we can determine whether that + # Literal[...] is valid or not. E.g. Literal[foo] is most likely invalid + # (unless 'foo' is an alias for another literal or something) and + # Literal["foo"] most likely is. + # + # We keep track of the entire string instead of just using a boolean flag + # so we can distinguish between things like Literal["foo"] vs + # Literal[" foo "]. + # + # We also keep track of what the original base fallback type was supposed to be + # so we don't have to try and recompute it later + self.original_str_expr = original_str_expr + self.original_str_fallback = original_str_fallback + + def copy_modified(self, args: Bogus[Sequence[Type] | None] = _dummy) -> UnboundType: + if args is _dummy: + args = self.args + return UnboundType( + name=self.name, + args=args, + line=self.line, + column=self.column, + optional=self.optional, + empty_tuple_index=self.empty_tuple_index, + original_str_expr=self.original_str_expr, + original_str_fallback=self.original_str_fallback, + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_unbound_type(self) + + def __hash__(self) -> int: + return hash((self.name, self.optional, tuple(self.args), self.original_str_expr)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnboundType): + return NotImplemented + return ( + self.name == other.name + and self.optional == other.optional + and self.args == other.args + and self.original_str_expr == other.original_str_expr + and self.original_str_fallback == other.original_str_fallback + ) + + def serialize(self) -> JsonDict: + return { + ".class": "UnboundType", + "name": self.name, + "args": [a.serialize() for a in self.args], + "expr": self.original_str_expr, + "expr_fallback": self.original_str_fallback, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> UnboundType: + assert data[".class"] == "UnboundType" + return UnboundType( + data["name"], + [deserialize_type(a) for a in data["args"]], + original_str_expr=data["expr"], + original_str_fallback=data["expr_fallback"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNBOUND_TYPE) + write_str(data, self.name) + write_type_list(data, self.args) + write_str_opt(data, self.original_str_expr) + write_str_opt(data, self.original_str_fallback) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UnboundType: + ret = UnboundType( + read_str(data), + read_type_list(data), + original_str_expr=read_str_opt(data), + original_str_fallback=read_str_opt(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class CallableArgument(ProperType): + """Represents a Arg(type, 'name') inside a Callable's type list. + + Note that this is a synthetic type for helping parse ASTs, not a real type. + """ + + __slots__ = ("typ", "name", "constructor") + + typ: Type + name: str | None + constructor: str | None + + def __init__( + self, + typ: Type, + name: str | None, + constructor: str | None, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.typ = typ + self.name = name + self.constructor = constructor + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_callable_argument(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + +class TypeList(ProperType): + """Information about argument types and names [...]. + + This is used for the arguments of a Callable type, i.e. for + [arg, ...] in Callable[[arg, ...], ret]. This is not a real type + but a syntactic AST construct. UnboundTypes can also have TypeList + types before they are processed into Callable types. + """ + + __slots__ = ("items",) + + items: list[Type] + + def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self.items = items + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_type_list(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + def __hash__(self) -> int: + return hash(tuple(self.items)) + + def __eq__(self, other: object) -> bool: + return isinstance(other, TypeList) and self.items == other.items + + +class UnpackType(ProperType): + """Type operator Unpack from PEP646. Can be either with Unpack[] + or unpacking * syntax. + + The inner type should be either a TypeVarTuple, or a variable length tuple. + In an exceptional case of callable star argument it can be a fixed length tuple. + + Note: the above restrictions are only guaranteed by normalizations after semantic + analysis, if your code needs to handle UnpackType *during* semantic analysis, it is + wild west, technically anything can be present in the wrapped type. + """ + + __slots__ = ["type", "from_star_syntax"] + + def __init__( + self, typ: Type, line: int = -1, column: int = -1, from_star_syntax: bool = False + ) -> None: + super().__init__(line, column) + self.type = typ + self.from_star_syntax = from_star_syntax + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_unpack_type(self) + + def serialize(self) -> JsonDict: + return {".class": "UnpackType", "type": self.type.serialize()} + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNPACK_TYPE) + self.type.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UnpackType: + ret = UnpackType(read_type(data)) + assert read_tag(data) == END_TAG + return ret + + @classmethod + def deserialize(cls, data: JsonDict) -> UnpackType: + assert data[".class"] == "UnpackType" + typ = data["type"] + return UnpackType(deserialize_type(typ)) + + def __hash__(self) -> int: + return hash(self.type) + + def __eq__(self, other: object) -> bool: + return isinstance(other, UnpackType) and self.type == other.type + + +class AnyType(ProperType): + """The type 'Any'.""" + + __slots__ = ("type_of_any", "source_any", "missing_import_name") + + def __init__( + self, + type_of_any: int, + source_any: AnyType | None = None, + missing_import_name: str | None = None, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.type_of_any = type_of_any + # If this Any was created as a result of interacting with another 'Any', record the source + # and use it in reports. + self.source_any = source_any + if source_any and source_any.source_any: + self.source_any = source_any.source_any + + if source_any is None: + self.missing_import_name = missing_import_name + else: + self.missing_import_name = source_any.missing_import_name + + # Only unimported type anys and anys from other anys should have an import name + assert missing_import_name is None or type_of_any in ( + TypeOfAny.from_unimported_type, + TypeOfAny.from_another_any, + ) + # Only Anys that come from another Any can have source_any. + assert type_of_any != TypeOfAny.from_another_any or source_any is not None + # We should not have chains of Anys. + assert not self.source_any or self.source_any.type_of_any != TypeOfAny.from_another_any + + @property + def is_from_error(self) -> bool: + return self.type_of_any == TypeOfAny.from_error + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_any(self) + + def copy_modified( + self, + # Mark with Bogus because _dummy is just an object (with type Any) + type_of_any: int = _dummy_int, + original_any: Bogus[AnyType | None] = _dummy, + missing_import_name: Bogus[str | None] = _dummy, + ) -> AnyType: + if type_of_any == _dummy_int: + type_of_any = self.type_of_any + if original_any is _dummy: + original_any = self.source_any + if missing_import_name is _dummy: + missing_import_name = self.missing_import_name + return AnyType( + type_of_any=type_of_any, + source_any=original_any, + missing_import_name=missing_import_name, + line=self.line, + column=self.column, + ) + + def __hash__(self) -> int: + return hash(AnyType) + + def __eq__(self, other: object) -> bool: + return isinstance(other, AnyType) + + def serialize(self) -> JsonDict: + return { + ".class": "AnyType", + "type_of_any": self.type_of_any, + "source_any": self.source_any.serialize() if self.source_any is not None else None, + "missing_import_name": self.missing_import_name, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> AnyType: + assert data[".class"] == "AnyType" + source = data["source_any"] + return AnyType( + data["type_of_any"], + AnyType.deserialize(source) if source is not None else None, + data["missing_import_name"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, ANY_TYPE) + write_type_opt(data, self.source_any) + write_int(data, self.type_of_any) + write_str_opt(data, self.missing_import_name) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> AnyType: + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == ANY_TYPE + source_any = AnyType.read(data) + else: + source_any = None + ret = AnyType(read_int(data), source_any, read_str_opt(data)) + assert read_tag(data) == END_TAG + return ret + + +class UninhabitedType(ProperType): + """This type has no members. + + This type is the bottom type. + With strict Optional checking, it is the only common subtype between all + other types, which allows `meet` to be well defined. Without strict + Optional checking, NoneType fills this role. + + In general, for any type T: + join(UninhabitedType, T) = T + meet(UninhabitedType, T) = UninhabitedType + is_subtype(UninhabitedType, T) = True + """ + + __slots__ = ("ambiguous",) + + ambiguous: bool # Is this a result of inference for a variable without constraints? + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self.ambiguous = False + + def can_be_true_default(self) -> bool: + return False + + def can_be_false_default(self) -> bool: + return False + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_uninhabited_type(self) + + def __hash__(self) -> int: + return hash((UninhabitedType, self.ambiguous)) + + def __eq__(self, other: object) -> bool: + return isinstance(other, UninhabitedType) and other.ambiguous == self.ambiguous + + def serialize(self) -> JsonDict: + return {".class": "UninhabitedType"} + + @classmethod + def deserialize(cls, data: JsonDict) -> UninhabitedType: + assert data[".class"] == "UninhabitedType" + return UninhabitedType() + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNINHABITED_TYPE) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UninhabitedType: + assert read_tag(data) == END_TAG + return UninhabitedType() + + +class NoneType(ProperType): + """The type of 'None'. + + This type can be written by users as 'None'. + """ + + __slots__ = () + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + + def can_be_true_default(self) -> bool: + return False + + def __hash__(self) -> int: + return hash(NoneType) + + def __eq__(self, other: object) -> bool: + return isinstance(other, NoneType) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_none_type(self) + + def serialize(self) -> JsonDict: + return {".class": "NoneType"} + + @classmethod + def deserialize(cls, data: JsonDict) -> NoneType: + assert data[".class"] == "NoneType" + return NoneType() + + def write(self, data: WriteBuffer) -> None: + write_tag(data, NONE_TYPE) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> NoneType: + assert read_tag(data) == END_TAG + return NoneType() + + +# NoneType used to be called NoneTyp so to avoid needlessly breaking +# external plugins we keep that alias here. +NoneTyp = NoneType + + +class ErasedType(ProperType): + """Placeholder for an erased type. + + This is used during type inference. This has the special property that + it is ignored during type inference. + """ + + __slots__ = () + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_erased_type(self) + + +class DeletedType(ProperType): + """Type of deleted variables. + + These can be used as lvalues but not rvalues. + """ + + __slots__ = ("source",) + + source: str | None # May be None; name that generated this value + + def __init__(self, source: str | None = None, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self.source = source + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_deleted_type(self) + + def serialize(self) -> JsonDict: + return {".class": "DeletedType", "source": self.source} + + @classmethod + def deserialize(cls, data: JsonDict) -> DeletedType: + assert data[".class"] == "DeletedType" + return DeletedType(data["source"]) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, DELETED_TYPE) + write_str_opt(data, self.source) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> DeletedType: + ret = DeletedType(read_str_opt(data)) + assert read_tag(data) == END_TAG + return ret + + +# Fake TypeInfo to be used as a placeholder during Instance de-serialization. +NOT_READY: Final = mypy.nodes.FakeInfo("De-serialization failure: TypeInfo not fixed") + + +class ExtraAttrs: + """Summary of module attributes and types. + + This is used for instances of types.ModuleType, because they can have different + attributes per instance, and for type narrowing with hasattr() checks. + """ + + def __init__( + self, + attrs: dict[str, Type], + immutable: set[str] | None = None, + mod_name: str | None = None, + ) -> None: + self.attrs = attrs + if immutable is None: + immutable = set() + self.immutable = immutable + self.mod_name = mod_name + + def __hash__(self) -> int: + return hash((tuple(self.attrs.items()), tuple(sorted(self.immutable)))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ExtraAttrs): + return NotImplemented + return self.attrs == other.attrs and self.immutable == other.immutable + + def copy(self) -> ExtraAttrs: + return ExtraAttrs(self.attrs.copy(), self.immutable.copy(), self.mod_name) + + def __repr__(self) -> str: + return f"ExtraAttrs({self.attrs!r}, {self.immutable!r}, {self.mod_name!r})" + + def serialize(self) -> JsonDict: + return { + ".class": "ExtraAttrs", + "attrs": {k: v.serialize() for k, v in self.attrs.items()}, + "immutable": sorted(self.immutable), + "mod_name": self.mod_name, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ExtraAttrs: + assert data[".class"] == "ExtraAttrs" + return ExtraAttrs( + {k: deserialize_type(v) for k, v in data["attrs"].items()}, + set(data["immutable"]), + data["mod_name"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, EXTRA_ATTRS) + write_type_map(data, self.attrs) + write_str_list(data, sorted(self.immutable)) + write_str_opt(data, self.mod_name) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ExtraAttrs: + ret = ExtraAttrs(read_type_map(data), set(read_str_list(data)), read_str_opt(data)) + assert read_tag(data) == END_TAG + return ret + + +class Instance(ProperType): + """An instance type of form C[T1, ..., Tn]. + + The list of type variables may be empty. + + Several types have fallbacks to `Instance`, because in Python everything is an object + and this concept is impossible to express without intersection types. We therefore use + fallbacks for all "non-special" (like UninhabitedType, ErasedType etc) types. + """ + + __slots__ = ("type", "args", "invalid", "type_ref", "last_known_value", "_hash", "extra_attrs") + + def __init__( + self, + typ: mypy.nodes.TypeInfo, + args: Sequence[Type], + line: int = -1, + column: int = -1, + *, + last_known_value: LiteralType | None = None, + extra_attrs: ExtraAttrs | None = None, + ) -> None: + super().__init__(line, column) + self.type = typ + self.args = tuple(args) + self.type_ref: str | None = None + + # This field keeps track of the underlying Literal[...] value associated with + # this instance, if one is known. + # + # This field is set whenever possible within expressions, but is erased upon + # variable assignment (see erasetype.remove_instance_last_known_values) unless + # the variable is declared to be final. + # + # For example, consider the following program: + # + # a = 1 + # b: Final[int] = 2 + # c: Final = 3 + # print(a + b + c + 4) + # + # The 'Instance' objects associated with the expressions '1', '2', '3', and '4' will + # have last_known_values of type Literal[1], Literal[2], Literal[3], and Literal[4] + # respectively. However, the Instance object assigned to 'a' and 'b' will have their + # last_known_value erased: variable 'a' is mutable; variable 'b' was declared to be + # specifically an int. + # + # Or more broadly, this field lets this Instance "remember" its original declaration + # when applicable. We want this behavior because we want implicit Final declarations + # to act pretty much identically with constants: we should be able to replace any + # places where we use some Final variable with the original value and get the same + # type-checking behavior. For example, we want this program: + # + # def expects_literal(x: Literal[3]) -> None: pass + # var: Final = 3 + # expects_literal(var) + # + # ...to type-check in the exact same way as if we had written the program like this: + # + # def expects_literal(x: Literal[3]) -> None: pass + # expects_literal(3) + # + # In order to make this work (especially with literal types), we need var's type + # (an Instance) to remember the "original" value. + # + # Preserving this value within expressions is useful for similar reasons. + # + # Currently most of mypy will ignore this field and will continue to treat this type like + # a regular Instance. We end up using this field only when we are explicitly within a + # Literal context. + self.last_known_value = last_known_value + + # Cached hash value + self._hash = -1 + + # Additional attributes defined per instance of this type. For example modules + # have different attributes per instance of types.ModuleType. + self.extra_attrs = extra_attrs + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_instance(self) + + def __hash__(self) -> int: + if self._hash == -1: + self._hash = hash((self.type, self.args, self.last_known_value, self.extra_attrs)) + return self._hash + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Instance): + return NotImplemented + return ( + self.type == other.type + and self.args == other.args + and self.last_known_value == other.last_known_value + and self.extra_attrs == other.extra_attrs + ) + + def serialize(self) -> JsonDict | str: + assert self.type is not None + type_ref = self.type.fullname + if not self.args and not self.last_known_value and not self.extra_attrs: + return type_ref + data: JsonDict = { + ".class": "Instance", + "type_ref": type_ref, + "args": [arg.serialize() for arg in self.args], + } + if self.last_known_value is not None: + data["last_known_value"] = self.last_known_value.serialize() + data["extra_attrs"] = self.extra_attrs.serialize() if self.extra_attrs else None + return data + + @classmethod + def deserialize(cls, data: JsonDict | str) -> Instance: + if isinstance(data, str): + inst = Instance(NOT_READY, []) + inst.type_ref = data + return inst + assert data[".class"] == "Instance" + args: list[Type] = [] + if "args" in data: + args_list = data["args"] + assert isinstance(args_list, list) + args = [deserialize_type(arg) for arg in args_list] + inst = Instance(NOT_READY, args) + inst.type_ref = data["type_ref"] # Will be fixed up by fixup.py later. + if "last_known_value" in data: + inst.last_known_value = LiteralType.deserialize(data["last_known_value"]) + if data.get("extra_attrs") is not None: + inst.extra_attrs = ExtraAttrs.deserialize(data["extra_attrs"]) + return inst + + def write(self, data: WriteBuffer) -> None: + write_tag(data, INSTANCE) + if not self.args and not self.last_known_value and not self.extra_attrs: + type_ref = self.type.fullname + if type_ref == "builtins.str": + write_tag(data, INSTANCE_STR) + elif type_ref == "builtins.function": + write_tag(data, INSTANCE_FUNCTION) + elif type_ref == "builtins.int": + write_tag(data, INSTANCE_INT) + elif type_ref == "builtins.bool": + write_tag(data, INSTANCE_BOOL) + elif type_ref == "builtins.object": + write_tag(data, INSTANCE_OBJECT) + else: + write_tag(data, INSTANCE_SIMPLE) + write_str_bare(data, type_ref) + return + write_tag(data, INSTANCE_GENERIC) + write_str(data, self.type.fullname) + write_type_list(data, self.args) + write_type_opt(data, self.last_known_value) + if self.extra_attrs is None: + write_tag(data, LITERAL_NONE) + else: + self.extra_attrs.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Instance: + tag = read_tag(data) + # This is quite verbose, but this is very hot code, so we are not + # using dictionary lookups here. + if tag == INSTANCE_STR: + if instance_cache.str_type is None: + instance_cache.str_type = Instance(NOT_READY, []) + instance_cache.str_type.type_ref = "builtins.str" + return instance_cache.str_type + if tag == INSTANCE_FUNCTION: + if instance_cache.function_type is None: + instance_cache.function_type = Instance(NOT_READY, []) + instance_cache.function_type.type_ref = "builtins.function" + return instance_cache.function_type + if tag == INSTANCE_INT: + if instance_cache.int_type is None: + instance_cache.int_type = Instance(NOT_READY, []) + instance_cache.int_type.type_ref = "builtins.int" + return instance_cache.int_type + if tag == INSTANCE_BOOL: + if instance_cache.bool_type is None: + instance_cache.bool_type = Instance(NOT_READY, []) + instance_cache.bool_type.type_ref = "builtins.bool" + return instance_cache.bool_type + if tag == INSTANCE_OBJECT: + if instance_cache.object_type is None: + instance_cache.object_type = Instance(NOT_READY, []) + instance_cache.object_type.type_ref = "builtins.object" + return instance_cache.object_type + if tag == INSTANCE_SIMPLE: + inst = Instance(NOT_READY, []) + inst.type_ref = read_str_bare(data) + return inst + assert tag == INSTANCE_GENERIC + type_ref = read_str(data) + inst = Instance(NOT_READY, read_type_list(data)) + inst.type_ref = type_ref + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == LITERAL_TYPE + inst.last_known_value = LiteralType.read(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == EXTRA_ATTRS + inst.extra_attrs = ExtraAttrs.read(data) + assert read_tag(data) == END_TAG + return inst + + def copy_modified( + self, + *, + args: Bogus[list[Type]] = _dummy, + last_known_value: Bogus[LiteralType | None] = _dummy, + ) -> Instance: + new = Instance( + typ=self.type, + args=args if args is not _dummy else self.args, + line=self.line, + column=self.column, + last_known_value=( + last_known_value if last_known_value is not _dummy else self.last_known_value + ), + extra_attrs=self.extra_attrs, + ) + new.can_be_true = self.can_be_true + new.can_be_false = self.can_be_false + return new + + def copy_with_extra_attr(self, name: str, typ: Type) -> Instance: + if self.extra_attrs: + existing_attrs = self.extra_attrs.copy() + else: + existing_attrs = ExtraAttrs({}, set(), None) + existing_attrs.attrs[name] = typ + new = self.copy_modified() + new.extra_attrs = existing_attrs + return new + + +class InstanceCache: + def __init__(self) -> None: + self.str_type: Instance | None = None + self.function_type: Instance | None = None + self.int_type: Instance | None = None + self.bool_type: Instance | None = None + self.object_type: Instance | None = None + + def reset(self) -> None: + self.str_type = None + self.function_type = None + self.int_type = None + self.bool_type = None + self.object_type = None + + +instance_cache: Final = InstanceCache() + + +class FunctionLike(ProperType): + """Abstract base class for function types.""" + + __slots__ = ("fallback",) + + fallback: Instance + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self._can_be_false = False + + @abstractmethod + def is_type_obj(self) -> bool: + pass + + @abstractmethod + def type_object(self) -> mypy.nodes.TypeInfo: + pass + + @property + @abstractmethod + def items(self) -> list[CallableType]: + pass + + @abstractmethod + def with_name(self, name: str) -> FunctionLike: + pass + + @abstractmethod + def get_name(self) -> str | None: + pass + + def bound(self) -> bool: + return bool(self.items) and self.items[0].is_bound + + +class FormalArgument: + def __init__(self, name: str | None, pos: int | None, typ: Type, required: bool) -> None: + self.name = name + self.pos = pos + self.typ = typ + self.required = required + + def __eq__(self, other: object) -> bool: + if not isinstance(other, FormalArgument): + return NotImplemented + return ( + self.name == other.name + and self.pos == other.pos + and self.typ == other.typ + and self.required == other.required + ) + + def __hash__(self) -> int: + return hash((self.name, self.pos, self.typ, self.required)) + + +class Parameters(ProperType): + """Type that represents the parameters to a function. + + Used for ParamSpec analysis. Note that by convention we handle this + type as a Callable without return type, not as a "tuple with names", + so that it behaves contravariantly, in particular [x: int] <: [int]. + """ + + __slots__ = ( + "arg_types", + "arg_kinds", + "arg_names", + "min_args", + "is_ellipsis_args", + # TODO: variables don't really belong here, but they are used to allow hacky support + # for forall . Foo[[x: T], T] by capturing generic callable with ParamSpec, see #15909 + "variables", + "imprecise_arg_kinds", + ) + + def __init__( + self, + arg_types: Sequence[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None], + *, + variables: Sequence[TypeVarLikeType] | None = None, + is_ellipsis_args: bool = False, + imprecise_arg_kinds: bool = False, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.arg_types = list(arg_types) + self.arg_kinds = arg_kinds + self.arg_names = list(arg_names) + assert len(arg_types) == len(arg_kinds) == len(arg_names) + assert not any(isinstance(t, Parameters) for t in arg_types) + self.min_args = arg_kinds.count(ARG_POS) + self.is_ellipsis_args = is_ellipsis_args + self.variables = variables or [] + self.imprecise_arg_kinds = imprecise_arg_kinds + + def copy_modified( + self, + arg_types: Bogus[Sequence[Type]] = _dummy, + arg_kinds: Bogus[list[ArgKind]] = _dummy, + arg_names: Bogus[Sequence[str | None]] = _dummy, + *, + variables: Bogus[Sequence[TypeVarLikeType]] = _dummy, + is_ellipsis_args: Bogus[bool] = _dummy, + imprecise_arg_kinds: Bogus[bool] = _dummy, + ) -> Parameters: + return Parameters( + arg_types=arg_types if arg_types is not _dummy else self.arg_types, + arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds, + arg_names=arg_names if arg_names is not _dummy else self.arg_names, + is_ellipsis_args=( + is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args + ), + variables=variables if variables is not _dummy else self.variables, + imprecise_arg_kinds=( + imprecise_arg_kinds + if imprecise_arg_kinds is not _dummy + else self.imprecise_arg_kinds + ), + ) + + # TODO: here is a lot of code duplication with Callable type, fix this. + def var_arg(self) -> FormalArgument | None: + """The formal argument for *args.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR: + return FormalArgument(None, position, type, False) + return None + + def kw_arg(self) -> FormalArgument | None: + """The formal argument for **kwargs.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR2: + return FormalArgument(None, position, type, False) + return None + + def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]: + """Yields the formal arguments corresponding to this callable, ignoring *arg and **kwargs. + + To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields, + if they are not None. + + If you really want to include star args in the yielded output, set the + 'include_star_args' parameter to 'True'.""" + args = [] + done_with_positional = False + for i in range(len(self.arg_types)): + kind = self.arg_kinds[i] + if kind.is_named() or kind.is_star(): + done_with_positional = True + if not include_star_args and kind.is_star(): + continue + + required = kind.is_required() + pos = None if done_with_positional else i + arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required) + args.append(arg) + return args + + def argument_by_name(self, name: str | None) -> FormalArgument | None: + if name is None: + return None + seen_star = False + for i, (arg_name, kind, typ) in enumerate( + zip(self.arg_names, self.arg_kinds, self.arg_types) + ): + # No more positional arguments after these. + if kind.is_named() or kind.is_star(): + seen_star = True + if kind.is_star(): + continue + if arg_name == name: + position = None if seen_star else i + return FormalArgument(name, position, typ, kind.is_required()) + return self.try_synthesizing_arg_from_kwarg(name) + + def argument_by_position(self, position: int | None) -> FormalArgument | None: + if position is None: + return None + if position >= len(self.arg_names): + return self.try_synthesizing_arg_from_vararg(position) + name, kind, typ = ( + self.arg_names[position], + self.arg_kinds[position], + self.arg_types[position], + ) + if kind.is_positional(): + return FormalArgument(name, position, typ, kind == ARG_POS) + else: + return self.try_synthesizing_arg_from_vararg(position) + + def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None: + kw_arg = self.kw_arg() + if kw_arg is not None: + return FormalArgument(name, None, kw_arg.typ, False) + else: + return None + + def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None: + var_arg = self.var_arg() + if var_arg is not None: + return FormalArgument(None, position, var_arg.typ, False) + else: + return None + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_parameters(self) + + def serialize(self) -> JsonDict: + return { + ".class": "Parameters", + "arg_types": [t.serialize() for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "variables": [tv.serialize() for tv in self.variables], + "imprecise_arg_kinds": self.imprecise_arg_kinds, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> Parameters: + assert data[".class"] == "Parameters" + return Parameters( + [deserialize_type(t) for t in data["arg_types"]], + # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise, + # we would spend ~20% of types deserialization time in Enum.__call__(). + [ARG_KINDS[x] for x in data["arg_kinds"]], + data["arg_names"], + variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]], + imprecise_arg_kinds=data["imprecise_arg_kinds"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, PARAMETERS) + write_type_list(data, self.arg_types) + write_int_list(data, [int(x.value) for x in self.arg_kinds]) + write_str_opt_list(data, self.arg_names) + write_type_list(data, self.variables) + write_bool(data, self.imprecise_arg_kinds) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Parameters: + ret = Parameters( + read_type_list(data), + # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise, + # we would spend ~20% of types deserialization time in Enum.__call__(). + [ARG_KINDS[ak] for ak in read_int_list(data)], + read_str_opt_list(data), + variables=read_type_var_likes(data), + imprecise_arg_kinds=read_bool(data), + ) + assert read_tag(data) == END_TAG + return ret + + def __hash__(self) -> int: + return hash( + ( + self.is_ellipsis_args, + tuple(self.arg_types), + tuple(self.arg_names), + tuple(self.arg_kinds), + ) + ) + + def __eq__(self, other: object) -> bool: + if isinstance(other, Parameters): + return ( + self.arg_types == other.arg_types + and self.arg_names == other.arg_names + and self.arg_kinds == other.arg_kinds + and self.is_ellipsis_args == other.is_ellipsis_args + ) + else: + return NotImplemented + + +CT = TypeVar("CT", bound="CallableType") + + +class CallableType(FunctionLike): + """Type of a non-overloaded callable object (such as function).""" + + __slots__ = ( + "arg_types", # Types of function arguments + "arg_kinds", # ARG_ constants + "arg_names", # Argument names; None if not a keyword argument + "min_args", # Minimum number of arguments; derived from arg_kinds + "ret_type", # Return value type + "name", # Name (may be None; for error messages and plugins) + "definition", # For error messages. May be None. + "variables", # Type variables for a generic function + "is_ellipsis_args", # Is this Callable[..., t] (with literal '...')? + "implicit", # Was this type implicitly generated instead of explicitly + # specified by the user? + "special_sig", # Non-None for signatures that require special handling + # (currently only values are 'dict' for a signature similar to + # 'dict' and 'partial' for a `functools.partial` evaluation) + "from_type_type", # Was this callable generated by analyzing Type[...] + # instantiation? + "is_bound", # Is this a bound method? + "type_guard", # T, if -> TypeGuard[T] (ret_type is bool in this case). + "type_is", # T, if -> TypeIs[T] (ret_type is bool in this case). + "from_concatenate", # whether this callable is from a concatenate object + # (this is used for error messages) + "imprecise_arg_kinds", + "unpack_kwargs", # Was an Unpack[...] with **kwargs used to define this callable? + ) + + def __init__( + self, + # maybe this should be refactored to take a Parameters object + arg_types: Sequence[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None], + ret_type: Type, + fallback: Instance, + name: str | None = None, + definition: SymbolNode | None = None, + variables: Sequence[TypeVarLikeType] | None = None, + line: int = -1, + column: int = -1, + is_ellipsis_args: bool = False, + implicit: bool = False, + special_sig: str | None = None, + from_type_type: bool = False, + is_bound: bool = False, + type_guard: Type | None = None, + type_is: Type | None = None, + from_concatenate: bool = False, + imprecise_arg_kinds: bool = False, + unpack_kwargs: bool = False, + ) -> None: + super().__init__(line, column) + assert len(arg_types) == len(arg_kinds) == len(arg_names) + self.arg_types = list(arg_types) + for t in self.arg_types: + if isinstance(t, ParamSpecType): + assert not t.prefix.arg_types + # TODO: should we assert that only ARG_STAR contain ParamSpecType? + # See testParamSpecJoin, that relies on passing e.g `P.args` as plain argument. + self.arg_kinds = arg_kinds + self.arg_names = list(arg_names) + self.min_args = arg_kinds.count(ARG_POS) + self.ret_type = ret_type + self.fallback = fallback + assert not name or " CT: + modified = CallableType( + arg_types=arg_types if arg_types is not _dummy else self.arg_types, + arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds, + arg_names=arg_names if arg_names is not _dummy else self.arg_names, + ret_type=ret_type if ret_type is not _dummy else self.ret_type, + fallback=fallback if fallback is not _dummy else self.fallback, + name=name if name is not _dummy else self.name, + definition=definition if definition is not _dummy else self.definition, + variables=variables if variables is not _dummy else self.variables, + line=line if line != _dummy_int else self.line, + column=column if column != _dummy_int else self.column, + is_ellipsis_args=( + is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args + ), + implicit=implicit if implicit is not _dummy else self.implicit, + special_sig=special_sig if special_sig is not _dummy else self.special_sig, + from_type_type=from_type_type if from_type_type is not _dummy else self.from_type_type, + is_bound=is_bound if is_bound is not _dummy else self.is_bound, + type_guard=type_guard if type_guard is not _dummy else self.type_guard, + type_is=type_is if type_is is not _dummy else self.type_is, + from_concatenate=( + from_concatenate if from_concatenate is not _dummy else self.from_concatenate + ), + imprecise_arg_kinds=( + imprecise_arg_kinds + if imprecise_arg_kinds is not _dummy + else self.imprecise_arg_kinds + ), + unpack_kwargs=unpack_kwargs if unpack_kwargs is not _dummy else self.unpack_kwargs, + ) + # Optimization: Only NewTypes are supported as subtypes since + # the class is effectively final, so we can use a cast safely. + return cast(CT, modified) + + def var_arg(self) -> FormalArgument | None: + """The formal argument for *args.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR: + return FormalArgument(None, position, type, False) + return None + + def kw_arg(self) -> FormalArgument | None: + """The formal argument for **kwargs.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR2: + return FormalArgument(None, position, type, False) + return None + + @property + def is_var_arg(self) -> bool: + """Does this callable have a *args argument?""" + return ARG_STAR in self.arg_kinds + + @property + def is_kw_arg(self) -> bool: + """Does this callable have a **kwargs argument?""" + return ARG_STAR2 in self.arg_kinds + + def is_type_obj(self) -> bool: + return self.fallback.type.is_metaclass() and not isinstance( + get_proper_type(self.ret_type), UninhabitedType + ) + + def type_object(self) -> mypy.nodes.TypeInfo: + assert self.is_type_obj() + ret = get_proper_type(self.ret_type) + if isinstance(ret, TypeVarType): + ret = get_proper_type(ret.upper_bound) + if isinstance(ret, TupleType): + ret = ret.partial_fallback + if isinstance(ret, TypedDictType): + ret = ret.fallback + if isinstance(ret, LiteralType): + ret = ret.fallback + assert isinstance(ret, Instance) + return ret.type + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_callable_type(self) + + def with_name(self, name: str) -> CallableType: + """Return a copy of this type with the specified name.""" + return self.copy_modified(ret_type=self.ret_type, name=name) + + def get_name(self) -> str | None: + return self.name + + def max_possible_positional_args(self) -> int: + """Returns maximum number of positional arguments this method could possibly accept. + + This takes into account *arg and **kwargs but excludes keyword-only args.""" + if self.is_var_arg or self.is_kw_arg: + return sys.maxsize + return sum(kind.is_positional() for kind in self.arg_kinds) + + def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]: + """Return a list of the formal arguments of this callable, ignoring *arg and **kwargs. + + To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields, + if they are not None. + + If you really want to include star args in the yielded output, set the + 'include_star_args' parameter to 'True'.""" + args = [] + done_with_positional = False + for i in range(len(self.arg_types)): + kind = self.arg_kinds[i] + if kind.is_named() or kind.is_star(): + done_with_positional = True + if not include_star_args and kind.is_star(): + continue + + required = kind.is_required() + pos = None if done_with_positional else i + arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required) + args.append(arg) + return args + + def argument_by_name(self, name: str | None) -> FormalArgument | None: + if name is None: + return None + seen_star = False + for i, (arg_name, kind, typ) in enumerate( + zip(self.arg_names, self.arg_kinds, self.arg_types) + ): + # No more positional arguments after these. + if kind.is_named() or kind.is_star(): + seen_star = True + if kind.is_star(): + continue + if arg_name == name: + position = None if seen_star else i + return FormalArgument(name, position, typ, kind.is_required()) + return self.try_synthesizing_arg_from_kwarg(name) + + def argument_by_position(self, position: int | None) -> FormalArgument | None: + if position is None: + return None + if position >= len(self.arg_names): + return self.try_synthesizing_arg_from_vararg(position) + name, kind, typ = ( + self.arg_names[position], + self.arg_kinds[position], + self.arg_types[position], + ) + if kind.is_positional(): + return FormalArgument(name, position, typ, kind == ARG_POS) + else: + return self.try_synthesizing_arg_from_vararg(position) + + def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None: + kw_arg = self.kw_arg() + if kw_arg is not None: + return FormalArgument(name, None, kw_arg.typ, False) + else: + return None + + def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None: + var_arg = self.var_arg() + if var_arg is not None: + return FormalArgument(None, position, var_arg.typ, False) + else: + return None + + @property + def items(self) -> list[CallableType]: + return [self] + + def is_generic(self) -> bool: + return bool(self.variables) + + def type_var_ids(self) -> list[TypeVarId]: + a: list[TypeVarId] = [] + for tv in self.variables: + a.append(tv.id) + return a + + def param_spec(self) -> ParamSpecType | None: + """Return ParamSpec if callable can be called with one. + + A Callable accepting ParamSpec P args (*args, **kwargs) must have the + two final parameters like this: *args: P.args, **kwargs: P.kwargs. + """ + if len(self.arg_types) < 2: + return None + if self.arg_kinds[-2] != ARG_STAR or self.arg_kinds[-1] != ARG_STAR2: + return None + arg_type = self.arg_types[-2] + if not isinstance(arg_type, ParamSpecType): + return None + + # Prepend prefix for def f(prefix..., *args: P.args, **kwargs: P.kwargs) -> ... + # TODO: confirm that all arg kinds are positional + prefix = Parameters(self.arg_types[:-2], self.arg_kinds[:-2], self.arg_names[:-2]) + return arg_type.copy_modified(flavor=ParamSpecFlavor.BARE, prefix=prefix) + + def normalize_trivial_unpack(self) -> None: + # Normalize trivial unpack in var args as *args: *tuple[X, ...] -> *args: X in place. + if self.is_var_arg: + star_index = self.arg_kinds.index(ARG_STAR) + star_type = self.arg_types[star_index] + if isinstance(star_type, UnpackType): + p_type = get_proper_type(star_type.type) + if isinstance(p_type, Instance): + assert p_type.type.fullname == "builtins.tuple" + self.arg_types[star_index] = p_type.args[0] + + def with_unpacked_kwargs(self) -> NormalizedCallableType: + if not self.unpack_kwargs: + return cast(NormalizedCallableType, self) + last_type = get_proper_type(self.arg_types[-1]) + assert isinstance(last_type, TypedDictType) + extra_kinds = [ + ArgKind.ARG_NAMED if name in last_type.required_keys else ArgKind.ARG_NAMED_OPT + for name in last_type.items + ] + new_arg_kinds = self.arg_kinds[:-1] + extra_kinds + new_arg_names = self.arg_names[:-1] + list(last_type.items) + new_arg_types = self.arg_types[:-1] + list(last_type.items.values()) + return NormalizedCallableType( + self.copy_modified( + arg_kinds=new_arg_kinds, + arg_names=new_arg_names, + arg_types=new_arg_types, + unpack_kwargs=False, + ) + ) + + def with_normalized_var_args(self) -> Self: + var_arg = self.var_arg() + if not var_arg or not isinstance(var_arg.typ, UnpackType): + return self + unpacked = get_proper_type(var_arg.typ.type) + if not isinstance(unpacked, TupleType): + # Note that we don't normalize *args: *tuple[X, ...] -> *args: X, + # this should be done once in semanal_typeargs.py for user-defined types, + # and we ourselves rarely construct such type. + return self + unpack_index = find_unpack_in_list(unpacked.items) + if unpack_index == 0 and len(unpacked.items) > 1: + # Already normalized. + return self + + # Boilerplate: + var_arg_index = self.arg_kinds.index(ARG_STAR) + types_prefix = self.arg_types[:var_arg_index] + kinds_prefix = self.arg_kinds[:var_arg_index] + names_prefix = self.arg_names[:var_arg_index] + types_suffix = self.arg_types[var_arg_index + 1 :] + kinds_suffix = self.arg_kinds[var_arg_index + 1 :] + names_suffix = self.arg_names[var_arg_index + 1 :] + no_name: str | None = None # to silence mypy + + # Now we have something non-trivial to do. + if unpack_index is None: + # Plain *Tuple[X, Y, Z] -> replace with ARG_POS completely + types_middle = unpacked.items + kinds_middle = [ARG_POS] * len(unpacked.items) + names_middle = [no_name] * len(unpacked.items) + else: + # *Tuple[X, *Ts, Y, Z] or *Tuple[X, *tuple[T, ...], X, Z], here + # we replace the prefix by ARG_POS (this is how some places expect + # Callables to be represented) + nested_unpack = unpacked.items[unpack_index] + assert isinstance(nested_unpack, UnpackType) + nested_unpacked = get_proper_type(nested_unpack.type) + if unpack_index == len(unpacked.items) - 1: + # Normalize also single item tuples like + # *args: *Tuple[*tuple[X, ...]] -> *args: X + # *args: *Tuple[*Ts] -> *args: *Ts + # This may be not strictly necessary, but these are very verbose. + if isinstance(nested_unpacked, Instance): + assert nested_unpacked.type.fullname == "builtins.tuple" + new_unpack = nested_unpacked.args[0] + else: + if not isinstance(nested_unpacked, TypeVarTupleType): + # We found a non-normalized tuple type, this means this method + # is called during semantic analysis (e.g. from get_proper_type()) + # there is no point in normalizing callables at this stage. + return self + new_unpack = nested_unpack + else: + new_unpack = UnpackType( + unpacked.copy_modified(items=unpacked.items[unpack_index:]) + ) + types_middle = unpacked.items[:unpack_index] + [new_unpack] + kinds_middle = [ARG_POS] * unpack_index + [ARG_STAR] + names_middle = [no_name] * unpack_index + [self.arg_names[var_arg_index]] + return self.copy_modified( + arg_types=types_prefix + types_middle + types_suffix, + arg_kinds=kinds_prefix + kinds_middle + kinds_suffix, + arg_names=names_prefix + names_middle + names_suffix, + ) + + def __hash__(self) -> int: + return hash( + ( + self.ret_type, + self.is_ellipsis_args, + self.name, + tuple(self.arg_types), + tuple(self.arg_names), + tuple(self.arg_kinds), + self.fallback, + ) + ) + + def __eq__(self, other: object) -> bool: + if isinstance(other, CallableType): + return ( + self.ret_type == other.ret_type + and self.arg_types == other.arg_types + and self.arg_names == other.arg_names + and self.arg_kinds == other.arg_kinds + and self.name == other.name + and self.is_ellipsis_args == other.is_ellipsis_args + and self.type_guard == other.type_guard + and self.type_is == other.type_is + and self.fallback == other.fallback + ) + else: + return NotImplemented + + def serialize(self) -> JsonDict: + # TODO: As an optimization, leave out everything related to + # generic functions for non-generic functions. + return { + ".class": "CallableType", + "arg_types": [t.serialize() for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "ret_type": self.ret_type.serialize(), + "fallback": self.fallback.serialize(), + "name": self.name, + # We don't serialize the definition (only used for error messages). + "variables": [v.serialize() for v in self.variables], + "is_ellipsis_args": self.is_ellipsis_args, + "implicit": self.implicit, + "is_bound": self.is_bound, + "type_guard": self.type_guard.serialize() if self.type_guard is not None else None, + "type_is": (self.type_is.serialize() if self.type_is is not None else None), + "from_concatenate": self.from_concatenate, + "imprecise_arg_kinds": self.imprecise_arg_kinds, + "unpack_kwargs": self.unpack_kwargs, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> CallableType: + assert data[".class"] == "CallableType" + # The .definition link is set in fixup.py. + return CallableType( + [deserialize_type(t) for t in data["arg_types"]], + [ARG_KINDS[x] for x in data["arg_kinds"]], + data["arg_names"], + deserialize_type(data["ret_type"]), + Instance.deserialize(data["fallback"]), + name=data["name"], + variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]], + is_ellipsis_args=data["is_ellipsis_args"], + implicit=data["implicit"], + is_bound=data["is_bound"], + type_guard=( + deserialize_type(data["type_guard"]) if data["type_guard"] is not None else None + ), + type_is=(deserialize_type(data["type_is"]) if data["type_is"] is not None else None), + from_concatenate=data["from_concatenate"], + imprecise_arg_kinds=data["imprecise_arg_kinds"], + unpack_kwargs=data["unpack_kwargs"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, CALLABLE_TYPE) + self.fallback.write(data) + write_type_list(data, self.arg_types) + write_int_list(data, [int(x.value) for x in self.arg_kinds]) + write_str_opt_list(data, self.arg_names) + self.ret_type.write(data) + write_str_opt(data, self.name) + write_type_list(data, self.variables) + write_bool(data, self.is_ellipsis_args) + write_bool(data, self.implicit) + write_bool(data, self.is_bound) + write_type_opt(data, self.type_guard) + write_type_opt(data, self.type_is) + write_bool(data, self.from_concatenate) + write_bool(data, self.imprecise_arg_kinds) + write_bool(data, self.unpack_kwargs) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> CallableType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = CallableType( + read_type_list(data), + [ARG_KINDS[ak] for ak in read_int_list(data)], + read_str_opt_list(data), + read_type(data), + fallback, + name=read_str_opt(data), + variables=read_type_var_likes(data), + is_ellipsis_args=read_bool(data), + implicit=read_bool(data), + is_bound=read_bool(data), + type_guard=read_type_opt(data), + type_is=read_type_opt(data), + from_concatenate=read_bool(data), + imprecise_arg_kinds=read_bool(data), + unpack_kwargs=read_bool(data), + ) + assert read_tag(data) == END_TAG + return ret + + +# This is a little safety net to prevent reckless special-casing of callables +# that can potentially break Unpack[...] with **kwargs. +# TODO: use this in more places in checkexpr.py etc? +NormalizedCallableType = NewType("NormalizedCallableType", CallableType) + + +class Overloaded(FunctionLike): + """Overloaded function type T1, ... Tn, where each Ti is CallableType. + + The variant to call is chosen based on static argument + types. Overloaded function types can only be defined in stub + files, and thus there is no explicit runtime dispatch + implementation. + """ + + __slots__ = ("_items",) + + _items: list[CallableType] # Must not be empty + + def __init__(self, items: list[CallableType]) -> None: + super().__init__(items[0].line, items[0].column) + self._items = items + self.fallback = items[0].fallback + + @property + def items(self) -> list[CallableType]: + return self._items + + def name(self) -> str | None: + return self.get_name() + + def is_type_obj(self) -> bool: + # All the items must have the same type object status, so it's + # sufficient to query only (any) one of them. + return self._items[0].is_type_obj() + + def type_object(self) -> mypy.nodes.TypeInfo: + # All the items must have the same type object, so it's sufficient to + # query only (any) one of them. + return self._items[0].type_object() + + def with_name(self, name: str) -> Overloaded: + ni: list[CallableType] = [] + for it in self._items: + ni.append(it.with_name(name)) + return Overloaded(ni) + + def get_name(self) -> str | None: + return self._items[0].name + + def with_unpacked_kwargs(self) -> Overloaded: + if any(i.unpack_kwargs for i in self.items): + return Overloaded([i.with_unpacked_kwargs() for i in self.items]) + return self + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_overloaded(self) + + def __hash__(self) -> int: + return hash(tuple(self.items)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Overloaded): + return NotImplemented + return self.items == other.items + + def serialize(self) -> JsonDict: + return {".class": "Overloaded", "items": [t.serialize() for t in self.items]} + + @classmethod + def deserialize(cls, data: JsonDict) -> Overloaded: + assert data[".class"] == "Overloaded" + return Overloaded([CallableType.deserialize(t) for t in data["items"]]) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, OVERLOADED) + write_type_list(data, self.items) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Overloaded: + items = [] + assert read_tag(data) == LIST_GEN + for _ in range(read_int_bare(data)): + assert read_tag(data) == CALLABLE_TYPE + items.append(CallableType.read(data)) + assert read_tag(data) == END_TAG + return Overloaded(items) + + +class TupleType(ProperType): + """The tuple type Tuple[T1, ..., Tn] (at least one type argument). + + Instance variables: + items: Tuple item types + partial_fallback: The (imprecise) underlying instance type that is used + for non-tuple methods. This is generally builtins.tuple[Any, ...] for + regular tuples, but it's different for named tuples and classes with + a tuple base class. Use mypy.typeops.tuple_fallback to calculate the + precise fallback type derived from item types. + implicit: If True, derived from a tuple expression (t,....) instead of Tuple[t, ...] + """ + + __slots__ = ("items", "partial_fallback", "implicit") + + items: list[Type] + partial_fallback: Instance + implicit: bool + + def __init__( + self, + items: list[Type], + fallback: Instance, + line: int = -1, + column: int = -1, + implicit: bool = False, + ) -> None: + super().__init__(line, column) + self.partial_fallback = fallback + self.items = items + self.implicit = implicit + + def can_be_true_default(self) -> bool: + if self.can_be_any_bool(): + # Corner case: it is a `NamedTuple` with `__bool__` method defined. + # It can be anything: both `True` and `False`. + return True + return self.length() > 0 + + def can_be_false_default(self) -> bool: + if self.can_be_any_bool(): + # Corner case: it is a `NamedTuple` with `__bool__` method defined. + # It can be anything: both `True` and `False`. + return True + if self.length() == 0: + return True + if self.length() > 1: + return False + # Special case tuple[*Ts] may or may not be false. + item = self.items[0] + if not isinstance(item, UnpackType): + return False + if not isinstance(item.type, TypeVarTupleType): + # Non-normalized tuple[int, ...] can be false. + return True + return item.type.min_len == 0 + + def can_be_any_bool(self) -> bool: + return bool( + self.partial_fallback.type + and self.partial_fallback.type.fullname != "builtins.tuple" + and self.partial_fallback.type.names.get("__bool__") + ) + + def length(self) -> int: + return len(self.items) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_tuple_type(self) + + def __hash__(self) -> int: + return hash((tuple(self.items), self.partial_fallback)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TupleType): + return NotImplemented + return self.items == other.items and self.partial_fallback == other.partial_fallback + + def serialize(self) -> JsonDict: + return { + ".class": "TupleType", + "items": [t.serialize() for t in self.items], + "partial_fallback": self.partial_fallback.serialize(), + "implicit": self.implicit, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TupleType: + assert data[".class"] == "TupleType" + return TupleType( + [deserialize_type(t) for t in data["items"]], + Instance.deserialize(data["partial_fallback"]), + implicit=data["implicit"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TUPLE_TYPE) + self.partial_fallback.write(data) + write_type_list(data, self.items) + write_bool(data, self.implicit) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TupleType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = TupleType(read_type_list(data), fallback, implicit=read_bool(data)) + assert read_tag(data) == END_TAG + return ret + + def copy_modified( + self, *, fallback: Instance | None = None, items: list[Type] | None = None + ) -> TupleType: + if fallback is None: + fallback = self.partial_fallback + if items is None: + items = self.items + return TupleType(items, fallback, self.line, self.column) + + def slice( + self, begin: int | None, end: int | None, stride: int | None, *, fallback: Instance | None + ) -> TupleType | None: + if fallback is None: + fallback = self.partial_fallback + + if stride == 0: + return None + + if any(isinstance(t, UnpackType) for t in self.items): + total = len(self.items) + unpack_index = find_unpack_in_list(self.items) + assert unpack_index is not None + if begin is None and end is None: + # We special-case this to support reversing variadic tuples. + # General support for slicing is tricky, so we handle only simple cases. + if stride == -1: + slice_items = self.items[::-1] + elif stride is None or stride == 1: + slice_items = self.items + else: + return None + elif (begin is None or unpack_index >= begin >= 0) and ( + end is not None and unpack_index >= end >= 0 + ): + # Start and end are in the prefix, everything works in this case. + slice_items = self.items[begin:end:stride] + elif (begin is not None and unpack_index - total < begin < 0) and ( + end is None or unpack_index - total < end < 0 + ): + # Start and end are in the suffix, everything works in this case. + slice_items = self.items[begin:end:stride] + elif (begin is None or unpack_index >= begin >= 0) and ( + end is None or unpack_index - total < end < 0 + ): + # Start in the prefix, end in the suffix, we can support only trivial strides. + if stride is None or stride == 1: + slice_items = self.items[begin:end:stride] + else: + return None + elif (begin is not None and unpack_index - total < begin < 0) and ( + end is not None and unpack_index >= end >= 0 + ): + # Start in the suffix, end in the prefix, we can support only trivial strides. + if stride is None or stride == -1: + slice_items = self.items[begin:end:stride] + else: + return None + else: + # TODO: there some additional cases we can support for homogeneous variadic + # items, we can "eat away" finite number of items. + return None + else: + slice_items = self.items[begin:end:stride] + return TupleType(slice_items, fallback, self.line, self.column, self.implicit) + + +class TypedDictType(ProperType): + """Type of TypedDict object {'k1': v1, ..., 'kn': vn}. + + A TypedDict object is a dictionary with specific string (literal) keys. Each + key has a value with a distinct type that depends on the key. TypedDict objects + are normal dict objects at runtime. + + A TypedDictType can be either named or anonymous. If it's anonymous, its + fallback will be typing_extensions._TypedDict (Instance). _TypedDict is a subclass + of Mapping[str, object] and defines all non-mapping dict methods that TypedDict + supports. Some dict methods are unsafe and not supported. _TypedDict isn't defined + at runtime. + + If a TypedDict is named, its fallback will be an Instance of the named type + (ex: "Point") whose TypeInfo has a typeddict_type that is anonymous. This + is similar to how named tuples work. + + TODO: The fallback structure is perhaps overly complicated. + """ + + __slots__ = ( + "items", + "required_keys", + "readonly_keys", + "fallback", + "extra_items_from", + "to_be_mutated", + ) + + items: dict[str, Type] # item_name -> item_type + required_keys: set[str] + readonly_keys: set[str] + fallback: Instance + + extra_items_from: list[ProperType] # only used during semantic analysis + to_be_mutated: bool # only used in a plugin for `.update`, `|=`, etc + + def __init__( + self, + items: dict[str, Type], + required_keys: set[str], + readonly_keys: set[str], + fallback: Instance, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.items = items + self.required_keys = required_keys + self.readonly_keys = readonly_keys + self.fallback = fallback + self.can_be_true = len(self.items) > 0 + self.can_be_false = len(self.required_keys) == 0 + self.extra_items_from = [] + self.to_be_mutated = False + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_typeddict_type(self) + + def __hash__(self) -> int: + return hash( + ( + frozenset(self.items.items()), + self.fallback, + frozenset(self.required_keys), + frozenset(self.readonly_keys), + ) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypedDictType): + return NotImplemented + if self is other: + return True + return ( + frozenset(self.items.keys()) == frozenset(other.items.keys()) + and all( + left_item_type == right_item_type + for (_, left_item_type, right_item_type) in self.zip(other) + ) + and self.fallback == other.fallback + and self.required_keys == other.required_keys + and self.readonly_keys == other.readonly_keys + ) + + def serialize(self) -> JsonDict: + return { + ".class": "TypedDictType", + "items": [[n, t.serialize()] for (n, t) in self.items.items()], + "required_keys": sorted(self.required_keys), + "readonly_keys": sorted(self.readonly_keys), + "fallback": self.fallback.serialize(), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypedDictType: + assert data[".class"] == "TypedDictType" + return TypedDictType( + {n: deserialize_type(t) for (n, t) in data["items"]}, + set(data["required_keys"]), + set(data["readonly_keys"]), + Instance.deserialize(data["fallback"]), + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPED_DICT_TYPE) + self.fallback.write(data) + write_type_map(data, self.items) + write_str_list(data, sorted(self.required_keys)) + write_str_list(data, sorted(self.readonly_keys)) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypedDictType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = TypedDictType( + read_type_map(data), set(read_str_list(data)), set(read_str_list(data)), fallback + ) + assert read_tag(data) == END_TAG + return ret + + @property + def is_final(self) -> bool: + return self.fallback.type.is_final + + def is_anonymous(self) -> bool: + return self.fallback.type.fullname in TPDICT_FB_NAMES + + def create_anonymous_fallback(self) -> Instance: + if self.is_anonymous(): + return self.fallback + assert self.fallback.type.typeddict_type is not None + return self.fallback.type.typeddict_type.create_anonymous_fallback() + + def copy_modified( + self, + *, + fallback: Instance | None = None, + item_types: list[Type] | None = None, + item_names: list[str] | None = None, + required_keys: set[str] | None = None, + readonly_keys: set[str] | None = None, + ) -> TypedDictType: + if fallback is None: + fallback = self.fallback + if item_types is None: + items = self.items + else: + items = dict(zip(self.items, item_types)) + if required_keys is None: + required_keys = self.required_keys + if readonly_keys is None: + readonly_keys = self.readonly_keys + if item_names is not None: + items = {k: v for (k, v) in items.items() if k in item_names} + required_keys &= set(item_names) + return TypedDictType(items, required_keys, readonly_keys, fallback, self.line, self.column) + + def names_are_wider_than(self, other: TypedDictType) -> bool: + return len(other.items.keys() - self.items.keys()) == 0 + + def zip(self, right: TypedDictType) -> Iterable[tuple[str, Type, Type]]: + left = self + for item_name, left_item_type in left.items.items(): + right_item_type = right.items.get(item_name) + if right_item_type is not None: + yield (item_name, left_item_type, right_item_type) + + def zipall(self, right: TypedDictType) -> Iterable[tuple[str, Type | None, Type | None]]: + left = self + for item_name, left_item_type in left.items.items(): + right_item_type = right.items.get(item_name) + yield (item_name, left_item_type, right_item_type) + for item_name, right_item_type in right.items.items(): + if item_name in left.items: + continue + yield (item_name, None, right_item_type) + + +class RawExpressionType(ProperType): + """A synthetic type representing some arbitrary expression that does not cleanly + translate into a type. + + This synthetic type is only used at the beginning stages of semantic analysis + and should be completely removing during the process for mapping UnboundTypes to + actual types: we either turn it into a LiteralType or an AnyType. + + For example, suppose `Foo[1]` is initially represented as the following: + + UnboundType( + name='Foo', + args=[ + RawExpressionType(value=1, base_type_name='builtins.int'), + ], + ) + + As we perform semantic analysis, this type will transform into one of two + possible forms. + + If 'Foo' was an alias for 'Literal' all along, this type is transformed into: + + LiteralType(value=1, fallback=int_instance_here) + + Alternatively, if 'Foo' is an unrelated class, we report an error and instead + produce something like this: + + Instance(type=typeinfo_for_foo, args=[AnyType(TypeOfAny.from_error)) + + If the "note" field is not None, the provided note will be reported alongside the + error at this point. + + Note: if "literal_value" is None, that means this object is representing some + expression that cannot possibly be a parameter of Literal[...]. For example, + "Foo[3j]" would be represented as: + + UnboundType( + name='Foo', + args=[ + RawExpressionType(value=None, base_type_name='builtins.complex'), + ], + ) + """ + + __slots__ = ("literal_value", "base_type_name", "note") + + def __init__( + self, + literal_value: LiteralValue | None, + base_type_name: str, + line: int = -1, + column: int = -1, + note: str | None = None, + ) -> None: + super().__init__(line, column) + self.literal_value = literal_value + self.base_type_name = base_type_name + self.note = note + + def simple_name(self) -> str: + return self.base_type_name.replace("builtins.", "") + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_raw_expression_type(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + def __hash__(self) -> int: + return hash((self.literal_value, self.base_type_name)) + + def __eq__(self, other: object) -> bool: + if isinstance(other, RawExpressionType): + return ( + self.base_type_name == other.base_type_name + and self.literal_value == other.literal_value + ) + else: + return NotImplemented + + +class LiteralType(ProperType): + """The type of a Literal instance. Literal[Value] + + A Literal always consists of: + + 1. A native Python object corresponding to the contained inner value + 2. A fallback for this Literal. The fallback also corresponds to the + parent type this Literal subtypes. + + For example, 'Literal[42]' is represented as + 'LiteralType(value=42, fallback=instance_of_int)' + + As another example, `Literal[Color.RED]` (where Color is an enum) is + represented as `LiteralType(value="RED", fallback=instance_of_color)'. + """ + + __slots__ = ("value", "fallback", "_hash") + + def __init__( + self, value: LiteralValue, fallback: Instance, line: int = -1, column: int = -1 + ) -> None: + super().__init__(line, column) + self.value = value + self.fallback = fallback + + # NOTE: Enum types are always truthy by default, but this can be changed + # in subclasses, so we need to get the truthyness from the Enum + # type rather than base it on the value (which is a non-empty + # string for enums, so always truthy) + # TODO: We should consider moving this branch to the `can_be_true` + # `can_be_false` properties instead, so the truthyness only + # needs to be determined once per set of Enum literals. + # However, the same can be said for `TypeAliasType` in some + # cases and we only set the default based on the type it is + # aliasing. So if we decide to change this, we may want to + # change that as well. perf_compare output was inconclusive + # but slightly favored this version, probably because we have + # almost no test cases where we would redundantly compute + # `can_be_false`/`can_be_true`. + def can_be_false_default(self) -> bool: + if self.fallback.type.is_enum: + return self.fallback.can_be_false + return not self.value + + def can_be_true_default(self) -> bool: + if self.fallback.type.is_enum: + return self.fallback.can_be_true + return bool(self.value) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_literal_type(self) + + def __hash__(self) -> int: + # Intentionally a subset of __eq__ for perf + return hash(self.value) + + def __eq__(self, other: object) -> bool: + if isinstance(other, LiteralType): + return self.value == other.value and self.fallback == other.fallback + else: + return NotImplemented + + def is_enum_literal(self) -> bool: + return self.fallback.type.is_enum + + def value_repr(self) -> str: + """Returns the string representation of the underlying type. + + This function is almost equivalent to running `repr(self.value)`, + except it includes some additional logic to correctly handle cases + where the value is a string, byte string, a unicode string, or an enum. + """ + raw = repr(self.value) + fallback_name = self.fallback.type.fullname + + # If this is backed by an enum, + if self.is_enum_literal(): + return f"{fallback_name}.{self.value}" + + if fallback_name == "builtins.bytes": + # Note: 'builtins.bytes' only appears in Python 3, so we want to + # explicitly prefix with a "b" + return "b" + raw + else: + # 'builtins.str' could mean either depending on context, but either way + # we don't prefix: it's the "native" string. And of course, if value is + # some other type, we just return that string repr directly. + return raw + + def serialize(self) -> JsonDict | str: + return { + ".class": "LiteralType", + "value": self.value, + "fallback": self.fallback.serialize(), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> LiteralType: + assert data[".class"] == "LiteralType" + return LiteralType(value=data["value"], fallback=Instance.deserialize(data["fallback"])) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, LITERAL_TYPE) + self.fallback.write(data) + write_literal(data, self.value) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> LiteralType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + tag = read_tag(data) + ret = LiteralType(read_literal(data, tag), fallback) + assert read_tag(data) == END_TAG + return ret + + +class UnionType(ProperType): + """The union type Union[T1, ..., Tn] (at least one type argument).""" + + __slots__ = ( + "items", + "is_evaluated", + "uses_pep604_syntax", + "original_str_expr", + "original_str_fallback", + ) + + def __init__( + self, + items: Sequence[Type], + line: int = -1, + column: int = -1, + *, + is_evaluated: bool = True, + uses_pep604_syntax: bool = False, + ) -> None: + super().__init__(line, column) + # We must keep this false to avoid crashes during semantic analysis. + # TODO: maybe switch this to True during type-checking pass? + self.items = flatten_nested_unions(items, handle_type_alias_type=False) + # is_evaluated should be set to false for type comments and string literals + self.is_evaluated = is_evaluated + # uses_pep604_syntax is True if Union uses OR syntax (X | Y) + self.uses_pep604_syntax = uses_pep604_syntax + # The meaning of these two is the same as for UnboundType. A UnionType can be + # return by type parser from a string "A|B", and we need to be able to fall back + # to plain string, when such a string appears inside a Literal[...]. + self.original_str_expr: str | None = None + self.original_str_fallback: str | None = None + + def can_be_true_default(self) -> bool: + return any(item.can_be_true for item in self.items) + + def can_be_false_default(self) -> bool: + return any(item.can_be_false for item in self.items) + + def __hash__(self) -> int: + return hash(frozenset(self.items)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnionType): + return NotImplemented + if self is other: + return True + return frozenset(self.items) == frozenset(other.items) + + @overload + @staticmethod + def make_union( + items: Sequence[ProperType], line: int = -1, column: int = -1 + ) -> ProperType: ... + + @overload + @staticmethod + def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type: ... + + @staticmethod + def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type: + if len(items) > 1: + return UnionType(items, line, column) + elif len(items) == 1: + return items[0] + else: + return UninhabitedType() + + def length(self) -> int: + return len(self.items) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_union_type(self) + + def relevant_items(self) -> list[Type]: + """Removes NoneTypes from Unions when strict Optional checking is off.""" + if state.strict_optional: + return self.items + else: + return [i for i in self.items if not isinstance(get_proper_type(i), NoneType)] + + def serialize(self) -> JsonDict: + return { + ".class": "UnionType", + "items": [t.serialize() for t in self.items], + "uses_pep604_syntax": self.uses_pep604_syntax, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> UnionType: + assert data[".class"] == "UnionType" + return UnionType( + [deserialize_type(t) for t in data["items"]], + uses_pep604_syntax=data["uses_pep604_syntax"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNION_TYPE) + write_type_list(data, self.items) + write_bool(data, self.uses_pep604_syntax) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UnionType: + ret = UnionType(read_type_list(data), uses_pep604_syntax=read_bool(data)) + assert read_tag(data) == END_TAG + return ret + + +class PartialType(ProperType): + """Type such as List[?] where type arguments are unknown, or partial None type. + + These are used for inferring types in multiphase initialization such as this: + + x = [] # x gets a partial type List[?], as item type is unknown + x.append(1) # partial type gets replaced with normal type List[int] + + Or with None: + + x = None # x gets a partial type None + if c: + x = 1 # Infer actual type int for x + """ + + __slots__ = ("type", "var", "value_type") + + # None for the 'None' partial type; otherwise a generic class + type: mypy.nodes.TypeInfo | None + var: mypy.nodes.Var + # For partial defaultdict[K, V], the type V (K is unknown). If V is generic, + # the type argument is Any and will be replaced later. + value_type: Instance | None + + def __init__( + self, + type: mypy.nodes.TypeInfo | None, + var: mypy.nodes.Var, + value_type: Instance | None = None, + ) -> None: + super().__init__() + self.type = type + self.var = var + self.value_type = value_type + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_partial_type(self) + + +class EllipsisType(ProperType): + """The type ... (ellipsis). + + This is not a real type but a syntactic AST construct, used in Callable[..., T], for example. + + A semantically analyzed type will never have ellipsis types. + """ + + __slots__ = () + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_ellipsis_type(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + +class TypeType(ProperType): + """For types like Type[User] or TypeForm[User | None]. + + Type[C] annotates variables that are class objects, constrained by + the type argument. See PEP 484 for more details. + + TypeForm[T] annotates variables that hold the result of evaluating + a type expression. See PEP 747 for more details. + + We may encounter expressions whose values are specific classes; + those are represented as callables (possibly overloaded) + corresponding to the class's constructor's signature and returning + an instance of that class. The difference with Type[C] is that + those callables always represent the exact class given as the + return type; Type[C] represents any class that's a subclass of C, + and C may also be a type variable or a union (or Any). + + Many questions around subtype relationships between Type[C1] and + def(...) -> C2 are answered by looking at the subtype + relationships between C1 and C2, since Type[] is considered + covariant. + + There's an unsolved problem with constructor signatures (also + unsolved in PEP 484): calling a variable whose type is Type[C] + assumes the constructor signature for C, even though a subclass of + C might completely change the constructor signature. For now we + just assume that users of Type[C] are careful not to do that (in + the future we might detect when they are violating that + assumption). + """ + + __slots__ = ("item", "is_type_form") + + # This can't be everything, but it can be a class reference, + # a generic class instance, a union, Any, a type variable... + item: ProperType + + # If True then this TypeType represents a TypeForm[T]. + # If False then this TypeType represents a Type[C]. + is_type_form: bool + + def __init__( + self, + item: Bogus[Instance | AnyType | TypeVarType | TupleType | NoneType | CallableType], + *, + line: int = -1, + column: int = -1, + is_type_form: bool = False, + ) -> None: + """To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of + type UnionType must be handled through make_normalized static method. + """ + super().__init__(line, column) + self.item = item + self.is_type_form = is_type_form + + @staticmethod + def make_normalized( + item: Type, *, line: int = -1, column: int = -1, is_type_form: bool = False + ) -> ProperType: + item = get_proper_type(item) + if is_type_form: + # Don't convert TypeForm[X | Y] to (TypeForm[X] | TypeForm[Y]) + pass + else: + if isinstance(item, UnionType): + return UnionType.make_union( + [TypeType.make_normalized(union_item) for union_item in item.items], + line=line, + column=column, + ) + return TypeType(item, line=line, column=column, is_type_form=is_type_form) # type: ignore[arg-type] + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_type(self) + + def __hash__(self) -> int: + return hash(self.item) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypeType): + return NotImplemented + return self.item == other.item and self.is_type_form == other.is_type_form + + def serialize(self) -> JsonDict: + return { + ".class": "TypeType", + "item": self.item.serialize(), + "is_type_form": self.is_type_form, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> Type: + assert data[".class"] == "TypeType" + return TypeType.make_normalized( + deserialize_type(data["item"]), is_type_form=data["is_type_form"] + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_TYPE) + self.item.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Type: + ret = TypeType.make_normalized(read_type(data)) + assert read_tag(data) == END_TAG + return ret + + +class PlaceholderType(ProperType): + """Temporary, yet-unknown type during semantic analysis. + + This is needed when there's a reference to a type before the real symbol + table entry of the target type is available (specifically, we use a + temporary PlaceholderNode symbol node). Consider this example: + + class str(Sequence[str]): ... + + We use a PlaceholderType for the 'str' in 'Sequence[str]' since we can't create + a TypeInfo for 'str' until all base classes have been resolved. We'll soon + perform another analysis iteration which replaces the base class with a complete + type without any placeholders. After semantic analysis, no placeholder types must + exist. + """ + + __slots__ = ("fullname", "args") + + def __init__(self, fullname: str | None, args: list[Type], line: int) -> None: + super().__init__(line) + self.fullname = fullname # Must be a valid full name of an actual node (or None). + self.args = args + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_placeholder_type(self) + return ret + + def __hash__(self) -> int: + return hash((self.fullname, tuple(self.args))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PlaceholderType): + return NotImplemented + return self.fullname == other.fullname and self.args == other.args + + def serialize(self) -> str: + # We should never get here since all placeholders should be replaced + # during semantic analysis. + assert False, f"Internal error: unresolved placeholder type {self.fullname}" + + +@overload +def get_proper_type(typ: None) -> None: ... + + +@overload +def get_proper_type(typ: Type) -> ProperType: ... + + +def get_proper_type(typ: Type | None) -> ProperType | None: + """Get the expansion of a type alias type. + + If the type is already a proper type, this is a no-op. Use this function + wherever a decision is made on a call like e.g. 'if isinstance(typ, UnionType): ...', + because 'typ' in this case may be an alias to union. Note: if after making the decision + on the isinstance() call you pass on the original type (and not one of its components) + it is recommended to *always* pass on the unexpanded alias. + """ + if typ is None: + return None + # TODO: this is an ugly hack, remove. + if isinstance(typ, TypeGuardedType): + typ = typ.type_guard + while isinstance(typ, TypeAliasType): + typ = typ._expand_once() + # TODO: store the name of original type alias on this type, so we can show it in errors. + return cast(ProperType, typ) + + +@overload +def get_proper_types(types: list[Type] | tuple[Type, ...]) -> list[ProperType]: ... + + +@overload +def get_proper_types( + types: list[Type | None] | tuple[Type | None, ...], +) -> list[ProperType | None]: ... + + +def get_proper_types( + types: list[Type] | list[Type | None] | tuple[Type | None, ...], +) -> list[ProperType] | list[ProperType | None]: + if isinstance(types, list): + typelist = types + # Optimize for the common case so that we don't need to allocate anything + if not any(isinstance(t, (TypeAliasType, TypeGuardedType)) for t in typelist): + return cast("list[ProperType]", typelist) + return [get_proper_type(t) for t in typelist] + else: + return [get_proper_type(t) for t in types] + + +# We split off the type visitor base classes to another module +# to make it easier to gradually get modules working with mypyc. +# Import them here, after the types are defined. +# This is intended as a re-export also. +from mypy.type_visitor import ( + ALL_STRATEGY as ALL_STRATEGY, + ANY_STRATEGY as ANY_STRATEGY, + BoolTypeQuery as BoolTypeQuery, + SyntheticTypeVisitor as SyntheticTypeVisitor, + TypeQuery as TypeQuery, + TypeTranslator as TypeTranslator, + TypeVisitor as TypeVisitor, +) + + +class TypeStrVisitor(SyntheticTypeVisitor[str]): + """Visitor for pretty-printing types into strings. + + This is mostly for debugging/testing. + + Do not preserve original formatting. + + Notes: + - Represent unbound types as Foo? or Foo?[...]. + - Represent the NoneType type as None. + - Represent Union[x, y] as x | y + """ + + def __init__(self, id_mapper: IdMapper | None = None, *, options: Options) -> None: + self.id_mapper = id_mapper + self.options = options + self.dotted_aliases: set[TypeAliasType] | None = None + + def visit_unbound_type(self, t: UnboundType, /) -> str: + s = t.name + "?" + if t.args: + s += f"[{self.list_str(t.args)}]" + return s + + def visit_type_list(self, t: TypeList, /) -> str: + return f"" + + def visit_callable_argument(self, t: CallableArgument, /) -> str: + typ = t.typ.accept(self) + if t.name is None: + return f"{t.constructor}({typ})" + else: + return f"{t.constructor}({typ}, {t.name})" + + def visit_any(self, t: AnyType, /) -> str: + return "Any" + + def visit_none_type(self, t: NoneType, /) -> str: + return "None" + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> str: + return "Never" + + def visit_erased_type(self, t: ErasedType, /) -> str: + return "" + + def visit_deleted_type(self, t: DeletedType, /) -> str: + if t.source is None: + return "" + else: + return f"" + + def visit_instance(self, t: Instance, /) -> str: + fullname = t.type.fullname + if not self.options.reveal_verbose_types and fullname.startswith("builtins."): + fullname = t.type.name + if t.last_known_value and not t.args: + # Instances with a literal fallback should never be generic. If they are, + # something went wrong so we fall back to showing the full Instance repr. + s = f"{t.last_known_value.accept(self)}?" + + else: + s = fullname or t.type.name or "" + + if t.args: + if t.type.fullname == "builtins.tuple": + assert len(t.args) == 1 + s += f"[{self.list_str(t.args)}, ...]" + else: + s += f"[{self.list_str(t.args)}]" + elif t.type.has_type_var_tuple_type and len(t.type.type_vars) == 1: + s += "[()]" + if self.id_mapper: + s += f"<{self.id_mapper.id(t.type)}>" + return s + + def visit_type_var(self, t: TypeVarType, /) -> str: + if not self.options.reveal_verbose_types: + s = t.name + else: + s = f"{t.name}`{t.id}" + if self.id_mapper and t.upper_bound: + s += f"(upper_bound={t.upper_bound.accept(self)})" + if t.has_default() and self.options.reveal_verbose_types: + s += f" = {t.default.accept(self)}" + # TODO: disambiguate type variables with same name using namespace. + # We should reuse find_type_overlaps() and scoped_type_var_name(). + return s + + def visit_param_spec(self, t: ParamSpecType, /) -> str: + # prefixes are displayed as Concatenate + s = "" + if t.prefix.arg_types: + s += f"[{self.list_str(t.prefix.arg_types)}, **" + if not self.options.reveal_verbose_types: + s += t.name_with_suffix() + else: + s += f"{t.name_with_suffix()}`{t.id}" + if t.prefix.arg_types: + s += "]" + if t.has_default() and self.options.reveal_verbose_types: + s += f" = {t.default.accept(self)}" + return s + + def visit_parameters(self, t: Parameters, /) -> str: + # This is copied from visit_callable -- is there a way to decrease duplication? + if t.is_ellipsis_args: + return "..." + + s = "" + bare_asterisk = False + for i in range(len(t.arg_types)): + if s != "": + s += ", " + if t.arg_kinds[i].is_named() and not bare_asterisk: + s += "*, " + bare_asterisk = True + if t.arg_kinds[i] == ARG_STAR: + s += "*" + if t.arg_kinds[i] == ARG_STAR2: + s += "**" + name = t.arg_names[i] + if name: + s += f"{name}: " + r = t.arg_types[i].accept(self) + + s += r + + if t.arg_kinds[i].is_optional(): + s += " =" + + return f"[{s}]" + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> str: + if not self.options.reveal_verbose_types: + s = t.name + else: + s = f"{t.name}`{t.id}" + if t.has_default() and self.options.reveal_verbose_types: + s += f" = {t.default.accept(self)}" + return s + + def visit_callable_type(self, t: CallableType, /) -> str: + param_spec = t.param_spec() + if param_spec is not None: + num_skip = 2 + else: + num_skip = 0 + + s = "" + asterisk = False + for i in range(len(t.arg_types) - num_skip): + if s != "": + s += ", " + if t.arg_kinds[i].is_named() and not asterisk: + s += "*, " + asterisk = True + if t.arg_kinds[i] == ARG_STAR: + s += "*" + asterisk = True + if t.arg_kinds[i] == ARG_STAR2: + s += "**" + name = t.arg_names[i] + if not name and not self.options.reveal_verbose_types: + # Avoid ambiguous (and weird) formatting for anonymous args/kwargs. + if t.arg_kinds[i] == ARG_STAR and isinstance(t.arg_types[i], UnpackType): + name = "args" + elif t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs: + name = "kwargs" + if name: + s += name + ": " + type_str = t.arg_types[i].accept(self) + if t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs: + if not self.options.reveal_verbose_types: + type_str = f"**{type_str}" + else: + type_str = f"Unpack[{type_str}]" + s += type_str + if t.arg_kinds[i].is_optional(): + s += " =" + + if param_spec is not None: + n = param_spec.name + if s: + s += ", " + s += f"*{n}.args, **{n}.kwargs" + if param_spec.has_default(): + s += f" = {param_spec.default.accept(self)}" + + s = f"({s})" + + if not isinstance(get_proper_type(t.ret_type), NoneType): + if t.type_guard is not None: + s += f" -> TypeGuard[{t.type_guard.accept(self)}]" + elif t.type_is is not None: + s += f" -> TypeIs[{t.type_is.accept(self)}]" + else: + s += f" -> {t.ret_type.accept(self)}" + + if t.variables: + vs = [] + for var in t.variables: + if isinstance(var, TypeVarType): + if var.values: + vals = f"({', '.join(val.accept(self) for val in var.values)})" + vs.append(f"{var.name} in {vals}") + elif not is_named_instance(var.upper_bound, "builtins.object"): + vs.append( + f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}" + ) + else: + vs.append( + f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}" + ) + else: + # For other TypeVarLikeTypes, use the name and default + vs.append( + f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}" + ) + s = f"[{', '.join(vs)}] {s}" + + return f"def {s}" + + def visit_overloaded(self, t: Overloaded, /) -> str: + a = [] + for i in t.items: + a.append(i.accept(self)) + return f"Overload({', '.join(a)})" + + def visit_tuple_type(self, t: TupleType, /) -> str: + s = self.list_str(t.items) or "()" + if t.partial_fallback and t.partial_fallback.type: + fallback_name = t.partial_fallback.type.fullname + if fallback_name != "builtins.tuple": + return f"tuple[{s}, fallback={t.partial_fallback.accept(self)}]" + return f"tuple[{s}]" + + def visit_typeddict_type(self, t: TypedDictType, /) -> str: + def item_str(name: str, typ: str) -> str: + modifier = "" + if name not in t.required_keys: + modifier += "?" + if name in t.readonly_keys: + modifier += "=" + return f"{name!r}{modifier}: {typ}" + + s = ( + "{" + + ", ".join(item_str(name, typ.accept(self)) for name, typ in t.items.items()) + + "}" + ) + prefix = "" + if t.fallback and t.fallback.type: + if t.fallback.type.fullname not in TPDICT_FB_NAMES: + if not self.options.reveal_verbose_types: + prefix = t.fallback.type.fullname + ", " + else: + prefix = repr(t.fallback.type.fullname) + ", " + return f"TypedDict({prefix}{s})" + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> str: + # For bytes literals, the value is already escaped, just add quotes and b prefix + if t.base_type_name == "builtins.bytes": + # The value is already escaped (e.g., "foo" or "hello\\nworld") + # Just add quotes and b prefix + return f"b'{t.literal_value}'" + return repr(t.literal_value) + + def visit_literal_type(self, t: LiteralType, /) -> str: + return f"Literal[{t.value_repr()}]" + + def visit_union_type(self, t: UnionType, /) -> str: + return self.list_str(t.items, use_or_syntax=True) + + def visit_partial_type(self, t: PartialType, /) -> str: + if t.type is None: + return "" + else: + return "".format(t.type.name, ", ".join(["?"] * len(t.type.type_vars))) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> str: + return "..." + + def visit_type_type(self, t: TypeType, /) -> str: + if t.is_type_form: + type_name = "TypeForm" + else: + type_name = "type" + return f"{type_name}[{t.item.accept(self)}]" + + def visit_placeholder_type(self, t: PlaceholderType, /) -> str: + return f"" + + def visit_type_alias_type(self, t: TypeAliasType, /) -> str: + if t.alias is None: + return "" + if not t.is_recursive: + return get_proper_type(t).accept(self) + if self.dotted_aliases is None: + self.dotted_aliases = set() + elif t in self.dotted_aliases: + return "..." + self.dotted_aliases.add(t) + type_str = get_proper_type(t).accept(self) + self.dotted_aliases.discard(t) + return type_str + + def visit_unpack_type(self, t: UnpackType, /) -> str: + if not self.options.reveal_verbose_types: + return f"*{t.type.accept(self)}" + return f"Unpack[{t.type.accept(self)}]" + + def list_str(self, a: Iterable[Type], *, use_or_syntax: bool = False) -> str: + """Convert items of an array to strings (pretty-print types) + and join the results with commas. + """ + res = [] + for t in a: + s = t.accept(self) + if use_or_syntax and isinstance(get_proper_type(t), CallableType): + res.append(f"({s})") + else: + res.append(s) + sep = ", " if not use_or_syntax else " | " + return sep.join(res) + + +class TrivialSyntheticTypeTranslator(TypeTranslator, SyntheticTypeVisitor[Type]): + """A base class for type translators that need to be run during semantic analysis.""" + + def visit_placeholder_type(self, t: PlaceholderType, /) -> Type: + return t + + def visit_callable_argument(self, t: CallableArgument, /) -> Type: + return t + + def visit_ellipsis_type(self, t: EllipsisType, /) -> Type: + return t + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> Type: + return t + + def visit_type_list(self, t: TypeList, /) -> Type: + return t + + +class CollectAliasesVisitor(TypeQuery[list[mypy.nodes.TypeAlias]]): + def __init__(self) -> None: + super().__init__() + self.seen_alias_nodes: set[mypy.nodes.TypeAlias] = set() + + def strategy(self, items: list[list[mypy.nodes.TypeAlias]]) -> list[mypy.nodes.TypeAlias]: + out = [] + for item in items: + out.extend(item) + return out + + def visit_type_alias_type(self, t: TypeAliasType, /) -> list[mypy.nodes.TypeAlias]: + assert t.alias is not None + if t.alias not in self.seen_alias_nodes: + self.seen_alias_nodes.add(t.alias) + res = [t.alias] + t.alias.target.accept(self) + else: + res = [] + for arg in t.args: + res.extend(arg.accept(self)) + return res + + +def is_named_instance(t: Type, fullnames: str | tuple[str, ...]) -> TypeGuard[Instance]: + if not isinstance(fullnames, tuple): + fullnames = (fullnames,) + + t = get_proper_type(t) + return isinstance(t, Instance) and t.type.fullname in fullnames + + +class HasTypeVars(BoolTypeQuery): + """Visitor for querying whether a type has a type variable component.""" + + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + self.skip_alias_target = True + + def visit_type_var(self, t: TypeVarType) -> bool: + return True + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool: + return True + + def visit_param_spec(self, t: ParamSpecType) -> bool: + return True + + +def has_type_vars(typ: Type) -> bool: + """Check if a type contains any type variables (recursively).""" + return typ.accept(HasTypeVars()) + + +class HasRecursiveType(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_type_alias_type(self, t: TypeAliasType) -> bool: + return t.is_recursive or self.query_types(t.args) + + +# Use singleton since this is hot (note: call reset() before using) +_has_recursive_type: Final = HasRecursiveType() + + +def has_recursive_types(typ: Type) -> bool: + """Check if a type contains any recursive aliases (recursively).""" + _has_recursive_type.reset() + return typ.accept(_has_recursive_type) + + +def split_with_prefix_and_suffix( + types: tuple[Type, ...], prefix: int, suffix: int +) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]: + if len(types) <= prefix + suffix: + types = extend_args_for_prefix_and_suffix(types, prefix, suffix) + if suffix: + return types[:prefix], types[prefix:-suffix], types[-suffix:] + else: + return types[:prefix], types[prefix:], () + + +def extend_args_for_prefix_and_suffix( + types: tuple[Type, ...], prefix: int, suffix: int +) -> tuple[Type, ...]: + """Extend list of types by eating out from variadic tuple to satisfy prefix and suffix.""" + idx = None + item = None + for i, t in enumerate(types): + if isinstance(t, UnpackType): + p_type = get_proper_type(t.type) + if isinstance(p_type, Instance) and p_type.type.fullname == "builtins.tuple": + item = p_type.args[0] + idx = i + break + + if idx is None: + return types + assert item is not None + if idx < prefix: + start = (item,) * (prefix - idx) + else: + start = () + if len(types) - idx - 1 < suffix: + end = (item,) * (suffix - len(types) + idx + 1) + else: + end = () + return types[:idx] + start + (types[idx],) + end + types[idx + 1 :] + + +def flatten_nested_unions( + types: Sequence[Type], *, handle_type_alias_type: bool = True, handle_recursive: bool = True +) -> list[Type]: + """Flatten nested unions in a type list.""" + if not isinstance(types, list): + typelist = list(types) + else: + typelist = cast("list[Type]", types) + + # Fast path: most of the time there is nothing to flatten + if not any(isinstance(t, (TypeAliasType, UnionType)) for t in typelist): # type: ignore[misc] + return typelist + + flat_items: list[Type] = [] + for t in typelist: + if handle_type_alias_type and isinstance(t, TypeAliasType): + if not handle_recursive and t.is_recursive: + tp: Type = t + else: + tp = get_proper_type(t) + else: + tp = t + if isinstance(tp, ProperType) and isinstance(tp, UnionType): + flat_items.extend( + flatten_nested_unions( + tp.items, + handle_type_alias_type=handle_type_alias_type, + handle_recursive=handle_recursive, + ) + ) + else: + # Must preserve original aliases when possible. + flat_items.append(t) + return flat_items + + +def find_unpack_in_list(items: Sequence[Type]) -> int | None: + unpack_index: int | None = None + for i, item in enumerate(items): + if isinstance(item, UnpackType): + # We cannot fail here, so we must check this in an earlier + # semanal phase. + # Funky code here avoids mypyc narrowing the type of unpack_index. + old_index = unpack_index + assert old_index is None + # Don't return so that we can also sanity check there is only one. + unpack_index = i + return unpack_index + + +def flatten_nested_tuples(types: Iterable[Type]) -> list[Type]: + """Recursively flatten TupleTypes nested with Unpack. + + For example this will transform + Tuple[A, Unpack[Tuple[B, Unpack[Tuple[C, D]]]]] + into + Tuple[A, B, C, D] + """ + res = [] + for typ in types: + if not isinstance(typ, UnpackType): + res.append(typ) + continue + p_type = get_proper_type(typ.type) + if not isinstance(p_type, TupleType): + res.append(typ) + continue + if isinstance(typ.type, TypeAliasType): + items = [] + for item in p_type.items: + if ( + isinstance(item, ProperType) + and isinstance(item, Instance) + or isinstance(item, TypeAliasType) + ): + if len(item.args) == 0: + item = item.copy_modified() + item.set_line(typ) + items.append(item) + else: + items = p_type.items + res.extend(flatten_nested_tuples(items)) + return res + + +def is_literal_type(typ: ProperType, fallback_fullname: str, value: LiteralValue) -> bool: + """Check if this type is a LiteralType with the given fallback type and value.""" + if isinstance(typ, Instance) and typ.last_known_value: + typ = typ.last_known_value + return ( + isinstance(typ, LiteralType) + and typ.fallback.type.fullname == fallback_fullname + and typ.value == value + ) + + +names: Final = globals().copy() +names.pop("NOT_READY", None) +deserialize_map: Final = { + key: obj.deserialize + for key, obj in names.items() + if isinstance(obj, type) and issubclass(obj, Type) and obj is not Type +} + + +def callable_with_ellipsis(any_type: AnyType, ret_type: Type, fallback: Instance) -> CallableType: + """Construct type Callable[..., ret_type].""" + return CallableType( + [any_type, any_type], + [ARG_STAR, ARG_STAR2], + [None, None], + ret_type=ret_type, + fallback=fallback, + is_ellipsis_args=True, + ) + + +def remove_dups(types: list[T]) -> list[T]: + if len(types) <= 1: + return types + # Get unique elements in order of appearance + all_types: set[T] = set() + new_types: list[T] = [] + for t in types: + if t not in all_types: + new_types.append(t) + all_types.add(t) + return new_types + + +def type_vars_as_args(type_vars: Sequence[TypeVarLikeType]) -> tuple[Type, ...]: + """Represent type variables as they would appear in a type argument list.""" + args: list[Type] = [] + for tv in type_vars: + if isinstance(tv, TypeVarTupleType): + args.append(UnpackType(tv)) + else: + args.append(tv) + return tuple(args) + + +# See docstring for mypy/cache.py for reserved tag ranges. +# Instance-related tags. +INSTANCE: Final[Tag] = 80 +INSTANCE_SIMPLE: Final[Tag] = 81 +INSTANCE_GENERIC: Final[Tag] = 82 +INSTANCE_STR: Final[Tag] = 83 +INSTANCE_FUNCTION: Final[Tag] = 84 +INSTANCE_INT: Final[Tag] = 85 +INSTANCE_BOOL: Final[Tag] = 86 +INSTANCE_OBJECT: Final[Tag] = 87 + +# Other type tags. +TYPE_ALIAS_TYPE: Final[Tag] = 100 +TYPE_VAR_TYPE: Final[Tag] = 101 +PARAM_SPEC_TYPE: Final[Tag] = 102 +TYPE_VAR_TUPLE_TYPE: Final[Tag] = 103 +UNBOUND_TYPE: Final[Tag] = 104 +UNPACK_TYPE: Final[Tag] = 105 +ANY_TYPE: Final[Tag] = 106 +UNINHABITED_TYPE: Final[Tag] = 107 +NONE_TYPE: Final[Tag] = 108 +DELETED_TYPE: Final[Tag] = 109 +CALLABLE_TYPE: Final[Tag] = 110 +OVERLOADED: Final[Tag] = 111 +TUPLE_TYPE: Final[Tag] = 112 +TYPED_DICT_TYPE: Final[Tag] = 113 +LITERAL_TYPE: Final[Tag] = 114 +UNION_TYPE: Final[Tag] = 115 +TYPE_TYPE: Final[Tag] = 116 +PARAMETERS: Final[Tag] = 117 +LIST_TYPE: Final[Tag] = 118 # Only valid in serialized ASTs +ELLIPSIS_TYPE: Final[Tag] = 119 # Only valid in serialized ASTs +RAW_EXPRESSION_TYPE: Final[Tag] = 120 # Only valid in serialized ASTs +CALL_TYPE: Final[Tag] = 121 # Only valid in serialized ASTs + + +def read_type(data: ReadBuffer, tag: Tag | None = None) -> Type: + if tag is None: + tag = read_tag(data) + # The branches here are ordered manually by type "popularity". + if tag == INSTANCE: + return Instance.read(data) + if tag == ANY_TYPE: + return AnyType.read(data) + if tag == TYPE_VAR_TYPE: + return TypeVarType.read(data) + if tag == CALLABLE_TYPE: + return CallableType.read(data) + if tag == NONE_TYPE: + return NoneType.read(data) + if tag == UNION_TYPE: + return UnionType.read(data) + if tag == LITERAL_TYPE: + return LiteralType.read(data) + if tag == TYPE_ALIAS_TYPE: + return TypeAliasType.read(data) + if tag == TUPLE_TYPE: + return TupleType.read(data) + if tag == TYPED_DICT_TYPE: + return TypedDictType.read(data) + if tag == TYPE_TYPE: + return TypeType.read(data) + if tag == OVERLOADED: + return Overloaded.read(data) + if tag == PARAM_SPEC_TYPE: + return ParamSpecType.read(data) + if tag == TYPE_VAR_TUPLE_TYPE: + return TypeVarTupleType.read(data) + if tag == UNPACK_TYPE: + return UnpackType.read(data) + if tag == PARAMETERS: + return Parameters.read(data) + if tag == UNINHABITED_TYPE: + return UninhabitedType.read(data) + if tag == UNBOUND_TYPE: + return UnboundType.read(data) + if tag == DELETED_TYPE: + return DeletedType.read(data) + assert False, f"Unknown type tag {tag}" + + +def read_function_like(data: ReadBuffer, tag: Tag) -> FunctionLike: + if tag == CALLABLE_TYPE: + return CallableType.read(data) + if tag == OVERLOADED: + return Overloaded.read(data) + assert False, f"Invalid type tag for FunctionLike {tag}" + + +def read_type_var_likes(data: ReadBuffer) -> list[TypeVarLikeType]: + """Specialized version of read_type_list() for lists of type variables.""" + assert read_tag(data) == LIST_GEN + ret: list[TypeVarLikeType] = [] + for _ in range(read_int_bare(data)): + tag = read_tag(data) + if tag == TYPE_VAR_TYPE: + ret.append(TypeVarType.read(data)) + elif tag == PARAM_SPEC_TYPE: + ret.append(ParamSpecType.read(data)) + elif tag == TYPE_VAR_TUPLE_TYPE: + ret.append(TypeVarTupleType.read(data)) + else: + assert False, f"Invalid type tag for TypeVarLikeType {tag}" + return ret + + +def read_type_opt(data: ReadBuffer) -> Type | None: + tag = read_tag(data) + if tag == LITERAL_NONE: + return None + return read_type(data, tag) + + +def write_type_opt(data: WriteBuffer, value: Type | None) -> None: + if value is not None: + value.write(data) + else: + write_tag(data, LITERAL_NONE) + + +def read_type_list(data: ReadBuffer) -> list[Type]: + assert read_tag(data) == LIST_GEN + size = read_int_bare(data) + return [read_type(data) for _ in range(size)] + + +def write_type_list(data: WriteBuffer, value: Sequence[Type]) -> None: + write_tag(data, LIST_GEN) + write_int_bare(data, len(value)) + for item in value: + item.write(data) + + +def read_type_map(data: ReadBuffer) -> dict[str, Type]: + assert read_tag(data) == DICT_STR_GEN + size = read_int_bare(data) + return {read_str_bare(data): read_type(data) for _ in range(size)} + + +def write_type_map(data: WriteBuffer, value: dict[str, Type]) -> None: + write_tag(data, DICT_STR_GEN) + write_int_bare(data, len(value)) + for key in sorted(value): + write_str_bare(data, key) + value[key].write(data) + + +# This cyclic import is unfortunate, but to avoid it we would need to move away all uses +# of get_proper_type() from types.py. Majority of them have been removed, but few remaining +# are quite tricky to get rid of, but ultimately we want to do it at some point. +from mypy.expandtype import ExpandTypeVisitor + + +class InstantiateAliasVisitor(ExpandTypeVisitor): + def visit_union_type(self, t: UnionType) -> Type: + # Unlike regular expand_type(), we don't do any simplification for unions, + # not even removing strict duplicates. There are three reasons for this: + # * get_proper_type() is a very hot function, even slightest slow down will + # cause a perf regression + # * We want to preserve this historical behaviour, to avoid possible + # regressions + # * Simplifying unions may (indirectly) call get_proper_type(), causing + # infinite recursion. + return TypeTranslator.visit_union_type(self, t) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types_utils.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types_utils.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..9fa1b10e106cf699bc7a6d7ba198edd06759902b Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types_utils.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types_utils.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..160f6c0365d63a3c6ab5005d1f4ddbe4d9b9c6a9 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/types_utils.py @@ -0,0 +1,183 @@ +""" +This module is for (more basic) type operations that should not depend on is_subtype(), +meet_types(), join_types() etc. We don't want to keep them in mypy/types.py for two reasons: +* Reduce the size of that module. +* Reduce use of get_proper_type() in types.py to avoid cyclic imports + expand_type <-> types, if we move get_proper_type() to the former. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from typing import cast + +from mypy.nodes import ARG_STAR, ARG_STAR2, FuncItem, TypeAlias +from mypy.types import ( + AnyType, + CallableType, + Instance, + LiteralType, + NoneType, + Overloaded, + ParamSpecType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypeType, + TypeVarType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + get_proper_types, +) + + +def flatten_types(types: Iterable[Type]) -> Iterable[Type]: + for t in types: + tp = get_proper_type(t) + if isinstance(tp, UnionType): + yield from flatten_types(tp.items) + else: + yield t + + +def strip_type(typ: Type) -> Type: + """Make a copy of type without 'debugging info' (function name).""" + orig_typ = typ + typ = get_proper_type(typ) + if isinstance(typ, CallableType): + return typ.copy_modified(name=None) + elif isinstance(typ, Overloaded): + return Overloaded([cast(CallableType, strip_type(item)) for item in typ.items]) + else: + return orig_typ + + +def is_invalid_recursive_alias(seen_nodes: set[TypeAlias], target: Type) -> bool: + """Flag aliases like A = Union[int, A], T = tuple[int, *T] (and similar mutual aliases). + + Such aliases don't make much sense, and cause problems in later phases. + """ + if isinstance(target, TypeAliasType): + if target.alias in seen_nodes: + return True + assert target.alias, f"Unfixed type alias {target.type_ref}" + return is_invalid_recursive_alias(seen_nodes | {target.alias}, get_proper_type(target)) + assert isinstance(target, ProperType) + if not isinstance(target, (UnionType, TupleType)): + return False + if isinstance(target, UnionType): + return any(is_invalid_recursive_alias(seen_nodes, item) for item in target.items) + for item in target.items: + if isinstance(item, UnpackType): + if is_invalid_recursive_alias(seen_nodes, item.type): + return True + return False + + +def get_bad_type_type_item(item: Type) -> str | None: + """Prohibit types like Type[Type[...]]. + + Such types are explicitly prohibited by PEP 484. Also, they cause problems + with recursive types like T = Type[T], because internal representation of + TypeType item is normalized (i.e. always a proper type). + + Also forbids `Type[Literal[...]]`, because typing spec does not allow it. + """ + # TODO: what else cannot be present in `type[...]`? + item = get_proper_type(item) + if isinstance(item, TypeType): + return "Type[...]" + if isinstance(item, LiteralType): + return "Literal[...]" + if isinstance(item, UnionType): + items = [ + bad_item + for typ in flatten_nested_unions(item.items) + if (bad_item := get_bad_type_type_item(typ)) is not None + ] + if not items: + return None + if len(items) == 1: + return items[0] + return f"Union[{', '.join(items)}]" + return None + + +def is_union_with_any(tp: Type) -> bool: + """Is this a union with Any or a plain Any type?""" + tp = get_proper_type(tp) + if isinstance(tp, AnyType): + return True + if not isinstance(tp, UnionType): + return False + return any(is_union_with_any(t) for t in get_proper_types(tp.items)) + + +def is_generic_instance(tp: Type) -> bool: + tp = get_proper_type(tp) + return isinstance(tp, Instance) and bool(tp.args) + + +def is_overlapping_none(t: Type) -> bool: + t = get_proper_type(t) + return isinstance(t, NoneType) or ( + isinstance(t, UnionType) and any(isinstance(get_proper_type(e), NoneType) for e in t.items) + ) + + +def remove_optional(typ: Type) -> Type: + typ = get_proper_type(typ) + if isinstance(typ, UnionType): + return UnionType.make_union( + [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)] + ) + elif isinstance(typ, NoneType): + return UninhabitedType() + else: + return typ + + +def is_self_type_like(typ: Type, *, is_classmethod: bool) -> bool: + """Does this look like a self-type annotation?""" + typ = get_proper_type(typ) + if not is_classmethod: + return isinstance(typ, TypeVarType) + if not isinstance(typ, TypeType): + return False + return isinstance(typ.item, TypeVarType) + + +def store_argument_type( + defn: FuncItem, i: int, typ: CallableType, named_type: Callable[[str, list[Type]], Instance] +) -> None: + arg_type = typ.arg_types[i] + if typ.arg_kinds[i] == ARG_STAR: + if isinstance(arg_type, ParamSpecType): + pass + elif isinstance(arg_type, UnpackType): + unpacked_type = get_proper_type(arg_type.type) + if isinstance(unpacked_type, TupleType): + # Instead of using Tuple[Unpack[Tuple[...]]], just use Tuple[...] + arg_type = unpacked_type + elif ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ): + arg_type = unpacked_type + else: + # TODO: verify that we can only have a TypeVarTuple here. + arg_type = TupleType( + [arg_type], + fallback=named_type("builtins.tuple", [named_type("builtins.object", [])]), + ) + else: + # builtins.tuple[T] is typing.Tuple[T, ...] + arg_type = named_type("builtins.tuple", [arg_type]) + elif typ.arg_kinds[i] == ARG_STAR2: + if not isinstance(arg_type, ParamSpecType) and not typ.unpack_kwargs: + arg_type = named_type("builtins.dict", [named_type("builtins.str", []), arg_type]) + defn.arguments[i].variable.type = arg_type diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typestate.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typestate.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f9846bcf84835f08aadd820870bbc6924204a1db Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typestate.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typestate.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typestate.py new file mode 100644 index 0000000000000000000000000000000000000000..d45837dad645adcea8901fcd5bac3f5d263b3fdf --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typestate.py @@ -0,0 +1,328 @@ +""" +A shared state for all TypeInfos that holds global cache and dependency information, +and potentially other mutable TypeInfo state. This module contains mutable global state. +""" + +from __future__ import annotations + +from typing import Final, TypeAlias as _TypeAlias + +from mypy.nodes import VARIANCE_NOT_READY, TypeInfo +from mypy.server.trigger import make_trigger +from mypy.types import Instance, Type, TypeVarId, TypeVarType, get_proper_type + +MAX_NEGATIVE_CACHE_TYPES: Final = 1000 +MAX_NEGATIVE_CACHE_ENTRIES: Final = 10000 + +# Represents that the 'left' instance is a subtype of the 'right' instance +SubtypeRelationship: _TypeAlias = tuple[Instance, Instance] + +# A tuple encoding the specific conditions under which we performed the subtype check. +# (e.g. did we want a proper subtype? A regular subtype while ignoring variance?) +SubtypeKind: _TypeAlias = tuple[bool, ...] + +# A cache that keeps track of whether the given TypeInfo is a part of a particular +# subtype relationship +SubtypeCache: _TypeAlias = dict[TypeInfo, dict[SubtypeKind, set[SubtypeRelationship]]] + + +class TypeState: + """This class provides subtype caching to improve performance of subtype checks. + It also holds protocol fine grained dependencies. + + Note: to avoid leaking global state, 'reset_all_subtype_caches()' should be called + after a build has finished and after a daemon shutdown. This subtype cache only exists for + performance reasons, resetting subtype caches for a class has no semantic effect. + The protocol dependencies however are only stored here, and shouldn't be deleted unless + not needed any more (e.g. during daemon shutdown). + """ + + # '_subtype_caches' keeps track of (subtype, supertype) pairs where supertypes are + # instances of the given TypeInfo. The cache also keeps track of whether the check + # was done in strict optional mode and of the specific *kind* of subtyping relationship, + # which we represent as an arbitrary hashable tuple. + # We need the caches, since subtype checks for structural types are very slow. + _subtype_caches: Final[SubtypeCache] + + # Same as above but for negative subtyping results. + _negative_subtype_caches: Final[SubtypeCache] + + # This contains protocol dependencies generated after running a full build, + # or after an update. These dependencies are special because: + # * They are a global property of the program; i.e. some dependencies for imported + # classes can be generated in the importing modules. + # * Because of the above, they are serialized separately, after a full run, + # or a full update. + # `proto_deps` can be None if after deserialization it turns out that they are + # inconsistent with the other cache files (or an error occurred during deserialization). + # A blocking error will be generated in this case, since we can't proceed safely. + # For the description of kinds of protocol dependencies and corresponding examples, + # see _snapshot_protocol_deps. + proto_deps: dict[str, set[str]] | None + + # Protocols (full names) a given class attempted to implement. + # Used to calculate fine grained protocol dependencies and optimize protocol + # subtype cache invalidation in fine grained mode. For example, if we pass a value + # of type a.A to a function expecting something compatible with protocol p.P, + # we'd have 'a.A' -> {'p.P', ...} in the map. This map is flushed after every incremental + # update. + _attempted_protocols: Final[dict[str, set[str]]] + # We also snapshot protocol members of the above protocols. For example, if we pass + # a value of type a.A to a function expecting something compatible with Iterable, we'd have + # 'a.A' -> {'__iter__', ...} in the map. This map is also flushed after every incremental + # update. This map is needed to only generate dependencies like -> + # instead of a wildcard to avoid unnecessarily invalidating classes. + _checked_against_members: Final[dict[str, set[str]]] + # TypeInfos that appeared as a left type (subtype) in a subtype check since latest + # dependency snapshot update. This is an optimisation for fine grained mode; during a full + # run we only take a dependency snapshot at the very end, so this set will contain all + # subtype-checked TypeInfos. After a fine grained update however, we can gather only new + # dependencies generated from (typically) few TypeInfos that were subtype-checked + # (i.e. appeared as r.h.s. in an assignment or an argument in a function call in + # a re-checked target) during the update. + _rechecked_types: Final[set[TypeInfo]] + + # The two attributes below are assumption stacks for subtyping relationships between + # recursive type aliases. Normally, one would pass type assumptions as an additional + # arguments to is_subtype(), but this would mean updating dozens of related functions + # threading this through all callsites (see also comment for TypeInfo.assuming). + _assuming: Final[list[tuple[Type, Type]]] + _assuming_proper: Final[list[tuple[Type, Type]]] + # Ditto for inference of generic constraints against recursive type aliases. + inferring: Final[list[tuple[Type, Type]]] + # Whether to use joins or unions when solving constraints, see checkexpr.py for details. + infer_unions: bool + # Whether to use new type inference algorithm that can infer polymorphic types. + # This is temporary and will be removed soon when new algorithm is more polished. + infer_polymorphic: bool + + # N.B: We do all of the accesses to these properties through + # TypeState, instead of making these classmethods and accessing + # via the cls parameter, since mypyc can optimize accesses to + # Final attributes of a directly referenced type. + + def __init__(self) -> None: + self._subtype_caches = {} + self._negative_subtype_caches = {} + self.proto_deps = {} + self._attempted_protocols = {} + self._checked_against_members = {} + self._rechecked_types = set() + self._assuming = [] + self._assuming_proper = [] + self.inferring = [] + self.infer_unions = False + self.infer_polymorphic = False + + def is_assumed_subtype(self, left: Type, right: Type) -> bool: + for l, r in reversed(self._assuming): + if get_proper_type(l) == get_proper_type(left) and get_proper_type( + r + ) == get_proper_type(right): + return True + return False + + def is_assumed_proper_subtype(self, left: Type, right: Type) -> bool: + for l, r in reversed(self._assuming_proper): + if get_proper_type(l) == get_proper_type(left) and get_proper_type( + r + ) == get_proper_type(right): + return True + return False + + def get_assumptions(self, is_proper: bool) -> list[tuple[Type, Type]]: + if is_proper: + return self._assuming_proper + return self._assuming + + def reset_all_subtype_caches(self) -> None: + """Completely reset all known subtype caches.""" + self._subtype_caches.clear() + self._negative_subtype_caches.clear() + + def reset_subtype_caches_for(self, info: TypeInfo) -> None: + """Reset subtype caches (if any) for a given supertype TypeInfo.""" + if info in self._subtype_caches: + self._subtype_caches[info].clear() + if info in self._negative_subtype_caches: + self._negative_subtype_caches[info].clear() + + def reset_all_subtype_caches_for(self, info: TypeInfo) -> None: + """Reset subtype caches (if any) for a given supertype TypeInfo and its MRO.""" + for item in info.mro: + self.reset_subtype_caches_for(item) + + def is_cached_subtype_check(self, kind: SubtypeKind, left: Instance, right: Instance) -> bool: + if left.last_known_value is not None or right.last_known_value is not None: + # If there is a literal last known value, give up. There + # will be an unbounded number of potential types to cache, + # making caching less effective. + return False + info = right.type + cache = self._subtype_caches.get(info) + if cache is None: + return False + subcache = cache.get(kind) + if subcache is None: + return False + return (left, right) in subcache + + def is_cached_negative_subtype_check( + self, kind: SubtypeKind, left: Instance, right: Instance + ) -> bool: + if left.last_known_value is not None or right.last_known_value is not None: + # If there is a literal last known value, give up. There + # will be an unbounded number of potential types to cache, + # making caching less effective. + return False + info = right.type + cache = self._negative_subtype_caches.get(info) + if cache is None: + return False + subcache = cache.get(kind) + if subcache is None: + return False + return (left, right) in subcache + + def record_subtype_cache_entry( + self, kind: SubtypeKind, left: Instance, right: Instance + ) -> None: + if left.last_known_value is not None or right.last_known_value is not None: + # These are unlikely to match, due to the large space of + # possible values. Avoid uselessly increasing cache sizes. + return + if any( + (isinstance(tv, TypeVarType) and tv.variance == VARIANCE_NOT_READY) + for tv in right.type.defn.type_vars + ): + # Variance indeterminate -- don't know the result + return + cache = self._subtype_caches.setdefault(right.type, {}) + cache.setdefault(kind, set()).add((left, right)) + + def record_negative_subtype_cache_entry( + self, kind: SubtypeKind, left: Instance, right: Instance + ) -> None: + if left.last_known_value is not None or right.last_known_value is not None: + # These are unlikely to match, due to the large space of + # possible values. Avoid uselessly increasing cache sizes. + return + if len(self._negative_subtype_caches) > MAX_NEGATIVE_CACHE_TYPES: + self._negative_subtype_caches.clear() + cache = self._negative_subtype_caches.setdefault(right.type, {}) + subcache = cache.setdefault(kind, set()) + if len(subcache) > MAX_NEGATIVE_CACHE_ENTRIES: + subcache.clear() + cache.setdefault(kind, set()).add((left, right)) + + def reset_protocol_deps(self) -> None: + """Reset dependencies after a full run or before a daemon shutdown.""" + self.proto_deps = {} + self._attempted_protocols.clear() + self._checked_against_members.clear() + self._rechecked_types.clear() + + def record_protocol_subtype_check(self, left_type: TypeInfo, right_type: TypeInfo) -> None: + assert right_type.is_protocol + self._rechecked_types.add(left_type) + self._attempted_protocols.setdefault(left_type.fullname, set()).add(right_type.fullname) + self._checked_against_members.setdefault(left_type.fullname, set()).update( + right_type.protocol_members + ) + + def _snapshot_protocol_deps(self) -> dict[str, set[str]]: + """Collect protocol attribute dependencies found so far from registered subtype checks. + + There are three kinds of protocol dependencies. For example, after a subtype check: + + x: Proto = C() + + the following dependencies will be generated: + 1. ..., , -> + 2. ..., , -> [for every attr in Proto members] + 3. -> Proto # this one to invalidate the subtype cache + + The first kind is generated immediately per-module in deps.py (see also an example there + for motivation why it is needed). While two other kinds are generated here after all + modules are type checked and we have recorded all the subtype checks. To understand these + two kinds, consider a simple example: + + class A: + def __iter__(self) -> Iterator[int]: + ... + + it: Iterable[int] = A() + + We add -> to invalidate the assignment (module target in this case), + whenever the signature of a.A.__iter__ changes. We also add -> typing.Iterable, + to invalidate the subtype caches of the latter. (Note that the same logic applies to + proper subtype checks, and calculating meets and joins, if this involves calling + 'subtypes.is_protocol_implementation'). + """ + deps: dict[str, set[str]] = {} + for info in self._rechecked_types: + for attr in self._checked_against_members[info.fullname]: + # The need for full MRO here is subtle, during an update, base classes of + # a concrete class may not be reprocessed, so not all -> deps + # are added. + for base_info in info.mro[:-1]: + trigger = make_trigger(f"{base_info.fullname}.{attr}") + if "typing" in trigger or "builtins" in trigger: + # TODO: avoid everything from typeshed + continue + deps.setdefault(trigger, set()).add(make_trigger(info.fullname)) + for proto in self._attempted_protocols[info.fullname]: + trigger = make_trigger(info.fullname) + if "typing" in trigger or "builtins" in trigger: + continue + # If any class that was checked against a protocol changes, + # we need to reset the subtype cache for the protocol. + # + # Note: strictly speaking, the protocol doesn't need to be + # re-checked, we only need to reset the cache, and its uses + # elsewhere are still valid (unless invalidated by other deps). + deps.setdefault(trigger, set()).add(proto) + return deps + + def update_protocol_deps(self, second_map: dict[str, set[str]] | None = None) -> None: + """Update global protocol dependency map. + + We update the global map incrementally, using a snapshot only from recently + type checked types. If second_map is given, update it as well. This is currently used + by FineGrainedBuildManager that maintains normal (non-protocol) dependencies. + """ + assert self.proto_deps is not None, "This should not be called after failed cache load" + new_deps = self._snapshot_protocol_deps() + for trigger, targets in new_deps.items(): + self.proto_deps.setdefault(trigger, set()).update(targets) + if second_map is not None: + for trigger, targets in new_deps.items(): + second_map.setdefault(trigger, set()).update(targets) + self._rechecked_types.clear() + self._attempted_protocols.clear() + self._checked_against_members.clear() + + def add_all_protocol_deps(self, deps: dict[str, set[str]]) -> None: + """Add all known protocol dependencies to deps. + + This is used by tests and debug output, and also when collecting + all collected or loaded dependencies as part of build. + """ + self.update_protocol_deps() # just in case + if self.proto_deps is not None: + for trigger, targets in self.proto_deps.items(): + deps.setdefault(trigger, set()).update(targets) + + +type_state: Final = TypeState() + + +def reset_global_state() -> None: + """Reset most existing global state. + + Currently most of it is in this module. Few exceptions are strict optional status + and functools.lru_cache. + """ + type_state.reset_all_subtype_caches() + type_state.reset_protocol_deps() + TypeVarId.next_raw_id = 1 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typetraverser.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typetraverser.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..68d39eb3c7d50f1ca36c15f5a25e17674a28efa1 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typetraverser.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typetraverser.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typetraverser.py new file mode 100644 index 0000000000000000000000000000000000000000..abd0f6bf3bdfebf0b35a10e4f36656af2b73cd9d --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typetraverser.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +from collections.abc import Iterable + +from mypy_extensions import trait + +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + DeletedType, + EllipsisType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + PlaceholderType, + RawExpressionType, + SyntheticTypeVisitor, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeList, + TypeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, +) + + +@trait +class TypeTraverserVisitor(SyntheticTypeVisitor[None]): + """Visitor that traverses all components of a type""" + + # Atomic types + + def visit_any(self, t: AnyType, /) -> None: + pass + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> None: + pass + + def visit_none_type(self, t: NoneType, /) -> None: + pass + + def visit_erased_type(self, t: ErasedType, /) -> None: + pass + + def visit_deleted_type(self, t: DeletedType, /) -> None: + pass + + def visit_type_var(self, t: TypeVarType, /) -> None: + # Note that type variable values and upper bound aren't treated as + # components, since they are components of the type variable + # definition. We want to traverse everything just once. + t.default.accept(self) + + def visit_param_spec(self, t: ParamSpecType, /) -> None: + # TODO: do we need to traverse prefix here? + t.default.accept(self) + + def visit_parameters(self, t: Parameters, /) -> None: + self.traverse_type_list(t.arg_types) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> None: + t.default.accept(self) + + def visit_literal_type(self, t: LiteralType, /) -> None: + t.fallback.accept(self) + + # Composite types + + def visit_instance(self, t: Instance, /) -> None: + self.traverse_type_tuple(t.args) + + def visit_callable_type(self, t: CallableType, /) -> None: + # FIX generics + self.traverse_type_list(t.arg_types) + t.ret_type.accept(self) + t.fallback.accept(self) + + if t.type_guard is not None: + t.type_guard.accept(self) + + if t.type_is is not None: + t.type_is.accept(self) + + def visit_tuple_type(self, t: TupleType, /) -> None: + self.traverse_type_list(t.items) + t.partial_fallback.accept(self) + + def visit_typeddict_type(self, t: TypedDictType, /) -> None: + self.traverse_types(t.items.values()) + t.fallback.accept(self) + + def visit_union_type(self, t: UnionType, /) -> None: + self.traverse_type_list(t.items) + + def visit_overloaded(self, t: Overloaded, /) -> None: + self.traverse_types(t.items) + + def visit_type_type(self, t: TypeType, /) -> None: + t.item.accept(self) + + # Special types (not real types) + + def visit_callable_argument(self, t: CallableArgument, /) -> None: + t.typ.accept(self) + + def visit_unbound_type(self, t: UnboundType, /) -> None: + self.traverse_type_tuple(t.args) + + def visit_type_list(self, t: TypeList, /) -> None: + self.traverse_type_list(t.items) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> None: + pass + + def visit_placeholder_type(self, t: PlaceholderType, /) -> None: + self.traverse_type_list(t.args) + + def visit_partial_type(self, t: PartialType, /) -> None: + pass + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> None: + pass + + def visit_type_alias_type(self, t: TypeAliasType, /) -> None: + # TODO: sometimes we want to traverse target as well + # We need to find a way to indicate explicitly the intent, + # maybe make this method abstract (like for TypeTranslator)? + self.traverse_type_list(t.args) + + def visit_unpack_type(self, t: UnpackType, /) -> None: + t.type.accept(self) + + # Helpers + + def traverse_types(self, types: Iterable[Type], /) -> None: + for typ in types: + typ.accept(self) + + def traverse_type_list(self, types: list[Type], /) -> None: + # Micro-optimization: Specialized for lists + for typ in types: + typ.accept(self) + + def traverse_type_tuple(self, types: tuple[Type, ...], /) -> None: + # Micro-optimization: Specialized for tuples + for typ in types: + typ.accept(self) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevars.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevars.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..bfbae8cd567669aace09007b0d0db44aea551073 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevars.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevars.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevars.py new file mode 100644 index 0000000000000000000000000000000000000000..e871973104a2dd5b32c54d1519fc85ed5d971be1 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevars.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from mypy.erasetype import erase_typevars +from mypy.nodes import TypeInfo +from mypy.types import ( + Instance, + ParamSpecType, + ProperType, + TupleType, + Type, + TypeOfAny, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnpackType, +) +from mypy.typevartuples import erased_vars + + +def fill_typevars(typ: TypeInfo) -> Instance | TupleType: + """For a non-generic type, return instance type representing the type. + + For a generic G type with parameters T1, .., Tn, return G[T1, ..., Tn]. + """ + tvs: list[Type] = [] + # TODO: why do we need to keep both typ.type_vars and typ.defn.type_vars? + for i in range(len(typ.defn.type_vars)): + tv: TypeVarLikeType | UnpackType = typ.defn.type_vars[i] + # Change the line number + if isinstance(tv, TypeVarType): + tv = tv.copy_modified(line=-1, column=-1) + elif isinstance(tv, TypeVarTupleType): + tv = UnpackType( + TypeVarTupleType( + tv.name, + tv.fullname, + tv.id, + tv.upper_bound, + tv.tuple_fallback, + tv.default, + line=-1, + column=-1, + ) + ) + else: + assert isinstance(tv, ParamSpecType) + tv = ParamSpecType( + tv.name, + tv.fullname, + tv.id, + tv.flavor, + tv.upper_bound, + tv.default, + line=-1, + column=-1, + ) + tvs.append(tv) + inst = Instance(typ, tvs) + # TODO: do we need to also handle typeddict_type here and below? + if typ.tuple_type is None: + return inst + return typ.tuple_type.copy_modified(fallback=inst) + + +def fill_typevars_with_any(typ: TypeInfo) -> Instance | TupleType: + """Apply a correct number of Any's as type arguments to a type.""" + inst = Instance(typ, erased_vars(typ.defn.type_vars, TypeOfAny.special_form)) + if typ.tuple_type is None: + return inst + erased_tuple_type = erase_typevars(typ.tuple_type, {tv.id for tv in typ.defn.type_vars}) + assert isinstance(erased_tuple_type, ProperType) + if isinstance(erased_tuple_type, TupleType): + return typ.tuple_type.copy_modified(fallback=inst) + return inst + + +def has_no_typevars(typ: Type) -> bool: + # We test if a type contains type variables by erasing all type variables + # and comparing the result to the original type. We use comparison by equality that + # in turn uses `__eq__` defined for types. Note: we can't use `is_same_type` because + # it is not safe with unresolved forward references, while this function may be called + # before forward references resolution patch pass. Note also that it is not safe to use + # `is` comparison because `erase_typevars` doesn't preserve type identity. + return typ == erase_typevars(typ) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevartuples.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevartuples.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a252342ab43dd40679b27010968633fe195462d0 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevartuples.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevartuples.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevartuples.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf1a59f7d3fb9ca32c7d075795da45b727a0cec --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/typevartuples.py @@ -0,0 +1,36 @@ +"""Helpers for interacting with type var tuples.""" + +from __future__ import annotations + +from collections.abc import Sequence + +from mypy.types import ( + AnyType, + Instance, + Type, + TypeVarLikeType, + TypeVarTupleType, + UnpackType, + split_with_prefix_and_suffix, +) + + +def split_with_instance( + typ: Instance, +) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]: + assert typ.type.type_var_tuple_prefix is not None + assert typ.type.type_var_tuple_suffix is not None + return split_with_prefix_and_suffix( + typ.args, typ.type.type_var_tuple_prefix, typ.type.type_var_tuple_suffix + ) + + +def erased_vars(type_vars: Sequence[TypeVarLikeType], type_of_any: int) -> list[Type]: + args: list[Type] = [] + for tv in type_vars: + # Valid erasure for *Ts is *tuple[Any, ...], not just Any. + if isinstance(tv, TypeVarTupleType): + args.append(UnpackType(tv.tuple_fallback.copy_modified(args=[AnyType(type_of_any)]))) + else: + args.append(AnyType(type_of_any)) + return args diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/util.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/util.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ab66a77c3054722c3d8b26f66420bc7449903f5e Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/util.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/util.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/util.py new file mode 100644 index 0000000000000000000000000000000000000000..86998380ff0aa9a2037ccd6f8d065283a2d9ad69 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/util.py @@ -0,0 +1,961 @@ +"""Utility functions with no non-trivial dependencies.""" + +from __future__ import annotations + +import hashlib +import io +import json +import os +import re +import shutil +import sys +import time +from collections.abc import Callable, Container, Iterable, Sequence, Sized +from importlib import resources as importlib_resources +from typing import IO, Any, Final, Literal, TypeVar + +orjson: Any +try: + import orjson # type: ignore[import-not-found, no-redef, unused-ignore] +except ImportError: + orjson = None + +try: + import _curses # noqa: F401 + import curses + + CURSES_ENABLED = True +except ImportError: + CURSES_ENABLED = False + +T = TypeVar("T") + +TYPESHED_DIR: Final = str(importlib_resources.files("mypy") / "typeshed") + +ENCODING_RE: Final = re.compile(rb"([ \t\v]*#.*(\r\n?|\n))??[ \t\v]*#.*coding[:=][ \t]*([-\w.]+)") + +DEFAULT_SOURCE_OFFSET: Final = 4 +CODE_START: Final = " " * DEFAULT_SOURCE_OFFSET +DEFAULT_COLUMNS: Final = 80 + +# At least this number of columns will be shown on each side of +# error location when printing source code snippet. +MINIMUM_WIDTH: Final = 20 + +# VT100 color code processing was added in Windows 10, but only the second major update, +# Threshold 2. Fortunately, everyone (even on LTSB, Long Term Support Branch) should +# have a version of Windows 10 newer than this. Note that Windows 8 and below are not +# supported, but are either going out of support, or make up only a few % of the market. +MINIMUM_WINDOWS_MAJOR_VT100: Final = 10 +MINIMUM_WINDOWS_BUILD_VT100: Final = 10586 + +SPECIAL_DUNDERS: Final = frozenset( + ("__init__", "__new__", "__call__", "__init_subclass__", "__class_getitem__") +) + + +def is_dunder(name: str, exclude_special: bool = False) -> bool: + """Returns whether name is a dunder name. + + Args: + exclude_special: Whether to return False for a couple special dunder methods. + + """ + if exclude_special and name in SPECIAL_DUNDERS: + return False + return name.startswith("__") and name.endswith("__") + + +def is_sunder(name: str) -> bool: + return not is_dunder(name) and name.startswith("_") and name.endswith("_") and name != "_" + + +def split_module_names(mod_name: str) -> list[str]: + """Return the module and all parent module names. + + So, if `mod_name` is 'a.b.c', this function will return + ['a.b.c', 'a.b', and 'a']. + """ + out = [mod_name] + while "." in mod_name: + mod_name = mod_name.rsplit(".", 1)[0] + out.append(mod_name) + return out + + +def module_prefix(modules: Iterable[str], target: str) -> str | None: + result = split_target(modules, target) + if result is None: + return None + return result[0] + + +def split_target(modules: Iterable[str], target: str) -> tuple[str, str] | None: + remaining: list[str] = [] + while True: + if target in modules: + return target, ".".join(remaining) + components = target.rsplit(".", 1) + if len(components) == 1: + return None + target = components[0] + remaining.insert(0, components[1]) + + +def short_type(obj: object) -> str: + """Return the last component of the type name of an object. + + If obj is None, return 'nil'. For example, if obj is 1, return 'int'. + """ + if obj is None: + return "nil" + t = str(type(obj)) + return t.split(".")[-1].rstrip("'>") + + +def find_python_encoding(text: bytes) -> tuple[str, int]: + """PEP-263 for detecting Python file encoding""" + result = ENCODING_RE.match(text) + if result: + line = 2 if result.group(1) else 1 + encoding = result.group(3).decode("ascii") + # Handle some aliases that Python is happy to accept and that are used in the wild. + if encoding.startswith(("iso-latin-1-", "latin-1-")) or encoding == "iso-latin-1": + encoding = "latin-1" + return encoding, line + else: + default_encoding = "utf8" + return default_encoding, -1 + + +def bytes_to_human_readable_repr(b: bytes) -> str: + """Converts bytes into some human-readable representation. Unprintable + bytes such as the nul byte are escaped. For example: + + >>> b = bytes([102, 111, 111, 10, 0]) + >>> s = bytes_to_human_readable_repr(b) + >>> print(s) + foo\n\x00 + >>> print(repr(s)) + 'foo\\n\\x00' + """ + return repr(b)[2:-1] + + +class DecodeError(Exception): + """Exception raised when a file cannot be decoded due to an unknown encoding type. + + Essentially a wrapper for the LookupError raised by `bytearray.decode` + """ + + +def decode_python_encoding(source: bytes) -> str: + """Read the Python file with while obeying PEP-263 encoding detection. + + Returns the source as a string. + """ + # check for BOM UTF-8 encoding and strip it out if present + if source.startswith(b"\xef\xbb\xbf"): + encoding = "utf8" + source = source[3:] + else: + # look at first two lines and check if PEP-263 coding is present + encoding, _ = find_python_encoding(source) + + try: + source_text = source.decode(encoding) + except LookupError as lookuperr: + raise DecodeError(str(lookuperr)) from lookuperr + return source_text + + +def read_py_file(path: str, read: Callable[[str], bytes]) -> list[str] | None: + """Try reading a Python file as list of source lines. + + Return None if something goes wrong. + """ + try: + source = read(path) + except OSError: + return None + else: + try: + source_lines = decode_python_encoding(source).splitlines() + except DecodeError: + return None + return source_lines + + +def trim_source_line(line: str, max_len: int, col: int, min_width: int) -> tuple[str, int]: + """Trim a line of source code to fit into max_len. + + Show 'min_width' characters on each side of 'col' (an error location). If either + start or end is trimmed, this is indicated by adding '...' there. + A typical result looks like this: + ...some_variable = function_to_call(one_arg, other_arg) or... + + Return the trimmed string and the column offset to adjust error location. + """ + if max_len < 2 * min_width + 1: + # In case the window is too tiny it is better to still show something. + max_len = 2 * min_width + 1 + + # Trivial case: line already fits in. + if len(line) <= max_len: + return line, 0 + + # If column is not too large so that there is still min_width after it, + # the line doesn't need to be trimmed at the start. + if col + min_width < max_len: + return line[:max_len] + "...", 0 + + # Otherwise, if the column is not too close to the end, trim both sides. + if col < len(line) - min_width - 1: + offset = col - max_len + min_width + 1 + return "..." + line[offset : col + min_width + 1] + "...", offset - 3 + + # Finally, if the column is near the end, just trim the start. + return "..." + line[-max_len:], len(line) - max_len - 3 + + +def get_mypy_comments(source: str) -> list[tuple[int, str]]: + PREFIX = "# mypy: " + # Don't bother splitting up the lines unless we know it is useful + if PREFIX not in source: + return [] + lines = source.split("\n") + results = [] + for i, line in enumerate(lines): + if line.startswith(PREFIX): + results.append((i + 1, line[len(PREFIX) :])) + + return results + + +JUNIT_HEADER_TEMPLATE: Final = """ + +""" + +JUNIT_TESTCASE_FAIL_TEMPLATE: Final = """ + {text} + +""" + +JUNIT_ERROR_TEMPLATE: Final = """ + {text} + +""" + +JUNIT_TESTCASE_PASS_TEMPLATE: Final = """ + +""" + +JUNIT_FOOTER: Final = """ +""" + + +def _generate_junit_contents( + dt: float, + serious: bool, + messages_by_file: dict[str | None, list[str]], + version: str, + platform: str, +) -> str: + from xml.sax.saxutils import escape + + if serious: + failures = 0 + errors = len(messages_by_file) + else: + failures = len(messages_by_file) + errors = 0 + + xml = JUNIT_HEADER_TEMPLATE.format( + errors=errors, + failures=failures, + time=dt, + # If there are no messages, we still write one "test" indicating success. + tests=len(messages_by_file) or 1, + ) + + if not messages_by_file: + xml += JUNIT_TESTCASE_PASS_TEMPLATE.format(time=dt, ver=version, platform=platform) + else: + for filename, messages in messages_by_file.items(): + if filename is not None: + xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format( + text=escape("\n".join(messages)), + filename=filename, + time=dt, + name="mypy-py{ver}-{platform} {filename}".format( + ver=version, platform=platform, filename=filename + ), + ) + else: + xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format( + text=escape("\n".join(messages)), + filename="mypy", + time=dt, + name=f"mypy-py{version}-{platform}", + ) + + xml += JUNIT_FOOTER + + return xml + + +def write_junit_xml( + dt: float, + serious: bool, + messages_by_file: dict[str | None, list[str]], + path: str, + version: str, + platform: str, +) -> None: + xml = _generate_junit_contents(dt, serious, messages_by_file, version, platform) + + # creates folders if needed + xml_dirs = os.path.dirname(os.path.abspath(path)) + os.makedirs(xml_dirs, exist_ok=True) + + with open(path, "wb") as f: + f.write(xml.encode("utf-8")) + + +class IdMapper: + """Generate integer ids for objects. + + Unlike id(), these start from 0 and increment by 1, and ids won't + get reused across the life-time of IdMapper. + + Assume objects don't redefine __eq__ or __hash__. + """ + + def __init__(self) -> None: + self.id_map: dict[object, int] = {} + self.next_id = 0 + + def id(self, o: object) -> int: + if o not in self.id_map: + self.id_map[o] = self.next_id + self.next_id += 1 + return self.id_map[o] + + +def get_prefix(fullname: str) -> str: + """Drop the final component of a qualified name (e.g. ('x.y' -> 'x').""" + return fullname.rsplit(".", 1)[0] + + +def correct_relative_import( + cur_mod_id: str, relative: int, target: str, is_cur_package_init_file: bool +) -> tuple[str, bool]: + if relative == 0: + return target, True + parts = cur_mod_id.split(".") + rel = relative + if is_cur_package_init_file: + rel -= 1 + ok = len(parts) >= rel + if rel != 0: + cur_mod_id = ".".join(parts[:-rel]) + return cur_mod_id + (("." + target) if target else ""), ok + + +fields_cache: Final[dict[type[object], list[str]]] = {} + + +def get_class_descriptors(cls: type[object]) -> Sequence[str]: + import inspect # Lazy import for minor startup speed win + + # Maintain a cache of type -> attributes defined by descriptors in the class + # (that is, attributes from __slots__ and C extension classes) + if cls not in fields_cache: + members = inspect.getmembers( + cls, lambda o: inspect.isgetsetdescriptor(o) or inspect.ismemberdescriptor(o) + ) + fields_cache[cls] = [x for x, y in members if x != "__weakref__" and x != "__dict__"] + return fields_cache[cls] + + +def replace_object_state( + new: object, old: object, copy_dict: bool = False, skip_slots: tuple[str, ...] = () +) -> None: + """Copy state of old node to the new node. + + This handles cases where there is __dict__ and/or attribute descriptors + (either from slots or because the type is defined in a C extension module). + + Assume that both objects have the same __class__. + """ + if hasattr(old, "__dict__"): + if copy_dict: + new.__dict__ = dict(old.__dict__) + else: + new.__dict__ = old.__dict__ + + for attr in get_class_descriptors(old.__class__): + if attr in skip_slots: + continue + try: + if hasattr(old, attr): + setattr(new, attr, getattr(old, attr)) + elif hasattr(new, attr): + delattr(new, attr) + # There is no way to distinguish getsetdescriptors that allow + # writes from ones that don't (I think?), so we just ignore + # AttributeErrors if we need to. + # TODO: What about getsetdescriptors that act like properties??? + except AttributeError: + pass + + +def is_sub_path_normabs(path: str, dir: str) -> bool: + """Given two paths, return if path is a sub-path of dir. + + Moral equivalent of: Path(dir) in Path(path).parents + + Similar to the pathlib version: + - Treats paths case-sensitively + - Does not fully handle unnormalised paths (e.g. paths with "..") + - Does not handle a mix of absolute and relative paths + Unlike the pathlib version: + - Fast + - On Windows, assumes input has been slash normalised + - Handles even fewer unnormalised paths (e.g. paths with "." and "//") + + As a result, callers should ensure that inputs have had os.path.abspath called on them + (note that os.path.abspath will normalise) + """ + if not dir.endswith(os.sep): + dir += os.sep + return path.startswith(dir) + + +if sys.platform == "linux" or sys.platform == "darwin": + + def os_path_join(path: str, b: str) -> str: + # Based off of os.path.join, but simplified to str-only, 2 args and mypyc can compile it. + if b.startswith("/") or not path: + return b + elif path.endswith("/"): + return path + b + else: + return path + "/" + b + +else: + + def os_path_join(a: str, p: str) -> str: + return os.path.join(a, p) + + +def hard_exit(status: int = 0) -> None: + """Kill the current process without fully cleaning up. + + This can be quite a bit faster than a normal exit() since objects are not freed. + """ + sys.stdout.flush() + sys.stderr.flush() + os._exit(status) + + +def unmangle(name: str) -> str: + """Remove internal suffixes from a short name.""" + return name.rstrip("'") + + +def get_unique_redefinition_name(name: str, existing: Container[str]) -> str: + """Get a simple redefinition name not present among existing. + + For example, for name 'foo' we try 'foo-redefinition', 'foo-redefinition2', + 'foo-redefinition3', etc. until we find one that is not in existing. + """ + r_name = name + "-redefinition" + if r_name not in existing: + return r_name + + i = 2 + while r_name + str(i) in existing: + i += 1 + return r_name + str(i) + + +def check_python_version(program: str) -> None: + """Report issues with the Python used to run mypy, dmypy, or stubgen""" + # Check for known bad Python versions. + if sys.version_info[:2] < (3, 10): # noqa: UP036, RUF100 + sys.exit( + "Running {name} with Python 3.9 or lower is not supported; " + "please upgrade to 3.10 or newer".format(name=program) + ) + + +def count_stats(messages: list[str]) -> tuple[int, int, int]: + """Count total number of errors, notes and error_files in message list.""" + errors = [e for e in messages if ": error:" in e] + error_files = {e.split(":")[0] for e in errors} + notes = [e for e in messages if ": note:" in e] + return len(errors), len(notes), len(error_files) + + +def split_words(msg: str) -> list[str]: + """Split line of text into words (but not within quoted groups).""" + next_word = "" + res: list[str] = [] + allow_break = True + for c in msg: + if c == " " and allow_break: + res.append(next_word) + next_word = "" + continue + if c == '"': + allow_break = not allow_break + next_word += c + res.append(next_word) + return res + + +def get_terminal_width() -> int: + """Get current terminal width if possible, otherwise return the default one.""" + return ( + int(os.getenv("MYPY_FORCE_TERMINAL_WIDTH", "0")) + or shutil.get_terminal_size().columns + or DEFAULT_COLUMNS + ) + + +def soft_wrap(msg: str, max_len: int, first_offset: int, num_indent: int = 0) -> str: + """Wrap a long error message into few lines. + + Breaks will only happen between words, and never inside a quoted group + (to avoid breaking types such as "Union[int, str]"). The 'first_offset' is + the width before the start of first line. + + Pad every next line with 'num_indent' spaces. Every line will be at most 'max_len' + characters, except if it is a single word or quoted group. + + For example: + first_offset + ------------------------ + path/to/file: error: 58: Some very long error message + that needs to be split in separate lines. + "Long[Type, Names]" are never split. + ^^^^-------------------------------------------------- + num_indent max_len + """ + words = split_words(msg) + next_line = words.pop(0) + lines: list[str] = [] + while words: + next_word = words.pop(0) + max_line_len = max_len - num_indent if lines else max_len - first_offset + # Add 1 to account for space between words. + if len(next_line) + len(next_word) + 1 <= max_line_len: + next_line += " " + next_word + else: + lines.append(next_line) + next_line = next_word + lines.append(next_line) + padding = "\n" + " " * num_indent + return padding.join(lines) + + +def hash_digest(data: bytes) -> str: + """Compute a hash digest of some data. + + We use a cryptographic hash because we want a low probability of + accidental collision, but we don't really care about any of the + cryptographic properties. + """ + return hashlib.sha1(data).hexdigest() + + +def hash_digest_bytes(data: bytes) -> bytes: + """Compute a hash digest of some data. + + Similar to above but returns a bytes object. + """ + return hashlib.sha1(data).digest() + + +def parse_gray_color(cup: bytes) -> str: + """Reproduce a gray color in ANSI escape sequence""" + assert sys.platform != "win32", "curses is not available on Windows" + set_color = "".join([cup[:-1].decode(), "m"]) + gray = curses.tparm(set_color.encode("utf-8"), 1, 9).decode() + return gray + + +def should_force_color() -> bool: + env_var = os.getenv("MYPY_FORCE_COLOR", os.getenv("FORCE_COLOR", "0")) + try: + return bool(int(env_var)) + except ValueError: + return bool(env_var) + + +class FancyFormatter: + """Apply color and bold font to terminal output. + + This currently only works on Linux and Mac. + """ + + def __init__( + self, f_out: IO[str], f_err: IO[str], hide_error_codes: bool, hide_success: bool = False + ) -> None: + self.hide_error_codes = hide_error_codes + self.hide_success = hide_success + + # Check if we are in a human-facing terminal on a supported platform. + if sys.platform not in ("linux", "darwin", "win32", "emscripten"): + self.dummy_term = True + return + if not should_force_color() and (not f_out.isatty() or not f_err.isatty()): + self.dummy_term = True + return + if sys.platform == "win32": + self.dummy_term = not self.initialize_win_colors() + elif sys.platform == "emscripten": + self.dummy_term = not self.initialize_vt100_colors() + else: + self.dummy_term = not self.initialize_unix_colors() + if not self.dummy_term: + self.colors = { + "red": self.RED, + "green": self.GREEN, + "blue": self.BLUE, + "yellow": self.YELLOW, + "none": "", + } + + def initialize_vt100_colors(self) -> bool: + """Return True if initialization was successful and we can use colors, False otherwise""" + # Windows and Emscripten can both use ANSI/VT100 escape sequences for color + assert sys.platform in ("win32", "emscripten") + self.BOLD = "\033[1m" + self.UNDER = "\033[4m" + self.BLUE = "\033[94m" + self.GREEN = "\033[92m" + self.RED = "\033[91m" + self.YELLOW = "\033[93m" + self.NORMAL = "\033[0m" + self.DIM = "\033[2m" + return True + + def initialize_win_colors(self) -> bool: + """Return True if initialization was successful and we can use colors, False otherwise""" + # Windows ANSI escape sequences are only supported on Threshold 2 and above. + # we check with an assert at runtime and an if check for mypy, as asserts do not + # yet narrow platform + if sys.platform == "win32": # needed to find win specific sys apis + winver = sys.getwindowsversion() + if ( + winver.major < MINIMUM_WINDOWS_MAJOR_VT100 + or winver.build < MINIMUM_WINDOWS_BUILD_VT100 + ): + return False + import ctypes + + kernel32 = ctypes.windll.kernel32 + ENABLE_PROCESSED_OUTPUT = 0x1 + ENABLE_WRAP_AT_EOL_OUTPUT = 0x2 + ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 + STD_OUTPUT_HANDLE = -11 + kernel32.SetConsoleMode( + kernel32.GetStdHandle(STD_OUTPUT_HANDLE), + ENABLE_PROCESSED_OUTPUT + | ENABLE_WRAP_AT_EOL_OUTPUT + | ENABLE_VIRTUAL_TERMINAL_PROCESSING, + ) + self.initialize_vt100_colors() + return True + assert False, "Running not on Windows" + + def initialize_unix_colors(self) -> bool: + """Return True if initialization was successful and we can use colors, False otherwise""" + is_win = sys.platform == "win32" + if is_win or not CURSES_ENABLED: + return False + try: + # setupterm wants a fd to potentially write an "initialization sequence". + # We override sys.stdout for the daemon API so if stdout doesn't have an fd, + # just give it /dev/null. + try: + fd = sys.stdout.fileno() + except io.UnsupportedOperation: + with open("/dev/null", "rb") as f: + curses.setupterm(fd=f.fileno()) + else: + curses.setupterm(fd=fd) + except curses.error: + # Most likely terminfo not found. + return False + bold = curses.tigetstr("bold") + under = curses.tigetstr("smul") + set_color = curses.tigetstr("setaf") + set_eseq = curses.tigetstr("cup") + normal = curses.tigetstr("sgr0") + + if not (bold and under and set_color and set_eseq and normal): + return False + + self.NORMAL = normal.decode() + self.BOLD = bold.decode() + self.UNDER = under.decode() + self.DIM = parse_gray_color(set_eseq) + self.BLUE = curses.tparm(set_color, curses.COLOR_BLUE).decode() + self.GREEN = curses.tparm(set_color, curses.COLOR_GREEN).decode() + self.RED = curses.tparm(set_color, curses.COLOR_RED).decode() + self.YELLOW = curses.tparm(set_color, curses.COLOR_YELLOW).decode() + return True + + def style( + self, + text: str, + color: Literal["red", "green", "blue", "yellow", "none"], + bold: bool = False, + underline: bool = False, + dim: bool = False, + ) -> str: + """Apply simple color and style (underlined or bold).""" + if self.dummy_term: + return text + if bold: + start = self.BOLD + else: + start = "" + if underline: + start += self.UNDER + if dim: + start += self.DIM + return start + self.colors[color] + text + self.NORMAL + + def is_marker_line(self, line: str) -> bool: + s_line = line.lstrip() + return ( + line.startswith(CODE_START) + and s_line.startswith("^") + and set(s_line).issubset({"^", "~"}) + ) + + def fit_in_terminal( + self, messages: list[str], fixed_terminal_width: int | None = None + ) -> list[str]: + """Improve readability by wrapping error messages and trimming source code.""" + width = fixed_terminal_width or get_terminal_width() + new_messages = messages.copy() + for i, error in enumerate(messages): + # TODO: detecting source code highlights through an indent can be surprising. + if not error.startswith(CODE_START) and ": error:" in error: + loc, msg = error.split("error:", maxsplit=1) + msg = soft_wrap(msg, width, first_offset=len(loc) + len("error: ")) + new_messages[i] = loc + "error:" + msg + elif error.startswith(CODE_START) and not self.is_marker_line(error): + # Restore original error message and error location. + error = error[DEFAULT_SOURCE_OFFSET:] + marker_line = messages[i + 1] + marker_column = marker_line.index("^") + column = marker_column - DEFAULT_SOURCE_OFFSET + if "~" not in marker_line: + marker = "^" + else: + # +1 because both ends are included + marker = marker_line[marker_column : marker_line.rindex("~") + 1] + + # Let source have some space also on the right side, plus 6 + # to accommodate ... on each side. + max_len = width - DEFAULT_SOURCE_OFFSET - 6 + source_line, offset = trim_source_line(error, max_len, column, MINIMUM_WIDTH) + + new_messages[i] = " " * DEFAULT_SOURCE_OFFSET + source_line + # Also adjust the error marker position and trim error marker is needed. + new_marker_line = " " * (DEFAULT_SOURCE_OFFSET + column - offset) + marker + if len(new_marker_line) > len(new_messages[i]) and len(marker) > 3: + new_marker_line = new_marker_line[: len(new_messages[i]) - 3] + "..." + new_messages[i + 1] = new_marker_line + return new_messages + + def colorize(self, error: str) -> str: + """Colorize an output line by highlighting the status and error code.""" + # TODO: detecting source code highlights through an indent can be surprising. + if error.startswith(CODE_START): + if not self.is_marker_line(error): + return self.style(error, "none", dim=True) + return self.style(error, "red") + elif ": error:" in error: + loc, msg = error.split("error:", maxsplit=1) + if self.hide_error_codes: + return ( + loc + self.style("error:", "red", bold=True) + self.highlight_quote_groups(msg) + ) + codepos = msg.rfind("[") + if codepos != -1: + code = msg[codepos:] + msg = msg[:codepos] + else: + code = "" # no error code specified + return ( + loc + + self.style("error:", "red", bold=True) + + self.highlight_quote_groups(msg) + + self.style(code, "yellow") + ) + elif ": note:" in error: + loc, msg = error.split("note:", maxsplit=1) + formatted = self.highlight_quote_groups(self.underline_link(msg)) + return loc + self.style("note:", "blue") + formatted + else: + return error + + def highlight_quote_groups(self, msg: str) -> str: + """Make groups quoted with double quotes bold (including quotes). + + This is used to highlight types, attribute names etc. + """ + if msg.count('"') % 2: + # Broken error message, don't do any formatting. + return msg + parts = msg.split('"') + out = "" + for i, part in enumerate(parts): + if i % 2 == 0: + out += self.style(part, "none") + else: + out += self.style('"' + part + '"', "none", bold=True) + return out + + def underline_link(self, note: str) -> str: + """Underline a link in a note message (if any). + + This assumes there is at most one link in the message. + """ + match = re.search(r"https?://\S*", note) + if not match: + return note + start = match.start() + end = match.end() + return note[:start] + self.style(note[start:end], "none", underline=True) + note[end:] + + def format_success(self, n_sources: int, use_color: bool = True) -> str: + """Format short summary in case of success. + + n_sources is total number of files passed directly on command line, + i.e. excluding stubs and followed imports. + """ + if self.hide_success: + return "" + + msg = f"Success: no issues found in {n_sources} source file{plural_s(n_sources)}" + if not use_color: + return msg + return self.style(msg, "green", bold=True) + + def format_error( + self, + n_errors: int, + n_files: int, + n_sources: int, + *, + blockers: bool = False, + use_color: bool = True, + ) -> str: + """Format a short summary in case of errors.""" + msg = f"Found {n_errors} error{plural_s(n_errors)} in {n_files} file{plural_s(n_files)}" + if blockers: + msg += " (errors prevented further checking)" + else: + msg += f" (checked {n_sources} source file{plural_s(n_sources)})" + if not use_color: + return msg + return self.style(msg, "red", bold=True) + + +def is_typeshed_file(typeshed_dir: str | None, file: str) -> bool: + typeshed_dir = typeshed_dir if typeshed_dir is not None else TYPESHED_DIR + try: + return os.path.commonpath((typeshed_dir, os.path.abspath(file))) == typeshed_dir + except ValueError: # Different drives on Windows + return False + + +def is_stdlib_file(typeshed_dir: str | None, file: str) -> bool: + if "stdlib" not in file: + # Fast path + return False + typeshed_dir = typeshed_dir if typeshed_dir is not None else TYPESHED_DIR + stdlib_dir = os.path.join(typeshed_dir, "stdlib") + try: + return os.path.commonpath((stdlib_dir, os.path.abspath(file))) == stdlib_dir + except ValueError: # Different drives on Windows + return False + + +def is_stub_package_file(file: str) -> bool: + # Use hacky heuristics to check whether file is part of a PEP 561 stub package. + if not file.endswith(".pyi"): + return False + return any(component.endswith("-stubs") for component in os.path.split(os.path.abspath(file))) + + +def unnamed_function(name: str | None) -> bool: + return name is not None and name == "_" + + +time_ref = time.perf_counter_ns + + +def time_spent_us(t0: int) -> int: + return int((time.perf_counter_ns() - t0) / 1000) + + +def plural_s(s: int | Sized) -> str: + count = s if isinstance(s, int) else len(s) + if count != 1: + return "s" + else: + return "" + + +def quote_docstring(docstr: str) -> str: + """Returns docstring correctly encapsulated in a single or double quoted form.""" + # Uses repr to get hint on the correct quotes and escape everything properly. + # Creating multiline string for prettier output. + docstr_repr = "\n".join(re.split(r"(?<=[^\\])\\n", repr(docstr))) + + if docstr_repr.startswith("'"): + # Enforce double quotes when it's safe to do so. + # That is when double quotes are not in the string + # or when it doesn't end with a single quote. + if '"' not in docstr_repr[1:-1] and docstr_repr[-2] != "'": + return f'"""{docstr_repr[1:-1]}"""' + return f"''{docstr_repr}''" + else: + return f'""{docstr_repr}""' + + +def json_dumps(obj: object, debug: bool = False) -> bytes: + if orjson is not None: + if debug: + dumps_option = orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS + else: + # TODO: If we don't sort keys here, testIncrementalInternalScramble fails + # We should document exactly what is going on there + dumps_option = orjson.OPT_SORT_KEYS + + try: + return orjson.dumps(obj, option=dumps_option) # type: ignore[no-any-return] + except TypeError as e: + if str(e) != "Integer exceeds 64-bit range": + raise + + if debug: + return json.dumps(obj, indent=2, sort_keys=True).encode("utf-8") + else: + # See above for sort_keys comment + return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def json_loads(data: bytes) -> Any: + if orjson is not None: + return orjson.loads(data) + return json.loads(data) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/version.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/version.py new file mode 100644 index 0000000000000000000000000000000000000000..cd954b0f8e5579119866c434db923837e456e300 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/version.py @@ -0,0 +1 @@ +__version__ = "1.20.2" diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/visitor.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/visitor.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5ea2f0e28e84d234cb5e2f1b50657fb6913fcc88 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/visitor.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/visitor.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/visitor.py new file mode 100644 index 0000000000000000000000000000000000000000..de754c408f97d767ddbdcbf0be44bdac2833f3a5 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/visitor.py @@ -0,0 +1,639 @@ +"""Generic abstract syntax tree node visitor""" + +from __future__ import annotations + +from abc import abstractmethod +from typing import TYPE_CHECKING, Generic, TypeVar + +from mypy_extensions import mypyc_attr, trait + +if TYPE_CHECKING: + # break import cycle only needed for mypy + import mypy.nodes + import mypy.patterns + + +T = TypeVar("T") + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class ExpressionVisitor(Generic[T]): + @abstractmethod + def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T: + pass + + @abstractmethod + def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T: + pass + + @abstractmethod + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T: + pass + + @abstractmethod + def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T: + pass + + @abstractmethod + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T: + pass + + @abstractmethod + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T: + pass + + @abstractmethod + def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T: + pass + + @abstractmethod + def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T: + pass + + @abstractmethod + def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T: + pass + + @abstractmethod + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T: + pass + + @abstractmethod + def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T: + pass + + @abstractmethod + def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T: + pass + + @abstractmethod + def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T: + pass + + @abstractmethod + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T: + pass + + @abstractmethod + def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T: + pass + + @abstractmethod + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T: + pass + + @abstractmethod + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T: + pass + + @abstractmethod + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T: + pass + + @abstractmethod + def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T: + pass + + @abstractmethod + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T: + pass + + @abstractmethod + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T: + pass + + @abstractmethod + def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T: + pass + + @abstractmethod + def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T: + pass + + @abstractmethod + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr, /) -> T: + pass + + @abstractmethod + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T: + pass + + @abstractmethod + def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T: + pass + + @abstractmethod + def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T: + pass + + @abstractmethod + def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T: + pass + + @abstractmethod + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T: + pass + + @abstractmethod + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T: + pass + + @abstractmethod + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T: + pass + + @abstractmethod + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T: + pass + + @abstractmethod + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T: + pass + + @abstractmethod + def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T: + pass + + @abstractmethod + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T: + pass + + @abstractmethod + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T: + pass + + @abstractmethod + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T: + pass + + @abstractmethod + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T: + pass + + @abstractmethod + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T: + pass + + @abstractmethod + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T: + pass + + @abstractmethod + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T: + pass + + @abstractmethod + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T: + pass + + @abstractmethod + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T: + pass + + @abstractmethod + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T: + pass + + @abstractmethod + def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T: + pass + + @abstractmethod + def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class StatementVisitor(Generic[T]): + # Definitions + + @abstractmethod + def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T: + pass + + @abstractmethod + def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T: + pass + + @abstractmethod + def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T: + pass + + @abstractmethod + def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T: + pass + + @abstractmethod + def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T: + pass + + @abstractmethod + def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T: + pass + + @abstractmethod + def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T: + pass + + @abstractmethod + def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T: + pass + + @abstractmethod + def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T: + pass + + @abstractmethod + def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T: + pass + + # Module structure + + @abstractmethod + def visit_import(self, o: mypy.nodes.Import, /) -> T: + pass + + @abstractmethod + def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T: + pass + + @abstractmethod + def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T: + pass + + # Statements + + @abstractmethod + def visit_block(self, o: mypy.nodes.Block, /) -> T: + pass + + @abstractmethod + def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T: + pass + + @abstractmethod + def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T: + pass + + @abstractmethod + def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T: + pass + + @abstractmethod + def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T: + pass + + @abstractmethod + def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T: + pass + + @abstractmethod + def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T: + pass + + @abstractmethod + def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T: + pass + + @abstractmethod + def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T: + pass + + @abstractmethod + def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T: + pass + + @abstractmethod + def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T: + pass + + @abstractmethod + def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T: + pass + + @abstractmethod + def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T: + pass + + @abstractmethod + def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class PatternVisitor(Generic[T]): + @abstractmethod + def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T: + pass + + @abstractmethod + def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T: + pass + + @abstractmethod + def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T: + pass + + @abstractmethod + def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T: + pass + + @abstractmethod + def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T: + pass + + @abstractmethod + def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T: + pass + + @abstractmethod + def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T: + pass + + @abstractmethod + def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class NodeVisitor(Generic[T], ExpressionVisitor[T], StatementVisitor[T], PatternVisitor[T]): + """Empty base class for parse tree node visitors. + + The T type argument specifies the return type of the visit + methods. As all methods defined here raise by default, + subclasses do not always need to override all the methods. + """ + + # Not in superclasses: + + def visit_mypy_file(self, o: mypy.nodes.MypyFile, /) -> T: + raise NotImplementedError() + + # TODO: We have a visit_var method, but no visit_typeinfo or any + # other non-Statement SymbolNode (accepting those will raise a + # runtime error). Maybe this should be resolved in some direction. + def visit_var(self, o: mypy.nodes.Var, /) -> T: + raise NotImplementedError() + + # Module structure + + def visit_import(self, o: mypy.nodes.Import, /) -> T: + raise NotImplementedError() + + def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T: + raise NotImplementedError() + + def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T: + raise NotImplementedError() + + # Definitions + + def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T: + raise NotImplementedError() + + def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T: + raise NotImplementedError() + + def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T: + raise NotImplementedError() + + def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T: + raise NotImplementedError() + + def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T: + raise NotImplementedError() + + def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T: + raise NotImplementedError() + + def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> T: + raise NotImplementedError() + + def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> T: + raise NotImplementedError() + + # Statements + + def visit_block(self, o: mypy.nodes.Block, /) -> T: + raise NotImplementedError() + + def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T: + raise NotImplementedError() + + def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T: + raise NotImplementedError() + + def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T: + raise NotImplementedError() + + def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T: + raise NotImplementedError() + + def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T: + raise NotImplementedError() + + def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T: + raise NotImplementedError() + + def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T: + raise NotImplementedError() + + def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T: + raise NotImplementedError() + + def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T: + raise NotImplementedError() + + def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T: + raise NotImplementedError() + + def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T: + raise NotImplementedError() + + def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T: + raise NotImplementedError() + + def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T: + raise NotImplementedError() + + def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T: + raise NotImplementedError() + + def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T: + raise NotImplementedError() + + def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T: + raise NotImplementedError() + + def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T: + raise NotImplementedError() + + # Expressions (default no-op implementation) + + def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T: + raise NotImplementedError() + + def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T: + raise NotImplementedError() + + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T: + raise NotImplementedError() + + def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T: + raise NotImplementedError() + + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T: + raise NotImplementedError() + + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T: + raise NotImplementedError() + + def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T: + raise NotImplementedError() + + def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T: + raise NotImplementedError() + + def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T: + raise NotImplementedError() + + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T: + raise NotImplementedError() + + def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T: + raise NotImplementedError() + + def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T: + raise NotImplementedError() + + def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T: + raise NotImplementedError() + + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T: + raise NotImplementedError() + + def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T: + raise NotImplementedError() + + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T: + raise NotImplementedError() + + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T: + raise NotImplementedError() + + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T: + raise NotImplementedError() + + def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T: + raise NotImplementedError() + + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T: + raise NotImplementedError() + + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T: + raise NotImplementedError() + + def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T: + raise NotImplementedError() + + def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T: + raise NotImplementedError() + + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr, /) -> T: + raise NotImplementedError() + + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T: + raise NotImplementedError() + + def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T: + raise NotImplementedError() + + def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T: + raise NotImplementedError() + + def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T: + raise NotImplementedError() + + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T: + raise NotImplementedError() + + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T: + raise NotImplementedError() + + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T: + raise NotImplementedError() + + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T: + raise NotImplementedError() + + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T: + raise NotImplementedError() + + def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T: + raise NotImplementedError() + + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T: + raise NotImplementedError() + + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T: + raise NotImplementedError() + + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T: + raise NotImplementedError() + + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T: + raise NotImplementedError() + + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T: + raise NotImplementedError() + + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T: + raise NotImplementedError() + + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T: + raise NotImplementedError() + + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T: + raise NotImplementedError() + + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T: + raise NotImplementedError() + + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T: + raise NotImplementedError() + + def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T: + raise NotImplementedError() + + def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T: + raise NotImplementedError() + + # Patterns + + def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T: + raise NotImplementedError() + + def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T: + raise NotImplementedError() + + def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T: + raise NotImplementedError() + + def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T: + raise NotImplementedError() + + def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T: + raise NotImplementedError() + + def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T: + raise NotImplementedError() + + def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T: + raise NotImplementedError() + + def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T: + raise NotImplementedError() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__init__.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f88f94b98530986c66fad1bd0276af380cde0ae3 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__init__.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__main__.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3973710efac36fbb129f5c0ff7dacc4ff5e5d0 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/__main__.py @@ -0,0 +1,72 @@ +"""Mypyc command-line tool. + +Usage: + + $ mypyc foo.py [...] + $ python3 -c 'import foo' # Uses compiled 'foo' + + +This is just a thin wrapper that generates a setup.py file that uses +mypycify, suitable for prototyping and testing. +""" + +from __future__ import annotations + +import os +import os.path +import subprocess +import sys + +base_path = os.path.join(os.path.dirname(__file__), "..") + +setup_format = """\ +from setuptools import setup +from mypyc.build import mypycify + +setup( + name='mypyc_output', + ext_modules=mypycify( + {}, + opt_level="{}", + debug_level="{}", + strict_dunder_typing={}, + log_trace={}, + ), +) +""" + + +def main() -> None: + build_dir = "build" # can this be overridden?? + try: + os.mkdir(build_dir) + except FileExistsError: + pass + + opt_level = os.getenv("MYPYC_OPT_LEVEL", "3") + debug_level = os.getenv("MYPYC_DEBUG_LEVEL", "1") + strict_dunder_typing = bool(int(os.getenv("MYPYC_STRICT_DUNDER_TYPING", "0"))) + # If enabled, compiled code writes a sampled log of executed ops (or events) to + # mypyc_trace.txt. + log_trace = bool(int(os.getenv("MYPYC_LOG_TRACE", "0"))) + + setup_file = os.path.join(build_dir, "setup.py") + with open(setup_file, "w") as f: + f.write( + setup_format.format( + sys.argv[1:], opt_level, debug_level, strict_dunder_typing, log_trace + ) + ) + + # We don't use run_setup (like we do in the test suite) because it throws + # away the error code from distutils, and we don't care about the slight + # performance loss here. + env = os.environ.copy() + base_path = os.path.join(os.path.dirname(__file__), "..") + env["PYTHONPATH"] = base_path + os.pathsep + env.get("PYTHONPATH", "") + cmd = subprocess.run([sys.executable, setup_file, "build_ext", "--inplace"], env=env) + sys.exit(cmd.returncode) + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ce68f532776ca350aa358e7adeb2e3e6d03c14c6 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/__init__.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..654e15a3b3f06a6bbe47d368457652244a749a8c Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/attrdefined.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/attrdefined.py new file mode 100644 index 0000000000000000000000000000000000000000..1dfd33630f1c03e3b2f796c8d7ea4acc339fd2ae --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/attrdefined.py @@ -0,0 +1,437 @@ +"""Always defined attribute analysis. + +An always defined attribute has some statements in __init__ or the +class body that cause the attribute to be always initialized when an +instance is constructed. It must also not be possible to read the +attribute before initialization, and it can't be deletable. + +We can assume that the value is always defined when reading an always +defined attribute. Otherwise we'll need to raise AttributeError if the +value is undefined (i.e. has the error value). + +We use data flow analysis to figure out attributes that are always +defined. Example: + + class C: + def __init__(self) -> None: + self.x = 0 + if func(): + self.y = 1 + else: + self.y = 2 + self.z = 3 + +In this example, the attributes 'x' and 'y' are always defined, but 'z' +is not. The analysis assumes that we know that there won't be any subclasses. + +The analysis also works if there is a known, closed set of subclasses. +An attribute defined in a base class can only be always defined if it's +also always defined in all subclasses. + +As soon as __init__ contains an op that can 'leak' self to another +function, we will stop inferring always defined attributes, since the +analysis is mostly intra-procedural and only looks at __init__ methods. +The called code could read an uninitialized attribute. Example: + + class C: + def __init__(self) -> None: + self.x = self.foo() + + def foo(self) -> int: + ... + +Now we won't infer 'x' as always defined, since 'foo' might read 'x' +before initialization. + +As an exception to the above limitation, we perform inter-procedural +analysis of super().__init__ calls, since these are very common. + +Our analysis is somewhat optimistic. We assume that nobody calls a +method of a partially uninitialized object through gc.get_objects(), in +particular. Code like this could potentially cause a segfault with a null +pointer dereference. This seems very unlikely to be an issue in practice, +however. + +Accessing an attribute via getattr always checks for undefined attributes +and thus works if the object is partially uninitialized. This can be used +as a workaround if somebody ever needs to inspect partially uninitialized +objects via gc.get_objects(). + +The analysis runs after IR building as a separate pass. Since we only +run this on __init__ methods, this analysis pass will be fairly quick. +""" + +from __future__ import annotations + +from typing import Final + +from mypyc.analysis.dataflow import ( + CFG, + MAYBE_ANALYSIS, + AnalysisResult, + BaseAnalysisVisitor, + get_cfg, + run_analysis, +) +from mypyc.analysis.selfleaks import analyze_self_leaks +from mypyc.ir.class_ir import ClassIR +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BasicBlock, + Branch, + Call, + ControlOp, + GetAttr, + Register, + RegisterOp, + Return, + SetAttr, + SetMem, + Unreachable, +) +from mypyc.ir.rtypes import RInstance + +# If True, print out all always-defined attributes of native classes (to aid +# debugging and testing) +dump_always_defined: Final = False + + +def analyze_always_defined_attrs(class_irs: list[ClassIR]) -> None: + """Find always defined attributes all classes of a compilation unit. + + Also tag attribute initialization ops to not decref the previous + value (as this would read a NULL pointer and segfault). + + Update the _always_initialized_attrs, _sometimes_initialized_attrs + and init_self_leak attributes in ClassIR instances. + + This is the main entry point. + """ + seen: set[ClassIR] = set() + + # First pass: only look at target class and classes in MRO + for cl in class_irs: + analyze_always_defined_attrs_in_class(cl, seen) + + # Second pass: look at all derived class + seen = set() + for cl in class_irs: + update_always_defined_attrs_using_subclasses(cl, seen) + + # Final pass: detect attributes that need to use a bitmap to track definedness + seen = set() + for cl in class_irs: + detect_undefined_bitmap(cl, seen) + + +def analyze_always_defined_attrs_in_class(cl: ClassIR, seen: set[ClassIR]) -> None: + if cl in seen: + return + + seen.add(cl) + + if ( + cl.is_trait + or cl.inherits_python + or cl.allow_interpreted_subclasses + or cl.builtin_base is not None + or cl.children is None + or cl.is_serializable() + or cl.has_method("__new__") + ): + # Give up -- we can't enforce that attributes are always defined. + return + + # First analyze all base classes. Track seen classes to avoid duplicate work. + for base in cl.mro[1:]: + analyze_always_defined_attrs_in_class(base, seen) + + m = cl.get_method("__init__") + if m is None: + cl._always_initialized_attrs = cl.attrs_with_defaults.copy() + cl._sometimes_initialized_attrs = cl.attrs_with_defaults.copy() + return + self_reg = m.arg_regs[0] + cfg = get_cfg(m.blocks) + dirty = analyze_self_leaks(m.blocks, self_reg, cfg) + maybe_defined = analyze_maybe_defined_attrs_in_init( + m.blocks, self_reg, cl.attrs_with_defaults, cfg + ) + all_attrs: set[str] = set() + for base in cl.mro: + all_attrs.update(base.attributes) + maybe_undefined = analyze_maybe_undefined_attrs_in_init( + m.blocks, self_reg, initial_undefined=all_attrs - cl.attrs_with_defaults, cfg=cfg + ) + + always_defined = find_always_defined_attributes( + m.blocks, self_reg, all_attrs, maybe_defined, maybe_undefined, dirty + ) + always_defined = {a for a in always_defined if not cl.is_deletable(a)} + + cl._always_initialized_attrs = always_defined + if dump_always_defined: + print(cl.name, sorted(always_defined)) + cl._sometimes_initialized_attrs = find_sometimes_defined_attributes( + m.blocks, self_reg, maybe_defined, dirty + ) + + mark_attr_initialization_ops(m.blocks, self_reg, maybe_defined, dirty) + + # Check if __init__ can run unpredictable code (leak 'self'). + any_dirty = False + for b in m.blocks: + for i, op in enumerate(b.ops): + if dirty.after[b, i] and not isinstance(op, Return): + any_dirty = True + break + cl.init_self_leak = any_dirty + + +def find_always_defined_attributes( + blocks: list[BasicBlock], + self_reg: Register, + all_attrs: set[str], + maybe_defined: AnalysisResult[str], + maybe_undefined: AnalysisResult[str], + dirty: AnalysisResult[None], +) -> set[str]: + """Find attributes that are always initialized in some basic blocks. + + The analysis results are expected to be up-to-date for the blocks. + + Return a set of always defined attributes. + """ + attrs = all_attrs.copy() + for block in blocks: + for i, op in enumerate(block.ops): + # If an attribute we *read* may be undefined, it isn't always defined. + if isinstance(op, GetAttr) and op.obj is self_reg: + if op.attr in maybe_undefined.before[block, i]: + attrs.discard(op.attr) + # If an attribute we *set* may be sometimes undefined and + # sometimes defined, don't consider it always defined. Unlike + # the get case, it's fine for the attribute to be undefined. + # The set operation will then be treated as initialization. + if isinstance(op, SetAttr) and op.obj is self_reg: + if ( + op.attr in maybe_undefined.before[block, i] + and op.attr in maybe_defined.before[block, i] + ): + attrs.discard(op.attr) + # Treat an op that might run arbitrary code as an "exit" + # in terms of the analysis -- we can't do any inference + # afterwards reliably. + if dirty.after[block, i]: + if not dirty.before[block, i]: + attrs = attrs & ( + maybe_defined.after[block, i] - maybe_undefined.after[block, i] + ) + break + if isinstance(op, ControlOp): + for target in op.targets(): + # Gotos/branches can also be "exits". + if not dirty.after[block, i] and dirty.before[target, 0]: + attrs = attrs & ( + maybe_defined.after[target, 0] - maybe_undefined.after[target, 0] + ) + return attrs + + +def find_sometimes_defined_attributes( + blocks: list[BasicBlock], + self_reg: Register, + maybe_defined: AnalysisResult[str], + dirty: AnalysisResult[None], +) -> set[str]: + """Find attributes that are sometimes initialized in some basic blocks.""" + attrs: set[str] = set() + for block in blocks: + for i, op in enumerate(block.ops): + # Only look at possibly defined attributes at exits. + if dirty.after[block, i]: + if not dirty.before[block, i]: + attrs = attrs | maybe_defined.after[block, i] + break + if isinstance(op, ControlOp): + for target in op.targets(): + if not dirty.after[block, i] and dirty.before[target, 0]: + attrs = attrs | maybe_defined.after[target, 0] + return attrs + + +def mark_attr_initialization_ops( + blocks: list[BasicBlock], + self_reg: Register, + maybe_defined: AnalysisResult[str], + dirty: AnalysisResult[None], +) -> None: + """Tag all SetAttr ops in the basic blocks that initialize attributes. + + Initialization ops assume that the previous attribute value is the error value, + so there's no need to decref or check for definedness. + """ + for block in blocks: + for i, op in enumerate(block.ops): + if isinstance(op, SetAttr) and op.obj is self_reg: + attr = op.attr + if attr not in maybe_defined.before[block, i] and not dirty.after[block, i]: + op.mark_as_initializer() + + +GenAndKill = tuple[set[str], set[str]] + + +def attributes_initialized_by_init_call(op: Call) -> set[str]: + """Calculate attributes that are always initialized by a super().__init__ call.""" + self_type = op.fn.sig.args[0].type + assert isinstance(self_type, RInstance), self_type + cl = self_type.class_ir + return {a for base in cl.mro for a in base.attributes if base.is_always_defined(a)} + + +def attributes_maybe_initialized_by_init_call(op: Call) -> set[str]: + """Calculate attributes that may be initialized by a super().__init__ call.""" + self_type = op.fn.sig.args[0].type + assert isinstance(self_type, RInstance), self_type + cl = self_type.class_ir + return attributes_initialized_by_init_call(op) | cl._sometimes_initialized_attrs + + +class AttributeMaybeDefinedVisitor(BaseAnalysisVisitor[str]): + """Find attributes that may have been defined via some code path. + + Consider initializations in class body and assignments to 'self.x' + and calls to base class '__init__'. + """ + + def __init__(self, self_reg: Register) -> None: + self.self_reg = self_reg + + def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_return(self, op: Return) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]: + if isinstance(op, SetAttr) and op.obj is self.self_reg: + return {op.attr}, set() + if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__": + return attributes_maybe_initialized_by_init_call(op), set() + return set(), set() + + def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]: + return set(), set() + + +def analyze_maybe_defined_attrs_in_init( + blocks: list[BasicBlock], self_reg: Register, attrs_with_defaults: set[str], cfg: CFG +) -> AnalysisResult[str]: + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=AttributeMaybeDefinedVisitor(self_reg), + initial=attrs_with_defaults, + backward=False, + kind=MAYBE_ANALYSIS, + ) + + +class AttributeMaybeUndefinedVisitor(BaseAnalysisVisitor[str]): + """Find attributes that may be undefined via some code path. + + Consider initializations in class body, assignments to 'self.x' + and calls to base class '__init__'. + """ + + def __init__(self, self_reg: Register) -> None: + self.self_reg = self_reg + + def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_return(self, op: Return) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]: + if isinstance(op, SetAttr) and op.obj is self.self_reg: + return set(), {op.attr} + if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__": + return set(), attributes_initialized_by_init_call(op) + return set(), set() + + def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]: + return set(), set() + + +def analyze_maybe_undefined_attrs_in_init( + blocks: list[BasicBlock], self_reg: Register, initial_undefined: set[str], cfg: CFG +) -> AnalysisResult[str]: + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=AttributeMaybeUndefinedVisitor(self_reg), + initial=initial_undefined, + backward=False, + kind=MAYBE_ANALYSIS, + ) + + +def update_always_defined_attrs_using_subclasses(cl: ClassIR, seen: set[ClassIR]) -> None: + """Remove attributes not defined in all subclasses from always defined attrs.""" + if cl in seen: + return + if cl.children is None: + # Subclasses are unknown + return + removed = set() + for attr in cl._always_initialized_attrs: + for child in cl.children: + update_always_defined_attrs_using_subclasses(child, seen) + if attr not in child._always_initialized_attrs: + removed.add(attr) + cl._always_initialized_attrs -= removed + seen.add(cl) + + +def detect_undefined_bitmap(cl: ClassIR, seen: set[ClassIR]) -> None: + if cl.is_trait: + return + + if cl in seen: + return + seen.add(cl) + for base in cl.base_mro[1:]: + detect_undefined_bitmap(base, seen) + + if len(cl.base_mro) > 1: + cl.bitmap_attrs.extend(cl.base_mro[1].bitmap_attrs) + for n, t in cl.attributes.items(): + if t.error_overlap and not cl.is_always_defined(n): + cl.bitmap_attrs.append(n) + + for base in cl.mro[1:]: + if base.is_trait: + for n, t in base.attributes.items(): + if t.error_overlap and not cl.is_always_defined(n) and n not in cl.bitmap_attrs: + cl.bitmap_attrs.append(n) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c4bf1abf69117818b6fd71730c14e692ce77ef81 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/blockfreq.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/blockfreq.py new file mode 100644 index 0000000000000000000000000000000000000000..74a1bc0579c61c166ed69f575b3848e30f21a74c --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/blockfreq.py @@ -0,0 +1,32 @@ +"""Find basic blocks that are likely to be executed frequently. + +For example, this would not include blocks that have exception handlers. + +We can use different optimization heuristics for common and rare code. For +example, we can make IR fast to compile instead of fast to execute for rare +code. +""" + +from __future__ import annotations + +from mypyc.ir.ops import BasicBlock, Branch, Goto + + +def frequently_executed_blocks(entry_point: BasicBlock) -> set[BasicBlock]: + result: set[BasicBlock] = set() + worklist = [entry_point] + while worklist: + block = worklist.pop() + if block in result: + continue + result.add(block) + t = block.terminator + if isinstance(t, Goto): + worklist.append(t.label) + elif isinstance(t, Branch): + if t.rare or t.traceback_entry is not None: + worklist.append(t.false) + else: + worklist.append(t.true) + worklist.append(t.false) + return result diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3c2e6b7704c19c03ef99c39f921c4b16a1941cd3 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/capsule_deps.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/capsule_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..5b39b8bd2e101f967ea51fbbc8e565b8a2af9b03 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/capsule_deps.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from mypyc.ir.class_ir import ClassIR +from mypyc.ir.deps import Dependency +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.ops import Assign, CallC, PrimitiveOp +from mypyc.ir.rtypes import RStruct, RTuple, RType, RUnion, RVec + + +def find_implicit_op_dependencies(fn: FuncIR) -> set[Dependency] | None: + """Find implicit dependencies that need to be imported. + + Using primitives or types defined in librt submodules such as "librt.base64" + requires dependency imports (e.g., capsule imports). + + Note that a module can depend on a librt module even if it doesn't explicitly + import it, for example via re-exported names or via return types of functions + defined in other modules. + """ + deps: set[Dependency] | None = None + # Check function signature types for dependencies + deps = find_type_dependencies(fn, deps) + # Check ops for dependencies + for block in fn.blocks: + for op in block.ops: + assert not isinstance(op, PrimitiveOp), "Lowered IR is expected" + if isinstance(op, CallC) and op.dependencies is not None: + for dep in op.dependencies: + if deps is None: + deps = set() + deps.add(dep) + deps = collect_type_deps(op.type, deps) + if isinstance(op, Assign): + deps = collect_type_deps(op.dest.type, deps) + return deps + + +def find_type_dependencies(fn: FuncIR, deps: set[Dependency] | None) -> set[Dependency] | None: + """Find dependencies from RTypes in function signatures. + + Some RTypes (e.g., those for librt types) have associated dependencies + that need to be imported when the type is used. + """ + # Check parameter types + for arg in fn.decl.sig.args: + deps = collect_type_deps(arg.type, deps) + # Check return type + deps = collect_type_deps(fn.decl.sig.ret_type, deps) + return deps + + +def find_class_dependencies(cl: ClassIR) -> set[Dependency] | None: + """Find dependencies from class attribute types.""" + deps: set[Dependency] | None = None + for base in cl.mro: + for attr_type in base.attributes.values(): + deps = collect_type_deps(attr_type, deps) + return deps + + +def collect_type_deps(typ: RType, deps: set[Dependency] | None) -> set[Dependency] | None: + """Collect dependencies from an RType, recursively checking compound types.""" + if typ.dependencies is not None: + for dep in typ.dependencies: + if deps is None: + deps = set() + deps.add(dep) + if isinstance(typ, RUnion): + for item in typ.items: + deps = collect_type_deps(item, deps) + elif isinstance(typ, RTuple): + for item in typ.types: + deps = collect_type_deps(item, deps) + elif isinstance(typ, RStruct): + for item in typ.types: + deps = collect_type_deps(item, deps) + elif isinstance(typ, RVec): + deps = collect_type_deps(typ.item_type, deps) + return deps diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ef2ffcdcf55c9d715c5064229a3371a6a46f102e Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/dataflow.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/dataflow.py new file mode 100644 index 0000000000000000000000000000000000000000..480a725a0aecc8341be16aa655aecbfe61e0a90d --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/dataflow.py @@ -0,0 +1,645 @@ +"""Data-flow analyses.""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Iterable, Iterator, Set as AbstractSet +from typing import Any, Generic, TypeVar + +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + ControlOp, + DecRef, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + RegisterOp, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Undef, + Unreachable, + Value, +) + + +class CFG: + """Control-flow graph. + + Node 0 is always assumed to be the entry point. There must be a + non-empty set of exits. + """ + + def __init__( + self, + succ: dict[BasicBlock, list[BasicBlock]], + pred: dict[BasicBlock, list[BasicBlock]], + exits: set[BasicBlock], + ) -> None: + assert exits + self.succ = succ + self.pred = pred + self.exits = exits + + def __str__(self) -> str: + exits = sorted(self.exits, key=lambda e: int(e.label)) + return f"exits: {exits}\nsucc: {self.succ}\npred: {self.pred}" + + +def get_cfg(blocks: list[BasicBlock], *, use_yields: bool = False) -> CFG: + """Calculate basic block control-flow graph. + + If use_yields is set, then we treat returns inserted by yields as gotos + instead of exits. + """ + succ_map = {} + pred_map: dict[BasicBlock, list[BasicBlock]] = {} + exits = set() + for block in blocks: + assert not any( + isinstance(op, ControlOp) for op in block.ops[:-1] + ), "Control-flow ops must be at the end of blocks" + + if use_yields and isinstance(block.terminator, Return) and block.terminator.yield_target: + succ = [block.terminator.yield_target] + else: + succ = list(block.terminator.targets()) + if not succ: + exits.add(block) + + # Errors can occur anywhere inside a block, which means that + # we can't assume that the entire block has executed before + # jumping to the error handler. In our CFG construction, we + # model this as saying that a block can jump to its error + # handler or the error handlers of any of its normal + # successors (to represent an error before that next block + # completes). This works well for analyses like "must + # defined", where it implies that registers assigned in a + # block may be undefined in its error handler, but is in + # general not a precise representation of reality; any + # analyses that require more fidelity must wait until after + # exception insertion. + for error_point in [block] + succ: + if error_point.error_handler: + succ.append(error_point.error_handler) + + succ_map[block] = succ + pred_map[block] = [] + for prev, nxt in succ_map.items(): + for label in nxt: + pred_map[label].append(prev) + return CFG(succ_map, pred_map, exits) + + +def get_real_target(label: BasicBlock) -> BasicBlock: + if len(label.ops) == 1 and isinstance(label.ops[-1], Goto): + label = label.ops[-1].label + return label + + +def cleanup_cfg(blocks: list[BasicBlock]) -> None: + """Cleanup the control flow graph. + + This eliminates obviously dead basic blocks and eliminates blocks that contain + nothing but a single jump. + + There is a lot more that could be done. + """ + changed = True + while changed: + # First collapse any jumps to basic block that only contain a goto + for block in blocks: + for i, tgt in enumerate(block.terminator.targets()): + block.terminator.set_target(i, get_real_target(tgt)) + + # Then delete any blocks that have no predecessors + changed = False + cfg = get_cfg(blocks) + orig_blocks = blocks.copy() + blocks.clear() + for i, block in enumerate(orig_blocks): + if i == 0 or cfg.pred[block]: + blocks.append(block) + else: + changed = True + + +T = TypeVar("T") + +AnalysisDict = dict[tuple[BasicBlock, int], set[T]] + + +class AnalysisResult(Generic[T]): + def __init__(self, before: AnalysisDict[T], after: AnalysisDict[T]) -> None: + self.before = before + self.after = after + + def __str__(self) -> str: + return f"before: {self.before}\nafter: {self.after}\n" + + +GenAndKill = tuple[AbstractSet[T], AbstractSet[T]] + +_EMPTY: tuple[frozenset[Any], frozenset[Any]] = (frozenset(), frozenset()) + + +class BaseAnalysisVisitor(OpVisitor[GenAndKill[T]]): + def visit_goto(self, op: Goto) -> GenAndKill[T]: + return _EMPTY + + @abstractmethod + def visit_register_op(self, op: RegisterOp) -> GenAndKill[T]: + raise NotImplementedError + + @abstractmethod + def visit_assign(self, op: Assign) -> GenAndKill[T]: + raise NotImplementedError + + @abstractmethod + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[T]: + raise NotImplementedError + + @abstractmethod + def visit_set_mem(self, op: SetMem) -> GenAndKill[T]: + raise NotImplementedError + + def visit_inc_ref(self, op: IncRef) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_dec_ref(self, op: DecRef) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_call(self, op: Call) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_method_call(self, op: MethodCall) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_literal(self, op: LoadLiteral) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_get_attr(self, op: GetAttr) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_set_attr(self, op: SetAttr) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_static(self, op: LoadStatic) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_init_static(self, op: InitStatic) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_tuple_get(self, op: TupleGet) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_tuple_set(self, op: TupleSet) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_box(self, op: Box) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_unbox(self, op: Unbox) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_cast(self, op: Cast) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_call_c(self, op: CallC) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_truncate(self, op: Truncate) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_extend(self, op: Extend) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_global(self, op: LoadGlobal) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_int_op(self, op: IntOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_float_op(self, op: FloatOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_float_neg(self, op: FloatNeg) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_mem(self, op: LoadMem) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_get_element(self, op: GetElement) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_set_element(self, op: SetElement) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_address(self, op: LoadAddress) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_keep_alive(self, op: KeepAlive) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_unborrow(self, op: Unborrow) -> GenAndKill[T]: + return self.visit_register_op(op) + + +class DefinedVisitor(BaseAnalysisVisitor[Value]): + """Visitor for finding defined registers. + + Note that this only deals with registers and not temporaries, on + the assumption that we never access temporaries when they might be + undefined. + + If strict_errors is True, then we regard any use of LoadErrorValue + as making a register undefined. Otherwise we only do if + `undefines` is set on the error value. + + This lets us only consider the things we care about during + uninitialized variable checking while capturing all possibly + undefined things for refcounting. + """ + + def __init__(self, strict_errors: bool = False) -> None: + self.strict_errors = strict_errors + + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return _EMPTY + + def visit_return(self, op: Return) -> GenAndKill[Value]: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + return _EMPTY + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + # Loading an error value may undefine the register. + if isinstance(op.src, LoadErrorValue) and (op.src.undefines or self.strict_errors): + return set(), {op.dest} + else: + return {op.dest}, set() + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + # Array registers are special and we don't track the definedness of them. + return _EMPTY + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return _EMPTY + + +def analyze_maybe_defined_regs( + blocks: list[BasicBlock], cfg: CFG, initial_defined: set[Value] +) -> AnalysisResult[Value]: + """Calculate potentially defined registers at each CFG location. + + A register is defined if it has a value along some path from the initial location. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=DefinedVisitor(), + initial=initial_defined, + backward=False, + kind=MAYBE_ANALYSIS, + ) + + +def analyze_must_defined_regs( + blocks: list[BasicBlock], + cfg: CFG, + initial_defined: set[Value], + regs: Iterable[Value], + strict_errors: bool = False, +) -> AnalysisResult[Value]: + """Calculate always defined registers at each CFG location. + + This analysis can work before exception insertion, since it is a + sound assumption that registers defined in a block might not be + initialized in its error handler. + + A register is defined if it has a value along all paths from the + initial location. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=DefinedVisitor(strict_errors=strict_errors), + initial=initial_defined, + backward=False, + kind=MUST_ANALYSIS, + universe=set(regs), + ) + + +class BorrowedArgumentsVisitor(BaseAnalysisVisitor[Value]): + def __init__(self, args: set[Value]) -> None: + self.args = args + + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return _EMPTY + + def visit_return(self, op: Return) -> GenAndKill[Value]: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + return _EMPTY + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + if op.dest in self.args: + return set(), {op.dest} + return _EMPTY + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + return _EMPTY + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return _EMPTY + + +def analyze_borrowed_arguments( + blocks: list[BasicBlock], cfg: CFG, borrowed: set[Value] +) -> AnalysisResult[Value]: + """Calculate arguments that can use references borrowed from the caller. + + When assigning to an argument, it no longer is borrowed. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=BorrowedArgumentsVisitor(borrowed), + initial=borrowed, + backward=False, + kind=MUST_ANALYSIS, + universe=borrowed, + ) + + +class UndefinedVisitor(BaseAnalysisVisitor[Value]): + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return _EMPTY + + def visit_return(self, op: Return) -> GenAndKill[Value]: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + return set(), {op} if not op.is_void else set() + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + return set(), {op.dest} + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + return set(), {op.dest} + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return _EMPTY + + +def non_trivial_sources(op: Op) -> set[Value]: + result = set() + for source in op.sources(): + if not isinstance(source, (Integer, Float, Undef)): + result.add(source) + return result + + +class LivenessVisitor(BaseAnalysisVisitor[Value]): + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return non_trivial_sources(op), set() + + def visit_return(self, op: Return) -> GenAndKill[Value]: + if not isinstance(op.value, (Integer, Float)): + return {op.value}, set() + else: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + gen = non_trivial_sources(op) + if not op.is_void: + return gen, {op} + else: + return gen, set() + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + return non_trivial_sources(op), {op.dest} + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + return non_trivial_sources(op), {op.dest} + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return non_trivial_sources(op), set() + + def visit_inc_ref(self, op: IncRef) -> GenAndKill[Value]: + return _EMPTY + + def visit_dec_ref(self, op: DecRef) -> GenAndKill[Value]: + return _EMPTY + + +def analyze_live_regs(blocks: list[BasicBlock], cfg: CFG) -> AnalysisResult[Value]: + """Calculate live registers at each CFG location. + + A register is live at a location if it can be read along some CFG path starting + from the location. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=LivenessVisitor(), + initial=set(), + backward=True, + kind=MAYBE_ANALYSIS, + ) + + +# Analysis kinds +MUST_ANALYSIS = 0 +MAYBE_ANALYSIS = 1 + + +def run_analysis( + blocks: list[BasicBlock], + cfg: CFG, + gen_and_kill: OpVisitor[GenAndKill[T]], + initial: set[T], + kind: int, + backward: bool, + universe: set[T] | None = None, +) -> AnalysisResult[T]: + """Run a general set-based data flow analysis. + + Args: + blocks: All basic blocks + cfg: Control-flow graph for the code + gen_and_kill: Implementation of gen and kill functions for each op + initial: Value of analysis for the entry points (for a forward analysis) or the + exit points (for a backward analysis) + kind: MUST_ANALYSIS or MAYBE_ANALYSIS + backward: If False, the analysis is a forward analysis; it's backward otherwise + universe: For a must analysis, the set of all possible values. This is the starting + value for the work list algorithm, which will narrow this down until reaching a + fixed point. For a maybe analysis the iteration always starts from an empty set + and this argument is ignored. + + Return analysis results: (before, after) + """ + block_gen = {} + block_kill = {} + + # Calculate kill and gen sets for entire basic blocks. + for block in blocks: + gen: set[T] = set() + kill: set[T] = set() + ops = block.ops + if backward: + ops = list(reversed(ops)) + for op in ops: + opgen, opkill = op.accept(gen_and_kill) + if opkill: + gen -= opkill + + if opgen: + gen |= opgen + kill -= opgen + + if opkill: + kill |= opkill + + block_gen[block] = gen + block_kill[block] = kill + + # Set up initial state for worklist algorithm. + worklist = list(blocks) + if not backward: + worklist.reverse() # Reverse for a small performance improvement + workset = set(worklist) + before: dict[BasicBlock, set[T]] = {} + after: dict[BasicBlock, set[T]] = {} + for block in blocks: + if kind == MAYBE_ANALYSIS: + before[block] = set() + after[block] = set() + else: + assert universe is not None, "Universe must be defined for a must analysis" + before[block] = set(universe) + after[block] = set(universe) + + if backward: + pred_map = cfg.succ + succ_map = cfg.pred + else: + pred_map = cfg.pred + succ_map = cfg.succ + + # Run work list algorithm to generate in and out sets for each basic block. + while worklist: + label = worklist.pop() + workset.remove(label) + if pred_map[label]: + new_before: set[T] | None = None + for pred in pred_map[label]: + if new_before is None: + new_before = set(after[pred]) + elif kind == MAYBE_ANALYSIS: + new_before |= after[pred] + else: + new_before &= after[pred] + assert new_before is not None + else: + new_before = set(initial) + before[label] = new_before + new_after = (new_before - block_kill[label]) | block_gen[label] + if new_after != after[label]: + for succ in succ_map[label]: + if succ not in workset: + worklist.append(succ) + workset.add(succ) + after[label] = new_after + + # Run algorithm for each basic block to generate opcode-level sets. + op_before: dict[tuple[BasicBlock, int], set[T]] = {} + op_after: dict[tuple[BasicBlock, int], set[T]] = {} + for block in blocks: + label = block + cur = before[label] + ops_enum: Iterator[tuple[int, Op]] = enumerate(block.ops) + if backward: + ops_enum = reversed(list(ops_enum)) + for idx, op in ops_enum: + op_before[label, idx] = cur + opgen, opkill = op.accept(gen_and_kill) + if opkill: + cur = cur - opkill + if opgen: + cur = cur | opgen + op_after[label, idx] = cur + if backward: + op_after, op_before = op_before, op_after + + return AnalysisResult(op_before, op_after) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..67883b7b09d7498de35a1b905a234570f7ea3a1e Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/ircheck.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/ircheck.py new file mode 100644 index 0000000000000000000000000000000000000000..384bcdbe5cd801ccdf9b1a3d22351245bfd7db90 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/ircheck.py @@ -0,0 +1,498 @@ +"""Utilities for checking that internal ir is valid and consistent.""" + +from __future__ import annotations + +from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BaseAssign, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + ControlOp, + DecRef, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + Register, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Undef, + Unreachable, + Value, +) +from mypyc.ir.pprint import format_func +from mypyc.ir.rtypes import ( + KNOWN_NATIVE_TYPES, + RArray, + RInstance, + RPrimitive, + RType, + RUnion, + RVec, + bytes_rprimitive, + dict_rprimitive, + int_rprimitive, + is_c_py_ssize_t_rprimitive, + is_fixed_width_rtype, + is_float_rprimitive, + is_object_rprimitive, + is_pointer_rprimitive, + list_rprimitive, + pointer_rprimitive, + range_rprimitive, + set_rprimitive, + str_rprimitive, + tuple_rprimitive, +) + + +class FnError: + def __init__(self, source: Op | BasicBlock, desc: str) -> None: + self.source = source + self.desc = desc + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, FnError) and self.source == other.source and self.desc == other.desc + ) + + def __repr__(self) -> str: + return f"FnError(source={self.source}, desc={self.desc})" + + +def check_func_ir(fn: FuncIR) -> list[FnError]: + """Applies validations to a given function ir and returns a list of errors found.""" + errors = [] + + op_set = set() + + for block in fn.blocks: + if not block.terminated: + errors.append( + FnError(source=block.ops[-1] if block.ops else block, desc="Block not terminated") + ) + for op in block.ops[:-1]: + if isinstance(op, ControlOp): + errors.append(FnError(source=op, desc="Block has operations after control op")) + + if op in op_set: + errors.append(FnError(source=op, desc="Func has a duplicate op")) + op_set.add(op) + + errors.extend(check_op_sources_valid(fn)) + if errors: + return errors + + op_checker = OpChecker(fn) + for block in fn.blocks: + for op in block.ops: + op.accept(op_checker) + + return op_checker.errors + + +class IrCheckException(Exception): + pass + + +def assert_func_ir_valid(fn: FuncIR) -> None: + errors = check_func_ir(fn) + if errors: + raise IrCheckException( + "Internal error: Generated invalid IR: \n" + + "\n".join(format_func(fn, [(e.source, e.desc) for e in errors])) + ) + + +def check_op_sources_valid(fn: FuncIR) -> list[FnError]: + errors = [] + valid_ops: set[Op] = set() + valid_registers: set[Register] = set() + + for block in fn.blocks: + valid_ops.update(block.ops) + + for op in block.ops: + if isinstance(op, BaseAssign): + valid_registers.add(op.dest) + elif isinstance(op, LoadAddress) and isinstance(op.src, Register): + valid_registers.add(op.src) + + valid_registers.update(fn.arg_regs) + + for block in fn.blocks: + for op in block.ops: + for source in op.sources(): + if isinstance(source, (Integer, Float, Undef)): + pass + elif isinstance(source, Op): + if source not in valid_ops: + errors.append( + FnError( + source=op, + desc=f"Invalid op reference to op of type {type(source).__name__}", + ) + ) + elif isinstance(source, Register): + if source not in valid_registers: + errors.append( + FnError( + source=op, desc=f"Invalid op reference to register {source.name!r}" + ) + ) + + return errors + + +disjoint_types = { + int_rprimitive.name, + bytes_rprimitive.name, + str_rprimitive.name, + dict_rprimitive.name, + list_rprimitive.name, + set_rprimitive.name, + tuple_rprimitive.name, + range_rprimitive.name, +} | set(KNOWN_NATIVE_TYPES) + + +def can_coerce_to(src: RType, dest: RType) -> bool: + """Check if src can be assigned to dest_rtype. + + Currently okay to have false positives. + """ + if isinstance(dest, RUnion): + return any(can_coerce_to(src, d) for d in dest.items) + + if isinstance(dest, RPrimitive): + if isinstance(src, RPrimitive): + # If either src or dest is a disjoint type, then they must both be. + if src.name in disjoint_types and dest.name in disjoint_types: + return src.name == dest.name + return src.size == dest.size + if isinstance(src, (RInstance, RVec)): + return is_object_rprimitive(dest) + if isinstance(src, RUnion): + # IR doesn't have the ability to narrow unions based on + # control flow, so cannot be a strict all() here. + return any(can_coerce_to(s, dest) for s in src.items) + return False + + return True + + +def is_valid_ptr_displacement_type(rtype: RType) -> bool: + """Check if rtype is a valid displacement type for pointer arithmetic.""" + if not (is_fixed_width_rtype(rtype) or is_c_py_ssize_t_rprimitive(rtype)): + return False + assert isinstance(rtype, RPrimitive) + return rtype.size == pointer_rprimitive.size + + +def is_pointer_arithmetic(op: IntOp) -> bool: + """Check if op is add/subtract targeting pointer_rprimitive and integer of the same size.""" + if op.op not in (IntOp.ADD, IntOp.SUB): + return False + if not is_pointer_rprimitive(op.type): + return False + left = op.lhs.type + right = op.rhs.type + if is_pointer_rprimitive(left): + return is_valid_ptr_displacement_type(right) + if is_pointer_rprimitive(right): + return is_valid_ptr_displacement_type(left) + return False + + +class OpChecker(OpVisitor[None]): + def __init__(self, parent_fn: FuncIR) -> None: + self.parent_fn = parent_fn + self.errors: list[FnError] = [] + + def fail(self, source: Op, desc: str) -> None: + self.errors.append(FnError(source=source, desc=desc)) + + def check_control_op_targets(self, op: ControlOp) -> None: + for target in op.targets(): + if target not in self.parent_fn.blocks: + self.fail(source=op, desc=f"Invalid control operation target: {target.label}") + + def check_type_coercion(self, op: Op, src: RType, dest: RType) -> None: + if not can_coerce_to(src, dest): + self.fail( + source=op, desc=f"Cannot coerce source type {src.name} to dest type {dest.name}" + ) + + def check_compatibility(self, op: Op, t: RType, s: RType) -> None: + if not can_coerce_to(t, s) or not can_coerce_to(s, t): + self.fail(source=op, desc=f"{t.name} and {s.name} are not compatible") + + def expect_float(self, op: Op, v: Value) -> None: + if not is_float_rprimitive(v.type): + self.fail(op, f"Float expected (actual type is {v.type})") + + def expect_non_float(self, op: Op, v: Value) -> None: + if is_float_rprimitive(v.type): + self.fail(op, "Float not expected") + + def expect_primitive_type(self, op: Op, v: Value) -> None: + if not isinstance(v.type, RPrimitive): + self.fail(op, f"RPrimitive expected, got {type(v.type).__name__}") + + def visit_goto(self, op: Goto) -> None: + self.check_control_op_targets(op) + + def visit_branch(self, op: Branch) -> None: + self.check_control_op_targets(op) + + def visit_return(self, op: Return) -> None: + self.check_type_coercion(op, op.value.type, self.parent_fn.decl.sig.ret_type) + + def visit_unreachable(self, op: Unreachable) -> None: + # Unreachables are checked at a higher level since validation + # requires access to the entire basic block. + pass + + def visit_assign(self, op: Assign) -> None: + self.check_type_coercion(op, op.src.type, op.dest.type) + + def visit_assign_multi(self, op: AssignMulti) -> None: + for src in op.src: + assert isinstance(op.dest.type, RArray) + self.check_type_coercion(op, src.type, op.dest.type.item_type) + + def visit_load_error_value(self, op: LoadErrorValue) -> None: + # Currently it is assumed that all types have an error value. + # Once this is fixed we can validate that the rtype here actually + # has an error value. + pass + + def check_tuple_items_valid_literals(self, op: LoadLiteral, t: tuple[object, ...]) -> None: + for x in t: + if x is not None and not isinstance(x, (str, bytes, bool, int, float, complex, tuple)): + self.fail(op, f"Invalid type for item of tuple literal: {type(x)})") + if isinstance(x, tuple): + self.check_tuple_items_valid_literals(op, x) + + def check_frozenset_items_valid_literals(self, op: LoadLiteral, s: frozenset[object]) -> None: + for x in s: + if x is None or isinstance(x, (str, bytes, bool, int, float, complex)): + pass + elif isinstance(x, tuple): + self.check_tuple_items_valid_literals(op, x) + else: + self.fail(op, f"Invalid type for item of frozenset literal: {type(x)})") + + def visit_load_literal(self, op: LoadLiteral) -> None: + expected_type = None + if op.value is None: + expected_type = "builtins.object" + elif isinstance(op.value, int): + expected_type = "builtins.int" + elif isinstance(op.value, str): + expected_type = "builtins.str" + elif isinstance(op.value, bytes): + expected_type = "builtins.bytes" + elif isinstance(op.value, float): + expected_type = "builtins.float" + elif isinstance(op.value, complex): + expected_type = "builtins.object" + elif isinstance(op.value, tuple): + expected_type = "builtins.tuple" + self.check_tuple_items_valid_literals(op, op.value) + elif isinstance(op.value, frozenset): + # There's no frozenset_rprimitive type since it'd be pretty useless so we just pretend + # it's a set (when it's really a frozenset). + expected_type = "builtins.set" + self.check_frozenset_items_valid_literals(op, op.value) + + assert expected_type is not None, "Missed a case for LoadLiteral check" + + if op.type.name not in [expected_type, "builtins.object"]: + self.fail( + op, + f"Invalid literal value for type: value has " + f"type {expected_type}, but op has type {op.type.name}", + ) + + def visit_get_attr(self, op: GetAttr) -> None: + # Nothing to do. + pass + + def visit_set_attr(self, op: SetAttr) -> None: + # Nothing to do. + pass + + # Static operations cannot be checked at the function level. + def visit_load_static(self, op: LoadStatic) -> None: + pass + + def visit_init_static(self, op: InitStatic) -> None: + pass + + def visit_tuple_get(self, op: TupleGet) -> None: + # Nothing to do. + pass + + def visit_tuple_set(self, op: TupleSet) -> None: + # Nothing to do. + pass + + def visit_inc_ref(self, op: IncRef) -> None: + # Nothing to do. + pass + + def visit_dec_ref(self, op: DecRef) -> None: + # Nothing to do. + pass + + def visit_call(self, op: Call) -> None: + # Length is checked in constructor, and return type is set + # in a way that can't be incorrect + for arg_value, arg_runtime in zip(op.args, op.fn.sig.args): + self.check_type_coercion(op, arg_value.type, arg_runtime.type) + + def visit_method_call(self, op: MethodCall) -> None: + # Similar to above, but we must look up method first. + method_decl = op.receiver_type.class_ir.method_decl(op.method) + if method_decl.kind == FUNC_STATICMETHOD: + decl_index = 0 + else: + decl_index = 1 + + if len(op.args) + decl_index != len(method_decl.sig.args): + self.fail(op, "Incorrect number of args for method call.") + + # Skip the receiver argument (self) + for arg_value, arg_runtime in zip(op.args, method_decl.sig.args[decl_index:]): + self.check_type_coercion(op, arg_value.type, arg_runtime.type) + + def visit_cast(self, op: Cast) -> None: + pass + + def visit_box(self, op: Box) -> None: + pass + + def visit_unbox(self, op: Unbox) -> None: + pass + + def visit_raise_standard_error(self, op: RaiseStandardError) -> None: + pass + + def visit_call_c(self, op: CallC) -> None: + pass + + def visit_primitive_op(self, op: PrimitiveOp) -> None: + pass + + def visit_truncate(self, op: Truncate) -> None: + pass + + def visit_extend(self, op: Extend) -> None: + pass + + def visit_load_global(self, op: LoadGlobal) -> None: + pass + + def visit_int_op(self, op: IntOp) -> None: + self.expect_primitive_type(op, op.lhs) + self.expect_primitive_type(op, op.rhs) + self.expect_non_float(op, op.lhs) + self.expect_non_float(op, op.rhs) + left = op.lhs.type + right = op.rhs.type + op_str = op.op_str[op.op] + if ( + isinstance(left, RPrimitive) + and isinstance(right, RPrimitive) + and left.is_signed != right.is_signed + and ( + op_str in ("+", "-", "*", "/", "%") + or (op_str not in ("<<", ">>") and left.size != right.size) + ) + and not is_pointer_arithmetic(op) + ): + self.fail(op, f"Operand types have incompatible signs: {left}, {right}") + + def visit_comparison_op(self, op: ComparisonOp) -> None: + self.check_compatibility(op, op.lhs.type, op.rhs.type) + self.expect_non_float(op, op.lhs) + self.expect_non_float(op, op.rhs) + left = op.lhs.type + right = op.rhs.type + if ( + isinstance(left, RPrimitive) + and isinstance(right, RPrimitive) + and left.is_signed != right.is_signed + ): + self.fail(op, f"Operand types have incompatible signs: {left}, {right}") + + def visit_float_op(self, op: FloatOp) -> None: + self.expect_float(op, op.lhs) + self.expect_float(op, op.rhs) + + def visit_float_neg(self, op: FloatNeg) -> None: + self.expect_float(op, op.src) + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> None: + self.expect_float(op, op.lhs) + self.expect_float(op, op.rhs) + + def visit_load_mem(self, op: LoadMem) -> None: + pass + + def visit_set_mem(self, op: SetMem) -> None: + pass + + def visit_get_element(self, op: GetElement) -> None: + pass + + def visit_get_element_ptr(self, op: GetElementPtr) -> None: + pass + + def visit_set_element(self, op: SetElement) -> None: + pass + + def visit_load_address(self, op: LoadAddress) -> None: + pass + + def visit_keep_alive(self, op: KeepAlive) -> None: + pass + + def visit_unborrow(self, op: Unborrow) -> None: + pass diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..85af78d1ca58b1e663908d208e0d32d02b8cab81 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/selfleaks.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/selfleaks.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc7ef3fb4c685603ca0bda47f5b26af8fa7c610 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/analysis/selfleaks.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +from mypyc.analysis.dataflow import ( + CFG, + MAYBE_ANALYSIS, + AnalysisResult, + GenAndKill as _DataflowGenAndKill, + run_analysis, +) +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + DecRef, + Extend, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + Register, + RegisterOp, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Unreachable, +) +from mypyc.ir.rtypes import RInstance + +GenAndKill = _DataflowGenAndKill[None] + +CLEAN: GenAndKill = (set(), set()) +DIRTY: GenAndKill = ({None}, {None}) + + +class SelfLeakedVisitor(OpVisitor[GenAndKill]): + """Analyze whether 'self' may be seen by arbitrary code in '__init__'. + + More formally, the set is not empty if along some path from IR entry point + arbitrary code could have been executed that has access to 'self'. + + (We don't consider access via 'gc.get_objects()'.) + """ + + def __init__(self, self_reg: Register) -> None: + self.self_reg = self_reg + + def visit_goto(self, op: Goto) -> GenAndKill: + return CLEAN + + def visit_branch(self, op: Branch) -> GenAndKill: + return CLEAN + + def visit_return(self, op: Return) -> GenAndKill: + # Consider all exits from the function 'dirty' since they implicitly + # cause 'self' to be returned. + return DIRTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill: + return CLEAN + + def visit_assign(self, op: Assign) -> GenAndKill: + if op.src is self.self_reg or op.dest is self.self_reg: + return DIRTY + return CLEAN + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill: + return CLEAN + + def visit_set_mem(self, op: SetMem) -> GenAndKill: + return CLEAN + + def visit_inc_ref(self, op: IncRef) -> GenAndKill: + return CLEAN + + def visit_dec_ref(self, op: DecRef) -> GenAndKill: + return CLEAN + + def visit_call(self, op: Call) -> GenAndKill: + fn = op.fn + if fn.class_name and fn.name == "__init__": + self_type = op.fn.sig.args[0].type + assert isinstance(self_type, RInstance), self_type + cl = self_type.class_ir + if not cl.init_self_leak: + return CLEAN + return self.check_register_op(op) + + def visit_method_call(self, op: MethodCall) -> GenAndKill: + return self.check_register_op(op) + + def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill: + return CLEAN + + def visit_load_literal(self, op: LoadLiteral) -> GenAndKill: + return CLEAN + + def visit_get_attr(self, op: GetAttr) -> GenAndKill: + cl = op.class_type.class_ir + if cl.get_method(op.attr): + # Property -- calls a function + return self.check_register_op(op) + return CLEAN + + def visit_set_attr(self, op: SetAttr) -> GenAndKill: + cl = op.class_type.class_ir + if cl.get_method(op.attr): + # Property - calls a function + return self.check_register_op(op) + return CLEAN + + def visit_load_static(self, op: LoadStatic) -> GenAndKill: + return CLEAN + + def visit_init_static(self, op: InitStatic) -> GenAndKill: + return self.check_register_op(op) + + def visit_tuple_get(self, op: TupleGet) -> GenAndKill: + return CLEAN + + def visit_tuple_set(self, op: TupleSet) -> GenAndKill: + return self.check_register_op(op) + + def visit_box(self, op: Box) -> GenAndKill: + return self.check_register_op(op) + + def visit_unbox(self, op: Unbox) -> GenAndKill: + return self.check_register_op(op) + + def visit_cast(self, op: Cast) -> GenAndKill: + return self.check_register_op(op) + + def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill: + return CLEAN + + def visit_call_c(self, op: CallC) -> GenAndKill: + return self.check_register_op(op) + + def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill: + return self.check_register_op(op) + + def visit_truncate(self, op: Truncate) -> GenAndKill: + return CLEAN + + def visit_extend(self, op: Extend) -> GenAndKill: + return CLEAN + + def visit_load_global(self, op: LoadGlobal) -> GenAndKill: + return CLEAN + + def visit_int_op(self, op: IntOp) -> GenAndKill: + return CLEAN + + def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill: + return CLEAN + + def visit_float_op(self, op: FloatOp) -> GenAndKill: + return CLEAN + + def visit_float_neg(self, op: FloatNeg) -> GenAndKill: + return CLEAN + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill: + return CLEAN + + def visit_load_mem(self, op: LoadMem) -> GenAndKill: + return CLEAN + + def visit_get_element(self, op: GetElement) -> GenAndKill: + return CLEAN + + def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill: + return CLEAN + + def visit_set_element(self, op: SetElement) -> GenAndKill: + return CLEAN + + def visit_load_address(self, op: LoadAddress) -> GenAndKill: + return CLEAN + + def visit_keep_alive(self, op: KeepAlive) -> GenAndKill: + return CLEAN + + def visit_unborrow(self, op: Unborrow) -> GenAndKill: + return CLEAN + + def check_register_op(self, op: RegisterOp) -> GenAndKill: + if any(src is self.self_reg for src in op.sources()): + return DIRTY + return CLEAN + + +def analyze_self_leaks( + blocks: list[BasicBlock], self_reg: Register, cfg: CFG +) -> AnalysisResult[None]: + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=SelfLeakedVisitor(self_reg), + initial=set(), + backward=False, + kind=MAYBE_ANALYSIS, + ) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/annotate.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/annotate.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..76ca0dc71555556689182af4a69639d76ec25b96 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/annotate.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/annotate.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/annotate.py new file mode 100644 index 0000000000000000000000000000000000000000..bc282fc3ea6c137d5b069fe3b9cdd05a523b99c0 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/annotate.py @@ -0,0 +1,472 @@ +"""Generate source code formatted as HTML, with bottlenecks annotated and highlighted. + +Various heuristics are used to detect common issues that cause slower than +expected performance. +""" + +from __future__ import annotations + +import os.path +import sys +from html import escape +from typing import Final + +from mypy.build import BuildResult +from mypy.nodes import ( + AssignmentStmt, + CallExpr, + ClassDef, + Decorator, + DictionaryComprehension, + Expression, + ForStmt, + FuncDef, + GeneratorExpr, + IndexExpr, + LambdaExpr, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + Node, + OpExpr, + RefExpr, + TupleExpr, + TypedDictExpr, + TypeInfo, + TypeVarExpr, + Var, + WithStmt, +) +from mypy.traverser import TraverserVisitor +from mypy.types import AnyType, Instance, ProperType, Type, TypeOfAny, get_proper_type +from mypy.util import FancyFormatter +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.module_ir import ModuleIR +from mypyc.ir.ops import CallC, LoadLiteral, LoadStatic, Value +from mypyc.irbuild.mapper import Mapper + + +class Annotation: + """HTML annotation for compiled source code""" + + def __init__(self, message: str, priority: int = 1) -> None: + # Message as HTML that describes an issue and/or how to fix it. + # Multiple messages on a line may be concatenated. + self.message = message + # If multiple annotations are generated for a single line, only report + # the highest-priority ones. Some use cases generate multiple annotations, + # and this can be used to reduce verbosity by hiding the lower-priority + # ones. + self.priority = priority + + +op_hints: Final = { + "PyNumber_Add": Annotation('Generic "+" operation.'), + "PyNumber_Subtract": Annotation('Generic "-" operation.'), + "PyNumber_Multiply": Annotation('Generic "*" operation.'), + "PyNumber_TrueDivide": Annotation('Generic "/" operation.'), + "PyNumber_FloorDivide": Annotation('Generic "//" operation.'), + "PyNumber_Positive": Annotation('Generic unary "+" operation.'), + "PyNumber_Negative": Annotation('Generic unary "-" operation.'), + "PyNumber_And": Annotation('Generic "&" operation.'), + "PyNumber_Or": Annotation('Generic "|" operation.'), + "PyNumber_Xor": Annotation('Generic "^" operation.'), + "PyNumber_Lshift": Annotation('Generic "<<" operation.'), + "PyNumber_Rshift": Annotation('Generic ">>" operation.'), + "PyNumber_Invert": Annotation('Generic "~" operation.'), + "PyObject_Call": Annotation("Generic call operation."), + "PyObject_CallObject": Annotation("Generic call operation."), + "PyObject_RichCompare": Annotation("Generic comparison operation."), + "PyObject_GetItem": Annotation("Generic indexing operation."), + "PyObject_SetItem": Annotation("Generic indexed assignment."), +} + +stdlib_hints: Final = { + "functools.partial": Annotation( + '"functools.partial" is inefficient in compiled code.', priority=3 + ), + "itertools.chain": Annotation( + '"itertools.chain" is inefficient in compiled code (hint: replace with for loops).', + priority=3, + ), + "itertools.groupby": Annotation( + '"itertools.groupby" is inefficient in compiled code.', priority=3 + ), + "itertools.islice": Annotation( + '"itertools.islice" is inefficient in compiled code (hint: replace with for loop over index range).', + priority=3, + ), + "copy.deepcopy": Annotation( + '"copy.deepcopy" tends to be slow. Make a shallow copy if possible.', priority=2 + ), +} + +CSS = """\ +.collapsible { + cursor: pointer; +} + +.content { + display: block; + margin-top: 10px; + margin-bottom: 10px; +} + +.hint { + display: inline; + border: 1px solid #ccc; + padding: 5px; +} +""" + +JS = """\ +document.querySelectorAll('.collapsible').forEach(function(collapsible) { + collapsible.addEventListener('click', function() { + const content = this.nextElementSibling; + if (content.style.display === 'none') { + content.style.display = 'block'; + } else { + content.style.display = 'none'; + } + }); +}); +""" + + +class AnnotatedSource: + """Annotations for a single compiled source file.""" + + def __init__(self, path: str, annotations: dict[int, list[Annotation]]) -> None: + self.path = path + self.annotations = annotations + + +def generate_annotated_html( + html_fnam: str, result: BuildResult, modules: dict[str, ModuleIR], mapper: Mapper +) -> None: + annotations = [] + for mod, mod_ir in modules.items(): + path = result.graph[mod].path + tree = result.graph[mod].tree + assert tree is not None + annotations.append( + generate_annotations(path or "", tree, mod_ir, result.types, mapper) + ) + html = generate_html_report(annotations) + with open(html_fnam, "w") as f: + f.write(html) + + formatter = FancyFormatter(sys.stdout, sys.stderr, False) + formatted = formatter.style(os.path.abspath(html_fnam), "none", underline=True, bold=True) + print(f"\nWrote {formatted} -- open in browser to view\n") + + +def generate_annotations( + path: str, tree: MypyFile, ir: ModuleIR, type_map: dict[Expression, Type], mapper: Mapper +) -> AnnotatedSource: + anns = {} + for func_ir in ir.functions: + anns.update(function_annotations(func_ir, tree)) + visitor = ASTAnnotateVisitor(type_map, mapper) + for defn in tree.defs: + defn.accept(visitor) + anns.update(visitor.anns) + for line in visitor.ignored_lines: + if line in anns: + del anns[line] + return AnnotatedSource(path, anns) + + +def function_annotations(func_ir: FuncIR, tree: MypyFile) -> dict[int, list[Annotation]]: + """Generate annotations based on mypyc IR.""" + # TODO: check if func_ir.line is -1 + anns: dict[int, list[Annotation]] = {} + for block in func_ir.blocks: + for op in block.ops: + if isinstance(op, CallC): + name = op.function_name + ann: str | Annotation | None = None + if name == "CPyObject_GetAttr": + attr_name = get_str_literal(op.args[1]) + if attr_name in ("__prepare__", "GeneratorExit", "StopIteration"): + # These attributes are internal to mypyc/CPython, and/or accessed + # implicitly in generated code. The user has little control over + # them. + ann = None + elif attr_name: + ann = f'Get non-native attribute "{attr_name}".' + else: + ann = "Dynamic attribute lookup." + elif name == "PyObject_SetAttr": + attr_name = get_str_literal(op.args[1]) + if attr_name == "__mypyc_attrs__": + # This is set implicitly and can't be avoided. + ann = None + elif attr_name: + ann = f'Set non-native attribute "{attr_name}".' + else: + ann = "Dynamic attribute set." + elif name == "PyObject_VectorcallMethod": + method_name = get_str_literal(op.args[0]) + if method_name: + ann = f'Call non-native method "{method_name}" (it may be defined in a non-native class, or decorated).' + else: + ann = "Dynamic method call." + elif name in op_hints: + ann = op_hints[name] + elif name in ("CPyDict_GetItem", "CPyDict_SetItem"): + if ( + isinstance(op.args[0], LoadStatic) + and isinstance(op.args[1], LoadLiteral) + and func_ir.name != "__top_level__" + ): + load = op.args[0] + name = str(op.args[1].value) + sym = tree.names.get(name) + if ( + sym + and sym.node + and load.namespace == "static" + and load.identifier == "globals" + ): + if sym.node.fullname in stdlib_hints: + ann = stdlib_hints[sym.node.fullname] + elif isinstance(sym.node, Var): + ann = ( + f'Access global "{name}" through namespace ' + + "dictionary (hint: access is faster if you can make it Final)." + ) + else: + ann = f'Access "{name}" through global namespace dictionary.' + if ann: + if isinstance(ann, str): + ann = Annotation(ann) + anns.setdefault(op.line, []).append(ann) + return anns + + +class ASTAnnotateVisitor(TraverserVisitor): + """Generate annotations from mypy AST and inferred types.""" + + def __init__(self, type_map: dict[Expression, Type], mapper: Mapper) -> None: + self.anns: dict[int, list[Annotation]] = {} + self.ignored_lines: set[int] = set() + self.func_depth = 0 + self.type_map = type_map + self.mapper = mapper + + def visit_func_def(self, o: FuncDef, /) -> None: + if self.func_depth > 0: + self.annotate( + o, + "A nested function object is allocated each time statement is executed. " + + "A module-level function would be faster.", + ) + self.func_depth += 1 + super().visit_func_def(o) + self.func_depth -= 1 + + def visit_for_stmt(self, o: ForStmt, /) -> None: + self.check_iteration([o.expr], "For loop") + super().visit_for_stmt(o) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None: + self.check_iteration(o.sequences, "Comprehension") + super().visit_dictionary_comprehension(o) + + def visit_generator_expr(self, o: GeneratorExpr, /) -> None: + self.check_iteration(o.sequences, "Comprehension or generator") + super().visit_generator_expr(o) + + def check_iteration(self, expressions: list[Expression], kind: str) -> None: + for expr in expressions: + typ = self.get_type(expr) + if isinstance(typ, AnyType): + self.annotate(expr, f'{kind} uses generic operations (iterable has type "Any").') + elif isinstance(typ, Instance) and typ.type.fullname in ( + "typing.Iterable", + "typing.Iterator", + "typing.Sequence", + "typing.MutableSequence", + ): + self.annotate( + expr, + f'{kind} uses generic operations (iterable has the abstract type "{typ.type.fullname}").', + ) + + def visit_class_def(self, o: ClassDef, /) -> None: + super().visit_class_def(o) + if self.func_depth == 0: + # Don't complain about base classes at top level + for base in o.base_type_exprs: + self.ignored_lines.add(base.line) + + for s in o.defs.body: + if isinstance(s, AssignmentStmt): + # Don't complain about attribute initializers + self.ignored_lines.add(s.line) + elif isinstance(s, Decorator): + # Don't complain about decorator definitions that generate some + # dynamic operations. This is a bit heavy-handed. + self.ignored_lines.add(s.func.line) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + for expr in o.expr: + if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr): + node = expr.callee.node + if isinstance(node, Decorator): + if any( + isinstance(d, RefExpr) + and d.node + and d.node.fullname == "contextlib.contextmanager" + for d in node.decorators + ): + self.annotate( + expr, + f'"{node.name}" uses @contextmanager, which is slow ' + + "in compiled code. Use a native class with " + + '"__enter__" and "__exit__" methods instead.', + priority=3, + ) + super().visit_with_stmt(o) + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + special_form = False + if self.func_depth == 0: + analyzed: Expression | None = o.rvalue + if isinstance(o.rvalue, (CallExpr, IndexExpr, OpExpr)): + analyzed = o.rvalue.analyzed + if o.is_alias_def or isinstance( + analyzed, (TypeVarExpr, NamedTupleExpr, TypedDictExpr, NewTypeExpr) + ): + special_form = True + if special_form: + # TODO: Ignore all lines if multi-line + self.ignored_lines.add(o.line) + super().visit_assignment_stmt(o) + + def visit_name_expr(self, o: NameExpr, /) -> None: + if ann := stdlib_hints.get(o.fullname): + self.annotate(o, ann) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + super().visit_member_expr(o) + if ann := stdlib_hints.get(o.fullname): + self.annotate(o, ann) + + def visit_call_expr(self, o: CallExpr, /) -> None: + super().visit_call_expr(o) + if ( + isinstance(o.callee, RefExpr) + and o.callee.fullname == "builtins.isinstance" + and len(o.args) == 2 + ): + arg = o.args[1] + self.check_isinstance_arg(arg) + elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, TypeInfo): + info = o.callee.node + class_ir = self.mapper.type_to_ir.get(info) + if (class_ir and not class_ir.is_ext_class) or ( + class_ir is None and not info.fullname.startswith("builtins.") + ): + self.annotate( + o, f'Creating an instance of non-native class "{info.name}" ' + "is slow.", 2 + ) + elif class_ir and class_ir.is_augmented: + self.annotate( + o, + f'Class "{info.name}" is only partially native, and ' + + "constructing an instance is slow.", + 2, + ) + elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, Decorator): + decorator = o.callee.node + if self.mapper.is_native_ref_expr(o.callee): + self.annotate( + o, + f'Calling a decorated function ("{decorator.name}") is inefficient, even if it\'s native.', + 2, + ) + + def check_isinstance_arg(self, arg: Expression) -> None: + if isinstance(arg, RefExpr): + if isinstance(arg.node, TypeInfo) and arg.node.is_protocol: + self.annotate( + arg, f'Expensive isinstance() check against protocol "{arg.node.name}".' + ) + elif isinstance(arg, TupleExpr): + for item in arg.items: + self.check_isinstance_arg(item) + + def visit_lambda_expr(self, o: LambdaExpr, /) -> None: + self.annotate( + o, + "A new object is allocated for lambda each time it is evaluated. " + + "A module-level function would be faster.", + ) + super().visit_lambda_expr(o) + + def annotate(self, o: Node, ann: str | Annotation, priority: int = 1) -> None: + if isinstance(ann, str): + ann = Annotation(ann, priority=priority) + self.anns.setdefault(o.line, []).append(ann) + + def get_type(self, e: Expression) -> ProperType: + t = self.type_map.get(e) + if t: + return get_proper_type(t) + return AnyType(TypeOfAny.unannotated) + + +def get_str_literal(v: Value) -> str | None: + if isinstance(v, LoadLiteral) and isinstance(v.value, str): + return v.value + return None + + +def get_max_prio(anns: list[Annotation]) -> list[Annotation]: + max_prio = max(a.priority for a in anns) + return [a for a in anns if a.priority == max_prio] + + +def generate_html_report(sources: list[AnnotatedSource]) -> str: + html = [] + html.append("\n\n") + html.append(f"") + html.append("\n") + html.append("\n") + for src in sources: + html.append(f"

{src.path}

\n") + html.append("
")
+        src_anns = src.annotations
+        with open(src.path) as f:
+            lines = f.readlines()
+        for i, s in enumerate(lines):
+            s = escape(s)
+            line = i + 1
+            linenum = "%5d" % line
+            if line in src_anns:
+                anns = get_max_prio(src_anns[line])
+                ann_strs = [a.message for a in anns]
+                hint = " ".join(ann_strs)
+                s = colorize_line(linenum, s, hint_html=hint)
+            else:
+                s = linenum + "  " + s
+            html.append(s)
+        html.append("
") + + html.append("") + + html.append("\n") + return "".join(html) + + +def colorize_line(linenum: str, s: str, hint_html: str) -> str: + hint_prefix = " " * len(linenum) + " " + line_span = f'
{linenum} {s}
' + hint_div = f'
{hint_prefix}
{hint_html}
' + return f"{line_span}{hint_div}" diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..aedc8dc0e8f494afec7c9ba4903056cf2616d334 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build.py new file mode 100644 index 0000000000000000000000000000000000000000..f0384bd1a81d6c9aba131353d64b592ffe27d3b6 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build.py @@ -0,0 +1,842 @@ +"""Support for building extensions using mypyc with distutils or setuptools + +The main entry point is mypycify, which produces a list of extension +modules to be passed to setup. A trivial setup.py for a mypyc built +project, then, looks like: + + from setuptools import setup + from mypyc.build import mypycify + + setup(name='test_module', + ext_modules=mypycify(['foo.py']), + ) + +See the mypycify docs for additional arguments. + +mypycify can integrate with either distutils or setuptools, but needs +to know at import-time whether it is using distutils or setuputils. We +hackily decide based on whether setuptools has been imported already. +""" + +from __future__ import annotations + +import hashlib +import os.path +import re +import sys +import time +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any, NamedTuple, NoReturn, cast + +import mypyc.build_setup # noqa: F401 +from mypy.build import BuildSource +from mypy.errors import CompileError +from mypy.fscache import FileSystemCache +from mypy.main import process_options +from mypy.options import Options +from mypy.util import write_junit_xml +from mypyc.annotate import generate_annotated_html +from mypyc.codegen import emitmodule +from mypyc.common import IS_FREE_THREADED, RUNTIME_C_FILES, shared_lib_name +from mypyc.errors import Errors +from mypyc.ir.deps import SourceDep +from mypyc.ir.pprint import format_modules +from mypyc.namegen import exported_name +from mypyc.options import CompilerOptions + + +class ModDesc(NamedTuple): + module: str + c_files: list[str] + other_files: list[str] + include_dirs: list[str] + + +LIBRT_MODULES = [ + ModDesc("librt.internal", ["internal/librt_internal.c"], [], ["internal"]), + ModDesc("librt.strings", ["strings/librt_strings.c"], [], ["strings"]), + ModDesc( + "librt.base64", + [ + "base64/librt_base64.c", + "base64/lib.c", + "base64/codec_choose.c", + "base64/tables/tables.c", + "base64/arch/generic/codec.c", + "base64/arch/ssse3/codec.c", + "base64/arch/sse41/codec.c", + "base64/arch/sse42/codec.c", + "base64/arch/avx/codec.c", + "base64/arch/avx2/codec.c", + "base64/arch/avx512/codec.c", + "base64/arch/neon32/codec.c", + "base64/arch/neon64/codec.c", + ], + [ + "base64/arch/avx/enc_loop_asm.c", + "base64/arch/avx2/enc_loop.c", + "base64/arch/avx2/enc_loop_asm.c", + "base64/arch/avx2/enc_reshuffle.c", + "base64/arch/avx2/enc_translate.c", + "base64/arch/avx2/dec_loop.c", + "base64/arch/avx2/dec_reshuffle.c", + "base64/arch/generic/32/enc_loop.c", + "base64/arch/generic/64/enc_loop.c", + "base64/arch/generic/32/dec_loop.c", + "base64/arch/generic/enc_head.c", + "base64/arch/generic/enc_tail.c", + "base64/arch/generic/dec_head.c", + "base64/arch/generic/dec_tail.c", + "base64/arch/ssse3/dec_reshuffle.c", + "base64/arch/ssse3/dec_loop.c", + "base64/arch/ssse3/enc_loop_asm.c", + "base64/arch/ssse3/enc_translate.c", + "base64/arch/ssse3/enc_reshuffle.c", + "base64/arch/ssse3/enc_loop.c", + "base64/arch/neon64/dec_loop.c", + "base64/arch/neon64/enc_loop_asm.c", + "base64/codecs.h", + "base64/env.h", + "base64/lib_openmp.c", + "base64/tables/tables.h", + "base64/tables/table_dec_32bit.h", + "base64/tables/table_enc_12bit.h", + ], + ["base64"], + ), + ModDesc( + "librt.vecs", + [ + "vecs/librt_vecs.c", + "vecs/vec_i64.c", + "vecs/vec_i32.c", + "vecs/vec_i16.c", + "vecs/vec_u8.c", + "vecs/vec_float.c", + "vecs/vec_bool.c", + "vecs/vec_t.c", + "vecs/vec_nested.c", + ], + ["vecs/librt_vecs.h", "vecs/vec_template.c"], + ["vecs"], + ), + ModDesc("librt.time", ["time/librt_time.c"], ["time/librt_time.h"], []), +] + +try: + # Import setuptools so that it monkey-patch overrides distutils + import setuptools +except ImportError: + pass + +if TYPE_CHECKING: + if sys.version_info >= (3, 12): + from setuptools import Extension + else: + from distutils.core import Extension as _distutils_Extension + from typing import TypeAlias + + from setuptools import Extension as _setuptools_Extension + + Extension: TypeAlias = _setuptools_Extension | _distutils_Extension + +if sys.version_info >= (3, 12): + # From setuptools' monkeypatch + from distutils import ccompiler, sysconfig # type: ignore[import-not-found] +else: + from distutils import ccompiler, sysconfig + + +def get_extension() -> type[Extension]: + # We can work with either setuptools or distutils, and pick setuptools + # if it has been imported. + use_setuptools = "setuptools" in sys.modules + extension_class: type[Extension] + + if sys.version_info < (3, 12) and not use_setuptools: + import distutils.core + + extension_class = distutils.core.Extension + else: + if not use_setuptools: + sys.exit("error: setuptools not installed") + extension_class = setuptools.Extension + + return extension_class + + +def setup_mypycify_vars() -> None: + """Rewrite a bunch of config vars in pretty dubious ways.""" + # There has to be a better approach to this. + + # The vars can contain ints but we only work with str ones + vars = cast(dict[str, str], sysconfig.get_config_vars()) + if sys.platform == "darwin": + # Disable building 32-bit binaries, since we generate too much code + # for a 32-bit Mach-O object. There has to be a better way to do this. + vars["LDSHARED"] = vars["LDSHARED"].replace("-arch i386", "") + vars["LDFLAGS"] = vars["LDFLAGS"].replace("-arch i386", "") + vars["CFLAGS"] = vars["CFLAGS"].replace("-arch i386", "") + + +def fail(message: str) -> NoReturn: + # TODO: Is there something else we should do to fail? + sys.exit(message) + + +def emit_messages(options: Options, messages: list[str], dt: float, serious: bool = False) -> None: + # ... you know, just in case. + if options.junit_xml: + py_version = f"{options.python_version[0]}_{options.python_version[1]}" + write_junit_xml( + dt, + serious, + {None: messages} if messages else {}, + options.junit_xml, + py_version, + options.platform, + ) + if messages: + print("\n".join(messages)) + + +def get_mypy_config( + mypy_options: list[str], + only_compile_paths: Iterable[str] | None, + compiler_options: CompilerOptions, + fscache: FileSystemCache | None, +) -> tuple[list[BuildSource], list[BuildSource], Options]: + """Construct mypy BuildSources and Options from file and options lists""" + all_sources, options = process_options(mypy_options, fscache=fscache, mypyc=True) + if only_compile_paths is not None: + paths_set = set(only_compile_paths) + mypyc_sources = [s for s in all_sources if s.path in paths_set] + else: + mypyc_sources = all_sources + + if compiler_options.separate: + mypyc_sources = [src for src in mypyc_sources if src.path] + + if not mypyc_sources: + return mypyc_sources, all_sources, options + + # Override whatever python_version is inferred from the .ini file, + # and set the python_version to be the currently used version. + options.python_version = sys.version_info[:2] + + if options.python_version[0] == 2: + fail("Python 2 not supported") + if not options.strict_optional: + fail("Disabling strict optional checking not supported") + options.show_traceback = True + # Needed to get types for all AST nodes + options.export_types = True + # We use mypy incremental mode when doing separate/incremental mypyc compilation + options.incremental = compiler_options.separate + options.preserve_asts = True + + for source in mypyc_sources: + options.per_module_options.setdefault(source.module, {})["mypyc"] = True + + return mypyc_sources, all_sources, options + + +def is_package_source(source: BuildSource) -> bool: + return source.path is not None and os.path.split(source.path)[1] == "__init__.py" + + +def generate_c_extension_shim( + full_module_name: str, module_name: str, dir_name: str, group_name: str +) -> str: + """Create a C extension shim with a passthrough PyInit function. + + Arguments: + full_module_name: the dotted full module name + module_name: the final component of the module name + dir_name: the directory to place source code + group_name: the name of the group + """ + cname = "%s.c" % full_module_name.replace(".", os.sep) + cpath = os.path.join(dir_name, cname) + + if IS_FREE_THREADED: + # We use multi-phase init in free-threaded builds to enable free threading. + shim_name = "module_shim_no_gil_multiphase.tmpl" + else: + shim_name = "module_shim.tmpl" + + # We load the C extension shim template from a file. + # (So that the file could be reused as a bazel template also.) + with open(os.path.join(include_dir(), shim_name)) as f: + shim_template = f.read() + + write_file( + cpath, + shim_template.format( + modname=module_name, + libname=shared_lib_name(group_name), + full_modname=exported_name(full_module_name), + ), + ) + + return cpath + + +def group_name(modules: list[str]) -> str: + """Produce a probably unique name for a group from a list of module names.""" + if len(modules) == 1: + return modules[0] + + h = hashlib.sha1() + h.update(",".join(modules).encode()) + return h.hexdigest()[:20] + + +def include_dir() -> str: + """Find the path of the lib-rt dir that needs to be included""" + return os.path.join(os.path.abspath(os.path.dirname(__file__)), "lib-rt") + + +def generate_c( + sources: list[BuildSource], + options: Options, + groups: emitmodule.Groups, + fscache: FileSystemCache, + compiler_options: CompilerOptions, +) -> tuple[list[list[tuple[str, str]]], str, list[SourceDep]]: + """Drive the actual core compilation step. + + The groups argument describes how modules are assigned to C + extension modules. See the comments on the Groups type in + mypyc.emitmodule for details. + + Returns the C source code, (for debugging) the pretty printed IR, and list of SourceDeps. + """ + t0 = time.time() + + try: + result = emitmodule.parse_and_typecheck( + sources, options, compiler_options, groups, fscache + ) + except CompileError as e: + emit_messages(options, e.messages, time.time() - t0, serious=(not e.use_stdout)) + sys.exit(1) + + t1 = time.time() + if result.errors: + emit_messages(options, result.errors, t1 - t0) + sys.exit(1) + + if compiler_options.verbose: + print(f"Parsed and typechecked in {t1 - t0:.3f}s") + + errors = Errors(options) + modules, ctext, mapper = emitmodule.compile_modules_to_c( + result, compiler_options=compiler_options, errors=errors, groups=groups + ) + t2 = time.time() + emit_messages(options, errors.new_messages(), t2 - t1) + if errors.num_errors: + # No need to stop the build if only warnings were emitted. + sys.exit(1) + + if compiler_options.verbose: + print(f"Compiled to C in {t2 - t1:.3f}s") + + if options.mypyc_annotation_file: + generate_annotated_html(options.mypyc_annotation_file, result, modules, mapper) + + # Collect SourceDep dependencies + source_deps = sorted(emitmodule.collect_source_dependencies(modules), key=lambda d: d.path) + + return ctext, "\n".join(format_modules(modules)), source_deps + + +def build_using_shared_lib( + sources: list[BuildSource], + group_name: str, + cfiles: list[str], + deps: list[str], + build_dir: str, + extra_compile_args: list[str], +) -> list[Extension]: + """Produce the list of extension modules when a shared library is needed. + + This creates one shared library extension module that all the + others import, and one shim extension module for each + module in the build. Each shim simply calls an initialization function + in the shared library. + + The shared library (which lib_name is the name of) is a Python + extension module that exports the real initialization functions in + Capsules stored in module attributes. + """ + extensions = [ + get_extension()( + shared_lib_name(group_name), + sources=cfiles, + include_dirs=[include_dir(), build_dir], + depends=deps, + extra_compile_args=extra_compile_args, + ) + ] + + for source in sources: + module_name = source.module.split(".")[-1] + shim_file = generate_c_extension_shim(source.module, module_name, build_dir, group_name) + + # We include the __init__ in the "module name" we stick in the Extension, + # since this seems to be needed for it to end up in the right place. + full_module_name = source.module + assert source.path + if is_package_source(source): + full_module_name += ".__init__" + extensions.append( + get_extension()( + full_module_name, sources=[shim_file], extra_compile_args=extra_compile_args + ) + ) + + return extensions + + +def build_single_module( + sources: list[BuildSource], cfiles: list[str], extra_compile_args: list[str] +) -> list[Extension]: + """Produce the list of extension modules for a standalone extension. + + This contains just one module, since there is no need for a shared module. + """ + return [ + get_extension()( + sources[0].module, + sources=cfiles, + include_dirs=[include_dir()], + extra_compile_args=extra_compile_args, + ) + ] + + +def write_file(path: str, contents: str) -> None: + """Write data into a file. + + If the file already exists and has the same contents we + want to write, skip writing so as to preserve the mtime + and avoid triggering recompilation. + """ + # We encode it ourselves and open the files as binary to avoid windows + # newline translation + encoded_contents = contents.encode("utf-8") + try: + with open(path, "rb") as f: + old_contents: bytes | None = f.read() + except OSError: + old_contents = None + if old_contents != encoded_contents: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as g: + g.write(encoded_contents) + + # Fudge the mtime forward because otherwise when two builds happen close + # together (like in a test) setuptools might not realize the source is newer + # than the new artifact. + # XXX: This is bad though. + new_mtime = os.stat(path).st_mtime + 1 + os.utime(path, times=(new_mtime, new_mtime)) + + +def construct_groups( + sources: list[BuildSource], + separate: bool | list[tuple[list[str], str | None]], + use_shared_lib: bool, + group_name_override: str | None, +) -> emitmodule.Groups: + """Compute Groups given the input source list and separate configs. + + separate is the user-specified configuration for how to assign + modules to compilation groups (see mypycify docstring for details). + + This takes that and expands it into our internal representation of + group configuration, documented in mypyc.emitmodule's definition + of Group. + """ + + if separate is True: + groups: emitmodule.Groups = [([source], None) for source in sources] + elif isinstance(separate, list): + groups = [] + used_sources = set() + for files, name in separate: + normalized_files = {os.path.normpath(f) for f in files} + group_sources = [ + src + for src in sources + if src.path is not None and os.path.normpath(src.path) in normalized_files + ] + groups.append((group_sources, name)) + used_sources.update(group_sources) + unused_sources = [src for src in sources if src not in used_sources] + if unused_sources: + groups.extend([([source], None) for source in unused_sources]) + else: + groups = [(sources, None)] + + # Generate missing names + for i, (group, name) in enumerate(groups): + if use_shared_lib and not name: + if group_name_override is not None: + name = group_name_override + else: + name = group_name([source.module for source in group]) + groups[i] = (group, name) + + return groups + + +def get_header_deps(cfiles: list[tuple[str, str]]) -> list[str]: + """Find all the headers used by a group of cfiles. + + We do this by just regexping the source, which is a bit simpler than + properly plumbing the data through. + + Arguments: + cfiles: A list of (file name, file contents) pairs. + """ + headers: set[str] = set() + for _, contents in cfiles: + headers.update(re.findall(r'#include "(.*)"', contents)) + + return sorted(headers) + + +def mypyc_build( + paths: list[str], + compiler_options: CompilerOptions, + *, + separate: bool | list[tuple[list[str], str | None]] = False, + only_compile_paths: Iterable[str] | None = None, + skip_cgen_input: tuple[list[list[tuple[str, str]]], list[str]] | None = None, + always_use_shared_lib: bool = False, +) -> tuple[emitmodule.Groups, list[tuple[list[str], list[str]]], list[SourceDep]]: + """Do the front and middle end of mypyc building, producing and writing out C source.""" + fscache = FileSystemCache() + mypyc_sources, all_sources, options = get_mypy_config( + paths, only_compile_paths, compiler_options, fscache + ) + + # We generate a shared lib if there are multiple modules or if any + # of the modules are in package. (Because I didn't want to fuss + # around with making the single module code handle packages.) + use_shared_lib = ( + len(mypyc_sources) > 1 + or any("." in x.module for x in mypyc_sources) + or any(is_package_source(x) for x in mypyc_sources) + or always_use_shared_lib + ) + + groups = construct_groups(mypyc_sources, separate, use_shared_lib, compiler_options.group_name) + + if compiler_options.group_name is not None: + assert len(groups) == 1, "If using custom group_name, only one group is expected" + + # We let the test harness just pass in the c file contents instead + # so that it can do a corner-cutting version without full stubs. + source_deps: list[SourceDep] = [] + if not skip_cgen_input: + group_cfiles, ops_text, source_deps = generate_c( + all_sources, options, groups, fscache, compiler_options=compiler_options + ) + # TODO: unique names? + write_file(os.path.join(compiler_options.target_dir, "ops.txt"), ops_text) + else: + group_cfiles = skip_cgen_input[0] + source_deps = [SourceDep(d) for d in skip_cgen_input[1]] + + # Write out the generated C and collect the files for each group + # Should this be here?? + group_cfilenames: list[tuple[list[str], list[str]]] = [] + for cfiles in group_cfiles: + cfilenames = [] + for cfile, ctext in cfiles: + cfile = os.path.join(compiler_options.target_dir, cfile) + if not options.mypyc_skip_c_generation: + write_file(cfile, ctext) + if os.path.splitext(cfile)[1] == ".c": + cfilenames.append(cfile) + + deps = [os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles)] + group_cfilenames.append((cfilenames, deps)) + + return groups, group_cfilenames, source_deps + + +def get_cflags( + *, + compiler_type: str | None = None, + opt_level: str = "3", + debug_level: str = "1", + multi_file: bool = False, + experimental_features: bool = False, + log_trace: bool = False, +) -> list[str]: + """Get C compiler flags for the given configuration. + + Args: + compiler_type: Compiler type, e.g. "unix" or "msvc". If None, detected automatically. + opt_level: Optimization level as string ("0", "1", "2", or "3"). + debug_level: Debug level as string ("0", "1", "2", or "3"). + multi_file: Whether multi-file compilation mode is enabled. + experimental_features: Whether experimental features are enabled. + log_trace: Whether trace logging is enabled. + + Returns: + List of compiler flags. + """ + if compiler_type is None: + compiler: Any = ccompiler.new_compiler() + sysconfig.customize_compiler(compiler) + compiler_type = compiler.compiler_type + + cflags: list[str] = [] + if compiler_type == "unix": + cflags += [ + f"-O{opt_level}", + f"-g{debug_level}", + "-Werror", + "-Wno-unused-function", + "-Wno-unused-label", + "-Wno-unreachable-code", + "-Wno-unused-variable", + "-Wno-unused-command-line-argument", + "-Wno-unknown-warning-option", + "-Wno-unused-but-set-variable", + "-Wno-ignored-optimization-argument", + # GCC at -O3 false-positives on struct hack (items[1]) in vec buffers + "-Wno-array-bounds", + "-Wno-stringop-overread", + "-Wno-stringop-overflow", + # Disables C Preprocessor (cpp) warnings + # See https://github.com/mypyc/mypyc/issues/956 + "-Wno-cpp", + ] + if log_trace: + cflags.append("-DMYPYC_LOG_TRACE") + if experimental_features: + cflags.append("-DMYPYC_EXPERIMENTAL") + if opt_level == "0": + cflags.append("-UNDEBUG") + elif compiler_type == "msvc": + # msvc doesn't have levels, '/O2' is full and '/Od' is disable + if opt_level == "0": + opt_level = "d" + cflags.append("/UNDEBUG") + elif opt_level in ("1", "2", "3"): + opt_level = "2" + if debug_level == "0": + debug_level = "NONE" + elif debug_level == "1": + debug_level = "FASTLINK" + elif debug_level in ("2", "3"): + debug_level = "FULL" + cflags += [ + f"/O{opt_level}", + f"/DEBUG:{debug_level}", + "/wd4102", # unreferenced label + "/wd4101", # unreferenced local variable + "/wd4146", # negating unsigned int + ] + if multi_file: + # Disable whole program optimization in multi-file mode so + # that we actually get the compilation speed and memory + # use wins that multi-file mode is intended for. + cflags += ["/GL-", "/wd9025"] # warning about overriding /GL + if log_trace: + cflags.append("/DMYPYC_LOG_TRACE") + if experimental_features: + cflags.append("/DMYPYC_EXPERIMENTAL") + return cflags + + +def mypycify( + paths: list[str], + *, + only_compile_paths: Iterable[str] | None = None, + verbose: bool = False, + opt_level: str = "3", + debug_level: str = "1", + strip_asserts: bool = False, + multi_file: bool = False, + separate: bool | list[tuple[list[str], str | None]] = False, + skip_cgen_input: tuple[list[list[tuple[str, str]]], list[str]] | None = None, + target_dir: str | None = None, + include_runtime_files: bool | None = None, + strict_dunder_typing: bool = False, + group_name: str | None = None, + log_trace: bool = False, + depends_on_librt_internal: bool = False, + install_librt: bool = False, + experimental_features: bool = False, +) -> list[Extension]: + """Main entry point to building using mypyc. + + This produces a list of Extension objects that should be passed as the + ext_modules parameter to setup. + + Arguments: + paths: A list of file paths to build. It may also contain mypy options. + only_compile_paths: If not None, an iterable of paths that are to be + the only modules compiled, even if other modules + appear in the mypy command line given to paths. + (These modules must still be passed to paths.) + + verbose: Should mypyc be more verbose. Defaults to false. + + opt_level: The optimization level, as a string. Defaults to '3' (meaning '-O3'). + debug_level: The debug level, as a string. Defaults to '1' (meaning '-g1'). + strip_asserts: Should asserts be stripped from the generated code. + + multi_file: Should each Python module be compiled into its own C source file. + This can reduce compile time and memory requirements at the likely + cost of runtime performance of compiled code. Defaults to false. + separate: Should compiled modules be placed in separate extension modules. + If False, all modules are placed in a single shared library. + If True, every module is placed in its own library. + Otherwise, separate should be a list of + (file name list, optional shared library name) pairs specifying + groups of files that should be placed in the same shared library + (while all other modules will be placed in its own library). + + Each group can be compiled independently, which can + speed up compilation, but calls between groups can + be slower than calls within a group and can't be + inlined. + target_dir: The directory to write C output files. Defaults to 'build'. + include_runtime_files: If not None, whether the mypyc runtime library + should be directly #include'd instead of linked + separately in order to reduce compiler invocations. + Defaults to False in multi_file mode, True otherwise. + strict_dunder_typing: If True, force dunder methods to have the return type + of the method strictly, which can lead to more + optimization opportunities. Defaults to False. + group_name: If set, override the default group name derived from + the hash of module names. This is used for the names of the + output C files and the shared library. This is only supported + if there is a single group. [Experimental] + log_trace: If True, compiled code writes a trace log of events in + mypyc_trace.txt (derived from executed operations). This is + useful for performance analysis, such as analyzing which + primitive ops are used the most and on which lines. + depends_on_librt_internal: This is True only for mypy itself. + install_librt: If True, also build the librt extension modules. Normally, + those are build and published on PyPI separately, but during + tests, we want to use their development versions (i.e. from + current commit). + experimental_features: Enable experimental features (install_librt=True is + also needed if using experimental librt features). These + have no backward compatibility guarantees! + """ + + # Figure out our configuration + compiler_options = CompilerOptions( + strip_asserts=strip_asserts, + multi_file=multi_file, + verbose=verbose, + separate=separate is not False, + target_dir=target_dir, + include_runtime_files=include_runtime_files, + strict_dunder_typing=strict_dunder_typing, + group_name=group_name, + log_trace=log_trace, + depends_on_librt_internal=depends_on_librt_internal, + experimental_features=experimental_features, + ) + + # Generate all the actual important C code + groups, group_cfilenames, source_deps = mypyc_build( + paths, + only_compile_paths=only_compile_paths, + compiler_options=compiler_options, + separate=separate, + skip_cgen_input=skip_cgen_input, + ) + + # Mess around with setuptools and actually get the thing built + setup_mypycify_vars() + + # Create a compiler object so we can make decisions based on what + # compiler is being used. typeshed is missing some attributes on the + # compiler object so we give it type Any + compiler: Any = ccompiler.new_compiler() + sysconfig.customize_compiler(compiler) + + build_dir = compiler_options.target_dir + + cflags = get_cflags( + compiler_type=compiler.compiler_type, + opt_level=opt_level, + debug_level=debug_level, + multi_file=multi_file, + experimental_features=experimental_features, + log_trace=log_trace, + ) + + # If configured to (defaults to yes in multi-file mode), copy the + # runtime library in. Otherwise it just gets #included to save on + # compiler invocations. + shared_cfilenames = [] + if not compiler_options.include_runtime_files: + # Collect all files to copy: runtime files + conditional source files + files_to_copy = list(RUNTIME_C_FILES) + for source_dep in source_deps: + files_to_copy.append(source_dep.path) + files_to_copy.append(source_dep.get_header()) + + # Copy all files + for name in files_to_copy: + rt_file = os.path.join(build_dir, name) + with open(os.path.join(include_dir(), name), encoding="utf-8") as f: + write_file(rt_file, f.read()) + if name.endswith(".c"): + shared_cfilenames.append(rt_file) + + extensions = [] + for (group_sources, lib_name), (cfilenames, deps) in zip(groups, group_cfilenames): + if lib_name: + extensions.extend( + build_using_shared_lib( + group_sources, + lib_name, + cfilenames + shared_cfilenames, + deps, + build_dir, + cflags, + ) + ) + else: + extensions.extend( + build_single_module(group_sources, cfilenames + shared_cfilenames, cflags) + ) + + if install_librt: + for name in RUNTIME_C_FILES: + rt_file = os.path.join(build_dir, name) + with open(os.path.join(include_dir(), name), encoding="utf-8") as f: + write_file(rt_file, f.read()) + for mod, file_names, addit_files, includes in LIBRT_MODULES: + for file_name in file_names + addit_files: + rt_file = os.path.join(build_dir, file_name) + with open(os.path.join(include_dir(), file_name), encoding="utf-8") as f: + write_file(rt_file, f.read()) + extensions.append( + get_extension()( + mod, + sources=[ + os.path.join(build_dir, file) for file in file_names + RUNTIME_C_FILES + ], + include_dirs=[include_dir()] + + [os.path.join(include_dir(), d) for d in includes], + extra_compile_args=cflags, + ) + ) + + return extensions diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build_setup.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ec995935990c4d697e4a21f54fa7aff188f5dfa0 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/build_setup.py @@ -0,0 +1,69 @@ +# This file must have the same content for mypyc/build_setup.py and lib-rt/build_setup.py, +# it exists to work around absence of support for per-file compile flags in setuptools. +# The version in mypyc/ is the source of truth, and should be copied to lib-rt if modified. + +import os +import platform +import sys + +try: + # Import setuptools so that it monkey-patch overrides distutils + import setuptools # noqa: F401 +except ImportError: + pass + +if sys.version_info >= (3, 12): + # From setuptools' monkeypatch + from distutils import ccompiler # type: ignore[import-not-found] +else: + from distutils import ccompiler + +EXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT = { + "msvc": { + "base64/arch/sse42": ["/arch:SSE4.2"], + "base64/arch/avx2": ["/arch:AVX2"], + "base64/arch/avx": ["/arch:AVX"], + } +} + +ccompiler.CCompiler.__spawn = ccompiler.CCompiler.spawn # type: ignore[attr-defined] +X86_64 = platform.machine() in ("x86_64", "AMD64", "amd64") +PYODIDE = "PYODIDE" in os.environ +NO_EXTRA_FLAGS = "MYPYC_NO_EXTRA_FLAGS" in os.environ + + +def spawn(self, cmd, **kwargs) -> None: # type: ignore[no-untyped-def] + new_cmd = list(cmd) + if PYODIDE: + for argument in reversed(new_cmd): + if not str(argument).endswith(".c"): + continue + if "base64/arch/" in str(argument): + new_cmd.extend(["-msimd128"]) + elif not NO_EXTRA_FLAGS: + compiler_type: str = self.compiler_type + extra_options = EXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT.get(compiler_type, None) + if X86_64 and extra_options is not None: + # filenames are closer to the end of command line + for argument in reversed(new_cmd): + # Check if the matching argument contains a source filename. + if not str(argument).endswith(".c"): + continue + + for path in extra_options.keys(): + if path in str(argument): + if compiler_type == "bcpp": + compiler = new_cmd.pop() + # Borland accepts a source file name at the end, + # insert the options before it + new_cmd.extend(extra_options[path]) + new_cmd.append(compiler) + else: + new_cmd.extend(extra_options[path]) + + # path component is found, no need to search any further + break + self.__spawn(new_cmd, **kwargs) + + +ccompiler.CCompiler.spawn = spawn # type: ignore[method-assign] diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b2293519e1a0c0b0988724999d44a58ee82e56f6 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/__init__.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5e21c364a48dc59a872fb8536ef6e4bbf2bcebd0 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/cstring.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/cstring.py new file mode 100644 index 0000000000000000000000000000000000000000..853787f8161d4e9277eaac3312e914816b5e2e60 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/cstring.py @@ -0,0 +1,54 @@ +"""Encode valid C string literals from Python strings. + +If a character is not allowed in C string literals, it is either emitted +as a simple escape sequence (e.g. '\\n'), or an octal escape sequence +with exactly three digits ('\\oXXX'). Question marks are escaped to +prevent trigraphs in the string literal from being interpreted. Note +that '\\?' is an invalid escape sequence in Python. + +Consider the string literal "AB\\xCDEF". As one would expect, Python +parses it as ['A', 'B', 0xCD, 'E', 'F']. However, the C standard +specifies that all hexadecimal digits immediately following '\\x' will +be interpreted as part of the escape sequence. Therefore, it is +unexpectedly parsed as ['A', 'B', 0xCDEF]. + +Emitting ("AB\\xCD" "EF") would avoid this behaviour. However, we opt +for simplicity and use octal escape sequences instead. They do not +suffer from the same issue as they are defined to parse at most three +octal digits. +""" + +from __future__ import annotations + +import string +from typing import Final + +CHAR_MAP: Final = [f"\\{i:03o}" for i in range(256)] + +# It is safe to use string.printable as it always uses the C locale. +for c in string.printable: + CHAR_MAP[ord(c)] = c + +# These assignments must come last because we prioritize simple escape +# sequences over any other representation. +for c in ("'", '"', "\\", "a", "b", "f", "n", "r", "t", "v"): + escaped = f"\\{c}" + decoded = escaped.encode("ascii").decode("unicode_escape") + CHAR_MAP[ord(decoded)] = escaped + +# This escape sequence is invalid in Python. +CHAR_MAP[ord("?")] = r"\?" + + +def encode_bytes_as_c_string(b: bytes) -> str: + """Produce contents of a C string literal for a byte string, without quotes.""" + escaped = "".join([CHAR_MAP[i] for i in b]) + return escaped + + +def c_string_initializer(value: bytes) -> str: + """Create initializer for a C char[]/ char * variable from a string. + + For example, if value if b'foo', the result would be '"foo"'. + """ + return '"' + encode_bytes_as_c_string(value) + '"' diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..da607b25235874ea923b2d554908be6ae30392f8 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emit.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emit.py new file mode 100644 index 0000000000000000000000000000000000000000..e313c9231564d746a4a914aaef97a4a71b547899 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emit.py @@ -0,0 +1,1439 @@ +"""Utilities for emitting C code.""" + +from __future__ import annotations + +import pprint +import sys +import textwrap +from collections.abc import Callable +from typing import Final + +from mypyc.codegen.cstring import c_string_initializer +from mypyc.codegen.literals import Literals +from mypyc.common import ( + ATTR_PREFIX, + BITMAP_BITS, + FAST_ISINSTANCE_MAX_SUBCLASSES, + HAVE_IMMORTAL, + MODULE_PREFIX, + NATIVE_PREFIX, + PREFIX, + REG_PREFIX, + STATIC_PREFIX, + TYPE_PREFIX, + TYPE_VAR_PREFIX, +) +from mypyc.ir.class_ir import ClassIR, all_concrete_classes +from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncDecl, FuncIR, get_text_signature +from mypyc.ir.ops import ( + NAMESPACE_MODULE, + NAMESPACE_STATIC, + NAMESPACE_TYPE, + NAMESPACE_TYPE_VAR, + BasicBlock, + Value, +) +from mypyc.ir.rtypes import ( + RInstance, + RPrimitive, + RTuple, + RType, + RUnion, + RVec, + int_rprimitive, + is_bool_or_bit_rprimitive, + is_bytearray_rprimitive, + is_bytes_rprimitive, + is_dict_rprimitive, + is_fixed_width_rtype, + is_float_rprimitive, + is_frozenset_rprimitive, + is_int16_rprimitive, + is_int32_rprimitive, + is_int64_rprimitive, + is_int_rprimitive, + is_list_rprimitive, + is_native_rprimitive, + is_none_rprimitive, + is_object_rprimitive, + is_optional_type, + is_range_rprimitive, + is_set_rprimitive, + is_short_int_rprimitive, + is_str_rprimitive, + is_tuple_rprimitive, + is_uint8_rprimitive, + object_rprimitive, + optional_value_type, + vec_api_by_item_type, + vec_item_type_tags, +) +from mypyc.namegen import NameGenerator, exported_name +from mypyc.primitives.registry import builtin_names +from mypyc.sametype import is_same_type + +# Whether to insert debug asserts for all error handling, to quickly +# catch errors propagating without exceptions set. +DEBUG_ERRORS: Final = False + +PREFIX_MAP: Final = { + NAMESPACE_STATIC: STATIC_PREFIX, + NAMESPACE_TYPE: TYPE_PREFIX, + NAMESPACE_MODULE: MODULE_PREFIX, + NAMESPACE_TYPE_VAR: TYPE_VAR_PREFIX, +} + + +class HeaderDeclaration: + """A representation of a declaration in C. + + This is used to generate declarations in header files and + (optionally) definitions in source files. + + Attributes: + decl: C source code for the declaration. + defn: Optionally, C source code for a definition. + dependencies: The names of any objects that must be declared prior. + is_type: Whether the declaration is of a C type. (C types will be declared in + external header files and not marked 'extern'.) + needs_export: Whether the declared object needs to be exported to + other modules in the linking table. + """ + + def __init__( + self, + decl: str | list[str], + defn: list[str] | None = None, + *, + dependencies: set[str] | None = None, + is_type: bool = False, + needs_export: bool = False, + ) -> None: + self.decl = [decl] if isinstance(decl, str) else decl + self.defn = defn + self.dependencies = dependencies or set() + self.is_type = is_type + self.needs_export = needs_export + + +class EmitterContext: + """Shared emitter state for a compilation group.""" + + def __init__( + self, + names: NameGenerator, + strict_traceback_checks: bool, + group_name: str | None = None, + group_map: dict[str, str | None] | None = None, + ) -> None: + """Setup shared emitter state. + + Args: + names: The name generator to use + group_map: Map from module names to group name + group_name: Current group name + """ + self.temp_counter = 0 + self.names = names + self.group_name = group_name + self.group_map = group_map or {} + # Groups that this group depends on + self.group_deps: set[str] = set() + + # The map below is used for generating declarations and + # definitions at the top of the C file. The main idea is that they can + # be generated at any time during the emit phase. + + # A map of a C identifier to whatever the C identifier declares. Currently this is + # used for declaring structs and the key corresponds to the name of the struct. + # The declaration contains the body of the struct. + self.declarations: dict[str, HeaderDeclaration] = {} + + self.literals = Literals() + # See mypyc/options.py for context. + self.strict_traceback_checks = strict_traceback_checks + + +class ErrorHandler: + """Describes handling errors in unbox/cast operations.""" + + +class AssignHandler(ErrorHandler): + """Assign an error value on error.""" + + +class GotoHandler(ErrorHandler): + """Goto label on error.""" + + def __init__(self, label: str) -> None: + self.label = label + + +class TracebackAndGotoHandler(ErrorHandler): + """Add traceback item and goto label on error.""" + + def __init__( + self, label: str, source_path: str, module_name: str, traceback_entry: tuple[str, int] + ) -> None: + self.label = label + self.source_path = source_path + self.module_name = module_name + self.traceback_entry = traceback_entry + + +class ReturnHandler(ErrorHandler): + """Return a constant value on error.""" + + def __init__(self, value: str) -> None: + self.value = value + + +class Emitter: + """Helper for C code generation.""" + + def __init__( + self, + context: EmitterContext, + value_names: dict[Value, str] | None = None, + capi_version: tuple[int, int] | None = None, + filepath: str | None = None, + ) -> None: + self.context = context + self.capi_version = capi_version or sys.version_info[:2] + self.names = context.names + self.value_names = value_names or {} + self.fragments: list[str] = [] + self._indent = 0 + self.filepath = filepath + + # Low-level operations + + def indent(self) -> None: + self._indent += 4 + + def dedent(self) -> None: + self._indent -= 4 + assert self._indent >= 0 + + def label(self, label: BasicBlock) -> str: + return "CPyL%s" % label.label + + def reg(self, reg: Value) -> str: + return REG_PREFIX + self.value_names[reg] + + def attr(self, name: str) -> str: + return ATTR_PREFIX + name + + def object_annotation(self, obj: object, line: str) -> str: + """Build a C comment with an object's string representation. + + If the comment exceeds the line length limit, it's wrapped into a + multiline string (with the extra lines indented to be aligned with + the first line's comment). + + If it contains illegal characters, an empty string is returned.""" + line_width = self._indent + len(line) + formatted = pprint.pformat(obj, compact=True, width=max(90 - line_width, 20)) + if any(x in formatted for x in ("/*", "*/", "\0")): + return "" + + if "\n" in formatted: + first_line, rest = formatted.split("\n", maxsplit=1) + comment_continued = textwrap.indent(rest, (line_width + 3) * " ") + return f" /* {first_line}\n{comment_continued} */" + else: + return f" /* {formatted} */" + + def emit_line(self, line: str = "", *, ann: object = None) -> None: + if line.startswith("}"): + self.dedent() + comment = self.object_annotation(ann, line) if ann is not None else "" + self.fragments.append(self._indent * " " + line + comment + "\n") + if line.endswith("{"): + self.indent() + + def emit_lines(self, *lines: str) -> None: + for line in lines: + self.emit_line(line) + + def emit_label(self, label: BasicBlock | str) -> None: + if isinstance(label, str): + text = label + else: + if label.label == 0 or not label.referenced: + return + + text = self.label(label) + # Extra semicolon prevents an error when the next line declares a tempvar + self.fragments.append(f"{text}: ;\n") + + def emit_from_emitter(self, emitter: Emitter) -> None: + self.fragments.extend(emitter.fragments) + + def emit_printf(self, fmt: str, *args: str) -> None: + fmt = fmt.replace("\n", "\\n") + self.emit_line("printf(%s);" % ", ".join(['"%s"' % fmt] + list(args))) + self.emit_line("fflush(stdout);") + + def temp_name(self) -> str: + self.context.temp_counter += 1 + return "__tmp%d" % self.context.temp_counter + + def new_label(self) -> str: + self.context.temp_counter += 1 + return "__LL%d" % self.context.temp_counter + + def get_module_group_prefix(self, module_name: str) -> str: + """Get the group prefix for a module (relative to the current group). + + The prefix should be prepended to the object name whenever + accessing an object from this module. + + If the module lives is in the current compilation group, there is + no prefix. But if it lives in a different group (and hence a separate + extension module), we need to access objects from it indirectly via an + export table. + + For example, for code in group `a` to call a function `bar` in group `b`, + it would need to do `exports_b.CPyDef_bar(...)`, while code that is + also in group `b` can simply do `CPyDef_bar(...)`. + + Thus the prefix for a module in group `b` is 'exports_b.' if the current + group is *not* b and just '' if it is. + """ + groups = self.context.group_map + target_group_name = groups.get(module_name) + if target_group_name and target_group_name != self.context.group_name: + self.context.group_deps.add(target_group_name) + return f"exports_{exported_name(target_group_name)}." + else: + return "" + + def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str: + """Get the group prefix for an object.""" + # See docs above + return self.get_module_group_prefix(obj.module_name) + + def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str: + """Create name of a C static variable. + + These are used for literals and imported modules, among other + things. + + The caller should ensure that the (id, module) pair cannot + overlap with other calls to this method within a compilation + group. + """ + lib_prefix = "" if not module else self.get_module_group_prefix(module) + # If we are accessing static via the export table, we need to dereference + # the pointer also. + star_maybe = "*" if lib_prefix else "" + suffix = self.names.private_name(module or "", id) + return f"{star_maybe}{lib_prefix}{prefix}{suffix}" + + def type_struct_name(self, cl: ClassIR) -> str: + return self.static_name(cl.name, cl.module_name, prefix=TYPE_PREFIX) + + def ctype(self, rtype: RType) -> str: + return rtype._ctype + + def ctype_spaced(self, rtype: RType) -> str: + """Adds a space after ctype for non-pointers.""" + ctype = self.ctype(rtype) + if ctype[-1] == "*": + return ctype + else: + return ctype + " " + + def set_undefined_value(self, target: str, rtype: RType) -> None: + if isinstance(rtype, RVec): + self.emit_line(f"{target}.len = -1;") + self.emit_line(f"{target}.buf = NULL;") + else: + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + + def c_undefined_value(self, rtype: RType) -> str: + if not rtype.is_unboxed: + return "NULL" + elif isinstance(rtype, RPrimitive): + return rtype.c_undefined + elif isinstance(rtype, RTuple): + return self.tuple_undefined_value(rtype) + elif isinstance(rtype, RVec): + return f"({self.ctype(rtype)}) {{ -1, NULL }}" + assert False, rtype + + def c_error_value(self, rtype: RType) -> str: + return self.c_undefined_value(rtype) + + def native_function_name(self, fn: FuncDecl) -> str: + return f"{NATIVE_PREFIX}{fn.cname(self.names)}" + + def tuple_c_declaration(self, rtuple: RTuple) -> list[str]: + result = [ + f"#ifndef MYPYC_DECLARED_{rtuple.struct_name}", + f"#define MYPYC_DECLARED_{rtuple.struct_name}", + f"typedef struct {rtuple.struct_name} {{", + ] + if len(rtuple.types) == 0: # empty tuple + # Empty tuples contain a flag so that they can still indicate + # error values. + result.append("int empty_struct_error_flag;") + else: + i = 0 + for typ in rtuple.types: + result.append(f"{self.ctype_spaced(typ)}f{i};") + i += 1 + result.append(f"}} {rtuple.struct_name};") + result.append("#endif") + result.append("") + + return result + + def bitmap_field(self, index: int) -> str: + """Return C field name used for attribute bitmap.""" + n = index // BITMAP_BITS + if n == 0: + return "bitmap" + return f"bitmap{n + 1}" + + def attr_bitmap_expr(self, obj: str, cl: ClassIR, index: int) -> str: + """Return reference to the attribute definedness bitmap.""" + cast = f"({cl.struct_name(self.names)} *)" + attr = self.bitmap_field(index) + return f"({cast}{obj})->{attr}" + + def emit_attr_bitmap_set( + self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str + ) -> None: + """Mark an attribute as defined in the attribute bitmap. + + Assumes that the attribute is tracked in the bitmap (only some attributes + use the bitmap). If 'value' is not equal to the error value, do nothing. + """ + self._emit_attr_bitmap_update(value, obj, rtype, cl, attr, clear=False) + + def emit_attr_bitmap_clear(self, obj: str, rtype: RType, cl: ClassIR, attr: str) -> None: + """Mark an attribute as undefined in the attribute bitmap. + + Unlike emit_attr_bitmap_set, clear unconditionally. + """ + self._emit_attr_bitmap_update("", obj, rtype, cl, attr, clear=True) + + def _emit_attr_bitmap_update( + self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str, clear: bool + ) -> None: + if value: + check = self.error_value_check(rtype, value, "==") + self.emit_line(f"if (unlikely({check})) {{") + index = cl.bitmap_attrs.index(attr) + mask = 1 << (index & (BITMAP_BITS - 1)) + bitmap = self.attr_bitmap_expr(obj, cl, index) + if clear: + self.emit_line(f"{bitmap} &= ~{mask};") + else: + self.emit_line(f"{bitmap} |= {mask};") + if value: + self.emit_line("}") + + def emit_undefined_attr_check( + self, + rtype: RType, + attr_expr: str, + compare: str, + obj: str, + attr: str, + cl: ClassIR, + *, + unlikely: bool = False, + ) -> None: + check = self.error_value_check(rtype, attr_expr, compare) + if unlikely: + check = f"unlikely({check})" + if rtype.error_overlap: + index = cl.bitmap_attrs.index(attr) + bit = 1 << (index & (BITMAP_BITS - 1)) + attr = self.bitmap_field(index) + obj_expr = f"({cl.struct_name(self.names)} *){obj}" + check = f"{check} && !(({obj_expr})->{attr} & {bit})" + self.emit_line(f"if ({check}) {{") + + def error_value_check(self, rtype: RType, value: str, compare: str) -> str: + if isinstance(rtype, RTuple): + return self.tuple_undefined_check_cond( + rtype, value, self.c_error_value, compare, check_exception=False + ) + elif isinstance(rtype, RVec): + if compare == "==": + return f"{value}.len < 0" + elif compare == "!=": + return f"{value}.len >= 0" + assert False, compare + else: + return f"{value} {compare} {self.c_error_value(rtype)}" + + def tuple_undefined_check_cond( + self, + rtuple: RTuple, + tuple_expr_in_c: str, + c_type_compare_val: Callable[[RType], str], + compare: str, + *, + check_exception: bool = True, + ) -> str: + if len(rtuple.types) == 0: + # empty tuple + return "{}.empty_struct_error_flag {} {}".format( + tuple_expr_in_c, compare, c_type_compare_val(int_rprimitive) + ) + if rtuple.error_overlap: + i = 0 + item_type = rtuple.types[0] + else: + for i, typ in enumerate(rtuple.types): + if not typ.error_overlap: + item_type = rtuple.types[i] + break + else: + assert False, "not expecting tuple with error overlap" + if isinstance(item_type, RTuple): + return self.tuple_undefined_check_cond( + item_type, tuple_expr_in_c + f".f{i}", c_type_compare_val, compare + ) + elif isinstance(item_type, RVec): + return f"{tuple_expr_in_c}.f{i}.len {compare} -1" + else: + check = f"{tuple_expr_in_c}.f{i} {compare} {c_type_compare_val(item_type)}" + if rtuple.error_overlap and check_exception: + check += " && PyErr_Occurred()" + return check + + def tuple_undefined_value(self, rtuple: RTuple) -> str: + """Undefined tuple value suitable in an expression.""" + return f"({rtuple.struct_name}) {self.c_initializer_undefined_value(rtuple)}" + + def c_initializer_undefined_value(self, rtype: RType) -> str: + """Undefined value represented in a form suitable for variable initialization.""" + if isinstance(rtype, RTuple): + if not rtype.types: + # Empty tuples contain a flag so that they can still indicate + # error values. + return f"{{ {int_rprimitive.c_undefined} }}" + items = ", ".join([self.c_initializer_undefined_value(t) for t in rtype.types]) + return f"{{ {items} }}" + elif isinstance(rtype, RVec): + return "{ -1, NULL }" + else: + return self.c_undefined_value(rtype) + + # Higher-level operations + + def declare_tuple_struct(self, tuple_type: RTuple) -> None: + if tuple_type.struct_name not in self.context.declarations: + dependencies = set() + for typ in tuple_type.types: + # XXX other types might eventually need similar behavior + if isinstance(typ, RTuple): + dependencies.add(typ.struct_name) + + self.context.declarations[tuple_type.struct_name] = HeaderDeclaration( + self.tuple_c_declaration(tuple_type), dependencies=dependencies, is_type=True + ) + + def emit_inc_ref(self, dest: str, rtype: RType, *, rare: bool = False) -> None: + """Increment reference count of C expression `dest`. + + For composite unboxed structures (e.g. tuples) recursively + increment reference counts for each component. + + If rare is True, optimize for code size and compilation speed. + """ + if is_int_rprimitive(rtype): + if rare: + self.emit_line("CPyTagged_IncRef(%s);" % dest) + else: + self.emit_line("CPyTagged_INCREF(%s);" % dest) + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_inc_ref(f"{dest}.f{i}", item_type) + elif isinstance(rtype, RVec): + # TODO: Only use the X variant if buf can be NULL + self.emit_line(f"Py_XINCREF({dest}.buf);") + elif not rtype.is_unboxed: + # Always inline, since this is a simple but very hot op + if rtype.may_be_immortal or not HAVE_IMMORTAL: + self.emit_line("CPy_INCREF(%s);" % dest) + else: + self.emit_line("CPy_INCREF_NO_IMM(%s);" % dest) + # Otherwise assume it's an unboxed, pointerless value and do nothing. + + def emit_dec_ref( + self, dest: str, rtype: RType, *, is_xdec: bool = False, rare: bool = False + ) -> None: + """Decrement reference count of C expression `dest`. + + For composite unboxed structures (e.g. tuples) recursively + decrement reference counts for each component. + + If rare is True, optimize for code size and compilation speed. + """ + x = "X" if is_xdec else "" + if is_int_rprimitive(rtype): + if rare: + self.emit_line(f"CPyTagged_{x}DecRef({dest});") + else: + # Inlined + self.emit_line(f"CPyTagged_{x}DECREF({dest});") + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_dec_ref(f"{dest}.f{i}", item_type, is_xdec=is_xdec, rare=rare) + elif isinstance(rtype, RVec): + # TODO: Only use the X variant if buf can be NULL + if rare: + self.emit_line(f"CPy_XDecRef({dest}.buf);") + else: + self.emit_line(f"CPy_XDECREF({dest}.buf);") + elif not rtype.is_unboxed: + if rare: + self.emit_line(f"CPy_{x}DecRef({dest});") + else: + # Inlined + if rtype.may_be_immortal or not HAVE_IMMORTAL: + self.emit_line(f"CPy_{x}DECREF({dest});") + else: + self.emit_line(f"CPy_{x}DECREF_NO_IMM({dest});") + elif rtype.is_refcounted: + assert False, f"dec_ref not implemented for {rtype}" + # Otherwise assume it's an unboxed, pointerless value and do nothing. + + def pretty_name(self, typ: RType) -> str: + value_type = optional_value_type(typ) + if value_type is not None: + return "%s or None" % self.pretty_name(value_type) + return str(typ) + + def emit_cast( + self, + src: str, + dest: str, + typ: RType, + *, + declare_dest: bool = False, + error: ErrorHandler | None = None, + raise_exception: bool = True, + optional: bool = False, + src_type: RType | None = None, + likely: bool = True, + ) -> None: + """Emit code for casting a value of given type. + + Somewhat strangely, this supports unboxed types but only + operates on boxed versions. This is necessary to properly + handle types such as Optional[int] in compatibility glue. + + By default, assign NULL (error value) to dest if the value has + an incompatible type and raise TypeError. These can be customized + using 'error' and 'raise_exception'. + + Always copy/steal the reference in 'src'. + + Args: + src: Name of source C variable + dest: Name of target C variable + typ: Type of value + declare_dest: If True, also declare the variable 'dest' + error: What happens on error + raise_exception: If True, also raise TypeError on failure + likely: If the cast is likely to succeed (can be False for unions) + """ + error = error or AssignHandler() + + # Special case casting *from* optional + if src_type and is_optional_type(src_type) and not is_object_rprimitive(typ): + value_type = optional_value_type(src_type) + assert value_type is not None + if is_same_type(value_type, typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "({} != Py_None)" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + return + + # TODO: Verify refcount handling. + if ( + is_list_rprimitive(typ) + or is_dict_rprimitive(typ) + or is_set_rprimitive(typ) + or is_frozenset_rprimitive(typ) + or is_str_rprimitive(typ) + or is_range_rprimitive(typ) + or is_float_rprimitive(typ) + or is_int_rprimitive(typ) + or is_bool_or_bit_rprimitive(typ) + or is_fixed_width_rtype(typ) + ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + if is_list_rprimitive(typ): + prefix = "PyList" + elif is_dict_rprimitive(typ): + prefix = "PyDict" + elif is_set_rprimitive(typ): + prefix = "PySet" + elif is_frozenset_rprimitive(typ): + prefix = "PyFrozenSet" + elif is_str_rprimitive(typ): + prefix = "PyUnicode" + elif is_range_rprimitive(typ): + prefix = "PyRange" + elif is_float_rprimitive(typ): + prefix = "CPyFloat" + elif is_int_rprimitive(typ) or is_fixed_width_rtype(typ): + # TODO: Range check for fixed-width types? + prefix = "PyLong" + elif is_bool_or_bit_rprimitive(typ): + prefix = "PyBool" + else: + assert False, f"unexpected primitive type: {typ}" + check = "({}_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(prefix, src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_bytes_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "(PyBytes_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src, src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_bytearray_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "(PyByteArray_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src, src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_tuple_rprimitive(typ): + if declare_dest: + self.emit_line(f"{self.ctype(typ)} {dest};") + check = "(PyTuple_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif isinstance(typ, RInstance): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + concrete = all_concrete_classes(typ.class_ir) + # If there are too many concrete subclasses or we can't find any + # (meaning the code ought to be dead or we aren't doing global opts), + # fall back to a normal typecheck. + # Otherwise check all the subclasses. + if not concrete or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1: + check = "(PyObject_TypeCheck({}, {}))".format( + src, self.type_struct_name(typ.class_ir) + ) + else: + full_str = "(Py_TYPE({src}) == {targets[0]})" + for i in range(1, len(concrete)): + full_str += " || (Py_TYPE({src}) == {targets[%d]})" % i + if len(concrete) > 1: + full_str = "(%s)" % full_str + check = full_str.format( + src=src, targets=[self.type_struct_name(ir) for ir in concrete] + ) + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check, optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_none_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "({} == Py_None)" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_object_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + self.emit_arg_check(src, dest, typ, "", optional) + self.emit_line(f"{dest} = {src};") + if optional: + self.emit_line("}") + elif is_native_rprimitive(typ): + # Native primitive types have type check functions of form "CPy_Check(...)". + if declare_dest: + self.emit_line(f"PyObject *{dest};") + short_name = typ.name.rsplit(".", 1)[-1] + check = f"(CPy{short_name}_Check({src}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check, optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif isinstance(typ, RUnion): + self.emit_union_cast( + src, dest, typ, declare_dest, error, optional, src_type, raise_exception + ) + elif isinstance(typ, RTuple): + assert not optional + self.emit_tuple_cast(src, dest, typ, declare_dest, error, src_type) + elif isinstance(typ, RVec): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + # Build type check expression based on vec kind + api_name = vec_api_by_item_type.get(typ.item_type) + depth = typ.depth() + if api_name: + # Specialized vec types (vec[i64], vec[i32], etc.) + check = f"(Py_TYPE({src}) == {api_name}.boxed_type)" + elif depth == 0: + # Generic vec types (vec[T], vec[T | None]) with reference type items + item_type_c = self.vec_item_type_c(typ) + check = ( + f"(Py_TYPE({src}) == VecTApi.boxed_type && " + f"((VecTObject *){src})->vec.buf->item_type == {item_type_c})" + ) + else: + # Nested vec types (vec[vec[...]]). Check boxed type, item type, and depth. + unwrapped = typ.unwrap_item_type() + if unwrapped in vec_item_type_tags: + type_value = str(vec_item_type_tags[unwrapped]) + else: + type_value = self.vec_item_type_c(typ) + check = ( + f"(Py_TYPE({src}) == VecNestedApi.boxed_type && " + f"((VecNestedObject *){src})->vec.buf->item_type == {type_value} && " + f"((VecNestedObject *){src})->vec.buf->depth == {depth})" + ) + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check, optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + else: + assert False, "Cast not implemented: %s" % typ + + def emit_cast_error_handler( + self, error: ErrorHandler, src: str, dest: str, typ: RType, raise_exception: bool + ) -> None: + if raise_exception: + if isinstance(error, TracebackAndGotoHandler): + # Merge raising and emitting traceback entry into a single call. + self.emit_type_error_traceback( + error.source_path, error.module_name, error.traceback_entry, typ=typ, src=src + ) + self.emit_line("goto %s;" % error.label) + return + self.emit_line(f'CPy_TypeError("{self.pretty_name(typ)}", {src}); ') + if isinstance(error, AssignHandler): + self.emit_line("%s = NULL;" % dest) + elif isinstance(error, GotoHandler): + self.emit_line("goto %s;" % error.label) + elif isinstance(error, TracebackAndGotoHandler): + self.emit_line("%s = NULL;" % dest) + self.emit_traceback(error.source_path, error.module_name, error.traceback_entry) + self.emit_line("goto %s;" % error.label) + else: + assert isinstance(error, ReturnHandler), error + self.emit_line("return %s;" % error.value) + + def emit_union_cast( + self, + src: str, + dest: str, + typ: RUnion, + declare_dest: bool, + error: ErrorHandler, + optional: bool, + src_type: RType | None, + raise_exception: bool, + ) -> None: + """Emit cast to a union type. + + The arguments are similar to emit_cast. + """ + if declare_dest: + self.emit_line(f"PyObject *{dest};") + good_label = self.new_label() + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + self.emit_line(f"goto {good_label};") + self.emit_line("}") + for item in typ.items: + self.emit_cast( + src, + dest, + item, + declare_dest=False, + raise_exception=False, + optional=False, + likely=False, + ) + self.emit_line(f"if ({dest} != NULL) goto {good_label};") + # Handle cast failure. + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_label(good_label) + + def emit_tuple_cast( + self, + src: str, + dest: str, + typ: RTuple, + declare_dest: bool, + error: ErrorHandler, + src_type: RType | None, + ) -> None: + """Emit cast to a tuple type. + + The arguments are similar to emit_cast. + """ + if declare_dest: + self.emit_line(f"PyObject *{dest};") + # This reuse of the variable is super dodgy. We don't even + # care about the values except to check whether they are + # invalid. + out_label = self.new_label() + self.emit_lines( + "if (unlikely(!(PyTuple_Check({r}) && PyTuple_GET_SIZE({r}) == {size}))) {{".format( + r=src, size=len(typ.types) + ), + f"{dest} = NULL;", + f"goto {out_label};", + "}", + ) + for i, item in enumerate(typ.types): + # Since we did the checks above this should never fail + self.emit_cast( + f"PyTuple_GET_ITEM({src}, {i})", + dest, + item, + declare_dest=False, + raise_exception=False, + optional=False, + ) + self.emit_line(f"if ({dest} == NULL) goto {out_label};") + + self.emit_line(f"{dest} = {src};") + self.emit_label(out_label) + + def emit_arg_check(self, src: str, dest: str, typ: RType, check: str, optional: bool) -> None: + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + if check != "": + self.emit_line("{}if {}".format("} else " if optional else "", check)) + elif optional: + self.emit_line("else {") + + def emit_unbox( + self, + src: str, + dest: str, + typ: RType, + *, + declare_dest: bool = False, + error: ErrorHandler | None = None, + raise_exception: bool = True, + optional: bool = False, + borrow: bool = False, + ) -> None: + """Emit code for unboxing a value of given type (from PyObject *). + + By default, assign error value to dest if the value has an + incompatible type and raise TypeError. These can be customized + using 'error' and 'raise_exception'. + + Generate a new reference unless 'borrow' is True. + + Args: + src: Name of source C variable + dest: Name of target C variable + typ: Type of value + declare_dest: If True, also declare the variable 'dest' + error: What happens on error + raise_exception: If True, also raise TypeError on failure + optional: If True, NULL src value is allowed and will map to error value + borrow: If True, create a borrowed reference + + """ + error = error or AssignHandler() + # TODO: Verify refcount handling. + if isinstance(error, AssignHandler): + failure = f"{dest} = {self.c_error_value(typ)};" + elif isinstance(error, GotoHandler): + failure = "goto %s;" % error.label + else: + assert isinstance(error, ReturnHandler), error + failure = "return %s;" % error.value + if raise_exception: + raise_exc = f'CPy_TypeError("{self.pretty_name(typ)}", {src}); ' + failure = raise_exc + failure + if is_int_rprimitive(typ) or is_short_int_rprimitive(typ): + if declare_dest: + self.emit_line(f"CPyTagged {dest};") + self.emit_arg_check(src, dest, typ, f"(likely(PyLong_Check({src})))", optional) + if borrow: + self.emit_line(f" {dest} = CPyTagged_BorrowFromObject({src});") + else: + self.emit_line(f" {dest} = CPyTagged_FromObject({src});") + self.emit_line("else {") + self.emit_line(failure) + self.emit_line("}") + elif is_bool_or_bit_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + if declare_dest: + self.emit_line(f"char {dest};") + self.emit_arg_check(src, dest, typ, f"(unlikely(!PyBool_Check({src}))) {{", optional) + self.emit_line(failure) + self.emit_line("} else") + conversion = f"{src} == Py_True" + self.emit_line(f" {dest} = {conversion};") + elif is_none_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + if declare_dest: + self.emit_line(f"char {dest};") + self.emit_arg_check(src, dest, typ, f"(unlikely({src} != Py_None)) {{", optional) + self.emit_line(failure) + self.emit_line("} else") + self.emit_line(f" {dest} = 1;") + elif is_int64_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"int64_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsInt64({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_int32_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"int32_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsInt32({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_int16_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"int16_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsInt16({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_uint8_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"uint8_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsUInt8({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_float_rprimitive(typ): + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"double {dest};") + # TODO: Don't use __float__ and __index__ + self.emit_line(f"{dest} = PyFloat_AsDouble({src});") + self.emit_lines(f"if ({dest} == -1.0 && PyErr_Occurred()) {{", failure, "}") + elif isinstance(typ, RTuple): + self.declare_tuple_struct(typ) + if declare_dest: + self.emit_line(f"{self.ctype(typ)} {dest};") + # HACK: The error handling for unboxing tuples is busted + # and instead of fixing it I am just wrapping it in the + # cast code which I think is right. This is not good. + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + self.emit_line("} else {") + + cast_temp = self.temp_name() + self.emit_tuple_cast( + src, cast_temp, typ, declare_dest=True, error=error, src_type=None + ) + self.emit_line(f"if (unlikely({cast_temp} == NULL)) {{") + + # self.emit_arg_check(src, dest, typ, + # '(!PyTuple_Check({}) || PyTuple_Size({}) != {}) {{'.format( + # src, src, len(typ.types)), optional) + self.emit_line(failure) # TODO: Decrease refcount? + self.emit_line("} else {") + if not typ.types: + self.emit_line(f"{dest}.empty_struct_error_flag = 0;") + for i, item_type in enumerate(typ.types): + temp = self.temp_name() + # emit_tuple_cast above checks the size, so this should not fail + self.emit_line(f"PyObject *{temp} = PyTuple_GET_ITEM({src}, {i});") + temp2 = self.temp_name() + # Unbox or check the item. + if item_type.is_unboxed: + self.emit_unbox( + temp, + temp2, + item_type, + raise_exception=raise_exception, + error=error, + declare_dest=True, + borrow=borrow, + ) + else: + if not borrow: + self.emit_inc_ref(temp, object_rprimitive) + self.emit_cast(temp, temp2, item_type, declare_dest=True) + self.emit_line(f"{dest}.f{i} = {temp2};") + self.emit_line("}") + if optional: + self.emit_line("}") + elif isinstance(typ, RVec): + if declare_dest: + self.emit_line(f"{self.ctype(typ)} {dest};") + + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + self.emit_line("} else {") + + specialized_api_name = vec_api_by_item_type.get(typ.item_type) + if specialized_api_name is not None: + self.emit_line(f"{dest} = {specialized_api_name}.unbox({src});") + else: + depth = typ.depth() + unwrapped = typ.unwrap_item_type() + if unwrapped in vec_item_type_tags: + type_value = str(vec_item_type_tags[unwrapped]) + else: + type_value = self.vec_item_type_c(typ) + if depth == 0: + self.emit_line(f"{dest} = VecTApi.unbox({src}, {type_value});") + else: + self.emit_line(f"{dest} = VecNestedApi.unbox({src}, {type_value}, {depth});") + + self.emit_line(f"if (VEC_IS_ERROR({dest})) {{") + self.emit_line(failure) + self.emit_line("}") + + if optional: + self.emit_line("}") + else: + assert False, "Unboxing not implemented: %s" % typ + + def vec_item_type_c(self, typ: RVec) -> str: + item_type = typ.unwrap_item_type() + type_c_ptr = self.type_c_ptr(item_type) + # Can never be None, since we unwrapped the item type above + assert type_c_ptr is not None + type_value = f"(size_t){type_c_ptr}" + if typ.is_optional(): + type_value = f"({type_value} | 1)" + return type_value + + def type_c_ptr(self, typ: RPrimitive | RInstance) -> str | None: + if isinstance(typ, RPrimitive) and typ.is_refcounted: + return "&" + builtin_names[typ.name][1] + elif isinstance(typ, RInstance): + return self.type_struct_name(typ.class_ir) + return None + + def emit_box( + self, src: str, dest: str, typ: RType, declare_dest: bool = False, can_borrow: bool = False + ) -> None: + """Emit code for boxing a value of given type. + + Generate a simple assignment if no boxing is needed. + + The source reference count is stolen for the result (no need to decref afterwards). + """ + # TODO: Always generate a new reference (if a reference type) + if declare_dest: + declaration = "PyObject *" + else: + declaration = "" + if is_int_rprimitive(typ) or is_short_int_rprimitive(typ): + # Steal the existing reference if it exists. + self.emit_line(f"{declaration}{dest} = CPyTagged_StealAsObject({src});") + elif is_bool_or_bit_rprimitive(typ): + # N.B: bool is special cased to produce a borrowed value + # after boxing, so we don't need to increment the refcount + # when this comes directly from a Box op. + self.emit_lines(f"{declaration}{dest} = {src} ? Py_True : Py_False;") + if not can_borrow: + self.emit_inc_ref(dest, object_rprimitive) + elif is_none_rprimitive(typ): + # N.B: None is special cased to produce a borrowed value + # after boxing, so we don't need to increment the refcount + # when this comes directly from a Box op. + self.emit_lines(f"{declaration}{dest} = Py_None;") + if not can_borrow: + self.emit_inc_ref(dest, object_rprimitive) + elif is_int32_rprimitive(typ) or is_int16_rprimitive(typ) or is_uint8_rprimitive(typ): + self.emit_line(f"{declaration}{dest} = PyLong_FromLong({src});") + elif is_int64_rprimitive(typ): + self.emit_line(f"{declaration}{dest} = PyLong_FromLongLong({src});") + elif is_float_rprimitive(typ): + self.emit_line(f"{declaration}{dest} = PyFloat_FromDouble({src});") + elif isinstance(typ, RTuple): + self.declare_tuple_struct(typ) + if not typ.types: + self.emit_line(f"{declaration}{dest} = CPyTuple_LoadEmptyTupleConstant();") + else: + self.emit_line(f"{declaration}{dest} = PyTuple_New({len(typ.types)});") + self.emit_line(f"if (unlikely({dest} == NULL))") + self.emit_line(" CPyError_OutOfMemory();") + + # TODO: Fail if dest is None + for i in range(len(typ.types)): + if not typ.is_unboxed: + self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {src}.f{i}") + else: + inner_name = self.temp_name() + self.emit_box(f"{src}.f{i}", inner_name, typ.types[i], declare_dest=True) + self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {inner_name});") + elif isinstance(typ, RVec): + specialized_api_name = vec_api_by_item_type.get(typ.item_type) + if specialized_api_name is not None: + api = specialized_api_name + elif typ.depth() > 0: + api = "VecNestedApi" + else: + api = "VecTApi" + # Empty vecs of this sort don't describe item type, so it needs to be + # passed explicitly. + item_type = self.vec_item_type_c(typ) + self.emit_line(f"{declaration}{dest} = {api}.box({src}, {item_type});") + return + self.emit_line(f"{declaration}{dest} = {api}.box({src});") + else: + assert not typ.is_unboxed + # Type is boxed -- trivially just assign. + self.emit_line(f"{declaration}{dest} = {src};") + + def emit_error_check(self, value: str, rtype: RType, failure: str) -> None: + """Emit code for checking a native function return value for uncaught exception.""" + if isinstance(rtype, RTuple): + if len(rtype.types) == 0: + return # empty tuples can't fail. + else: + cond = self.tuple_undefined_check_cond(rtype, value, self.c_error_value, "==") + self.emit_line(f"if ({cond}) {{") + elif isinstance(rtype, RVec): + self.emit_line(f"if ({value}.len < 0) {{") + elif rtype.error_overlap: + # The error value is also valid as a normal value, so we need to also check + # for a raised exception. + self.emit_line(f"if ({value} == {self.c_error_value(rtype)} && PyErr_Occurred()) {{") + else: + self.emit_line(f"if ({value} == {self.c_error_value(rtype)}) {{") + self.emit_lines(failure, "}") + + def emit_gc_visit(self, target: str, rtype: RType) -> None: + """Emit code for GC visiting a C variable reference. + + Assume that 'target' represents a C expression that refers to a + struct member, such as 'self->x'. + """ + if not rtype.is_refcounted: + # Not refcounted -> no pointers -> no GC interaction. + return + elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int": + self.emit_line(f"if (CPyTagged_CheckLong({target})) {{") + self.emit_line(f"Py_VISIT(CPyTagged_LongAsObject({target}));") + self.emit_line("}") + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_gc_visit(f"{target}.f{i}", item_type) + elif isinstance(rtype, RVec): + self.emit_line(f"Py_VISIT({target}.buf);") + elif self.ctype(rtype) == "PyObject *": + # The simplest case. + self.emit_line(f"Py_VISIT({target});") + else: + assert False, "emit_gc_visit() not implemented for %s" % repr(rtype) + + def emit_gc_clear(self, target: str, rtype: RType) -> None: + """Emit code for clearing a C attribute reference for GC. + + Assume that 'target' represents a C expression that refers to a + struct member, such as 'self->x'. + """ + if not rtype.is_refcounted: + # Not refcounted -> no pointers -> no GC interaction. + return + elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int": + self.emit_line(f"if (CPyTagged_CheckLong({target})) {{") + self.emit_line(f"CPyTagged __tmp = {target};") + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));") + self.emit_line("}") + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_gc_clear(f"{target}.f{i}", item_type) + elif isinstance(rtype, RVec): + self.emit_line(f"Py_CLEAR({target}.buf);") + elif self.ctype(rtype) == "PyObject *" and self.c_undefined_value(rtype) == "NULL": + # The simplest case. + self.emit_line(f"Py_CLEAR({target});") + else: + assert False, "emit_gc_clear() not implemented for %s" % repr(rtype) + + def emit_reuse_clear(self, target: str, rtype: RType) -> None: + """Emit attribute clear before object is added into freelist. + + Assume that 'target' represents a C expression that refers to a + struct member, such as 'self->x'. + + Unlike emit_gc_clear(), initialize attribute value to match a freshly + allocated object. + """ + if isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_reuse_clear(f"{target}.f{i}", item_type) + elif not rtype.is_refcounted: + self.emit_line(f"{target} = {rtype.c_undefined};") + elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int": + self.emit_line(f"if (CPyTagged_CheckLong({target})) {{") + self.emit_line(f"CPyTagged __tmp = {target};") + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));") + self.emit_line("} else {") + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + self.emit_line("}") + else: + self.emit_gc_clear(target, rtype) + + def emit_traceback( + self, source_path: str, module_name: str, traceback_entry: tuple[str, int] + ) -> None: + return self._emit_traceback("CPy_AddTraceback", source_path, module_name, traceback_entry) + + def emit_type_error_traceback( + self, + source_path: str, + module_name: str, + traceback_entry: tuple[str, int], + *, + typ: RType, + src: str, + ) -> None: + func = "CPy_TypeErrorTraceback" + type_str = f'"{self.pretty_name(typ)}"' + return self._emit_traceback( + func, source_path, module_name, traceback_entry, type_str=type_str, src=src + ) + + def _emit_traceback( + self, + func: str, + source_path: str, + module_name: str, + traceback_entry: tuple[str, int], + type_str: str = "", + src: str = "", + ) -> None: + if self.context.strict_traceback_checks: + assert traceback_entry[1] >= 0, "Traceback cannot have a negative line number" + globals_static = self.static_name("globals", module_name) + line = '%s("%s", "%s", %d, %s' % ( + func, + source_path.replace("\\", "\\\\"), + traceback_entry[0], + traceback_entry[1], + globals_static, + ) + if type_str: + assert src + line += f", {type_str}, {src}" + line += ");" + self.emit_line(line) + if DEBUG_ERRORS: + self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");') + + def emit_unbox_failure_with_overlapping_error_value( + self, dest: str, typ: RType, failure: str + ) -> None: + self.emit_line(f"if ({dest} == {self.c_error_value(typ)} && PyErr_Occurred()) {{") + self.emit_line(failure) + self.emit_line("}") + + def emit_cpyfunction_instance( + self, fn: FuncIR, name: str, filepath: str, error_stmt: str + ) -> str: + module = self.static_name(fn.decl.module_name, None, prefix=MODULE_PREFIX) + cname = f"{PREFIX}{fn.cname(self.names)}" + wrapper_name = f"{cname}_wrapper" + cfunc = f"(PyCFunction){cname}" + func_flags = "METH_FASTCALL | METH_KEYWORDS" + doc = f"PyDoc_STR({native_function_doc_initializer(fn)})" + has_self_arg = "true" if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD else "false" + + code_flags = "CO_COROUTINE" + self.emit_line( + f'PyObject* {wrapper_name} = CPyFunction_New({module}, "{filepath}", "{name}", {cfunc}, {func_flags}, {doc}, {fn.line}, {code_flags}, {has_self_arg});' + ) + self.emit_line(f"if (unlikely(!{wrapper_name}))") + self.emit_line(error_stmt) + return wrapper_name + + +def c_array_initializer(components: list[str], *, indented: bool = False) -> str: + """Construct an initializer for a C array variable. + + Components are C expressions valid in an initializer. + + For example, if components are ["1", "2"], the result + would be "{1, 2}", which can be used like this: + + int a[] = {1, 2}; + + If the result is long, split it into multiple lines. + """ + indent = " " * 4 if indented else "" + res = [] + current: list[str] = [] + cur_len = 0 + for c in components: + if not current or cur_len + 2 + len(indent) + len(c) < 70: + current.append(c) + cur_len += len(c) + 2 + else: + res.append(indent + ", ".join(current)) + current = [c] + cur_len = len(c) + if not res: + # Result fits on a single line + return "{%s}" % ", ".join(current) + # Multi-line result + res.append(indent + ", ".join(current)) + return "{\n " + ",\n ".join(res) + "\n" + indent + "}" + + +def native_function_doc_initializer(func: FuncIR) -> str: + text_sig = get_text_signature(func) + if text_sig is None: + return "NULL" + docstring = f"{text_sig}\n--\n\n" + return c_string_initializer(docstring.encode("ascii", errors="backslashreplace")) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitclass.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitclass.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ab3ab46f01a2baaf308b7633040c612e8654e153 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitclass.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitclass.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitclass.py new file mode 100644 index 0000000000000000000000000000000000000000..26bf189694f97f703759e9e4e5f1659c31ce0fc1 --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitclass.py @@ -0,0 +1,1326 @@ +"""Code generation for native classes and related wrappers.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping + +from mypy.nodes import ARG_STAR, ARG_STAR2 +from mypyc.codegen.cstring import c_string_initializer +from mypyc.codegen.emit import ( + Emitter, + HeaderDeclaration, + ReturnHandler, + native_function_doc_initializer, +) +from mypyc.codegen.emitfunc import native_function_header +from mypyc.codegen.emitwrapper import ( + generate_bin_op_wrapper, + generate_bool_wrapper, + generate_contains_wrapper, + generate_dunder_wrapper, + generate_get_wrapper, + generate_hash_wrapper, + generate_ipow_wrapper, + generate_len_wrapper, + generate_richcompare_wrapper, + generate_set_del_item_wrapper, +) +from mypyc.common import ( + BITMAP_BITS, + BITMAP_TYPE, + CPYFUNCTION_NAME, + NATIVE_PREFIX, + PREFIX, + REG_PREFIX, + short_id_from_name, +) +from mypyc.ir.class_ir import ClassIR, VTableEntries +from mypyc.ir.func_ir import ( + FUNC_CLASSMETHOD, + FUNC_STATICMETHOD, + FuncDecl, + FuncIR, + get_text_signature, +) +from mypyc.ir.rtypes import RTuple, RType, object_rprimitive +from mypyc.namegen import NameGenerator +from mypyc.sametype import is_same_type + + +def native_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: + return f"{NATIVE_PREFIX}{fn.cname(emitter.names)}" + + +def dunder_attr_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: + wrapper_fn = cl.get_method(fn.name + "__wrapper") + assert wrapper_fn + return f"{NATIVE_PREFIX}{wrapper_fn.cname(emitter.names)}" + + +# We maintain a table from dunder function names to struct slots they +# correspond to and functions that generate a wrapper (if necessary) +# and return the function name to stick in the slot. +# TODO: Add remaining dunder methods +SlotGenerator = Callable[[ClassIR, FuncIR, Emitter], str] +SlotTable = Mapping[str, tuple[str, SlotGenerator]] + +SLOT_DEFS: SlotTable = { + "__init__": ("tp_init", lambda c, t, e: generate_init_for_class(c, t, e)), + "__call__": ("tp_call", lambda c, t, e: generate_call_wrapper(c, t, e)), + "__str__": ("tp_str", native_slot), + "__repr__": ("tp_repr", native_slot), + "__next__": ("tp_iternext", native_slot), + "__iter__": ("tp_iter", native_slot), + "__hash__": ("tp_hash", generate_hash_wrapper), + "__get__": ("tp_descr_get", generate_get_wrapper), + "__getattr__": ("tp_getattro", dunder_attr_slot), + "__setattr__": ("tp_setattro", dunder_attr_slot), +} + +AS_MAPPING_SLOT_DEFS: SlotTable = { + "__getitem__": ("mp_subscript", generate_dunder_wrapper), + "__setitem__": ("mp_ass_subscript", generate_set_del_item_wrapper), + "__delitem__": ("mp_ass_subscript", generate_set_del_item_wrapper), + "__len__": ("mp_length", generate_len_wrapper), +} + +AS_SEQUENCE_SLOT_DEFS: SlotTable = {"__contains__": ("sq_contains", generate_contains_wrapper)} + +AS_NUMBER_SLOT_DEFS: SlotTable = { + # Unary operations. + "__bool__": ("nb_bool", generate_bool_wrapper), + "__int__": ("nb_int", generate_dunder_wrapper), + "__float__": ("nb_float", generate_dunder_wrapper), + "__neg__": ("nb_negative", generate_dunder_wrapper), + "__pos__": ("nb_positive", generate_dunder_wrapper), + "__abs__": ("nb_absolute", generate_dunder_wrapper), + "__invert__": ("nb_invert", generate_dunder_wrapper), + # Binary operations. + "__add__": ("nb_add", generate_bin_op_wrapper), + "__radd__": ("nb_add", generate_bin_op_wrapper), + "__sub__": ("nb_subtract", generate_bin_op_wrapper), + "__rsub__": ("nb_subtract", generate_bin_op_wrapper), + "__mul__": ("nb_multiply", generate_bin_op_wrapper), + "__rmul__": ("nb_multiply", generate_bin_op_wrapper), + "__mod__": ("nb_remainder", generate_bin_op_wrapper), + "__rmod__": ("nb_remainder", generate_bin_op_wrapper), + "__truediv__": ("nb_true_divide", generate_bin_op_wrapper), + "__rtruediv__": ("nb_true_divide", generate_bin_op_wrapper), + "__floordiv__": ("nb_floor_divide", generate_bin_op_wrapper), + "__rfloordiv__": ("nb_floor_divide", generate_bin_op_wrapper), + "__divmod__": ("nb_divmod", generate_bin_op_wrapper), + "__rdivmod__": ("nb_divmod", generate_bin_op_wrapper), + "__lshift__": ("nb_lshift", generate_bin_op_wrapper), + "__rlshift__": ("nb_lshift", generate_bin_op_wrapper), + "__rshift__": ("nb_rshift", generate_bin_op_wrapper), + "__rrshift__": ("nb_rshift", generate_bin_op_wrapper), + "__and__": ("nb_and", generate_bin_op_wrapper), + "__rand__": ("nb_and", generate_bin_op_wrapper), + "__or__": ("nb_or", generate_bin_op_wrapper), + "__ror__": ("nb_or", generate_bin_op_wrapper), + "__xor__": ("nb_xor", generate_bin_op_wrapper), + "__rxor__": ("nb_xor", generate_bin_op_wrapper), + "__matmul__": ("nb_matrix_multiply", generate_bin_op_wrapper), + "__rmatmul__": ("nb_matrix_multiply", generate_bin_op_wrapper), + # In-place binary operations. + "__iadd__": ("nb_inplace_add", generate_dunder_wrapper), + "__isub__": ("nb_inplace_subtract", generate_dunder_wrapper), + "__imul__": ("nb_inplace_multiply", generate_dunder_wrapper), + "__imod__": ("nb_inplace_remainder", generate_dunder_wrapper), + "__itruediv__": ("nb_inplace_true_divide", generate_dunder_wrapper), + "__ifloordiv__": ("nb_inplace_floor_divide", generate_dunder_wrapper), + "__ilshift__": ("nb_inplace_lshift", generate_dunder_wrapper), + "__irshift__": ("nb_inplace_rshift", generate_dunder_wrapper), + "__iand__": ("nb_inplace_and", generate_dunder_wrapper), + "__ior__": ("nb_inplace_or", generate_dunder_wrapper), + "__ixor__": ("nb_inplace_xor", generate_dunder_wrapper), + "__imatmul__": ("nb_inplace_matrix_multiply", generate_dunder_wrapper), + # Ternary operations. (yes, really) + # These are special cased in generate_bin_op_wrapper(). + "__pow__": ("nb_power", generate_bin_op_wrapper), + "__rpow__": ("nb_power", generate_bin_op_wrapper), + "__ipow__": ("nb_inplace_power", generate_ipow_wrapper), +} + +AS_ASYNC_SLOT_DEFS: SlotTable = { + "__await__": ("am_await", native_slot), + "__aiter__": ("am_aiter", native_slot), + "__anext__": ("am_anext", native_slot), +} + +SIDE_TABLES = [ + ("as_mapping", "PyMappingMethods", AS_MAPPING_SLOT_DEFS), + ("as_sequence", "PySequenceMethods", AS_SEQUENCE_SLOT_DEFS), + ("as_number", "PyNumberMethods", AS_NUMBER_SLOT_DEFS), + ("as_async", "PyAsyncMethods", AS_ASYNC_SLOT_DEFS), +] + +# Slots that need to always be filled in because they don't get +# inherited right. +ALWAYS_FILL = {"__hash__"} + + +def generate_call_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: + return "PyVectorcall_Call" + + +def slot_key(attr: str) -> str: + """Map dunder method name to sort key. + + Sort reverse operator methods and __delitem__ after others ('x' > '_'). + """ + if (attr.startswith("__r") and attr != "__rshift__") or attr == "__delitem__": + return "x" + attr + return attr + + +def generate_slots(cl: ClassIR, table: SlotTable, emitter: Emitter) -> dict[str, str]: + fields: dict[str, str] = {} + generated: dict[str, str] = {} + # Sort for determinism on Python 3.5 + for name, (slot, generator) in sorted(table.items(), key=lambda x: slot_key(x[0])): + method_cls = cl.get_method_and_class(name) + if method_cls and (method_cls[1] == cl or name in ALWAYS_FILL): + if slot in generated: + # Reuse previously generated wrapper. + fields[slot] = generated[slot] + else: + # Generate new wrapper. + name = generator(cl, method_cls[0], emitter) + fields[slot] = name + generated[slot] = name + + return fields + + +def generate_class_type_decl( + cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter +) -> None: + context = c_emitter.context + name = emitter.type_struct_name(cl) + context.declarations[name] = HeaderDeclaration( + f"PyTypeObject *{emitter.type_struct_name(cl)};", needs_export=True + ) + + # If this is a non-extension class, all we want is the type object decl. + if not cl.is_ext_class: + return + + generate_object_struct(cl, external_emitter) + generate_full = not cl.is_trait and not cl.builtin_base + if generate_full: + context.declarations[emitter.native_function_name(cl.ctor)] = HeaderDeclaration( + f"{native_function_header(cl.ctor, emitter)};", needs_export=True + ) + + +def generate_class_reuse( + cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter +) -> None: + """Generate a definition of a single-object per-class free "list". + + This speeds up object allocation and freeing when there are many short-lived + objects. + + TODO: Generalize to support a free list with up to N objects. + """ + assert cl.reuse_freed_instance + context = c_emitter.context + name = cl.name_prefix(c_emitter.names) + "_free_instance" + struct_name = cl.struct_name(c_emitter.names) + context.declarations[name] = HeaderDeclaration( + f"CPyThreadLocal {struct_name} *{name};", needs_export=True + ) + + +def generate_class(cl: ClassIR, module: str, emitter: Emitter) -> None: + """Generate C code for a class. + + This is the main entry point to the module. + """ + name = cl.name + name_prefix = cl.name_prefix(emitter.names) + + setup_name = emitter.native_function_name(cl.setup) + new_name = f"{name_prefix}_new" + finalize_name = f"{name_prefix}_finalize" + members_name = f"{name_prefix}_members" + getseters_name = f"{name_prefix}_getseters" + vtable_name = f"{name_prefix}_vtable" + traverse_name = f"{name_prefix}_traverse" + clear_name = f"{name_prefix}_clear" + dealloc_name = f"{name_prefix}_dealloc" + methods_name = f"{name_prefix}_methods" + vtable_setup_name = f"{name_prefix}_trait_vtable_setup" + coroutine_setup_name = f"{name_prefix}_coroutine_setup" + + fields: dict[str, str] = {"tp_name": f'"{name}"'} + + generate_full = not cl.is_trait and not cl.builtin_base + needs_getseters = cl.needs_getseters or not cl.is_generated or cl.has_dict + + if not cl.builtin_base: + fields["tp_new"] = new_name + + if generate_full: + fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc" + if not cl.is_acyclic: + fields["tp_traverse"] = f"(traverseproc){name_prefix}_traverse" + fields["tp_clear"] = f"(inquiry){name_prefix}_clear" + # Populate .tp_finalize and generate a finalize method only if __del__ is defined for this class. + del_method = next((e.method for e in cl.vtable_entries if e.name == "__del__"), None) + if del_method: + fields["tp_finalize"] = f"(destructor){finalize_name}" + if needs_getseters: + fields["tp_getset"] = getseters_name + fields["tp_methods"] = methods_name + + def emit_line() -> None: + emitter.emit_line() + + emit_line() + + # If the class has a method to initialize default attribute + # values, we need to call it during initialization. + defaults_fn = cl.get_method("__mypyc_defaults_setup") + + # If there is a __init__ method, we'll use it in the native constructor. + init_fn = cl.get_method("__init__") + + # Fill out slots in the type object from dunder methods. + fields.update(generate_slots(cl, SLOT_DEFS, emitter)) + + # Fill out dunder methods that live in tables hanging off the side. + for table_name, type, slot_defs in SIDE_TABLES: + slots = generate_slots(cl, slot_defs, emitter) + if slots: + table_struct_name = generate_side_table_for_class(cl, table_name, type, slots, emitter) + fields[f"tp_{table_name}"] = f"&{table_struct_name}" + + richcompare_name = generate_richcompare_wrapper(cl, emitter) + if richcompare_name: + fields["tp_richcompare"] = richcompare_name + + # If the class inherits from python, make space for a __dict__ + struct_name = cl.struct_name(emitter.names) + if cl.builtin_base: + base_size = f"sizeof({cl.builtin_base})" + elif cl.is_trait: + base_size = "sizeof(PyObject)" + else: + base_size = f"sizeof({struct_name})" + # Since our types aren't allocated using type() we need to + # populate these fields ourselves if we want them to have correct + # values. PyType_Ready will inherit the offsets from tp_base but + # that isn't what we want. + + # XXX: there is no reason for the __weakref__ stuff to be mixed up with __dict__ + if cl.has_dict and not has_managed_dict(cl, emitter): + # __dict__ lives right after the struct and __weakref__ lives right after that + # TODO: They should get members in the struct instead of doing this nonsense. + weak_offset = f"{base_size} + sizeof(PyObject *)" + emitter.emit_lines( + f"PyMemberDef {members_name}[] = {{", + f'{{"__dict__", T_OBJECT_EX, {base_size}, 0, NULL}},', + f'{{"__weakref__", T_OBJECT_EX, {weak_offset}, 0, NULL}},', + "{0}", + "};", + ) + + fields["tp_members"] = members_name + fields["tp_basicsize"] = f"{base_size} + 2*sizeof(PyObject *)" + if emitter.capi_version < (3, 12): + fields["tp_dictoffset"] = base_size + fields["tp_weaklistoffset"] = weak_offset + else: + fields["tp_basicsize"] = base_size + + if generate_full: + assert cl.setup is not None + emitter.emit_line(native_function_header(cl.setup, emitter) + ";") + assert cl.ctor is not None + emitter.emit_line(native_function_header(cl.ctor, emitter) + ";") + + emit_line() + init_fn = cl.get_method("__init__") + generate_new_for_class(cl, new_name, vtable_name, setup_name, init_fn, emitter) + emit_line() + if not cl.is_acyclic: + generate_traverse_for_class(cl, traverse_name, emitter) + emit_line() + generate_clear_for_class(cl, clear_name, emitter) + emit_line() + generate_dealloc_for_class(cl, dealloc_name, clear_name, bool(del_method), emitter) + emit_line() + + if cl.allow_interpreted_subclasses: + shadow_vtable_name: str | None = generate_vtables( + cl, vtable_setup_name + "_shadow", vtable_name + "_shadow", emitter, shadow=True + ) + emit_line() + else: + shadow_vtable_name = None + vtable_name = generate_vtables(cl, vtable_setup_name, vtable_name, emitter, shadow=False) + emit_line() + generate_coroutine_setup(cl, coroutine_setup_name, module, emitter) + emit_line() + if del_method: + generate_finalize_for_class(del_method, finalize_name, emitter) + emit_line() + if needs_getseters: + generate_getseter_declarations(cl, emitter) + emit_line() + generate_getseters_table(cl, getseters_name, emitter) + emit_line() + + if cl.is_trait: + generate_new_for_trait(cl, new_name, emitter) + + generate_methods_table(cl, methods_name, setup_name if generate_full else None, emitter) + emit_line() + + flags = ["Py_TPFLAGS_DEFAULT", "Py_TPFLAGS_HEAPTYPE", "Py_TPFLAGS_BASETYPE"] + if generate_full and not cl.is_acyclic: + flags.append("Py_TPFLAGS_HAVE_GC") + if cl.has_method("__call__"): + fields["tp_vectorcall_offset"] = "offsetof({}, vectorcall)".format( + cl.struct_name(emitter.names) + ) + flags.append("_Py_TPFLAGS_HAVE_VECTORCALL") + if not fields.get("tp_vectorcall"): + # This is just a placeholder to please CPython. It will be + # overridden during setup. + fields["tp_call"] = "PyVectorcall_Call" + if has_managed_dict(cl, emitter): + flags.append("Py_TPFLAGS_MANAGED_DICT") + fields["tp_flags"] = " | ".join(flags) + + fields["tp_doc"] = f"PyDoc_STR({native_class_doc_initializer(cl)})" + + emitter.emit_line(f"static PyTypeObject {emitter.type_struct_name(cl)}_template_ = {{") + emitter.emit_line("PyVarObject_HEAD_INIT(NULL, 0)") + for field, value in fields.items(): + emitter.emit_line(f".{field} = {value},") + emitter.emit_line("};") + emitter.emit_line( + "static PyTypeObject *{t}_template = &{t}_template_;".format( + t=emitter.type_struct_name(cl) + ) + ) + + if cl.coroutine_name: + cpyfunction = emitter.static_name(cl.name + "_cpyfunction", module) + emitter.emit_line(f"static PyObject *{cpyfunction} = NULL;") + + emitter.emit_line() + if generate_full: + generate_setup_for_class(cl, defaults_fn, vtable_name, shadow_vtable_name, emitter) + emitter.emit_line() + generate_constructor_for_class(cl, cl.ctor, init_fn, setup_name, vtable_name, emitter) + emitter.emit_line() + if needs_getseters: + generate_getseters(cl, emitter) + + +def getter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str: + return names.private_name(cl.module_name, f"{cl.name}_get_{attribute}") + + +def setter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str: + return names.private_name(cl.module_name, f"{cl.name}_set_{attribute}") + + +def generate_object_struct(cl: ClassIR, emitter: Emitter) -> None: + seen_attrs: set[str] = set() + lines: list[str] = [] + lines += ["typedef struct {", "PyObject_HEAD", "CPyVTableItem *vtable;"] + if cl.has_method("__call__"): + lines.append("vectorcallfunc vectorcall;") + bitmap_attrs = [] + for base in reversed(cl.base_mro): + if not base.is_trait: + if base.bitmap_attrs: + # Do we need another attribute bitmap field? + if emitter.bitmap_field(len(base.bitmap_attrs) - 1) not in bitmap_attrs: + for i in range(0, len(base.bitmap_attrs), BITMAP_BITS): + attr = emitter.bitmap_field(i) + if attr not in bitmap_attrs: + lines.append(f"{BITMAP_TYPE} {attr};") + bitmap_attrs.append(attr) + for attr, rtype in base.attributes.items(): + # Generated class may redefine certain attributes with different + # types in subclasses (this would be unsafe for user-defined classes). + if attr not in seen_attrs: + lines.append(f"{emitter.ctype_spaced(rtype)}{emitter.attr(attr)};") + seen_attrs.add(attr) + + if isinstance(rtype, RTuple): + emitter.declare_tuple_struct(rtype) + + lines.append(f"}} {cl.struct_name(emitter.names)};") + lines.append("") + emitter.context.declarations[cl.struct_name(emitter.names)] = HeaderDeclaration( + lines, is_type=True + ) + + +def generate_vtables( + base: ClassIR, vtable_setup_name: str, vtable_name: str, emitter: Emitter, shadow: bool +) -> str: + """Emit the vtables and vtable setup functions for a class. + + This includes both the primary vtable and any trait implementation vtables. + The trait vtables go before the main vtable, and have the following layout: + { + CPyType_T1, // pointer to type object + C_T1_trait_vtable, // pointer to array of method pointers + C_T1_offset_table, // pointer to array of attribute offsets + CPyType_T2, + C_T2_trait_vtable, + C_T2_offset_table, + ... + } + The method implementations are calculated at the end of IR pass, attribute + offsets are {offsetof(native__C, _x1), offsetof(native__C, _y1), ...}. + + To account for both dynamic loading and dynamic class creation, + vtables are populated dynamically at class creation time, so we + emit empty array definitions to store the vtables and a function to + populate them. + + If shadow is True, generate "shadow vtables" that point to the + shadow glue methods (which should dispatch via the Python C-API). + + Returns the expression to use to refer to the vtable, which might be + different than the name, if there are trait vtables. + """ + + def trait_vtable_name(trait: ClassIR) -> str: + return "{}_{}_trait_vtable{}".format( + base.name_prefix(emitter.names), + trait.name_prefix(emitter.names), + "_shadow" if shadow else "", + ) + + def trait_offset_table_name(trait: ClassIR) -> str: + return "{}_{}_offset_table".format( + base.name_prefix(emitter.names), trait.name_prefix(emitter.names) + ) + + # Emit array definitions with enough space for all the entries + emitter.emit_line( + "static CPyVTableItem {}[{}];".format( + vtable_name, max(1, len(base.vtable_entries) + 3 * len(base.trait_vtables)) + ) + ) + + for trait, vtable in base.trait_vtables.items(): + # Trait methods entry (vtable index -> method implementation). + emitter.emit_line( + f"static CPyVTableItem {trait_vtable_name(trait)}[{max(1, len(vtable))}];" + ) + # Trait attributes entry (attribute number in trait -> offset in actual struct). + emitter.emit_line( + "static size_t {}[{}];".format( + trait_offset_table_name(trait), max(1, len(trait.attributes)) + ) + ) + + # Emit vtable setup function + emitter.emit_line("static bool") + emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}(void)") + emitter.emit_line("{") + + if base.allow_interpreted_subclasses and not shadow: + emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}_shadow();") + + subtables = [] + for trait, vtable in base.trait_vtables.items(): + name = trait_vtable_name(trait) + offset_name = trait_offset_table_name(trait) + generate_vtable(vtable, name, emitter, [], shadow) + generate_offset_table(offset_name, emitter, trait, base) + subtables.append((trait, name, offset_name)) + + generate_vtable(base.vtable_entries, vtable_name, emitter, subtables, shadow) + + emitter.emit_line("return 1;") + emitter.emit_line("}") + + return vtable_name if not subtables else f"{vtable_name} + {len(subtables) * 3}" + + +def generate_offset_table( + trait_offset_table_name: str, emitter: Emitter, trait: ClassIR, cl: ClassIR +) -> None: + """Generate attribute offset row of a trait vtable.""" + emitter.emit_line(f"size_t {trait_offset_table_name}_scratch[] = {{") + for attr in trait.attributes: + emitter.emit_line(f"offsetof({cl.struct_name(emitter.names)}, {emitter.attr(attr)}),") + if not trait.attributes: + # This is for msvc. + emitter.emit_line("0") + emitter.emit_line("};") + emitter.emit_line( + "memcpy({name}, {name}_scratch, sizeof({name}));".format(name=trait_offset_table_name) + ) + + +def generate_vtable( + entries: VTableEntries, + vtable_name: str, + emitter: Emitter, + subtables: list[tuple[ClassIR, str, str]], + shadow: bool, +) -> None: + emitter.emit_line(f"CPyVTableItem {vtable_name}_scratch[] = {{") + if subtables: + emitter.emit_line("/* Array of trait vtables */") + for trait, table, offset_table in subtables: + emitter.emit_line( + "(CPyVTableItem){}, (CPyVTableItem){}, (CPyVTableItem){},".format( + emitter.type_struct_name(trait), table, offset_table + ) + ) + emitter.emit_line("/* Start of real vtable */") + + for entry in entries: + method = entry.shadow_method if shadow and entry.shadow_method else entry.method + emitter.emit_line( + "(CPyVTableItem){}{}{},".format( + emitter.get_group_prefix(entry.method.decl), + NATIVE_PREFIX, + method.cname(emitter.names), + ) + ) + + # msvc doesn't allow empty arrays; maybe allowing them at all is an extension? + if not entries: + emitter.emit_line("NULL") + emitter.emit_line("};") + emitter.emit_line("memcpy({name}, {name}_scratch, sizeof({name}));".format(name=vtable_name)) + + +def generate_setup_for_class( + cl: ClassIR, + defaults_fn: FuncIR | None, + vtable_name: str, + shadow_vtable_name: str | None, + emitter: Emitter, +) -> None: + """Generate a native function that allocates an instance of a class.""" + emitter.emit_line(native_function_header(cl.setup, emitter)) + emitter.emit_line("{") + type_arg_name = REG_PREFIX + cl.setup.sig.args[0].name + emitter.emit_line(f"PyTypeObject *type = (PyTypeObject*){type_arg_name};") + struct_name = cl.struct_name(emitter.names) + emitter.emit_line(f"{struct_name} *self;") + + prefix = cl.name_prefix(emitter.names) + if cl.reuse_freed_instance: + # Attempt to use a per-type free list first (a free "list" with up to one object only). + emitter.emit_line(f"if ({prefix}_free_instance != NULL) {{") + emitter.emit_line(f"self = {prefix}_free_instance;") + emitter.emit_line(f"{prefix}_free_instance = NULL;") + emitter.emit_line("Py_SET_REFCNT(self, 1);") + if not cl.is_acyclic: + emitter.emit_line("PyObject_GC_Track(self);") + if defaults_fn is not None: + emit_attr_defaults_func_call(defaults_fn, "self", emitter) + emitter.emit_line("return (PyObject *)self;") + emitter.emit_line("}") + + emitter.emit_line(f"self = ({cl.struct_name(emitter.names)} *)type->tp_alloc(type, 0);") + emitter.emit_line("if (self == NULL)") + emitter.emit_line(" return NULL;") + + if shadow_vtable_name: + emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{") + emitter.emit_line(f"self->vtable = {shadow_vtable_name};") + emitter.emit_line("} else {") + emitter.emit_line(f"self->vtable = {vtable_name};") + emitter.emit_line("}") + else: + emitter.emit_line(f"self->vtable = {vtable_name};") + + emit_clear_bitmaps(cl, emitter) + + if cl.has_method("__call__"): + name = cl.method_decl("__call__").cname(emitter.names) + emitter.emit_line(f"self->vectorcall = {PREFIX}{name};") + + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + value = emitter.c_undefined_value(rtype) + + # We don't need to set this field to NULL since tp_alloc() already + # zero-initializes `self`. + if value != "NULL": + emitter.set_undefined_value(f"self->{emitter.attr(attr)}", rtype) + + # Initialize attributes to default values, if necessary + if defaults_fn is not None: + emit_attr_defaults_func_call(defaults_fn, "self", emitter) + + emitter.emit_line("return (PyObject *)self;") + emitter.emit_line("}") + + +def emit_clear_bitmaps(cl: ClassIR, emitter: Emitter) -> None: + """Emit C code to clear bitmaps that track if attributes have an assigned value.""" + for i in range(0, len(cl.bitmap_attrs), BITMAP_BITS): + field = emitter.bitmap_field(i) + emitter.emit_line(f"self->{field} = 0;") + + +def emit_attr_defaults_func_call(defaults_fn: FuncIR, self_name: str, emitter: Emitter) -> None: + """Emit C code to initialize attribute defaults by calling defaults_fn. + + The code returns NULL on a raised exception. + """ + emitter.emit_lines( + "if ({}{}((PyObject *){}) == 0) {{".format( + NATIVE_PREFIX, defaults_fn.cname(emitter.names), self_name + ), + "Py_DECREF(self);", + "return NULL;", + "}", + ) + + +def emit_setup_or_dunder_new_call( + cl: ClassIR, + setup_name: str, + type_arg: str, + native_prefix: bool, + new_args: str, + emitter: Emitter, +) -> None: + def emit_null_check() -> None: + emitter.emit_line("if (self == NULL)") + emitter.emit_line(" return NULL;") + + new_fn = cl.get_method("__new__") + if not new_fn: + emitter.emit_line(f"PyObject *self = {setup_name}({type_arg});") + emit_null_check() + return + prefix = emitter.get_group_prefix(new_fn.decl) + NATIVE_PREFIX if native_prefix else PREFIX + all_args = type_arg + if new_args != "": + all_args += ", " + new_args + emitter.emit_line(f"PyObject *self = {prefix}{new_fn.cname(emitter.names)}({all_args});") + emit_null_check() + + # skip __init__ if __new__ returns some other type + emitter.emit_line(f"if (Py_TYPE(self) != {emitter.type_struct_name(cl)})") + emitter.emit_line(" return self;") + + +def generate_constructor_for_class( + cl: ClassIR, + fn: FuncDecl, + init_fn: FuncIR | None, + setup_name: str, + vtable_name: str, + emitter: Emitter, +) -> None: + """Generate a native function that allocates and initializes an instance of a class.""" + emitter.emit_line(f"{native_function_header(fn, emitter)}") + emitter.emit_line("{") + + fn_args = [REG_PREFIX + arg.name for arg in fn.sig.args] + type_arg = "(PyObject *)" + emitter.type_struct_name(cl) + new_args = ", ".join(fn_args) + + use_wrapper = ( + cl.has_method("__new__") + and len(fn.sig.args) == 2 + and fn.sig.args[0].kind == ARG_STAR + and fn.sig.args[1].kind == ARG_STAR2 + ) + emit_setup_or_dunder_new_call(cl, setup_name, type_arg, not use_wrapper, new_args, emitter) + + args = ", ".join(["self"] + fn_args) + if init_fn is not None: + prefix = PREFIX if use_wrapper else NATIVE_PREFIX + cast = "!= NULL ? 0 : -1" if use_wrapper else "" + emitter.emit_line( + "char res = {}{}{}({}){};".format( + emitter.get_group_prefix(init_fn.decl), + prefix, + init_fn.cname(emitter.names), + args, + cast, + ) + ) + emitter.emit_line("if (res == 2) {") + emitter.emit_line("Py_DECREF(self);") + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + # If there is a nontrivial ctor that we didn't define, invoke it via tp_init + elif len(fn.sig.args) > 1: + emitter.emit_line(f"int res = {emitter.type_struct_name(cl)}->tp_init({args});") + + emitter.emit_line("if (res < 0) {") + emitter.emit_line("Py_DECREF(self);") + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + emitter.emit_line("return self;") + emitter.emit_line("}") + + +def generate_init_for_class(cl: ClassIR, init_fn: FuncIR, emitter: Emitter) -> str: + """Generate an init function suitable for use as tp_init. + + tp_init needs to be a function that returns an int, and our + __init__ methods return a PyObject. Translate NULL to -1, + everything else to 0. + """ + func_name = f"{cl.name_prefix(emitter.names)}_init" + + emitter.emit_line("static int") + emitter.emit_line(f"{func_name}(PyObject *self, PyObject *args, PyObject *kwds)") + emitter.emit_line("{") + if cl.allow_interpreted_subclasses or cl.builtin_base or cl.has_method("__new__"): + emitter.emit_line( + "return {}{}(self, args, kwds) != NULL ? 0 : -1;".format( + PREFIX, init_fn.cname(emitter.names) + ) + ) + else: + emitter.emit_line("return 0;") + emitter.emit_line("}") + + return func_name + + +def generate_new_for_class( + cl: ClassIR, + func_name: str, + vtable_name: str, + setup_name: str, + init_fn: FuncIR | None, + emitter: Emitter, +) -> None: + emitter.emit_line("static PyObject *") + emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)") + emitter.emit_line("{") + # TODO: Check and unbox arguments + if not cl.allow_interpreted_subclasses: + emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{") + emitter.emit_line( + 'PyErr_SetString(PyExc_TypeError, "interpreted classes cannot inherit from compiled");' + ) + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + type_arg = "(PyObject*)type" + new_args = "args, kwds" + emit_setup_or_dunder_new_call(cl, setup_name, type_arg, False, new_args, emitter) + if ( + not init_fn + or cl.allow_interpreted_subclasses + or cl.builtin_base + or cl.is_serializable() + or cl.has_method("__new__") + ): + # Match Python semantics -- __new__ doesn't call __init__. + emitter.emit_line("return self;") + else: + # __new__ of a native class implicitly calls __init__ so that we + # can enforce that instances are always properly initialized. This + # is needed to support always defined attributes. + emitter.emit_line( + f"PyObject *ret = {PREFIX}{init_fn.cname(emitter.names)}(self, args, kwds);" + ) + emitter.emit_lines("if (ret == NULL)", " return NULL;") + emitter.emit_line("return self;") + emitter.emit_line("}") + + +def generate_new_for_trait(cl: ClassIR, func_name: str, emitter: Emitter) -> None: + emitter.emit_line("static PyObject *") + emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)") + emitter.emit_line("{") + emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{") + emitter.emit_line( + "PyErr_SetString(PyExc_TypeError, " + '"interpreted classes cannot inherit from compiled traits");' + ) + emitter.emit_line("} else {") + emitter.emit_line('PyErr_SetString(PyExc_TypeError, "traits may not be directly created");') + emitter.emit_line("}") + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + +def generate_traverse_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None: + """Emit function that performs cycle GC traversal of an instance.""" + emitter.emit_line("static int") + emitter.emit_line( + f"{func_name}({cl.struct_name(emitter.names)} *self, visitproc visit, void *arg)" + ) + emitter.emit_line("{") + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + emitter.emit_gc_visit(f"self->{emitter.attr(attr)}", rtype) + if has_managed_dict(cl, emitter): + emitter.emit_line("PyObject_VisitManagedDict((PyObject *)self, visit, arg);") + elif cl.has_dict: + struct_name = cl.struct_name(emitter.names) + # __dict__ lives right after the struct and __weakref__ lives right after that + emitter.emit_gc_visit( + f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive + ) + emitter.emit_gc_visit( + f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))", + object_rprimitive, + ) + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def generate_clear_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None: + emitter.emit_line("static int") + emitter.emit_line(f"{func_name}({cl.struct_name(emitter.names)} *self)") + emitter.emit_line("{") + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + emitter.emit_gc_clear(f"self->{emitter.attr(attr)}", rtype) + if has_managed_dict(cl, emitter): + emitter.emit_line("PyObject_ClearManagedDict((PyObject *)self);") + elif cl.has_dict: + struct_name = cl.struct_name(emitter.names) + # __dict__ lives right after the struct and __weakref__ lives right after that + emitter.emit_gc_clear( + f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive + ) + emitter.emit_gc_clear( + f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))", + object_rprimitive, + ) + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def generate_dealloc_for_class( + cl: ClassIR, + dealloc_func_name: str, + clear_func_name: str, + has_tp_finalize: bool, + emitter: Emitter, +) -> None: + emitter.emit_line("static void") + emitter.emit_line(f"{dealloc_func_name}({cl.struct_name(emitter.names)} *self)") + emitter.emit_line("{") + if has_tp_finalize: + emitter.emit_line("PyObject *type, *value, *traceback;") + emitter.emit_line("PyErr_Fetch(&type, &value, &traceback);") + emitter.emit_line("int res = PyObject_CallFinalizerFromDealloc((PyObject *)self);") + # CPython interpreter uses PyErr_WriteUnraisable: https://docs.python.org/3/c-api/exceptions.html#c.PyErr_WriteUnraisable + # However, the message is slightly different due to the way mypyc compiles classes. + # CPython interpreter prints: Exception ignored in: + # mypyc prints: Exception ignored in: + emitter.emit_line("if (PyErr_Occurred() != NULL) {") + # Don't untrack instance if error occurred + emitter.emit_line("PyErr_WriteUnraisable((PyObject *)self);") + emitter.emit_line("res = -1;") + emitter.emit_line("}") + emitter.emit_line("PyErr_Restore(type, value, traceback);") + emitter.emit_line("if (res < 0) {") + emitter.emit_line("goto done;") + emitter.emit_line("}") + if not cl.is_acyclic: + emitter.emit_line("PyObject_GC_UnTrack(self);") + if cl.reuse_freed_instance: + emit_reuse_dealloc(cl, emitter) + # The trashcan is needed to handle deep recursive deallocations + emitter.emit_line(f"CPy_TRASHCAN_BEGIN(self, {dealloc_func_name})") + emitter.emit_line(f"{clear_func_name}(self);") + emitter.emit_line("Py_TYPE(self)->tp_free((PyObject *)self);") + emitter.emit_line("CPy_TRASHCAN_END(self)") + emitter.emit_line("done: ;") + emitter.emit_line("}") + + +def emit_reuse_dealloc(cl: ClassIR, emitter: Emitter) -> None: + """Emit code to deallocate object by putting it to per-type free list. + + The free "list" currently can have up to one object. + """ + prefix = cl.name_prefix(emitter.names) + emitter.emit_line(f"if ({prefix}_free_instance == NULL) {{") + emitter.emit_line(f"{prefix}_free_instance = self;") + + # Clear attributes and free referenced objects. + + emit_clear_bitmaps(cl, emitter) + + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + emitter.emit_reuse_clear(f"self->{emitter.attr(attr)}", rtype) + + emitter.emit_line("return;") + emitter.emit_line("}") + + +def generate_finalize_for_class( + del_method: FuncIR, finalize_func_name: str, emitter: Emitter +) -> None: + emitter.emit_line("static void") + emitter.emit_line(f"{finalize_func_name}(PyObject *self)") + emitter.emit_line("{") + emitter.emit_line( + "{}{}{}(self);".format( + emitter.get_group_prefix(del_method.decl), + NATIVE_PREFIX, + del_method.cname(emitter.names), + ) + ) + emitter.emit_line("}") + + +def generate_methods_table( + cl: ClassIR, name: str, setup_name: str | None, emitter: Emitter +) -> None: + emitter.emit_line(f"static PyMethodDef {name}[] = {{") + if setup_name: + # Store pointer to the setup function so it can be resolved dynamically + # in case of instance creation in __new__. + # CPy_SetupObject expects this method to be the first one in tp_methods. + emitter.emit_line( + f'{{"__internal_mypyc_setup", (PyCFunction){setup_name}, METH_O, NULL}},' + ) + for fn in cl.methods.values(): + if fn.decl.is_prop_setter or fn.decl.is_prop_getter or fn.internal: + continue + emitter.emit_line(f'{{"{fn.name}",') + emitter.emit_line(f" (PyCFunction){PREFIX}{fn.cname(emitter.names)},") + flags = ["METH_FASTCALL", "METH_KEYWORDS"] + if fn.decl.kind == FUNC_STATICMETHOD: + flags.append("METH_STATIC") + elif fn.decl.kind == FUNC_CLASSMETHOD: + flags.append("METH_CLASS") + + doc = native_function_doc_initializer(fn) + emitter.emit_line(" {}, PyDoc_STR({})}},".format(" | ".join(flags), doc)) + + # Provide a default __getstate__ and __setstate__ + if not cl.has_method("__setstate__") and not cl.has_method("__getstate__"): + emitter.emit_lines( + '{"__setstate__", (PyCFunction)CPyPickle_SetState, METH_O, NULL},', + '{"__getstate__", (PyCFunction)CPyPickle_GetState, METH_NOARGS, NULL},', + ) + + emitter.emit_line("{NULL} /* Sentinel */") + emitter.emit_line("};") + + +def generate_side_table_for_class( + cl: ClassIR, name: str, type: str, slots: dict[str, str], emitter: Emitter +) -> str | None: + name = f"{cl.name_prefix(emitter.names)}_{name}" + emitter.emit_line(f"static {type} {name} = {{") + for field, value in slots.items(): + emitter.emit_line(f".{field} = {value},") + emitter.emit_line("};") + return name + + +def generate_getseter_declarations(cl: ClassIR, emitter: Emitter) -> None: + if not cl.is_trait: + for attr in cl.attributes: + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure);".format( + getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure);".format( + setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + + for prop, (getter, setter) in cl.properties.items(): + if getter.decl.implicit: + continue + + # Generate getter declaration + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure);".format( + getter_name(cl, prop, emitter.names), cl.struct_name(emitter.names) + ) + ) + + # Generate property setter declaration if a setter exists + if setter: + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure);".format( + setter_name(cl, prop, emitter.names), cl.struct_name(emitter.names) + ) + ) + + +def generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None: + emitter.emit_line(f"static PyGetSetDef {name}[] = {{") + if not cl.is_trait: + for attr in cl.attributes: + emitter.emit_line(f'{{"{attr}",') + emitter.emit_line( + " (getter){}, (setter){},".format( + getter_name(cl, attr, emitter.names), setter_name(cl, attr, emitter.names) + ) + ) + emitter.emit_line(" NULL, NULL},") + for prop, (getter, setter) in cl.properties.items(): + if getter.decl.implicit: + continue + + emitter.emit_line(f'{{"{prop}",') + emitter.emit_line(f" (getter){getter_name(cl, prop, emitter.names)},") + + if setter: + emitter.emit_line(f" (setter){setter_name(cl, prop, emitter.names)},") + emitter.emit_line("NULL, NULL},") + else: + emitter.emit_line("NULL, NULL, NULL},") + + if cl.has_dict: + emitter.emit_line('{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},') + + emitter.emit_line("{NULL} /* Sentinel */") + emitter.emit_line("};") + + +def generate_getseters(cl: ClassIR, emitter: Emitter) -> None: + if not cl.is_trait: + for i, (attr, rtype) in enumerate(cl.attributes.items()): + generate_getter(cl, attr, rtype, emitter) + emitter.emit_line("") + generate_setter(cl, attr, rtype, emitter) + if i < len(cl.attributes) - 1: + emitter.emit_line("") + for prop, (getter, setter) in cl.properties.items(): + if getter.decl.implicit: + continue + + rtype = getter.sig.ret_type + emitter.emit_line("") + generate_readonly_getter(cl, prop, rtype, getter, emitter) + if setter: + arg_type = setter.sig.args[1].type + emitter.emit_line("") + generate_property_setter(cl, prop, arg_type, setter, emitter) + + +def generate_getter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None: + attr_field = emitter.attr(attr) + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure)".format( + getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + attr_expr = f"self->{attr_field}" + + # HACK: Don't consider refcounted values as always defined, since it's possible to + # access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted + # values is benign. + always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted + + if not always_defined: + emitter.emit_undefined_attr_check(rtype, attr_expr, "==", "self", attr, cl, unlikely=True) + emitter.emit_line("PyErr_SetString(PyExc_AttributeError,") + emitter.emit_line(f' "attribute {repr(attr)} of {repr(cl.name)} undefined");') + emitter.emit_line("return NULL;") + emitter.emit_line("}") + emitter.emit_inc_ref(f"self->{attr_field}", rtype) + emitter.emit_box(f"self->{attr_field}", "retval", rtype, declare_dest=True) + emitter.emit_line("return retval;") + emitter.emit_line("}") + + +def generate_setter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None: + attr_field = emitter.attr(attr) + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure)".format( + setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + + deletable = cl.is_deletable(attr) + if not deletable: + emitter.emit_line("if (value == NULL) {") + emitter.emit_line("PyErr_SetString(PyExc_AttributeError,") + emitter.emit_line( + f' "{repr(cl.name)} object attribute {repr(attr)} cannot be deleted");' + ) + emitter.emit_line("return -1;") + emitter.emit_line("}") + + # HACK: Don't consider refcounted values as always defined, since it's possible to + # access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted + # values is benign. + always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted + + if rtype.is_refcounted: + attr_expr = f"self->{attr_field}" + if not always_defined: + emitter.emit_undefined_attr_check(rtype, attr_expr, "!=", "self", attr, cl) + emitter.emit_dec_ref(f"self->{attr_field}", rtype) + if not always_defined: + emitter.emit_line("}") + + if deletable: + emitter.emit_line("if (value != NULL) {") + + if rtype.is_unboxed: + emitter.emit_unbox("value", "tmp", rtype, error=ReturnHandler("-1"), declare_dest=True) + elif is_same_type(rtype, object_rprimitive): + emitter.emit_line("PyObject *tmp = value;") + else: + emitter.emit_cast("value", "tmp", rtype, declare_dest=True) + emitter.emit_lines("if (!tmp)", " return -1;") + emitter.emit_inc_ref("tmp", rtype) + emitter.emit_line(f"self->{attr_field} = tmp;") + if rtype.error_overlap and not always_defined: + emitter.emit_attr_bitmap_set("tmp", "self", rtype, cl, attr) + + if deletable: + emitter.emit_line("} else {") + emitter.set_undefined_value(f"self->{attr_field}", rtype) + if rtype.error_overlap: + emitter.emit_attr_bitmap_clear("self", rtype, cl, attr) + emitter.emit_line("}") + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def generate_readonly_getter( + cl: ClassIR, attr: str, rtype: RType, func_ir: FuncIR, emitter: Emitter +) -> None: + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure)".format( + getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + if rtype.is_unboxed: + emitter.emit_line( + "{}retval = {}{}((PyObject *) self);".format( + emitter.ctype_spaced(rtype), NATIVE_PREFIX, func_ir.cname(emitter.names) + ) + ) + emitter.emit_error_check("retval", rtype, "return NULL;") + emitter.emit_box("retval", "retbox", rtype, declare_dest=True) + emitter.emit_line("return retbox;") + else: + emitter.emit_line( + f"return {NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self);" + ) + emitter.emit_line("}") + + +def generate_property_setter( + cl: ClassIR, attr: str, arg_type: RType, func_ir: FuncIR, emitter: Emitter +) -> None: + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure)".format( + setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + if arg_type.is_unboxed: + emitter.emit_unbox("value", "tmp", arg_type, error=ReturnHandler("-1"), declare_dest=True) + emitter.emit_line( + f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, tmp);" + ) + else: + emitter.emit_line( + f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, value);" + ) + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def has_managed_dict(cl: ClassIR, emitter: Emitter) -> bool: + """Should the class get the Py_TPFLAGS_MANAGED_DICT flag?""" + # On 3.11 and earlier the flag doesn't exist and we use + # tp_dictoffset instead. If a class inherits from Exception, the + # flag conflicts with tp_dictoffset set in the base class. + return ( + emitter.capi_version >= (3, 12) + and cl.has_dict + and cl.builtin_base != "PyBaseExceptionObject" + ) + + +def native_class_doc_initializer(cl: ClassIR) -> str: + init_fn = cl.get_method("__init__") + if init_fn is not None: + text_sig = get_text_signature(init_fn, bound=True) + if text_sig is None: + return "NULL" + text_sig = text_sig.replace("__init__", cl.name, 1) + else: + text_sig = f"{cl.name}()" + docstring = f"{text_sig}\n--\n\n" + return c_string_initializer(docstring.encode("ascii", errors="backslashreplace")) + + +def generate_coroutine_setup( + cl: ClassIR, coroutine_setup_name: str, module_name: str, emitter: Emitter +) -> None: + emitter.emit_line("static bool") + emitter.emit_line(f"{NATIVE_PREFIX}{coroutine_setup_name}(PyObject *type)") + emitter.emit_line("{") + + error_stmt = " return 2;" + + def emit_instance(fn: FuncIR, fn_name: str) -> str: + filepath = emitter.filepath or "" + return emitter.emit_cpyfunction_instance(fn, fn_name, filepath, error_stmt) + + def success() -> None: + emitter.emit_line("return 1;") + emitter.emit_line("}") + + if cl.coroutine_name: + # Callable class generated for a coroutine. It stores its function wrapper as an attribute. + wrapper_name = emit_instance(cl.methods["__call__"], cl.coroutine_name) + struct_name = cl.struct_name(emitter.names) + attr = emitter.attr(CPYFUNCTION_NAME) + emitter.emit_line(f"(({struct_name} *)type)->{attr} = {wrapper_name};") + return success() + + if not any(fn.decl.is_coroutine for fn in cl.methods.values()): + return success() + + emitter.emit_line("PyTypeObject *tp = (PyTypeObject *)type;") + + for fn in cl.methods.values(): + if not fn.decl.is_coroutine: + continue + + name = short_id_from_name(fn.name, fn.decl.shortname, fn.line) + wrapper_name = emit_instance(fn, name) + name_obj = f"{wrapper_name}_name" + emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString("{fn.name}");') + emitter.emit_line(f"if (unlikely(!{name_obj}))") + emitter.emit_line(error_stmt) + emitter.emit_line(f"if (PyDict_SetItem(tp->tp_dict, {name_obj}, {wrapper_name}) < 0)") + emitter.emit_line(error_stmt) + + return success() diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..14d98af039187b245689e587d3f60c79769b1593 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitfunc.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..a029ff8cc11f9e7fd46fe2faba16de2babf89c6a --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitfunc.py @@ -0,0 +1,993 @@ +"""Code generation for native function bodies.""" + +from __future__ import annotations + +from typing import Final + +from mypyc.analysis.blockfreq import frequently_executed_blocks +from mypyc.codegen.emit import ( + DEBUG_ERRORS, + PREFIX_MAP, + Emitter, + TracebackAndGotoHandler, + c_array_initializer, +) +from mypyc.common import GENERATOR_ATTRIBUTE_PREFIX, HAVE_IMMORTAL, NATIVE_PREFIX, REG_PREFIX +from mypyc.ir.class_ir import ClassIR +from mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD, FuncDecl, FuncIR, all_values +from mypyc.ir.ops import ( + ERR_FALSE, + NAMESPACE_TYPE, + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + ControlOp, + CString, + DecRef, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + Register, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Undef, + Unreachable, + Value, +) +from mypyc.ir.pprint import generate_names_for_ir +from mypyc.ir.rtypes import ( + RArray, + RInstance, + RStruct, + RTuple, + RType, + RVec, + is_bool_or_bit_rprimitive, + is_int32_rprimitive, + is_int64_rprimitive, + is_int_rprimitive, + is_none_rprimitive, + is_pointer_rprimitive, + is_tagged, +) + + +def native_function_type(fn: FuncIR, emitter: Emitter) -> str: + args = ", ".join(emitter.ctype(arg.type) for arg in fn.args) or "void" + ret = emitter.ctype(fn.ret_type) + return f"{ret} (*)({args})" + + +def native_function_header(fn: FuncDecl, emitter: Emitter) -> str: + args = [] + for arg in fn.sig.args: + args.append(f"{emitter.ctype_spaced(arg.type)}{REG_PREFIX}{arg.name}") + + return "{ret_type}{name}({args})".format( + ret_type=emitter.ctype_spaced(fn.sig.ret_type), + name=emitter.native_function_name(fn), + args=", ".join(args) or "void", + ) + + +def generate_native_function( + fn: FuncIR, emitter: Emitter, source_path: str, module_name: str +) -> None: + declarations = Emitter(emitter.context) + names = generate_names_for_ir(fn.arg_regs, fn.blocks) + body = Emitter(emitter.context, names) + visitor = FunctionEmitterVisitor(body, declarations, source_path, module_name) + + declarations.emit_line(f"{native_function_header(fn.decl, emitter)} {{") + body.indent() + + for r in all_values(fn.arg_regs, fn.blocks): + if isinstance(r.type, RTuple): + emitter.declare_tuple_struct(r.type) + if isinstance(r.type, RArray): + continue # Special: declared on first assignment + + if r in fn.arg_regs: + continue # Skip the arguments + + ctype = emitter.ctype_spaced(r.type) + init = "" + declarations.emit_line( + "{ctype}{prefix}{name}{init};".format( + ctype=ctype, prefix=REG_PREFIX, name=names[r], init=init + ) + ) + + # Before we emit the blocks, give them all labels + blocks = fn.blocks + for i, block in enumerate(blocks): + block.label = i + + # Find blocks that are never jumped to or are only jumped to from the + # block directly above it. This allows for more labels and gotos to be + # eliminated during code generation. + for block in fn.blocks: + terminator = block.terminator + assert isinstance(terminator, ControlOp), terminator + + for target in terminator.targets(): + is_next_block = target.label == block.label + 1 + + # Always emit labels for GetAttr error checks since the emit code that + # generates them will add instructions between the branch and the + # next label, causing the label to be wrongly removed. A better + # solution would be to change the IR so that it adds a basic block + # in between the calls. + is_problematic_op = isinstance(terminator, Branch) and any( + isinstance(s, GetAttr) for s in terminator.sources() + ) + + if not is_next_block or is_problematic_op: + fn.blocks[target.label].referenced = True + + common = frequently_executed_blocks(fn.blocks[0]) + + for i in range(len(blocks)): + block = blocks[i] + visitor.rare = block not in common + next_block = None + if i + 1 < len(blocks): + next_block = blocks[i + 1] + body.emit_label(block) + visitor.next_block = next_block + + ops = block.ops + visitor.ops = ops + visitor.op_index = 0 + while visitor.op_index < len(ops): + ops[visitor.op_index].accept(visitor) + visitor.op_index += 1 + + body.emit_line("}") + + emitter.emit_from_emitter(declarations) + emitter.emit_from_emitter(body) + + +class FunctionEmitterVisitor(OpVisitor[None]): + def __init__( + self, emitter: Emitter, declarations: Emitter, source_path: str, module_name: str + ) -> None: + self.emitter = emitter + self.names = emitter.names + self.declarations = declarations + self.source_path = source_path + self.module_name = module_name + self.literals = emitter.context.literals + self.rare = False + # Next basic block to be processed after the current one (if any), set by caller + self.next_block: BasicBlock | None = None + # Ops in the basic block currently being processed, set by caller + self.ops: list[Op] = [] + # Current index within ops; visit methods can increment this to skip/merge ops + self.op_index = 0 + + def temp_name(self) -> str: + return self.emitter.temp_name() + + def visit_goto(self, op: Goto) -> None: + if op.label is not self.next_block: + self.emit_line("goto %s;" % self.label(op.label)) + + def error_value_check(self, value: Value, compare: str) -> str: + typ = value.type + if isinstance(typ, RTuple): + # TODO: What about empty tuple? + return self.emitter.tuple_undefined_check_cond( + typ, self.reg(value), self.c_error_value, compare + ) + elif isinstance(typ, RVec): + # Error values for vecs are represented by a negative length. + vec_compare = ">=" if compare == "!=" else "<" + return f"{self.reg(value)}.len {vec_compare} 0" + else: + return f"{self.reg(value)} {compare} {self.c_error_value(typ)}" + + def visit_branch(self, op: Branch) -> None: + true, false = op.true, op.false + negated = op.negated + negated_rare = False + if true is self.next_block and op.traceback_entry is None: + # Switch true/false since it avoids an else block. + true, false = false, true + negated = not negated + negated_rare = True + + neg = "!" if negated else "" + cond = "" + if op.op == Branch.BOOL: + expr_result = self.reg(op.value) + cond = f"{neg}{expr_result}" + elif op.op == Branch.IS_ERROR: + compare = "!=" if negated else "==" + cond = self.error_value_check(op.value, compare) + else: + assert False, "Invalid branch" + + # For error checks, tell the compiler the branch is unlikely + if op.traceback_entry is not None or op.rare: + if not negated_rare: + cond = f"unlikely({cond})" + else: + cond = f"likely({cond})" + + if false is self.next_block: + if op.traceback_entry is None: + if true is not self.next_block: + self.emit_line(f"if ({cond}) goto {self.label(true)};") + else: + self.emit_line(f"if ({cond}) {{") + self.emit_traceback(op) + self.emit_lines("goto %s;" % self.label(true), "}") + else: + self.emit_line(f"if ({cond}) {{") + self.emit_traceback(op) + + if true is not self.next_block: + self.emit_line("goto %s;" % self.label(true)) + + self.emit_lines("} else", " goto %s;" % self.label(false)) + + def visit_return(self, op: Return) -> None: + value_str = self.reg(op.value) + self.emit_line("return %s;" % value_str) + + def visit_tuple_set(self, op: TupleSet) -> None: + dest = self.reg(op) + tuple_type = op.tuple_type + self.emitter.declare_tuple_struct(tuple_type) + if len(op.items) == 0: # empty tuple + self.emit_line(f"{dest}.empty_struct_error_flag = 0;") + else: + for i, item in enumerate(op.items): + self.emit_line(f"{dest}.f{i} = {self.reg(item)};") + + def visit_assign(self, op: Assign) -> None: + dest = self.reg(op.dest) + src = self.reg(op.src) + # clang whines about self assignment (which we might generate + # for some casts), so don't emit it. + if dest != src: + src_type = op.src.type + dest_type = op.dest.type + if src_type.is_unboxed and not dest_type.is_unboxed: + # We sometimes assign from an integer prepresentation of a pointer + # to a real pointer, and C compilers insist on a cast. + src = f"(void *){src}" + elif not src_type.is_unboxed and dest_type.is_unboxed: + # We sometimes assign a pointer to an integer type (e.g. to create + # tagged pointers), and here we need an explicit cast. + src = f"({self.emitter.ctype(dest_type)}){src}" + self.emit_line(f"{dest} = {src};") + + def visit_assign_multi(self, op: AssignMulti) -> None: + typ = op.dest.type + assert isinstance(typ, RArray), typ + dest = self.reg(op.dest) + # RArray values can only be assigned to once, so we can always + # declare them on initialization. + self.emit_line( + "%s%s[%d] = %s;" + % ( + self.emitter.ctype_spaced(typ.item_type), + dest, + len(op.src), + c_array_initializer([self.reg(s) for s in op.src], indented=True), + ) + ) + + def visit_load_error_value(self, op: LoadErrorValue) -> None: + reg = self.reg(op) + if isinstance(op.type, RTuple): + values = [self.c_undefined_value(item) for item in op.type.types] + tmp = self.temp_name() + self.emit_line("{} {} = {{ {} }};".format(self.ctype(op.type), tmp, ", ".join(values))) + self.emit_line(f"{reg} = {tmp};") + elif isinstance(op.type, RVec): + self.emitter.set_undefined_value(reg, op.type) + else: + self.emit_line(f"{self.reg(op)} = {self.c_error_value(op.type)};") + + def visit_load_literal(self, op: LoadLiteral) -> None: + index = self.literals.literal_index(op.value) + if not is_int_rprimitive(op.type): + self.emit_line("%s = CPyStatics[%d];" % (self.reg(op), index), ann=op.value) + else: + self.emit_line( + "%s = (CPyTagged)CPyStatics[%d] | 1;" % (self.reg(op), index), ann=op.value + ) + + def get_attr_expr(self, obj: str, op: GetAttr | SetAttr, decl_cl: ClassIR) -> str: + """Generate attribute accessor for normal (non-property) access. + + This either has a form like obj->attr_name for attributes defined in non-trait + classes, and *(obj + attr_offset) for attributes defined by traits. We also + insert all necessary C casts here. + """ + cast = f"({op.class_type.struct_name(self.emitter.names)} *)" + if decl_cl.is_trait and op.class_type.class_ir.is_trait: + # For pure trait access find the offset first, offsets + # are ordered by attribute position in the cl.attributes dict. + # TODO: pre-calculate the mapping to make this faster. + trait_attr_index = list(decl_cl.attributes).index(op.attr) + # TODO: reuse these names somehow? + offset = self.emitter.temp_name() + self.declarations.emit_line(f"size_t {offset};") + self.emitter.emit_line( + "{} = {};".format( + offset, + "CPy_FindAttrOffset({}, {}, {})".format( + self.emitter.type_struct_name(decl_cl), + f"({cast}{obj})->vtable", + trait_attr_index, + ), + ) + ) + attr_cast = f"({self.ctype(op.class_type.attr_type(op.attr))} *)" + return f"*{attr_cast}((char *){obj} + {offset})" + else: + # Cast to something non-trait. Note: for this to work, all struct + # members for non-trait classes must obey monotonic linear growth. + if op.class_type.class_ir.is_trait: + assert not decl_cl.is_trait + cast = f"({decl_cl.struct_name(self.emitter.names)} *)" + return f"({cast}{obj})->{self.emitter.attr(op.attr)}" + + def visit_get_attr(self, op: GetAttr) -> None: + if op.allow_error_value: + self.get_attr_with_allow_error_value(op) + return + dest = self.reg(op) + obj = self.reg(op.obj) + rtype = op.class_type + cl = rtype.class_ir + attr_rtype, decl_cl = cl.attr_details(op.attr) + prefer_method = cl.is_trait and attr_rtype.error_overlap + if cl.get_method(op.attr, prefer_method=prefer_method): + # Properties are essentially methods, so use vtable access for them. + if cl.is_method_final(op.attr): + self.emit_method_call(f"{dest} = ", op.obj, op.attr, []) + else: + version = "_TRAIT" if cl.is_trait else "" + self.emit_line( + "%s = CPY_GET_ATTR%s(%s, %s, %d, %s, %s); /* %s */" + % ( + dest, + version, + obj, + self.emitter.type_struct_name(rtype.class_ir), + rtype.getter_index(op.attr), + rtype.struct_name(self.names), + self.ctype(rtype.attr_type(op.attr)), + op.attr, + ) + ) + else: + # Otherwise, use direct or offset struct access. + attr_expr = self.get_attr_expr(obj, op, decl_cl) + self.emitter.emit_line(f"{dest} = {attr_expr};") + always_defined = cl.is_always_defined(op.attr) + merged_branch = None + if not always_defined: + self.emitter.emit_undefined_attr_check( + attr_rtype, dest, "==", obj, op.attr, cl, unlikely=True + ) + branch = self.next_branch() + if branch is not None: + if ( + branch.value is op + and branch.op == Branch.IS_ERROR + and branch.traceback_entry is not None + and not branch.negated + ): + # Generate code for the following branch here to avoid + # redundant branches in the generated code. + self.emit_attribute_error(branch, cl.name, op.attr) + self.emit_line("goto %s;" % self.label(branch.true)) + merged_branch = branch + self.emitter.emit_line("}") + if not merged_branch: + exc_class = "PyExc_AttributeError" + self.emitter.emit_line( + 'PyErr_SetString({}, "attribute {} of {} undefined");'.format( + exc_class, + repr(op.attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX)), + repr(cl.name), + ) + ) + + if attr_rtype.is_refcounted and not op.is_borrowed: + if not merged_branch and not always_defined: + self.emitter.emit_line("} else {") + self.emitter.emit_inc_ref(dest, attr_rtype) + if merged_branch: + if merged_branch.false is not self.next_block: + self.emit_line("goto %s;" % self.label(merged_branch.false)) + self.op_index += 1 + elif not always_defined: + self.emitter.emit_line("}") + + def get_attr_with_allow_error_value(self, op: GetAttr) -> None: + """Handle GetAttr with allow_error_value=True. + + This allows NULL or other error value without raising AttributeError. + """ + dest = self.reg(op) + obj = self.reg(op.obj) + rtype = op.class_type + cl = rtype.class_ir + attr_rtype, decl_cl = cl.attr_details(op.attr) + + # Direct struct access without NULL check + attr_expr = self.get_attr_expr(obj, op, decl_cl) + self.emitter.emit_line(f"{dest} = {attr_expr};") + + # Only emit inc_ref if not NULL + if attr_rtype.is_refcounted and not op.is_borrowed: + check = self.error_value_check(op, "!=") + self.emitter.emit_line(f"if ({check}) {{") + self.emitter.emit_inc_ref(dest, attr_rtype) + self.emitter.emit_line("}") + + def next_branch(self) -> Branch | None: + if self.op_index + 1 < len(self.ops): + next_op = self.ops[self.op_index + 1] + if isinstance(next_op, Branch): + return next_op + return None + + def visit_set_attr(self, op: SetAttr) -> None: + if op.error_kind == ERR_FALSE: + dest = self.reg(op) + obj = self.reg(op.obj) + src = self.reg(op.src) + rtype = op.class_type + cl = rtype.class_ir + attr_rtype, decl_cl = cl.attr_details(op.attr) + if op.is_propset: + # Again, use vtable access for properties... + assert not op.is_init and op.error_kind == ERR_FALSE, "%s %d %d %s" % ( + op.attr, + op.is_init, + op.error_kind, + rtype, + ) + version = "_TRAIT" if cl.is_trait else "" + self.emit_line( + "%s = CPY_SET_ATTR%s(%s, %s, %d, %s, %s, %s); /* %s */" + % ( + dest, + version, + obj, + self.emitter.type_struct_name(rtype.class_ir), + rtype.setter_index(op.attr), + src, + rtype.struct_name(self.names), + self.ctype(rtype.attr_type(op.attr)), + op.attr, + ) + ) + else: + # ...and struct access for normal attributes. + attr_expr = self.get_attr_expr(obj, op, decl_cl) + if not op.is_init and attr_rtype.is_refcounted: + # This is not an initialization (where we know that the attribute was + # previously undefined), so decref the old value. + always_defined = cl.is_always_defined(op.attr) + if not always_defined: + self.emitter.emit_undefined_attr_check( + attr_rtype, attr_expr, "!=", obj, op.attr, cl + ) + self.emitter.emit_dec_ref(attr_expr, attr_rtype) + if not always_defined: + self.emitter.emit_line("}") + elif attr_rtype.error_overlap and not cl.is_always_defined(op.attr): + # If there is overlap with the error value, update bitmap to mark + # attribute as defined. + self.emitter.emit_attr_bitmap_set(src, obj, attr_rtype, cl, op.attr) + + # This steals the reference to src, so we don't need to increment the arg + self.emitter.emit_line(f"{attr_expr} = {src};") + if op.error_kind == ERR_FALSE: + self.emitter.emit_line(f"{dest} = 1;") + + def visit_load_static(self, op: LoadStatic) -> None: + dest = self.reg(op) + prefix = PREFIX_MAP[op.namespace] + name = self.emitter.static_name(op.identifier, op.module_name, prefix) + if op.namespace == NAMESPACE_TYPE: + name = "(PyObject *)%s" % name + self.emit_line(f"{dest} = {name};", ann=op.ann) + + def visit_init_static(self, op: InitStatic) -> None: + value = self.reg(op.value) + prefix = PREFIX_MAP[op.namespace] + name = self.emitter.static_name(op.identifier, op.module_name, prefix) + if op.namespace == NAMESPACE_TYPE: + value = "(PyTypeObject *)%s" % value + self.emit_line(f"{name} = {value};") + self.emit_inc_ref(name, op.value.type) + + def visit_tuple_get(self, op: TupleGet) -> None: + dest = self.reg(op) + src = self.reg(op.src) + self.emit_line(f"{dest} = {src}.f{op.index};") + if not op.is_borrowed: + self.emit_inc_ref(dest, op.type) + + def get_dest_assign(self, dest: Value) -> str: + if not dest.is_void: + return self.reg(dest) + " = " + else: + return "" + + def visit_call(self, op: Call) -> None: + """Call native function.""" + dest = self.get_dest_assign(op) + args = ", ".join(self.reg(arg) for arg in op.args) + lib = self.emitter.get_group_prefix(op.fn) + cname = op.fn.cname(self.names) + self.emit_line(f"{dest}{lib}{NATIVE_PREFIX}{cname}({args});") + + def visit_method_call(self, op: MethodCall) -> None: + """Call native method.""" + dest = self.get_dest_assign(op) + self.emit_method_call(dest, op.obj, op.method, op.args) + + def emit_method_call(self, dest: str, op_obj: Value, name: str, op_args: list[Value]) -> None: + obj = self.reg(op_obj) + rtype = op_obj.type + assert isinstance(rtype, RInstance), rtype + class_ir = rtype.class_ir + method = rtype.class_ir.get_method(name) + assert method is not None + + # Can we call the method directly, bypassing vtable? + is_direct = class_ir.is_method_final(name) + + # The first argument gets omitted for static methods and + # turned into the class for class methods + obj_args = ( + [] + if method.decl.kind == FUNC_STATICMETHOD + else [f"(PyObject *)Py_TYPE({obj})"] if method.decl.kind == FUNC_CLASSMETHOD else [obj] + ) + args = ", ".join(obj_args + [self.reg(arg) for arg in op_args]) + mtype = native_function_type(method, self.emitter) + version = "_TRAIT" if rtype.class_ir.is_trait else "" + if is_direct: + # Directly call method, without going through the vtable. + lib = self.emitter.get_group_prefix(method.decl) + self.emit_line(f"{dest}{lib}{NATIVE_PREFIX}{method.cname(self.names)}({args});") + else: + # Call using vtable. + method_idx = rtype.method_index(name) + self.emit_line( + "{}CPY_GET_METHOD{}({}, {}, {}, {}, {})({}); /* {} */".format( + dest, + version, + obj, + self.emitter.type_struct_name(rtype.class_ir), + method_idx, + rtype.struct_name(self.names), + mtype, + args, + name, + ) + ) + + def visit_inc_ref(self, op: IncRef) -> None: + if ( + isinstance(op.src, Box) + and (is_none_rprimitive(op.src.src.type) or is_bool_or_bit_rprimitive(op.src.src.type)) + and HAVE_IMMORTAL + ): + # On Python 3.12+, None/True/False are immortal, and we can skip inc ref + return + + if isinstance(op.src, LoadLiteral) and HAVE_IMMORTAL: + value = op.src.value + # We can skip inc ref for immortal literals on Python 3.12+ + if type(value) is int and -5 <= value <= 256: + # Small integers are immortal + return + + src = self.reg(op.src) + self.emit_inc_ref(src, op.src.type) + + def visit_dec_ref(self, op: DecRef) -> None: + src = self.reg(op.src) + self.emit_dec_ref(src, op.src.type, is_xdec=op.is_xdec) + + def visit_box(self, op: Box) -> None: + self.emitter.emit_box(self.reg(op.src), self.reg(op), op.src.type, can_borrow=True) + + def visit_cast(self, op: Cast) -> None: + if op.is_unchecked and op.is_borrowed: + self.emit_line(f"{self.reg(op)} = {self.reg(op.src)};") + return + branch = self.next_branch() + handler = None + if branch is not None: + if ( + branch.value is op + and branch.op == Branch.IS_ERROR + and branch.traceback_entry is not None + and not branch.negated + and branch.false is self.next_block + ): + # Generate code also for the following branch here to avoid + # redundant branches in the generated code. + handler = TracebackAndGotoHandler( + self.label(branch.true), + self.source_path, + self.module_name, + branch.traceback_entry, + ) + self.op_index += 1 + + self.emitter.emit_cast( + self.reg(op.src), self.reg(op), op.type, src_type=op.src.type, error=handler + ) + + def visit_unbox(self, op: Unbox) -> None: + self.emitter.emit_unbox(self.reg(op.src), self.reg(op), op.type) + + def visit_unreachable(self, op: Unreachable) -> None: + self.emitter.emit_line("CPy_Unreachable();") + + def visit_raise_standard_error(self, op: RaiseStandardError) -> None: + # TODO: Better escaping of backspaces and such + if op.value is not None: + if isinstance(op.value, str): + message = op.value.replace('"', '\\"') + self.emitter.emit_line(f'PyErr_SetString(PyExc_{op.class_name}, "{message}");') + elif isinstance(op.value, Value): + self.emitter.emit_line( + "PyErr_SetObject(PyExc_{}, {});".format( + op.class_name, self.emitter.reg(op.value) + ) + ) + else: + assert False, "op value type must be either str or Value" + else: + self.emitter.emit_line(f"PyErr_SetNone(PyExc_{op.class_name});") + self.emitter.emit_line(f"{self.reg(op)} = 0;") + + def visit_call_c(self, op: CallC) -> None: + if op.is_void: + dest = "" + else: + dest = self.get_dest_assign(op) + args = ", ".join(self.reg(arg) for arg in op.args) + self.emitter.emit_line(f"{dest}{op.function_name}({args});") + + def visit_primitive_op(self, op: PrimitiveOp) -> None: + raise RuntimeError( + f"unexpected PrimitiveOp {op.desc.name}: they must be lowered before codegen" + ) + + def visit_truncate(self, op: Truncate) -> None: + dest = self.reg(op) + value = self.reg(op.src) + # for C backend the generated code are straight assignments + self.emit_line(f"{dest} = {value};") + + def visit_extend(self, op: Extend) -> None: + dest = self.reg(op) + value = self.reg(op.src) + if op.signed: + src_cast = self.emit_signed_int_cast(op.src.type) + else: + src_cast = self.emit_unsigned_int_cast(op.src.type) + self.emit_line(f"{dest} = {src_cast}{value};") + + def visit_load_global(self, op: LoadGlobal) -> None: + dest = self.reg(op) + self.emit_line(f"{dest} = {op.identifier};", ann=op.ann) + + def visit_int_op(self, op: IntOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + if op.op == IntOp.RIGHT_SHIFT: + # Signed right shift + lhs = self.emit_signed_int_cast(op.lhs.type) + lhs + rhs = self.emit_signed_int_cast(op.rhs.type) + rhs + self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};") + + def visit_comparison_op(self, op: ComparisonOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + lhs_cast = "" + rhs_cast = "" + if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE): + # Always signed comparison op + lhs_cast = self.emit_signed_int_cast(op.lhs.type) + rhs_cast = self.emit_signed_int_cast(op.rhs.type) + elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE): + # Always unsigned comparison op + lhs_cast = self.emit_unsigned_int_cast(op.lhs.type) + rhs_cast = self.emit_unsigned_int_cast(op.rhs.type) + elif isinstance(op.lhs, Integer) and op.lhs.value < 0: + # Force signed ==/!= with negative operand + rhs_cast = self.emit_signed_int_cast(op.rhs.type) + elif isinstance(op.rhs, Integer) and op.rhs.value < 0: + # Force signed ==/!= with negative operand + lhs_cast = self.emit_signed_int_cast(op.lhs.type) + self.emit_line(f"{dest} = {lhs_cast}{lhs} {op.op_str[op.op]} {rhs_cast}{rhs};") + + def visit_float_op(self, op: FloatOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + if op.op != FloatOp.MOD: + self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};") + else: + # TODO: This may set errno as a side effect, that is a little sketchy. + self.emit_line(f"{dest} = fmod({lhs}, {rhs});") + + def visit_float_neg(self, op: FloatNeg) -> None: + dest = self.reg(op) + src = self.reg(op.src) + self.emit_line(f"{dest} = -{src};") + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};") + + def visit_load_mem(self, op: LoadMem) -> None: + dest = self.reg(op) + src = self.reg(op.src) + # TODO: we shouldn't dereference to type that are pointer type so far + type = self.ctype(op.type) + self.emit_line(f"{dest} = *({type} *){src};") + if not op.is_borrowed: + self.emit_inc_ref(dest, op.type) + + def visit_set_mem(self, op: SetMem) -> None: + dest = self.reg(op.dest) + src = self.reg(op.src) + dest_type = self.ctype(op.dest_type) + # clang whines about self assignment (which we might generate + # for some casts), so don't emit it. + if dest != src: + self.emit_line(f"*({dest_type} *){dest} = {src};") + + def visit_get_element(self, op: GetElement) -> None: + dest = self.reg(op) + src = self.reg(op.src) + dest_type = self.ctype(op.type) + self.emit_line(f"{dest} = ({dest_type}){src}.{op.field};") + + def visit_get_element_ptr(self, op: GetElementPtr) -> None: + dest = self.reg(op) + src = self.reg(op.src) + # TODO: support tuple type + assert isinstance(op.src_type, RStruct), op.src_type + assert op.field in op.src_type.names, "Invalid field name." + # Use offsetof to avoid undefined behavior when src is NULL + # (e.g., vec buf pointer for empty vecs). The &((T*)p)->field + # pattern is UB when p is NULL, which GCC -O3 can exploit. + self.emit_line( + "{} = ({})((CPyPtr){} + offsetof({}, {}));".format( + dest, op.type._ctype, src, op.src_type.name, op.field + ) + ) + + def visit_set_element(self, op: SetElement) -> None: + dest = self.reg(op) + item = self.reg(op.item) + field = op.field + if isinstance(op.src, Undef): + # First assignment to an undefined struct is trivial. + self.emit_line(f"{dest}.{field} = {item};") + else: + # In the general case create a copy of the struct with a single + # item modified. + # + # TODO: Can we do better if only a subset of fields are initialized? + # TODO: Make this less verbose in the common case + # TODO: Support tuples (or use RStruct for tuples)? + src = self.reg(op.src) + src_type = op.src.type + assert isinstance(src_type, RStruct), src_type + init_items = [] + for n in src_type.names: + if n != field: + init_items.append(f"{src}.{n}") + else: + init_items.append(item) + self.emit_line(f"{dest} = ({self.ctype(src_type)}) {{ {', '.join(init_items)} }};") + + def visit_load_address(self, op: LoadAddress) -> None: + typ = op.type + dest = self.reg(op) + if isinstance(op.src, Register): + src = self.reg(op.src) + elif isinstance(op.src, LoadStatic): + prefix = PREFIX_MAP[op.src.namespace] + src = self.emitter.static_name(op.src.identifier, op.src.module_name, prefix) + else: + src = op.src + self.emit_line(f"{dest} = ({typ._ctype})&{src};") + + def visit_keep_alive(self, op: KeepAlive) -> None: + # This is a no-op. + pass + + def visit_unborrow(self, op: Unborrow) -> None: + # This is a no-op that propagates the source value. + dest = self.reg(op) + src = self.reg(op.src) + self.emit_line(f"{dest} = {src};") + + # Helpers + + def label(self, label: BasicBlock) -> str: + return self.emitter.label(label) + + def reg(self, reg: Value) -> str: + if isinstance(reg, Integer): + val = reg.value + if val == 0 and is_pointer_rprimitive(reg.type): + return "NULL" + s = str(val) + if val >= (1 << 31): + # Avoid overflowing signed 32-bit int + if val >= (1 << 63): + s += "ULL" + else: + s += "LL" + elif val == -(1 << 63): + # Avoid overflowing C integer literal + s = "(-9223372036854775807LL - 1)" + elif val <= -(1 << 31): + s += "LL" + return s + elif isinstance(reg, Float): + r = repr(reg.value) + if r == "inf": + return "INFINITY" + elif r == "-inf": + return "-INFINITY" + elif r == "nan": + return "NAN" + return r + elif isinstance(reg, CString): + return '"' + encode_c_string_literal(reg.value) + '"' + else: + return self.emitter.reg(reg) + + def ctype(self, rtype: RType) -> str: + return self.emitter.ctype(rtype) + + def c_error_value(self, rtype: RType) -> str: + return self.emitter.c_error_value(rtype) + + def c_undefined_value(self, rtype: RType) -> str: + return self.emitter.c_undefined_value(rtype) + + def emit_line(self, line: str, *, ann: object = None) -> None: + self.emitter.emit_line(line, ann=ann) + + def emit_lines(self, *lines: str) -> None: + self.emitter.emit_lines(*lines) + + def emit_inc_ref(self, dest: str, rtype: RType) -> None: + self.emitter.emit_inc_ref(dest, rtype, rare=self.rare) + + def emit_dec_ref(self, dest: str, rtype: RType, is_xdec: bool) -> None: + self.emitter.emit_dec_ref(dest, rtype, is_xdec=is_xdec, rare=self.rare) + + def emit_declaration(self, line: str) -> None: + self.declarations.emit_line(line) + + def emit_traceback(self, op: Branch) -> None: + if op.traceback_entry is not None: + self.emitter.emit_traceback(self.source_path, self.module_name, op.traceback_entry) + + def emit_attribute_error(self, op: Branch, class_name: str, attr: str) -> None: + assert op.traceback_entry is not None + if self.emitter.context.strict_traceback_checks: + assert ( + op.traceback_entry[1] >= 0 + ), "AttributeError traceback cannot have a negative line number" + globals_static = self.emitter.static_name("globals", self.module_name) + self.emit_line( + 'CPy_AttributeError("%s", "%s", "%s", "%s", %d, %s);' + % ( + self.source_path.replace("\\", "\\\\"), + op.traceback_entry[0], + class_name, + attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX), + op.traceback_entry[1], + globals_static, + ) + ) + if DEBUG_ERRORS: + self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");') + + def emit_signed_int_cast(self, type: RType) -> str: + if is_tagged(type): + return "(Py_ssize_t)" + else: + return "" + + def emit_unsigned_int_cast(self, type: RType) -> str: + if is_int32_rprimitive(type): + return "(uint32_t)" + elif is_int64_rprimitive(type): + return "(uint64_t)" + else: + return "" + + +_translation_table: Final[dict[int, str]] = {} + + +def encode_c_string_literal(b: bytes) -> str: + """Convert bytestring to the C string literal syntax (with necessary escaping). + + For example, b'foo\n' gets converted to 'foo\\n' (note that double quotes are not added). + """ + if not _translation_table: + # Initialize the translation table on the first call. + d = { + ord("\n"): "\\n", + ord("\r"): "\\r", + ord("\t"): "\\t", + ord('"'): '\\"', + ord("\\"): "\\\\", + } + for i in range(256): + if i not in d: + if i < 32 or i >= 127: + d[i] = "\\x%.2x" % i + else: + d[i] = chr(i) + _translation_table.update(str.maketrans(d)) + return b.decode("latin1").translate(_translation_table) diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..963a6f49b36aae467c866861fb45e2848c041bc7 Binary files /dev/null and b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd differ diff --git a/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitmodule.py b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitmodule.py new file mode 100644 index 0000000000000000000000000000000000000000..05b2e64b386523028344550cd241ea2e64e799db --- /dev/null +++ b/micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypyc/codegen/emitmodule.py @@ -0,0 +1,1494 @@ +"""Generate C code for a Python C extension module from Python source code.""" + +# FIXME: Basically nothing in this file operates on the level of a +# single module and it should be renamed. + +from __future__ import annotations + +import json +import os +import sys +from collections.abc import Iterable +from typing import TypeVar + +from mypy.build import ( + BuildResult, + BuildSource, + State, + build, + compute_hash, + create_metastore, + get_cache_names, + sorted_components, +) +from mypy.errors import CompileError +from mypy.fscache import FileSystemCache +from mypy.nodes import MypyFile +from mypy.options import Options +from mypy.plugin import Plugin, ReportConfigContext +from mypy.util import hash_digest, json_dumps +from mypyc.analysis.capsule_deps import find_class_dependencies, find_implicit_op_dependencies +from mypyc.codegen.cstring import c_string_initializer +from mypyc.codegen.emit import ( + Emitter, + EmitterContext, + HeaderDeclaration, + c_array_initializer, + native_function_doc_initializer, +) +from mypyc.codegen.emitclass import generate_class, generate_class_reuse, generate_class_type_decl +from mypyc.codegen.emitfunc import generate_native_function, native_function_header +from mypyc.codegen.emitwrapper import ( + generate_legacy_wrapper_function, + generate_wrapper_function, + legacy_wrapper_function_header, + wrapper_function_header, +) +from mypyc.codegen.literals import Literals +from mypyc.common import ( + EXT_SUFFIX, + IS_FREE_THREADED, + MODULE_PREFIX, + PREFIX, + RUNTIME_C_FILES, + TOP_LEVEL_NAME, + TYPE_VAR_PREFIX, + shared_lib_name, + short_id_from_name, +) +from mypyc.errors import Errors +from mypyc.ir.deps import LIBRT_BASE64, LIBRT_STRINGS, LIBRT_TIME, LIBRT_VECS, SourceDep +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.module_ir import ModuleIR, ModuleIRs, deserialize_modules +from mypyc.ir.ops import DeserMaps, LoadLiteral +from mypyc.ir.rtypes import RType +from mypyc.irbuild.main import build_ir +from mypyc.irbuild.mapper import Mapper +from mypyc.irbuild.prepare import load_type_map +from mypyc.namegen import NameGenerator, exported_name +from mypyc.options import CompilerOptions +from mypyc.transform.copy_propagation import do_copy_propagation +from mypyc.transform.exceptions import insert_exception_handling +from mypyc.transform.flag_elimination import do_flag_elimination +from mypyc.transform.log_trace import insert_event_trace_logging +from mypyc.transform.lower import lower_ir +from mypyc.transform.refcount import insert_ref_count_opcodes +from mypyc.transform.spill import insert_spills +from mypyc.transform.uninit import insert_uninit_checks + +# All the modules being compiled are divided into "groups". A group +# is a set of modules that are placed into the same shared library. +# Two common configurations are that every module is placed in a group +# by itself (fully separate compilation) and that every module is +# placed in the same group (fully whole-program compilation), but we +# support finer-grained control of the group as well. +# +# In fully whole-program compilation, we will generate N+1 extension +# modules: one shim per module and one shared library containing all +# the actual code. +# In fully separate compilation, we (unfortunately) will generate 2*N +# extension modules: one shim per module and also one library containing +# each module's actual code. (This might be fixable in the future, +# but allows a clean separation between setup of the export tables +# (see generate_export_table) and running module top levels.) +# +# A group is represented as a list of BuildSources containing all of +# its modules along with the name of the group. (Which can be None +# only if we are compiling only a single group with a single file in it +# and not using shared libraries). +Group = tuple[list[BuildSource], str | None] +Groups = list[Group] + +# A list of (file name, file contents) pairs. +FileContents = list[tuple[str, str]] + + +class MarkedDeclaration: + """Add a mark, useful for topological sort.""" + + def __init__(self, declaration: HeaderDeclaration, mark: bool) -> None: + self.declaration = declaration + self.mark = False + + +class MypycPlugin(Plugin): + """Plugin for making mypyc interoperate properly with mypy incremental mode. + + Basically the point of this plugin is to force mypy to recheck things + based on the demands of mypyc in a couple situations: + * Any modules in the same group must be compiled together, so we + tell mypy that modules depend on all their groupmates. + * If the IR metadata is missing or stale or any of the generated + C source files associated missing or stale, then we need to + recompile the module so we mark it as stale. + """ + + def __init__( + self, options: Options, compiler_options: CompilerOptions, groups: Groups + ) -> None: + super().__init__(options) + self.group_map: dict[str, tuple[str | None, list[str]]] = {} + for sources, name in groups: + modules = sorted(source.module for source in sources) + for id in modules: + self.group_map[id] = (name, modules) + + self.compiler_options = compiler_options + self.metastore = create_metastore(options, parallel_worker=False) + + def report_config_data(self, ctx: ReportConfigContext) -> tuple[str | None, list[str]] | None: + # The config data we report is the group map entry for the module. + # If the data is being used to check validity, we do additional checks + # that the IR cache exists and matches the metadata cache and all + # output source files exist and are up to date. + + id, path, is_check = ctx.id, ctx.path, ctx.is_check + + if id not in self.group_map: + return None + + # If we aren't doing validity checks, just return the cache data + if not is_check: + return self.group_map[id] + + # Load the metadata and IR cache + meta_path, _, _ = get_cache_names(id, path, self.options) + ir_path = get_ir_cache_name(id, path, self.options) + try: + meta_json = self.metastore.read(meta_path) + ir_json = self.metastore.read(ir_path) + except FileNotFoundError: + # This could happen if mypyc failed after mypy succeeded + # in the previous run or if some cache files got + # deleted. No big deal, just fail to load the cache. + return None + + ir_data = json.loads(ir_json) + + # Check that the IR cache matches the metadata cache + if hash_digest(meta_json) != ir_data["meta_hash"]: + return None + + # Check that all the source files are present and as + # expected. The main situation where this would come up is the + # user deleting the build directory without deleting + # .mypy_cache, which we should handle gracefully. + for path, hash in ir_data["src_hashes"].items(): + try: + with open(os.path.join(self.compiler_options.target_dir, path), "rb") as f: + contents = f.read() + except FileNotFoundError: + return None + real_hash = hash_digest(contents) + if hash != real_hash: + return None + + return self.group_map[id] + + def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: + # Report dependency on modules in the module's group + return [(10, id, -1) for id in self.group_map.get(file.fullname, (None, []))[1]] + + +def parse_and_typecheck( + sources: list[BuildSource], + options: Options, + compiler_options: CompilerOptions, + groups: Groups, + fscache: FileSystemCache | None = None, + alt_lib_path: str | None = None, +) -> BuildResult: + assert options.strict_optional, "strict_optional must be turned on" + mypyc_plugin = MypycPlugin(options, compiler_options, groups) + result = build( + sources=sources, + options=options, + alt_lib_path=alt_lib_path, + fscache=fscache, + extra_plugins=[mypyc_plugin], + ) + mypyc_plugin.metastore.close() + if result.errors: + raise CompileError(result.errors) + return result + + +def compile_scc_to_ir( + scc: list[MypyFile], + result: BuildResult, + mapper: Mapper, + compiler_options: CompilerOptions, + errors: Errors, +) -> ModuleIRs: + """Compile an SCC into ModuleIRs. + + Any modules that this SCC depends on must have either been compiled, + type checked, or loaded from a cache into mapper. + + Arguments: + scc: The list of MypyFiles to compile + result: The BuildResult from the mypy front-end + mapper: The Mapper object mapping mypy ASTs to class and func IRs + compiler_options: The compilation options + errors: Where to report any errors encountered + + Returns the IR of the modules. + """ + + if compiler_options.verbose: + print("Compiling {}".format(", ".join(x.name for x in scc))) + + # Generate basic IR, with missing exception and refcount handling. + modules = build_ir(scc, result.graph, result.types, mapper, compiler_options, errors) + if errors.num_errors > 0: + return modules + + env_user_functions = {} + for module in modules.values(): + for cls in module.classes: + if cls.env_user_function: + env_user_functions[cls.env_user_function] = cls + + for module in modules.values(): + for fn in module.functions: + # Insert checks for uninitialized values. + insert_uninit_checks(fn, compiler_options.strict_traceback_checks) + # Insert exception handling. + insert_exception_handling(fn, compiler_options.strict_traceback_checks) + # Insert reference count handling. + insert_ref_count_opcodes(fn) + + if fn in env_user_functions: + insert_spills(fn, env_user_functions[fn]) + + if compiler_options.log_trace: + insert_event_trace_logging(fn, compiler_options) + + # Switch to lower abstraction level IR. + lower_ir(fn, compiler_options) + # Calculate implicit module dependencies (needed for librt) + deps = find_implicit_op_dependencies(fn) + if deps is not None: + module.dependencies.update(deps) + # Perform optimizations. + do_copy_propagation(fn, compiler_options) + do_flag_elimination(fn, compiler_options) + + # Calculate implicit dependencies from class attribute types + for cl in module.classes: + deps = find_class_dependencies(cl) + if deps is not None: + module.dependencies.update(deps) + + return modules + + +def compile_modules_to_ir( + result: BuildResult, mapper: Mapper, compiler_options: CompilerOptions, errors: Errors +) -> ModuleIRs: + """Compile a collection of modules into ModuleIRs. + + The modules to compile are specified as part of mapper's group_map. + + Returns the IR of the modules. + """ + deser_ctx = DeserMaps({}, {}) + modules = {} + + # Process the graph by SCC in topological order, like we do in mypy.build + for scc in sorted_components(result.graph): + scc_states = [result.graph[id] for id in scc.mod_ids] + trees = [st.tree for st in scc_states if st.id in mapper.group_map and st.tree] + + if not trees: + continue + + fresh = all(id not in result.manager.rechecked_modules for id in scc.mod_ids) + if fresh: + load_scc_from_cache(trees, result, mapper, deser_ctx) + else: + scc_ir = compile_scc_to_ir(trees, result, mapper, compiler_options, errors) + modules.update(scc_ir) + + return modules + + +def compile_ir_to_c( + groups: Groups, + modules: ModuleIRs, + result: BuildResult, + mapper: Mapper, + compiler_options: CompilerOptions, +) -> dict[str | None, list[tuple[str, str]]]: + """Compile a collection of ModuleIRs to C source text. + + Returns a dictionary mapping group names to a list of (file name, + file text) pairs. + """ + source_paths = { + source.module: result.graph[source.module].xpath + for sources, _ in groups + for source in sources + } + + names = NameGenerator( + [[source.module for source in sources] for sources, _ in groups], + separate=compiler_options.separate, + ) + + # Generate C code for each compilation group. Each group will be + # compiled into a separate extension module. + ctext: dict[str | None, list[tuple[str, str]]] = {} + for group_sources, group_name in groups: + group_modules = { + source.module: modules[source.module] + for source in group_sources + if source.module in modules + } + if not group_modules: + ctext[group_name] = [] + continue + generator = GroupGenerator( + group_modules, source_paths, group_name, mapper.group_map, names, compiler_options + ) + ctext[group_name] = generator.generate_c_for_modules() + + return ctext + + +def get_ir_cache_name(id: str, path: str, options: Options) -> str: + meta_path, _, _ = get_cache_names(id, path, options) + # Mypyc uses JSON cache even with --fixed-format-cache (for now). + return meta_path.replace(".meta.json", ".ir.json").replace(".meta.ff", ".ir.json") + + +def get_state_ir_cache_name(state: State) -> str: + return get_ir_cache_name(state.id, state.xpath, state.options) + + +def write_cache( + modules: ModuleIRs, + result: BuildResult, + group_map: dict[str, str | None], + ctext: dict[str | None, list[tuple[str, str]]], +) -> None: + """Write out the cache information for modules. + + Each module has the following cache information written (which is + in addition to the cache information written by mypy itself): + * A serialized version of its mypyc IR, minus the bodies of + functions. This allows code that depends on it to use + these serialized data structures when compiling against it + instead of needing to recompile it. (Compiling against a + module requires access to both its mypy and mypyc data + structures.) + * The hash of the mypy metadata cache file for the module. + This is used to ensure that the mypyc cache and the mypy + cache are in sync and refer to the same version of the code. + This is particularly important if mypyc crashes/errors/is + stopped after mypy has written its cache but before mypyc has. + * The hashes of all the source file outputs for the group + the module is in. This is so that the module will be + recompiled if the source outputs are missing. + """ + + hashes = {} + for name, files in ctext.items(): + hashes[name] = {file: compute_hash(data) for file, data in files} + + # Write out cache data + for id, module in modules.items(): + st = result.graph[id] + + meta_path, _, _ = get_cache_names(id, st.xpath, result.manager.options) + # If the metadata isn't there, skip writing the cache. + try: + meta_data = result.manager.metastore.read(meta_path) + except OSError: + continue + + newpath = get_state_ir_cache_name(st) + ir_data = { + "ir": module.serialize(), + "meta_hash": hash_digest(meta_data), + "src_hashes": hashes[group_map[id]], + } + + result.manager.metastore.write(newpath, json_dumps(ir_data)) + + result.manager.metastore.commit() + + +def load_scc_from_cache( + scc: list[MypyFile], result: BuildResult, mapper: Mapper, ctx: DeserMaps +) -> ModuleIRs: + """Load IR for an SCC of modules from the cache. + + Arguments and return are as compile_scc_to_ir. + """ + cache_data = { + k.fullname: json.loads( + result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname])) + )["ir"] + for k in scc + } + modules = deserialize_modules(cache_data, ctx) + load_type_map(mapper, scc, ctx) + return modules + + +def collect_source_dependencies(modules: dict[str, ModuleIR]) -> set[SourceDep]: + """Collect all SourceDep dependencies from all modules.""" + source_deps: set[SourceDep] = set() + for module in modules.values(): + for dep in module.dependencies: + if isinstance(dep, SourceDep): + source_deps.add(dep) + return source_deps + + +def compile_modules_to_c( + result: BuildResult, compiler_options: CompilerOptions, errors: Errors, groups: Groups +) -> tuple[ModuleIRs, list[FileContents], Mapper]: + """Compile Python module(s) to the source of Python C extension modules. + + This generates the source code for the "shared library" module + for each group. The shim modules are generated in mypyc.build. + Each shared library module provides, for each module in its group, + a PyCapsule containing an initialization function. + Additionally, it provides a capsule containing an export table of + pointers to all the group's functions and static variables. + + Arguments: + result: The BuildResult from the mypy front-end + compiler_options: The compilation options + errors: Where to report any errors encountered + groups: The groups that we are compiling. See documentation of Groups type above. + + Returns the IR of the modules and a list containing the generated files for each group. + """ + # Construct a map from modules to what group they belong to + group_map = {source.module: lib_name for group, lib_name in groups for source in group} + mapper = Mapper(group_map) + + # Sometimes when we call back into mypy, there might be errors. + # We don't want to crash when that happens. + result.manager.errors.set_file( + "", module=None, scope=None, options=result.manager.options + ) + + modules = compile_modules_to_ir(result, mapper, compiler_options, errors) + if errors.num_errors > 0: + return {}, [], Mapper({}) + + ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options) + write_cache(modules, result, group_map, ctext) + + return modules, [ctext[name] for _, name in groups], mapper + + +def generate_function_declaration(fn: FuncIR, emitter: Emitter) -> None: + emitter.context.declarations[emitter.native_function_name(fn.decl)] = HeaderDeclaration( + f"{native_function_header(fn.decl, emitter)};", needs_export=True + ) + if fn.name != TOP_LEVEL_NAME and not fn.internal: + if is_fastcall_supported(fn, emitter.capi_version): + emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration( + f"{wrapper_function_header(fn, emitter.names)};" + ) + else: + emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration( + f"{legacy_wrapper_function_header(fn, emitter.names)};" + ) + + +def pointerize(decl: str, name: str) -> str: + """Given a C decl and its name, modify it to be a declaration to a pointer.""" + # This doesn't work in general but does work for all our types... + if "(" in decl: + # Function pointer. Stick an * in front of the name and wrap it in parens. + return decl.replace(name, f"(*{name})") + else: + # Non-function pointer. Just stick an * in front of the name. + return decl.replace(name, f"*{name}") + + +def group_dir(group_name: str) -> str: + """Given a group name, return the relative directory path for it.""" + return os.sep.join(group_name.split(".")[:-1]) + + +class GroupGenerator: + def __init__( + self, + modules: dict[str, ModuleIR], + source_paths: dict[str, str], + group_name: str | None, + group_map: dict[str, str | None], + names: NameGenerator, + compiler_options: CompilerOptions, + ) -> None: + """Generator for C source for a compilation group. + + The code for a compilation group contains an internal and an + external .h file, and then one .c if not in multi_file mode or + one .c file per module if in multi_file mode. + + Arguments: + modules: (name, ir) pairs for each module in the group + source_paths: Map from module names to source file paths + group_name: The name of the group (or None if this is single-module compilation) + group_map: A map of modules to their group names + names: The name generator for the compilation + compiler_options: Mypyc specific options, including multi_file mode + """ + self.modules = modules + self.source_paths = source_paths + self.context = EmitterContext( + names, compiler_options.strict_traceback_checks, group_name, group_map + ) + self.names = names + # Initializations of globals to simple values that we can't + # do statically because the windows loader is bad. + self.simple_inits: list[tuple[str, str]] = [] + self.group_name = group_name + self.use_shared_lib = group_name is not None + self.compiler_options = compiler_options + self.multi_file = compiler_options.multi_file + # Multi-phase init is needed to enable free-threading. In the future we'll + # probably want to enable it always, but we'll wait until it's stable. + self.multi_phase_init = IS_FREE_THREADED + + @property + def group_suffix(self) -> str: + return "_" + exported_name(self.group_name) if self.group_name else "" + + @property + def short_group_suffix(self) -> str: + return "_" + exported_name(self.group_name.split(".")[-1]) if self.group_name else "" + + def generate_c_for_modules(self) -> list[tuple[str, str]]: + file_contents = [] + multi_file = self.use_shared_lib and self.multi_file + + # Collect all literal refs in IR. + for module in self.modules.values(): + for fn in module.functions: + collect_literals(fn, self.context.literals) + + base_emitter = Emitter(self.context) + # Optionally just include the runtime library c files to + # reduce the number of compiler invocations needed + if self.compiler_options.include_runtime_files: + for name in RUNTIME_C_FILES: + base_emitter.emit_line(f'#include "{name}"') + # Include conditional source files + source_deps = collect_source_dependencies(self.modules) + for source_dep in sorted(source_deps, key=lambda d: d.path): + base_emitter.emit_line(f'#include "{source_dep.path}"') + base_emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"') + base_emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"') + emitter = base_emitter + + self.generate_literal_tables() + + for module_name, module in self.modules.items(): + if multi_file: + emitter = Emitter(self.context, filepath=self.source_paths[module_name]) + emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"') + emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"') + + self.declare_module(module_name, emitter) + self.declare_internal_globals(module_name, emitter) + self.declare_imports(module.imports, emitter) + + for cl in module.classes: + if cl.is_ext_class: + generate_class(cl, module_name, emitter) + + # Generate Python extension module definitions and module initialization functions. + self.generate_module_def(emitter, module_name, module) + + for fn in module.functions: + emitter.emit_line() + generate_native_function(fn, emitter, self.source_paths[module_name], module_name) + if fn.name != TOP_LEVEL_NAME and not fn.internal: + emitter.emit_line() + if is_fastcall_supported(fn, emitter.capi_version): + generate_wrapper_function( + fn, emitter, self.source_paths[module_name], module_name + ) + else: + generate_legacy_wrapper_function( + fn, emitter, self.source_paths[module_name], module_name + ) + if multi_file: + name = f"__native_{exported_name(module_name)}.c" + file_contents.append((name, "".join(emitter.fragments))) + + # The external header file contains type declarations while + # the internal contains declarations of functions and objects + # (which are shared between shared libraries via dynamic + # exports tables and not accessed directly.) + ext_declarations = Emitter(self.context) + ext_declarations.emit_line(f"#ifndef MYPYC_NATIVE{self.group_suffix}_H") + ext_declarations.emit_line(f"#define MYPYC_NATIVE{self.group_suffix}_H") + ext_declarations.emit_line("#include ") + ext_declarations.emit_line("#include ") + if self.compiler_options.depends_on_librt_internal: + ext_declarations.emit_line("#include ") + if any(LIBRT_BASE64 in mod.dependencies for mod in self.modules.values()): + ext_declarations.emit_line("#include ") + if any(LIBRT_STRINGS in mod.dependencies for mod in self.modules.values()): + ext_declarations.emit_line("#include ") + if any(LIBRT_TIME in mod.dependencies for mod in self.modules.values()): + ext_declarations.emit_line("#include