Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- 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 +1 -0
- 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 +56 -0
- 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
- 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 +0 -0
- 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 +5 -0
- 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 +1 -0
- 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 +6 -0
- 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 +3 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.py +1 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__main__.py +50 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.py +95 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.py +303 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.py +269 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.py +709 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/bogus_type.py +27 -0
- 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 +0 -0
- 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
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.py +532 -0
- 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 +0 -0
- 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
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_shared.py +365 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.py +30 -0
- 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 +0 -0
- 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
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.py +1588 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.py +885 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.py +1099 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.py +734 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.py +187 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.py +1687 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.py +134 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.py +51 -0
- 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 +0 -0
- micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.py +43 -0
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
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
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: mypy
|
| 3 |
+
Version: 1.20.2
|
| 4 |
+
Summary: Optional static typing for Python
|
| 5 |
+
Author-email: Jukka Lehtosalo <jukka.lehtosalo@iki.fi>
|
| 6 |
+
License-Expression: MIT
|
| 7 |
+
Project-URL: Homepage, https://www.mypy-lang.org/
|
| 8 |
+
Project-URL: Documentation, https://mypy.readthedocs.io/en/stable/index.html
|
| 9 |
+
Project-URL: Repository, https://github.com/python/mypy
|
| 10 |
+
Project-URL: Changelog, https://github.com/python/mypy/blob/master/CHANGELOG.md
|
| 11 |
+
Project-URL: Issues, https://github.com/python/mypy/issues
|
| 12 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 13 |
+
Classifier: Environment :: Console
|
| 14 |
+
Classifier: Intended Audience :: Developers
|
| 15 |
+
Classifier: Programming Language :: Python :: 3
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 21 |
+
Classifier: Topic :: Software Development
|
| 22 |
+
Classifier: Typing :: Typed
|
| 23 |
+
Requires-Python: >=3.10
|
| 24 |
+
Description-Content-Type: text/x-rst
|
| 25 |
+
License-File: LICENSE
|
| 26 |
+
License-File: mypy/typeshed/LICENSE
|
| 27 |
+
Requires-Dist: typing_extensions>=4.6.0; python_version < "3.15"
|
| 28 |
+
Requires-Dist: typing_extensions>=4.14.0; python_version >= "3.15"
|
| 29 |
+
Requires-Dist: mypy_extensions>=1.0.0
|
| 30 |
+
Requires-Dist: pathspec>=1.0.0
|
| 31 |
+
Requires-Dist: tomli>=1.1.0; python_version < "3.11"
|
| 32 |
+
Requires-Dist: librt>=0.8.0; platform_python_implementation != "PyPy"
|
| 33 |
+
Provides-Extra: dmypy
|
| 34 |
+
Requires-Dist: psutil>=4.0; extra == "dmypy"
|
| 35 |
+
Provides-Extra: mypyc
|
| 36 |
+
Requires-Dist: setuptools>=50; extra == "mypyc"
|
| 37 |
+
Provides-Extra: python2
|
| 38 |
+
Provides-Extra: reports
|
| 39 |
+
Requires-Dist: lxml; extra == "reports"
|
| 40 |
+
Provides-Extra: install-types
|
| 41 |
+
Requires-Dist: pip; extra == "install-types"
|
| 42 |
+
Provides-Extra: faster-cache
|
| 43 |
+
Requires-Dist: orjson; extra == "faster-cache"
|
| 44 |
+
Provides-Extra: native-parser
|
| 45 |
+
Requires-Dist: ast-serialize<1.0.0,>=0.1.1; extra == "native-parser"
|
| 46 |
+
Dynamic: license-file
|
| 47 |
+
|
| 48 |
+
Mypy -- Optional Static Typing for Python
|
| 49 |
+
=========================================
|
| 50 |
+
|
| 51 |
+
Add type annotations to your Python programs, and use mypy to type
|
| 52 |
+
check them. Mypy is essentially a Python linter on steroids, and it
|
| 53 |
+
can catch many programming errors by analyzing your program, without
|
| 54 |
+
actually having to run it. Mypy has a powerful type system with
|
| 55 |
+
features such as type inference, gradual typing, generics and union
|
| 56 |
+
types.
|
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
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
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
ADDED
|
File without changes
|
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
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (82.0.1)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp314-cp314-win_amd64
|
| 5 |
+
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///D:/bld/mypy-split_1776801208905/work"}
|
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
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
dmypy = mypy.dmypy.client:console_entry
|
| 3 |
+
mypy = mypy.__main__:console_entry
|
| 4 |
+
mypyc = mypyc.__main__:main
|
| 5 |
+
stubgen = mypy.stubgen:main
|
| 6 |
+
stubtest = mypy.stubtest:main
|
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
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
0aca9ce3d91742c5b361__mypyc
|
| 2 |
+
mypy
|
| 3 |
+
mypyc
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# This page intentionally left blank
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/__main__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mypy type checker command line tool."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
|
| 9 |
+
from mypy.main import main, process_options
|
| 10 |
+
from mypy.util import FancyFormatter
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def console_entry() -> None:
|
| 14 |
+
try:
|
| 15 |
+
main()
|
| 16 |
+
sys.stdout.flush()
|
| 17 |
+
sys.stderr.flush()
|
| 18 |
+
except BrokenPipeError:
|
| 19 |
+
# Python flushes standard streams on exit; redirect remaining output
|
| 20 |
+
# to devnull to avoid another BrokenPipeError at shutdown
|
| 21 |
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
| 22 |
+
os.dup2(devnull, sys.stdout.fileno())
|
| 23 |
+
sys.exit(2)
|
| 24 |
+
except KeyboardInterrupt:
|
| 25 |
+
_, options = process_options(args=sys.argv[1:])
|
| 26 |
+
if options.show_traceback:
|
| 27 |
+
sys.stdout.write(traceback.format_exc())
|
| 28 |
+
formatter = FancyFormatter(sys.stdout, sys.stderr, False)
|
| 29 |
+
msg = "Interrupted\n"
|
| 30 |
+
sys.stdout.write(formatter.style(msg, color="red", bold=True))
|
| 31 |
+
sys.stdout.flush()
|
| 32 |
+
sys.stderr.flush()
|
| 33 |
+
sys.exit(2)
|
| 34 |
+
except Exception as e:
|
| 35 |
+
# Try reporting any uncaught error canonically, otherwise just flush the traceback.
|
| 36 |
+
try:
|
| 37 |
+
import mypy.errors
|
| 38 |
+
|
| 39 |
+
_, options = process_options(args=sys.argv[1:])
|
| 40 |
+
mypy.errors.report_internal_error(e, None, 0, None, options)
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
sys.stdout.write(traceback.format_exc())
|
| 44 |
+
sys.stdout.flush()
|
| 45 |
+
sys.stderr.flush()
|
| 46 |
+
sys.exit(2)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
console_entry()
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/api.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module makes it possible to use mypy as part of a Python application.
|
| 2 |
+
|
| 3 |
+
Since mypy still changes, the API was kept utterly simple and non-intrusive.
|
| 4 |
+
It just mimics command line activation without starting a new interpreter.
|
| 5 |
+
So the normal docs about the mypy command line apply.
|
| 6 |
+
Changes in the command line version of mypy will be immediately usable.
|
| 7 |
+
|
| 8 |
+
Just import this module and then call the 'run' function with a parameter of
|
| 9 |
+
type List[str], containing what normally would have been the command line
|
| 10 |
+
arguments to mypy.
|
| 11 |
+
|
| 12 |
+
Function 'run' returns a Tuple[str, str, int], namely
|
| 13 |
+
(<normal_report>, <error_report>, <exit_status>),
|
| 14 |
+
in which <normal_report> is what mypy normally writes to sys.stdout,
|
| 15 |
+
<error_report> is what mypy normally writes to sys.stderr and exit_status is
|
| 16 |
+
the exit status mypy normally returns to the operating system.
|
| 17 |
+
|
| 18 |
+
Any pretty formatting is left to the caller.
|
| 19 |
+
|
| 20 |
+
The 'run_dmypy' function is similar, but instead mimics invocation of
|
| 21 |
+
dmypy. Note that run_dmypy is not thread-safe and modifies sys.stdout
|
| 22 |
+
and sys.stderr during its invocation.
|
| 23 |
+
|
| 24 |
+
Note that these APIs don't support incremental generation of error
|
| 25 |
+
messages.
|
| 26 |
+
|
| 27 |
+
Trivial example of code using this module:
|
| 28 |
+
|
| 29 |
+
import sys
|
| 30 |
+
from mypy import api
|
| 31 |
+
|
| 32 |
+
result = api.run(sys.argv[1:])
|
| 33 |
+
|
| 34 |
+
if result[0]:
|
| 35 |
+
print('\nType checking report:\n')
|
| 36 |
+
print(result[0]) # stdout
|
| 37 |
+
|
| 38 |
+
if result[1]:
|
| 39 |
+
print('\nError report:\n')
|
| 40 |
+
print(result[1]) # stderr
|
| 41 |
+
|
| 42 |
+
print('\nExit status:', result[2])
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
from __future__ import annotations
|
| 47 |
+
|
| 48 |
+
import sys
|
| 49 |
+
from collections.abc import Callable
|
| 50 |
+
from io import StringIO
|
| 51 |
+
from typing import TextIO
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _run(main_wrapper: Callable[[TextIO, TextIO], None]) -> tuple[str, str, int]:
|
| 55 |
+
stdout = StringIO()
|
| 56 |
+
stderr = StringIO()
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
main_wrapper(stdout, stderr)
|
| 60 |
+
exit_status = 0
|
| 61 |
+
except SystemExit as system_exit:
|
| 62 |
+
assert isinstance(system_exit.code, int)
|
| 63 |
+
exit_status = system_exit.code
|
| 64 |
+
|
| 65 |
+
return stdout.getvalue(), stderr.getvalue(), exit_status
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def run(args: list[str]) -> tuple[str, str, int]:
|
| 69 |
+
# Lazy import to avoid needing to import all of mypy to call run_dmypy
|
| 70 |
+
from mypy.main import main
|
| 71 |
+
|
| 72 |
+
return _run(
|
| 73 |
+
lambda stdout, stderr: main(args=args, stdout=stdout, stderr=stderr, clean_exit=True)
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def run_dmypy(args: list[str]) -> tuple[str, str, int]:
|
| 78 |
+
from mypy.dmypy.client import main
|
| 79 |
+
|
| 80 |
+
# A bunch of effort has been put into threading stdout and stderr
|
| 81 |
+
# through the main API to avoid the threadsafety problems of
|
| 82 |
+
# modifying sys.stdout/sys.stderr, but that hasn't been done for
|
| 83 |
+
# the dmypy client, so we just do the non-threadsafe thing.
|
| 84 |
+
def f(stdout: TextIO, stderr: TextIO) -> None:
|
| 85 |
+
old_stdout = sys.stdout
|
| 86 |
+
old_stderr = sys.stderr
|
| 87 |
+
try:
|
| 88 |
+
sys.stdout = stdout
|
| 89 |
+
sys.stderr = stderr
|
| 90 |
+
main(args)
|
| 91 |
+
finally:
|
| 92 |
+
sys.stdout = old_stdout
|
| 93 |
+
sys.stderr = old_stderr
|
| 94 |
+
|
| 95 |
+
return _run(f)
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/applytype.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 4 |
+
|
| 5 |
+
import mypy.subtypes
|
| 6 |
+
from mypy.erasetype import erase_typevars
|
| 7 |
+
from mypy.expandtype import expand_type
|
| 8 |
+
from mypy.nodes import Context, TypeInfo
|
| 9 |
+
from mypy.type_visitor import TypeTranslator
|
| 10 |
+
from mypy.typeops import get_all_type_vars
|
| 11 |
+
from mypy.types import (
|
| 12 |
+
AnyType,
|
| 13 |
+
CallableType,
|
| 14 |
+
Instance,
|
| 15 |
+
Parameters,
|
| 16 |
+
ParamSpecFlavor,
|
| 17 |
+
ParamSpecType,
|
| 18 |
+
PartialType,
|
| 19 |
+
ProperType,
|
| 20 |
+
Type,
|
| 21 |
+
TypeAliasType,
|
| 22 |
+
TypeVarId,
|
| 23 |
+
TypeVarLikeType,
|
| 24 |
+
TypeVarTupleType,
|
| 25 |
+
TypeVarType,
|
| 26 |
+
UninhabitedType,
|
| 27 |
+
UnpackType,
|
| 28 |
+
get_proper_type,
|
| 29 |
+
remove_dups,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_target_type(
|
| 34 |
+
tvar: TypeVarLikeType,
|
| 35 |
+
type: Type,
|
| 36 |
+
callable: CallableType,
|
| 37 |
+
report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None],
|
| 38 |
+
context: Context,
|
| 39 |
+
skip_unsatisfied: bool,
|
| 40 |
+
) -> Type | None:
|
| 41 |
+
p_type = get_proper_type(type)
|
| 42 |
+
if isinstance(p_type, UninhabitedType) and tvar.has_default():
|
| 43 |
+
return tvar.default
|
| 44 |
+
if isinstance(tvar, ParamSpecType):
|
| 45 |
+
return type
|
| 46 |
+
if isinstance(tvar, TypeVarTupleType):
|
| 47 |
+
return type
|
| 48 |
+
assert isinstance(tvar, TypeVarType)
|
| 49 |
+
values = tvar.values
|
| 50 |
+
if values:
|
| 51 |
+
if isinstance(p_type, AnyType):
|
| 52 |
+
return type
|
| 53 |
+
if isinstance(p_type, TypeVarType) and p_type.values:
|
| 54 |
+
# Allow substituting T1 for T if every allowed value of T1
|
| 55 |
+
# is also a legal value of T.
|
| 56 |
+
if all(any(mypy.subtypes.is_same_type(v, v1) for v in values) for v1 in p_type.values):
|
| 57 |
+
return type
|
| 58 |
+
matching = []
|
| 59 |
+
for value in values:
|
| 60 |
+
if mypy.subtypes.is_subtype(type, value):
|
| 61 |
+
matching.append(value)
|
| 62 |
+
if matching:
|
| 63 |
+
best = matching[0]
|
| 64 |
+
# If there are more than one matching value, we select the narrowest
|
| 65 |
+
for match in matching[1:]:
|
| 66 |
+
if mypy.subtypes.is_subtype(match, best):
|
| 67 |
+
best = match
|
| 68 |
+
return best
|
| 69 |
+
if skip_unsatisfied:
|
| 70 |
+
return None
|
| 71 |
+
report_incompatible_typevar_value(callable, type, tvar.name, context)
|
| 72 |
+
else:
|
| 73 |
+
upper_bound = tvar.upper_bound
|
| 74 |
+
if tvar.name == "Self":
|
| 75 |
+
# Internally constructed Self-types contain class type variables in upper bound,
|
| 76 |
+
# so we need to erase them to avoid false positives. This is safe because we do
|
| 77 |
+
# not support type variables in upper bounds of user defined types.
|
| 78 |
+
upper_bound = erase_typevars(upper_bound)
|
| 79 |
+
if not mypy.subtypes.is_subtype(type, upper_bound):
|
| 80 |
+
if skip_unsatisfied:
|
| 81 |
+
return None
|
| 82 |
+
report_incompatible_typevar_value(callable, type, tvar.name, context)
|
| 83 |
+
return type
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def apply_generic_arguments(
|
| 87 |
+
callable: CallableType,
|
| 88 |
+
orig_types: Sequence[Type | None],
|
| 89 |
+
report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None],
|
| 90 |
+
context: Context,
|
| 91 |
+
skip_unsatisfied: bool = False,
|
| 92 |
+
) -> CallableType:
|
| 93 |
+
"""Apply generic type arguments to a callable type.
|
| 94 |
+
|
| 95 |
+
For example, applying [int] to 'def [T] (T) -> T' results in
|
| 96 |
+
'def (int) -> int'.
|
| 97 |
+
|
| 98 |
+
Note that each type can be None; in this case, it will not be applied.
|
| 99 |
+
|
| 100 |
+
If `skip_unsatisfied` is True, then just skip the types that don't satisfy type variable
|
| 101 |
+
bound or constraints, instead of giving an error.
|
| 102 |
+
"""
|
| 103 |
+
tvars = callable.variables
|
| 104 |
+
assert len(orig_types) <= len(tvars)
|
| 105 |
+
# Check that inferred type variable values are compatible with allowed
|
| 106 |
+
# values and bounds. Also, promote subtype values to allowed values.
|
| 107 |
+
# Create a map from type variable id to target type.
|
| 108 |
+
id_to_type: dict[TypeVarId, Type] = {}
|
| 109 |
+
|
| 110 |
+
for tvar, type in zip(tvars, orig_types):
|
| 111 |
+
assert not isinstance(type, PartialType), "Internal error: must never apply partial type"
|
| 112 |
+
if type is None:
|
| 113 |
+
continue
|
| 114 |
+
|
| 115 |
+
target_type = get_target_type(
|
| 116 |
+
tvar, type, callable, report_incompatible_typevar_value, context, skip_unsatisfied
|
| 117 |
+
)
|
| 118 |
+
if target_type is not None:
|
| 119 |
+
id_to_type[tvar.id] = target_type
|
| 120 |
+
|
| 121 |
+
# TODO: validate arg_kinds/arg_names for ParamSpec and TypeVarTuple replacements,
|
| 122 |
+
# not just type variable bounds above.
|
| 123 |
+
param_spec = callable.param_spec()
|
| 124 |
+
if param_spec is not None:
|
| 125 |
+
nt = id_to_type.get(param_spec.id)
|
| 126 |
+
if nt is not None:
|
| 127 |
+
# ParamSpec expansion is special-cased, so we need to always expand callable
|
| 128 |
+
# as a whole, not expanding arguments individually.
|
| 129 |
+
callable = expand_type(callable, id_to_type)
|
| 130 |
+
assert isinstance(callable, CallableType)
|
| 131 |
+
return callable.copy_modified(
|
| 132 |
+
variables=[tv for tv in tvars if tv.id not in id_to_type]
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Apply arguments to argument types.
|
| 136 |
+
var_arg = callable.var_arg()
|
| 137 |
+
if var_arg is not None and isinstance(var_arg.typ, UnpackType):
|
| 138 |
+
# Same as for ParamSpec, callable with variadic types needs to be expanded as a whole.
|
| 139 |
+
callable = expand_type(callable, id_to_type)
|
| 140 |
+
assert isinstance(callable, CallableType)
|
| 141 |
+
return callable.copy_modified(variables=[tv for tv in tvars if tv.id not in id_to_type])
|
| 142 |
+
else:
|
| 143 |
+
callable = callable.copy_modified(
|
| 144 |
+
arg_types=[expand_type(at, id_to_type) for at in callable.arg_types]
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# Apply arguments to TypeGuard and TypeIs if any.
|
| 148 |
+
if callable.type_guard is not None:
|
| 149 |
+
type_guard = expand_type(callable.type_guard, id_to_type)
|
| 150 |
+
else:
|
| 151 |
+
type_guard = None
|
| 152 |
+
if callable.type_is is not None:
|
| 153 |
+
type_is = expand_type(callable.type_is, id_to_type)
|
| 154 |
+
else:
|
| 155 |
+
type_is = None
|
| 156 |
+
|
| 157 |
+
# The callable may retain some type vars if only some were applied.
|
| 158 |
+
# TODO: move apply_poly() logic here when new inference
|
| 159 |
+
# becomes universally used (i.e. in all passes + in unification).
|
| 160 |
+
# With this new logic we can actually *add* some new free variables.
|
| 161 |
+
remaining_tvars: list[TypeVarLikeType] = []
|
| 162 |
+
for tv in tvars:
|
| 163 |
+
if tv.id in id_to_type:
|
| 164 |
+
continue
|
| 165 |
+
if not tv.has_default():
|
| 166 |
+
remaining_tvars.append(tv)
|
| 167 |
+
continue
|
| 168 |
+
# TypeVarLike isn't in id_to_type mapping.
|
| 169 |
+
# Only expand the TypeVar default here.
|
| 170 |
+
typ = expand_type(tv, id_to_type)
|
| 171 |
+
assert isinstance(typ, TypeVarLikeType)
|
| 172 |
+
remaining_tvars.append(typ)
|
| 173 |
+
|
| 174 |
+
return callable.copy_modified(
|
| 175 |
+
ret_type=expand_type(callable.ret_type, id_to_type),
|
| 176 |
+
variables=remaining_tvars,
|
| 177 |
+
type_guard=type_guard,
|
| 178 |
+
type_is=type_is,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def apply_poly(tp: CallableType, poly_tvars: Sequence[TypeVarLikeType]) -> CallableType | None:
|
| 183 |
+
"""Make free type variables generic in the type if possible.
|
| 184 |
+
|
| 185 |
+
This will translate the type `tp` while trying to create valid bindings for
|
| 186 |
+
type variables `poly_tvars` while traversing the type. This follows the same rules
|
| 187 |
+
as we do during semantic analysis phase, examples:
|
| 188 |
+
* Callable[Callable[[T], T], T] -> def [T] (def (T) -> T) -> T
|
| 189 |
+
* Callable[[], Callable[[T], T]] -> def () -> def [T] (T -> T)
|
| 190 |
+
* List[T] -> None (not possible)
|
| 191 |
+
"""
|
| 192 |
+
try:
|
| 193 |
+
return tp.copy_modified(
|
| 194 |
+
arg_types=[t.accept(PolyTranslator(poly_tvars)) for t in tp.arg_types],
|
| 195 |
+
ret_type=tp.ret_type.accept(PolyTranslator(poly_tvars)),
|
| 196 |
+
variables=[],
|
| 197 |
+
)
|
| 198 |
+
except PolyTranslationError:
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class PolyTranslationError(Exception):
|
| 203 |
+
pass
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class PolyTranslator(TypeTranslator):
|
| 207 |
+
"""Make free type variables generic in the type if possible.
|
| 208 |
+
|
| 209 |
+
See docstring for apply_poly() for details.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
def __init__(
|
| 213 |
+
self,
|
| 214 |
+
poly_tvars: Iterable[TypeVarLikeType],
|
| 215 |
+
bound_tvars: frozenset[TypeVarLikeType] = frozenset(),
|
| 216 |
+
seen_aliases: frozenset[TypeInfo] = frozenset(),
|
| 217 |
+
) -> None:
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.poly_tvars = set(poly_tvars)
|
| 220 |
+
# This is a simplified version of TypeVarScope used during semantic analysis.
|
| 221 |
+
self.bound_tvars = bound_tvars
|
| 222 |
+
self.seen_aliases = seen_aliases
|
| 223 |
+
|
| 224 |
+
def collect_vars(self, t: CallableType | Parameters) -> list[TypeVarLikeType]:
|
| 225 |
+
found_vars = []
|
| 226 |
+
for arg in t.arg_types:
|
| 227 |
+
for tv in get_all_type_vars(arg):
|
| 228 |
+
if isinstance(tv, ParamSpecType):
|
| 229 |
+
normalized: TypeVarLikeType = tv.copy_modified(
|
| 230 |
+
flavor=ParamSpecFlavor.BARE, prefix=Parameters([], [], [])
|
| 231 |
+
)
|
| 232 |
+
else:
|
| 233 |
+
normalized = tv
|
| 234 |
+
if normalized in self.poly_tvars and normalized not in self.bound_tvars:
|
| 235 |
+
found_vars.append(normalized)
|
| 236 |
+
return remove_dups(found_vars)
|
| 237 |
+
|
| 238 |
+
def visit_callable_type(self, t: CallableType) -> Type:
|
| 239 |
+
found_vars = self.collect_vars(t)
|
| 240 |
+
self.bound_tvars |= set(found_vars)
|
| 241 |
+
result = super().visit_callable_type(t)
|
| 242 |
+
self.bound_tvars -= set(found_vars)
|
| 243 |
+
|
| 244 |
+
assert isinstance(result, ProperType) and isinstance(result, CallableType)
|
| 245 |
+
result.variables = result.variables + tuple(found_vars)
|
| 246 |
+
return result
|
| 247 |
+
|
| 248 |
+
def visit_type_var(self, t: TypeVarType) -> Type:
|
| 249 |
+
if t in self.poly_tvars and t not in self.bound_tvars:
|
| 250 |
+
raise PolyTranslationError()
|
| 251 |
+
return super().visit_type_var(t)
|
| 252 |
+
|
| 253 |
+
def visit_param_spec(self, t: ParamSpecType) -> Type:
|
| 254 |
+
if t in self.poly_tvars and t not in self.bound_tvars:
|
| 255 |
+
raise PolyTranslationError()
|
| 256 |
+
return super().visit_param_spec(t)
|
| 257 |
+
|
| 258 |
+
def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:
|
| 259 |
+
if t in self.poly_tvars and t not in self.bound_tvars:
|
| 260 |
+
raise PolyTranslationError()
|
| 261 |
+
return super().visit_type_var_tuple(t)
|
| 262 |
+
|
| 263 |
+
def visit_type_alias_type(self, t: TypeAliasType) -> Type:
|
| 264 |
+
if not t.args:
|
| 265 |
+
return t.copy_modified()
|
| 266 |
+
if not t.is_recursive:
|
| 267 |
+
return get_proper_type(t).accept(self)
|
| 268 |
+
# We can't handle polymorphic application for recursive generic aliases
|
| 269 |
+
# without risking an infinite recursion, just give up for now.
|
| 270 |
+
raise PolyTranslationError()
|
| 271 |
+
|
| 272 |
+
def visit_instance(self, t: Instance) -> Type:
|
| 273 |
+
if t.type.has_param_spec_type:
|
| 274 |
+
# We need this special-casing to preserve the possibility to store a
|
| 275 |
+
# generic function in an instance type. Things like
|
| 276 |
+
# forall T . Foo[[x: T], T]
|
| 277 |
+
# are not really expressible in current type system, but this looks like
|
| 278 |
+
# a useful feature, so let's keep it.
|
| 279 |
+
param_spec_index = next(
|
| 280 |
+
i for (i, tv) in enumerate(t.type.defn.type_vars) if isinstance(tv, ParamSpecType)
|
| 281 |
+
)
|
| 282 |
+
p = get_proper_type(t.args[param_spec_index])
|
| 283 |
+
if isinstance(p, Parameters):
|
| 284 |
+
found_vars = self.collect_vars(p)
|
| 285 |
+
self.bound_tvars |= set(found_vars)
|
| 286 |
+
new_args = [a.accept(self) for a in t.args]
|
| 287 |
+
self.bound_tvars -= set(found_vars)
|
| 288 |
+
|
| 289 |
+
repl = new_args[param_spec_index]
|
| 290 |
+
assert isinstance(repl, ProperType) and isinstance(repl, Parameters)
|
| 291 |
+
repl.variables = list(repl.variables) + list(found_vars)
|
| 292 |
+
return t.copy_modified(args=new_args)
|
| 293 |
+
# There is the same problem with callback protocols as with aliases
|
| 294 |
+
# (callback protocols are essentially more flexible aliases to callables).
|
| 295 |
+
if t.args and t.type.is_protocol and t.type.protocol_members == ["__call__"]:
|
| 296 |
+
if t.type in self.seen_aliases:
|
| 297 |
+
raise PolyTranslationError()
|
| 298 |
+
call = mypy.subtypes.find_member("__call__", t, t, is_operator=True)
|
| 299 |
+
assert call is not None
|
| 300 |
+
return call.accept(
|
| 301 |
+
PolyTranslator(self.poly_tvars, self.bound_tvars, self.seen_aliases | {t.type})
|
| 302 |
+
)
|
| 303 |
+
return super().visit_instance(t)
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/argmap.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities for mapping between actual and formal arguments (and their types)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable, Sequence
|
| 6 |
+
from typing import TYPE_CHECKING
|
| 7 |
+
|
| 8 |
+
from mypy import nodes
|
| 9 |
+
from mypy.maptype import map_instance_to_supertype
|
| 10 |
+
from mypy.types import (
|
| 11 |
+
AnyType,
|
| 12 |
+
Instance,
|
| 13 |
+
ParamSpecType,
|
| 14 |
+
TupleType,
|
| 15 |
+
Type,
|
| 16 |
+
TypedDictType,
|
| 17 |
+
TypeOfAny,
|
| 18 |
+
TypeVarTupleType,
|
| 19 |
+
UnpackType,
|
| 20 |
+
get_proper_type,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from mypy.infer import ArgumentInferContext
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def map_actuals_to_formals(
|
| 28 |
+
actual_kinds: list[nodes.ArgKind],
|
| 29 |
+
actual_names: Sequence[str | None] | None,
|
| 30 |
+
formal_kinds: list[nodes.ArgKind],
|
| 31 |
+
formal_names: Sequence[str | None],
|
| 32 |
+
actual_arg_type: Callable[[int], Type],
|
| 33 |
+
) -> list[list[int]]:
|
| 34 |
+
"""Calculate mapping between actual (caller) args and formals.
|
| 35 |
+
|
| 36 |
+
The result contains a list of caller argument indexes mapping to each
|
| 37 |
+
callee argument index, indexed by callee index.
|
| 38 |
+
|
| 39 |
+
The actual_arg_type argument should evaluate to the type of the actual
|
| 40 |
+
argument with the given index.
|
| 41 |
+
"""
|
| 42 |
+
nformals = len(formal_kinds)
|
| 43 |
+
formal_to_actual: list[list[int]] = [[] for i in range(nformals)]
|
| 44 |
+
ambiguous_actual_kwargs: list[int] = []
|
| 45 |
+
fi = 0
|
| 46 |
+
for ai, actual_kind in enumerate(actual_kinds):
|
| 47 |
+
if actual_kind == nodes.ARG_POS:
|
| 48 |
+
if fi < nformals:
|
| 49 |
+
if not formal_kinds[fi].is_star():
|
| 50 |
+
formal_to_actual[fi].append(ai)
|
| 51 |
+
fi += 1
|
| 52 |
+
elif formal_kinds[fi] == nodes.ARG_STAR:
|
| 53 |
+
formal_to_actual[fi].append(ai)
|
| 54 |
+
elif actual_kind == nodes.ARG_STAR:
|
| 55 |
+
# We need to know the actual type to map varargs.
|
| 56 |
+
actualt = get_proper_type(actual_arg_type(ai))
|
| 57 |
+
if isinstance(actualt, TupleType):
|
| 58 |
+
# A tuple actual maps to a fixed number of formals.
|
| 59 |
+
for _ in range(len(actualt.items)):
|
| 60 |
+
if fi < nformals:
|
| 61 |
+
if formal_kinds[fi] != nodes.ARG_STAR2:
|
| 62 |
+
formal_to_actual[fi].append(ai)
|
| 63 |
+
else:
|
| 64 |
+
break
|
| 65 |
+
if formal_kinds[fi] != nodes.ARG_STAR:
|
| 66 |
+
fi += 1
|
| 67 |
+
else:
|
| 68 |
+
# Assume that it is an iterable (if it isn't, there will be
|
| 69 |
+
# an error later).
|
| 70 |
+
while fi < nformals:
|
| 71 |
+
if formal_kinds[fi].is_named(star=True):
|
| 72 |
+
break
|
| 73 |
+
else:
|
| 74 |
+
formal_to_actual[fi].append(ai)
|
| 75 |
+
if formal_kinds[fi] == nodes.ARG_STAR:
|
| 76 |
+
break
|
| 77 |
+
fi += 1
|
| 78 |
+
elif actual_kind.is_named():
|
| 79 |
+
assert actual_names is not None, "Internal error: named kinds without names given"
|
| 80 |
+
name = actual_names[ai]
|
| 81 |
+
if name in formal_names and formal_kinds[formal_names.index(name)] != nodes.ARG_STAR:
|
| 82 |
+
formal_to_actual[formal_names.index(name)].append(ai)
|
| 83 |
+
elif nodes.ARG_STAR2 in formal_kinds:
|
| 84 |
+
formal_to_actual[formal_kinds.index(nodes.ARG_STAR2)].append(ai)
|
| 85 |
+
else:
|
| 86 |
+
assert actual_kind == nodes.ARG_STAR2
|
| 87 |
+
actualt = get_proper_type(actual_arg_type(ai))
|
| 88 |
+
if isinstance(actualt, TypedDictType):
|
| 89 |
+
for name in actualt.items:
|
| 90 |
+
if name in formal_names:
|
| 91 |
+
formal_to_actual[formal_names.index(name)].append(ai)
|
| 92 |
+
elif nodes.ARG_STAR2 in formal_kinds:
|
| 93 |
+
formal_to_actual[formal_kinds.index(nodes.ARG_STAR2)].append(ai)
|
| 94 |
+
else:
|
| 95 |
+
# We don't exactly know which **kwargs are provided by the
|
| 96 |
+
# caller, so we'll defer until all the other unambiguous
|
| 97 |
+
# actuals have been processed
|
| 98 |
+
ambiguous_actual_kwargs.append(ai)
|
| 99 |
+
|
| 100 |
+
if ambiguous_actual_kwargs:
|
| 101 |
+
# Assume the ambiguous kwargs will fill the remaining arguments.
|
| 102 |
+
#
|
| 103 |
+
# TODO: If there are also tuple varargs, we might be missing some potential
|
| 104 |
+
# matches if the tuple was short enough to not match everything.
|
| 105 |
+
unmatched_formals = [
|
| 106 |
+
fi
|
| 107 |
+
for fi in range(nformals)
|
| 108 |
+
if (
|
| 109 |
+
formal_names[fi]
|
| 110 |
+
and (
|
| 111 |
+
not formal_to_actual[fi]
|
| 112 |
+
or actual_kinds[formal_to_actual[fi][0]] == nodes.ARG_STAR
|
| 113 |
+
)
|
| 114 |
+
and formal_kinds[fi] != nodes.ARG_STAR
|
| 115 |
+
)
|
| 116 |
+
or formal_kinds[fi] == nodes.ARG_STAR2
|
| 117 |
+
]
|
| 118 |
+
for ai in ambiguous_actual_kwargs:
|
| 119 |
+
for fi in unmatched_formals:
|
| 120 |
+
formal_to_actual[fi].append(ai)
|
| 121 |
+
|
| 122 |
+
return formal_to_actual
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def map_formals_to_actuals(
|
| 126 |
+
actual_kinds: list[nodes.ArgKind],
|
| 127 |
+
actual_names: Sequence[str | None] | None,
|
| 128 |
+
formal_kinds: list[nodes.ArgKind],
|
| 129 |
+
formal_names: list[str | None],
|
| 130 |
+
actual_arg_type: Callable[[int], Type],
|
| 131 |
+
) -> list[list[int]]:
|
| 132 |
+
"""Calculate the reverse mapping of map_actuals_to_formals."""
|
| 133 |
+
formal_to_actual = map_actuals_to_formals(
|
| 134 |
+
actual_kinds, actual_names, formal_kinds, formal_names, actual_arg_type
|
| 135 |
+
)
|
| 136 |
+
# Now reverse the mapping.
|
| 137 |
+
actual_to_formal: list[list[int]] = [[] for _ in actual_kinds]
|
| 138 |
+
for formal, actuals in enumerate(formal_to_actual):
|
| 139 |
+
for actual in actuals:
|
| 140 |
+
actual_to_formal[actual].append(formal)
|
| 141 |
+
return actual_to_formal
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class ArgTypeExpander:
|
| 145 |
+
"""Utility class for mapping actual argument types to formal arguments.
|
| 146 |
+
|
| 147 |
+
One of the main responsibilities is to expand caller tuple *args and TypedDict
|
| 148 |
+
**kwargs, and to keep track of which tuple/TypedDict items have already been
|
| 149 |
+
consumed.
|
| 150 |
+
|
| 151 |
+
Example:
|
| 152 |
+
|
| 153 |
+
def f(x: int, *args: str) -> None: ...
|
| 154 |
+
f(*(1, 'x', 1.1))
|
| 155 |
+
|
| 156 |
+
We'd call expand_actual_type three times:
|
| 157 |
+
|
| 158 |
+
1. The first call would provide 'int' as the actual type of 'x' (from '1').
|
| 159 |
+
2. The second call would provide 'str' as one of the actual types for '*args'.
|
| 160 |
+
2. The third call would provide 'float' as one of the actual types for '*args'.
|
| 161 |
+
|
| 162 |
+
A single instance can process all the arguments for a single call. Each call
|
| 163 |
+
needs a separate instance since instances have per-call state.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
def __init__(self, context: ArgumentInferContext) -> None:
|
| 167 |
+
# Next tuple *args index to use.
|
| 168 |
+
self.tuple_index = 0
|
| 169 |
+
# Keyword arguments in TypedDict **kwargs used.
|
| 170 |
+
self.kwargs_used: set[str] | None = None
|
| 171 |
+
# Type context for `*` and `**` arg kinds.
|
| 172 |
+
self.context = context
|
| 173 |
+
|
| 174 |
+
def expand_actual_type(
|
| 175 |
+
self,
|
| 176 |
+
actual_type: Type,
|
| 177 |
+
actual_kind: nodes.ArgKind,
|
| 178 |
+
formal_name: str | None,
|
| 179 |
+
formal_kind: nodes.ArgKind,
|
| 180 |
+
allow_unpack: bool = False,
|
| 181 |
+
) -> Type:
|
| 182 |
+
"""Return the actual (caller) type(s) of a formal argument with the given kinds.
|
| 183 |
+
|
| 184 |
+
If the actual argument is a tuple *args, return the next individual tuple item that
|
| 185 |
+
maps to the formal arg.
|
| 186 |
+
|
| 187 |
+
If the actual argument is a TypedDict **kwargs, return the next matching typed dict
|
| 188 |
+
value type based on formal argument name and kind.
|
| 189 |
+
|
| 190 |
+
This is supposed to be called for each formal, in order. Call multiple times per
|
| 191 |
+
formal if multiple actuals map to a formal.
|
| 192 |
+
"""
|
| 193 |
+
original_actual = actual_type
|
| 194 |
+
actual_type = get_proper_type(actual_type)
|
| 195 |
+
if actual_kind == nodes.ARG_STAR:
|
| 196 |
+
if isinstance(actual_type, TypeVarTupleType):
|
| 197 |
+
# This code path is hit when *Ts is passed to a callable and various
|
| 198 |
+
# special-handling didn't catch this. The best thing we can do is to use
|
| 199 |
+
# the upper bound.
|
| 200 |
+
actual_type = get_proper_type(actual_type.upper_bound)
|
| 201 |
+
if isinstance(actual_type, Instance) and actual_type.args:
|
| 202 |
+
from mypy.subtypes import is_subtype
|
| 203 |
+
|
| 204 |
+
if is_subtype(actual_type, self.context.iterable_type):
|
| 205 |
+
return map_instance_to_supertype(
|
| 206 |
+
actual_type, self.context.iterable_type.type
|
| 207 |
+
).args[0]
|
| 208 |
+
else:
|
| 209 |
+
# We cannot properly unpack anything other
|
| 210 |
+
# than `Iterable` type with `*`.
|
| 211 |
+
# Just return `Any`, other parts of code would raise
|
| 212 |
+
# a different error for improper use.
|
| 213 |
+
return AnyType(TypeOfAny.from_error)
|
| 214 |
+
elif isinstance(actual_type, TupleType):
|
| 215 |
+
# Get the next tuple item of a tuple *arg.
|
| 216 |
+
if self.tuple_index >= len(actual_type.items):
|
| 217 |
+
# Exhausted a tuple -- continue to the next *args.
|
| 218 |
+
self.tuple_index = 1
|
| 219 |
+
else:
|
| 220 |
+
self.tuple_index += 1
|
| 221 |
+
item = actual_type.items[self.tuple_index - 1]
|
| 222 |
+
if isinstance(item, UnpackType) and not allow_unpack:
|
| 223 |
+
# An unpack item that doesn't have special handling, use upper bound as above.
|
| 224 |
+
unpacked = get_proper_type(item.type)
|
| 225 |
+
if isinstance(unpacked, TypeVarTupleType):
|
| 226 |
+
fallback = get_proper_type(unpacked.upper_bound)
|
| 227 |
+
else:
|
| 228 |
+
fallback = unpacked
|
| 229 |
+
assert (
|
| 230 |
+
isinstance(fallback, Instance)
|
| 231 |
+
and fallback.type.fullname == "builtins.tuple"
|
| 232 |
+
)
|
| 233 |
+
item = fallback.args[0]
|
| 234 |
+
return item
|
| 235 |
+
elif isinstance(actual_type, ParamSpecType):
|
| 236 |
+
# ParamSpec is valid in *args but it can't be unpacked.
|
| 237 |
+
return actual_type
|
| 238 |
+
else:
|
| 239 |
+
return AnyType(TypeOfAny.from_error)
|
| 240 |
+
elif actual_kind == nodes.ARG_STAR2:
|
| 241 |
+
from mypy.subtypes import is_subtype
|
| 242 |
+
|
| 243 |
+
if isinstance(actual_type, TypedDictType):
|
| 244 |
+
if self.kwargs_used is None:
|
| 245 |
+
self.kwargs_used = set()
|
| 246 |
+
if formal_kind != nodes.ARG_STAR2 and formal_name in actual_type.items:
|
| 247 |
+
# Lookup type based on keyword argument name.
|
| 248 |
+
assert formal_name is not None
|
| 249 |
+
else:
|
| 250 |
+
# Pick an arbitrary item if no specified keyword is expected.
|
| 251 |
+
formal_name = (set(actual_type.items.keys()) - self.kwargs_used).pop()
|
| 252 |
+
self.kwargs_used.add(formal_name)
|
| 253 |
+
return actual_type.items[formal_name]
|
| 254 |
+
elif isinstance(actual_type, Instance) and is_subtype(
|
| 255 |
+
actual_type, self.context.mapping_type
|
| 256 |
+
):
|
| 257 |
+
# Only `Mapping` type can be unpacked with `**`.
|
| 258 |
+
# Other types will produce an error somewhere else.
|
| 259 |
+
return map_instance_to_supertype(actual_type, self.context.mapping_type.type).args[
|
| 260 |
+
1
|
| 261 |
+
]
|
| 262 |
+
elif isinstance(actual_type, ParamSpecType):
|
| 263 |
+
# ParamSpec is valid in **kwargs but it can't be unpacked.
|
| 264 |
+
return actual_type
|
| 265 |
+
else:
|
| 266 |
+
return AnyType(TypeOfAny.from_error)
|
| 267 |
+
else:
|
| 268 |
+
# No translation for other kinds -- 1:1 mapping.
|
| 269 |
+
return original_actual
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/binder.py
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from collections.abc import Iterator
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from typing import Literal, NamedTuple, TypeAlias as _TypeAlias
|
| 7 |
+
|
| 8 |
+
from mypy.erasetype import remove_instance_last_known_values
|
| 9 |
+
from mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash, subkeys
|
| 10 |
+
from mypy.nodes import (
|
| 11 |
+
LITERAL_NO,
|
| 12 |
+
Expression,
|
| 13 |
+
IndexExpr,
|
| 14 |
+
MemberExpr,
|
| 15 |
+
NameExpr,
|
| 16 |
+
RefExpr,
|
| 17 |
+
TypeInfo,
|
| 18 |
+
Var,
|
| 19 |
+
)
|
| 20 |
+
from mypy.options import Options
|
| 21 |
+
from mypy.subtypes import is_same_type, is_subtype
|
| 22 |
+
from mypy.typeops import make_simplified_union
|
| 23 |
+
from mypy.types import (
|
| 24 |
+
AnyType,
|
| 25 |
+
Instance,
|
| 26 |
+
NoneType,
|
| 27 |
+
PartialType,
|
| 28 |
+
ProperType,
|
| 29 |
+
TupleType,
|
| 30 |
+
Type,
|
| 31 |
+
TypeOfAny,
|
| 32 |
+
TypeType,
|
| 33 |
+
TypeVarType,
|
| 34 |
+
UnionType,
|
| 35 |
+
UnpackType,
|
| 36 |
+
find_unpack_in_list,
|
| 37 |
+
flatten_nested_unions,
|
| 38 |
+
get_proper_type,
|
| 39 |
+
)
|
| 40 |
+
from mypy.typevars import fill_typevars_with_any
|
| 41 |
+
|
| 42 |
+
BindableExpression: _TypeAlias = IndexExpr | MemberExpr | NameExpr
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class CurrentType(NamedTuple):
|
| 46 |
+
type: Type
|
| 47 |
+
from_assignment: bool
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Frame:
|
| 51 |
+
"""A Frame represents a specific point in the execution of a program.
|
| 52 |
+
|
| 53 |
+
It carries information about the current types of expressions at
|
| 54 |
+
that point, arising either from assignments to those expressions
|
| 55 |
+
or the result of isinstance checks and other type narrowing
|
| 56 |
+
operations. It also records whether it is possible to reach that
|
| 57 |
+
point at all.
|
| 58 |
+
|
| 59 |
+
We add a new frame wherenever there is a new scope or control flow
|
| 60 |
+
branching.
|
| 61 |
+
|
| 62 |
+
This information is not copied into a new Frame when it is pushed
|
| 63 |
+
onto the stack, so a given Frame only has information about types
|
| 64 |
+
that were assigned in that frame.
|
| 65 |
+
|
| 66 |
+
Expressions are stored in dicts using 'literal hashes' as keys (type
|
| 67 |
+
"Key"). These are hashable values derived from expression AST nodes
|
| 68 |
+
(only those that can be narrowed). literal_hash(expr) is used to
|
| 69 |
+
calculate the hashes. Note that this isn't directly related to literal
|
| 70 |
+
types -- the concept predates literal types.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(self, id: int, conditional_frame: bool = False) -> None:
|
| 74 |
+
self.id = id
|
| 75 |
+
self.types: dict[Key, CurrentType] = {}
|
| 76 |
+
self.unreachable = False
|
| 77 |
+
self.conditional_frame = conditional_frame
|
| 78 |
+
self.suppress_unreachable_warnings = False
|
| 79 |
+
|
| 80 |
+
def __repr__(self) -> str:
|
| 81 |
+
return f"Frame({self.id}, {self.types}, {self.unreachable}, {self.conditional_frame})"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
Assigns = defaultdict[Expression, list[tuple[Type, Type | None]]]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class FrameContext:
|
| 88 |
+
"""Context manager pushing a Frame to ConditionalTypeBinder.
|
| 89 |
+
|
| 90 |
+
See frame_context() below for documentation on parameters. We use this class
|
| 91 |
+
instead of @contextmanager as a mypyc-specific performance optimization.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
binder: ConditionalTypeBinder,
|
| 97 |
+
can_skip: bool,
|
| 98 |
+
fall_through: int,
|
| 99 |
+
break_frame: int,
|
| 100 |
+
continue_frame: int,
|
| 101 |
+
conditional_frame: bool,
|
| 102 |
+
try_frame: bool,
|
| 103 |
+
discard: bool,
|
| 104 |
+
) -> None:
|
| 105 |
+
self.binder = binder
|
| 106 |
+
self.can_skip = can_skip
|
| 107 |
+
self.fall_through = fall_through
|
| 108 |
+
self.break_frame = break_frame
|
| 109 |
+
self.continue_frame = continue_frame
|
| 110 |
+
self.conditional_frame = conditional_frame
|
| 111 |
+
self.try_frame = try_frame
|
| 112 |
+
self.discard = discard
|
| 113 |
+
|
| 114 |
+
def __enter__(self) -> Frame:
|
| 115 |
+
assert len(self.binder.frames) > 1
|
| 116 |
+
|
| 117 |
+
if self.break_frame:
|
| 118 |
+
self.binder.break_frames.append(len(self.binder.frames) - self.break_frame)
|
| 119 |
+
if self.continue_frame:
|
| 120 |
+
self.binder.continue_frames.append(len(self.binder.frames) - self.continue_frame)
|
| 121 |
+
if self.try_frame:
|
| 122 |
+
self.binder.try_frames.add(len(self.binder.frames) - 1)
|
| 123 |
+
|
| 124 |
+
new_frame = self.binder.push_frame(self.conditional_frame)
|
| 125 |
+
if self.try_frame:
|
| 126 |
+
# An exception may occur immediately
|
| 127 |
+
self.binder.allow_jump(-1)
|
| 128 |
+
return new_frame
|
| 129 |
+
|
| 130 |
+
def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]:
|
| 131 |
+
self.binder.pop_frame(self.can_skip, self.fall_through, discard=self.discard)
|
| 132 |
+
|
| 133 |
+
if self.break_frame:
|
| 134 |
+
self.binder.break_frames.pop()
|
| 135 |
+
if self.continue_frame:
|
| 136 |
+
self.binder.continue_frames.pop()
|
| 137 |
+
if self.try_frame:
|
| 138 |
+
self.binder.try_frames.remove(len(self.binder.frames) - 1)
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class ConditionalTypeBinder:
|
| 143 |
+
"""Keep track of conditional types of variables.
|
| 144 |
+
|
| 145 |
+
NB: Variables are tracked by literal hashes of expressions, so it is
|
| 146 |
+
possible to confuse the binder when there is aliasing. Example:
|
| 147 |
+
|
| 148 |
+
class A:
|
| 149 |
+
a: int | str
|
| 150 |
+
|
| 151 |
+
x = A()
|
| 152 |
+
lst = [x]
|
| 153 |
+
reveal_type(x.a) # int | str
|
| 154 |
+
x.a = 1
|
| 155 |
+
reveal_type(x.a) # int
|
| 156 |
+
reveal_type(lst[0].a) # int | str
|
| 157 |
+
lst[0].a = 'a'
|
| 158 |
+
reveal_type(x.a) # int
|
| 159 |
+
reveal_type(lst[0].a) # str
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
# Stored assignments for situations with tuple/list lvalue and rvalue of union type.
|
| 163 |
+
# This maps an expression to a list of bound types for every item in the union type.
|
| 164 |
+
type_assignments: Assigns | None = None
|
| 165 |
+
|
| 166 |
+
def __init__(self, options: Options) -> None:
|
| 167 |
+
# Each frame gets an increasing, distinct id.
|
| 168 |
+
self.next_id = 1
|
| 169 |
+
|
| 170 |
+
# The stack of frames currently used. These map
|
| 171 |
+
# literal_hash(expr) -- literals like 'foo.bar' --
|
| 172 |
+
# to types. The last element of this list is the
|
| 173 |
+
# top-most, current frame. Each earlier element
|
| 174 |
+
# records the state as of when that frame was last
|
| 175 |
+
# on top of the stack.
|
| 176 |
+
self.frames = [Frame(self._get_id())]
|
| 177 |
+
|
| 178 |
+
# For frames higher in the stack, we record the set of
|
| 179 |
+
# Frames that can escape there, either by falling off
|
| 180 |
+
# the end of the frame or by a loop control construct
|
| 181 |
+
# or raised exception. The last element of self.frames
|
| 182 |
+
# has no corresponding element in this list.
|
| 183 |
+
self.options_on_return: list[list[Frame]] = []
|
| 184 |
+
|
| 185 |
+
# Maps literal_hash(expr) to get_declaration(expr)
|
| 186 |
+
# for every expr stored in the binder
|
| 187 |
+
self.declarations: dict[Key, Type | None] = {}
|
| 188 |
+
# Set of other keys to invalidate if a key is changed, e.g. x -> {x.a, x[0]}
|
| 189 |
+
# Whenever a new key (e.g. x.a.b) is added, we update this
|
| 190 |
+
self.dependencies: dict[Key, set[Key]] = {}
|
| 191 |
+
|
| 192 |
+
# Whether the last pop changed the newly top frame on exit
|
| 193 |
+
self.last_pop_changed = False
|
| 194 |
+
|
| 195 |
+
# These are used to track control flow in try statements and loops.
|
| 196 |
+
self.try_frames: set[int] = set()
|
| 197 |
+
self.break_frames: list[int] = []
|
| 198 |
+
self.continue_frames: list[int] = []
|
| 199 |
+
|
| 200 |
+
# If True, initial assignment to a simple variable (e.g. "x", but not "x.y")
|
| 201 |
+
# is added to the binder. This allows more precise narrowing and more
|
| 202 |
+
# flexible inference of variable types (--allow-redefinition-new).
|
| 203 |
+
self.bind_all = options.allow_redefinition_new
|
| 204 |
+
|
| 205 |
+
# This tracks any externally visible changes in binder to invalidate
|
| 206 |
+
# expression caches when needed.
|
| 207 |
+
self.version = 0
|
| 208 |
+
|
| 209 |
+
def _get_id(self) -> int:
|
| 210 |
+
self.next_id += 1
|
| 211 |
+
return self.next_id
|
| 212 |
+
|
| 213 |
+
def _add_dependencies(self, key: Key, value: Key | None = None) -> None:
|
| 214 |
+
if value is None:
|
| 215 |
+
value = key
|
| 216 |
+
else:
|
| 217 |
+
self.dependencies.setdefault(key, set()).add(value)
|
| 218 |
+
for elt in subkeys(key):
|
| 219 |
+
self._add_dependencies(elt, value)
|
| 220 |
+
|
| 221 |
+
def push_frame(self, conditional_frame: bool = False) -> Frame:
|
| 222 |
+
"""Push a new frame into the binder."""
|
| 223 |
+
f = Frame(self._get_id(), conditional_frame)
|
| 224 |
+
self.frames.append(f)
|
| 225 |
+
self.options_on_return.append([])
|
| 226 |
+
return f
|
| 227 |
+
|
| 228 |
+
def _put(self, key: Key, type: Type, from_assignment: bool, index: int = -1) -> None:
|
| 229 |
+
self.version += 1
|
| 230 |
+
self.frames[index].types[key] = CurrentType(type, from_assignment)
|
| 231 |
+
|
| 232 |
+
def _get(self, key: Key, index: int = -1) -> CurrentType | None:
|
| 233 |
+
if index < 0:
|
| 234 |
+
index += len(self.frames)
|
| 235 |
+
for i in range(index, -1, -1):
|
| 236 |
+
if key in self.frames[i].types:
|
| 237 |
+
return self.frames[i].types[key]
|
| 238 |
+
return None
|
| 239 |
+
|
| 240 |
+
@classmethod
|
| 241 |
+
def can_put_directly(cls, expr: Expression) -> bool:
|
| 242 |
+
"""Will `.put()` on this expression be successful?
|
| 243 |
+
|
| 244 |
+
This is inlined in `.put()` because the logic is rather hot and must be kept
|
| 245 |
+
in sync.
|
| 246 |
+
"""
|
| 247 |
+
return isinstance(expr, (IndexExpr, MemberExpr, NameExpr)) and literal(expr) > LITERAL_NO
|
| 248 |
+
|
| 249 |
+
def put(self, expr: Expression, typ: Type, *, from_assignment: bool = True) -> None:
|
| 250 |
+
"""Directly set the narrowed type of expression (if it supports it).
|
| 251 |
+
|
| 252 |
+
This is used for isinstance() etc. Assignments should go through assign_type().
|
| 253 |
+
"""
|
| 254 |
+
if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)):
|
| 255 |
+
return
|
| 256 |
+
if not literal(expr):
|
| 257 |
+
return
|
| 258 |
+
key = literal_hash(expr)
|
| 259 |
+
assert key is not None, "Internal error: binder tried to put non-literal"
|
| 260 |
+
if key not in self.declarations:
|
| 261 |
+
self.declarations[key] = get_declaration(expr)
|
| 262 |
+
self._add_dependencies(key)
|
| 263 |
+
self._put(key, typ, from_assignment)
|
| 264 |
+
|
| 265 |
+
def unreachable(self) -> None:
|
| 266 |
+
self.version += 1
|
| 267 |
+
self.frames[-1].unreachable = True
|
| 268 |
+
|
| 269 |
+
def suppress_unreachable_warnings(self) -> None:
|
| 270 |
+
self.frames[-1].suppress_unreachable_warnings = True
|
| 271 |
+
|
| 272 |
+
def get(self, expr: Expression) -> Type | None:
|
| 273 |
+
key = literal_hash(expr)
|
| 274 |
+
assert key is not None, "Internal error: binder tried to get non-literal"
|
| 275 |
+
found = self._get(key)
|
| 276 |
+
if found is None:
|
| 277 |
+
return None
|
| 278 |
+
return found.type
|
| 279 |
+
|
| 280 |
+
def is_unreachable(self) -> bool:
|
| 281 |
+
# TODO: Copy the value of unreachable into new frames to avoid
|
| 282 |
+
# this traversal on every statement?
|
| 283 |
+
return any(f.unreachable for f in self.frames)
|
| 284 |
+
|
| 285 |
+
def is_unreachable_warning_suppressed(self) -> bool:
|
| 286 |
+
return any(f.suppress_unreachable_warnings for f in self.frames)
|
| 287 |
+
|
| 288 |
+
def cleanse(self, expr: Expression) -> None:
|
| 289 |
+
"""Remove all references to a Node from the binder."""
|
| 290 |
+
key = literal_hash(expr)
|
| 291 |
+
assert key is not None, "Internal error: binder tried cleanse non-literal"
|
| 292 |
+
self._cleanse_key(key)
|
| 293 |
+
|
| 294 |
+
def _cleanse_key(self, key: Key) -> None:
|
| 295 |
+
"""Remove all references to a key from the binder."""
|
| 296 |
+
for frame in self.frames:
|
| 297 |
+
if key in frame.types:
|
| 298 |
+
del frame.types[key]
|
| 299 |
+
|
| 300 |
+
def update_from_options(self, frames: list[Frame]) -> bool:
|
| 301 |
+
"""Update the frame to reflect that each key will be updated
|
| 302 |
+
as in one of the frames. Return whether any item changes.
|
| 303 |
+
|
| 304 |
+
If a key is declared as AnyType, only update it if all the
|
| 305 |
+
options are the same.
|
| 306 |
+
"""
|
| 307 |
+
all_reachable = all(not f.unreachable for f in frames)
|
| 308 |
+
if not all_reachable:
|
| 309 |
+
frames = [f for f in frames if not f.unreachable]
|
| 310 |
+
changed = False
|
| 311 |
+
keys = [key for f in frames for key in f.types]
|
| 312 |
+
if len(keys) > 1:
|
| 313 |
+
keys = list(set(keys))
|
| 314 |
+
for key in keys:
|
| 315 |
+
current_value = self._get(key)
|
| 316 |
+
resulting_values = [f.types.get(key, current_value) for f in frames]
|
| 317 |
+
# Keys can be narrowed using two different semantics. The new semantics
|
| 318 |
+
# is enabled for inferred variables when bind_all is true, and it allows
|
| 319 |
+
# variable types to be widened using subsequent assignments. This is
|
| 320 |
+
# not allowed for instance attributes and annotated variables.
|
| 321 |
+
var = extract_var_from_literal_hash(key)
|
| 322 |
+
old_semantics = (
|
| 323 |
+
not self.bind_all or var is None or not var.is_inferred and not var.is_argument
|
| 324 |
+
)
|
| 325 |
+
if old_semantics and any(x is None for x in resulting_values):
|
| 326 |
+
# We didn't know anything about key before
|
| 327 |
+
# (current_value must be None), and we still don't
|
| 328 |
+
# know anything about key in at least one possible frame.
|
| 329 |
+
continue
|
| 330 |
+
|
| 331 |
+
resulting_values = [x for x in resulting_values if x is not None]
|
| 332 |
+
|
| 333 |
+
if all_reachable and all(not x.from_assignment for x in resulting_values):
|
| 334 |
+
# Do not synthesize a new type if we encountered a conditional block
|
| 335 |
+
# (if, while or match-case) without assignments.
|
| 336 |
+
# See check-isinstance.test::testNoneCheckDoesNotMakeTypeVarOptional
|
| 337 |
+
# This is a safe assumption: the fact that we checked something with `is`
|
| 338 |
+
# or `isinstance` does not change the type of the value.
|
| 339 |
+
continue
|
| 340 |
+
|
| 341 |
+
# Remove exact duplicates to save pointless work later, this is
|
| 342 |
+
# a micro-optimization for --allow-redefinition-new.
|
| 343 |
+
seen_types = set()
|
| 344 |
+
resulting_types = []
|
| 345 |
+
for rv in resulting_values:
|
| 346 |
+
assert rv is not None
|
| 347 |
+
if rv.type in seen_types:
|
| 348 |
+
continue
|
| 349 |
+
resulting_types.append(rv.type)
|
| 350 |
+
seen_types.add(rv.type)
|
| 351 |
+
|
| 352 |
+
type = resulting_types[0]
|
| 353 |
+
declaration_type = get_proper_type(self.declarations.get(key))
|
| 354 |
+
if isinstance(declaration_type, AnyType):
|
| 355 |
+
# At this point resulting values can't contain None, see continue above
|
| 356 |
+
if not all(is_same_type(type, t) for t in resulting_types[1:]):
|
| 357 |
+
type = AnyType(TypeOfAny.from_another_any, source_any=declaration_type)
|
| 358 |
+
else:
|
| 359 |
+
possible_types = []
|
| 360 |
+
for t in resulting_types:
|
| 361 |
+
assert t is not None
|
| 362 |
+
possible_types.append(t)
|
| 363 |
+
if len(possible_types) == 1:
|
| 364 |
+
# This is to avoid calling get_proper_type() unless needed, as this may
|
| 365 |
+
# interfere with our (hacky) TypeGuard support.
|
| 366 |
+
type = possible_types[0]
|
| 367 |
+
else:
|
| 368 |
+
type = make_simplified_union(possible_types)
|
| 369 |
+
# Legacy guard for corner case when the original type is TypeVarType.
|
| 370 |
+
if isinstance(declaration_type, TypeVarType) and not is_subtype(
|
| 371 |
+
type, declaration_type
|
| 372 |
+
):
|
| 373 |
+
type = declaration_type
|
| 374 |
+
# Try simplifying resulting type for unions involving variadic tuples.
|
| 375 |
+
# Technically, everything is still valid without this step, but if we do
|
| 376 |
+
# not do this, this may create long unions after exiting an if check like:
|
| 377 |
+
# x: tuple[int, ...]
|
| 378 |
+
# if len(x) < 10:
|
| 379 |
+
# ...
|
| 380 |
+
# We want the type of x to be tuple[int, ...] after this block (if it is
|
| 381 |
+
# still equivalent to such type).
|
| 382 |
+
if isinstance(type, UnionType):
|
| 383 |
+
type = collapse_variadic_union(type)
|
| 384 |
+
if (
|
| 385 |
+
old_semantics
|
| 386 |
+
and isinstance(type, ProperType)
|
| 387 |
+
and isinstance(type, UnionType)
|
| 388 |
+
):
|
| 389 |
+
# Simplify away any extra Any's that were added to the declared
|
| 390 |
+
# type when popping a frame.
|
| 391 |
+
simplified = UnionType.make_union(
|
| 392 |
+
[t for t in type.items if not isinstance(get_proper_type(t), AnyType)]
|
| 393 |
+
)
|
| 394 |
+
if simplified == self.declarations[key]:
|
| 395 |
+
type = simplified
|
| 396 |
+
if (
|
| 397 |
+
current_value is None
|
| 398 |
+
or not is_same_type(type, current_value.type)
|
| 399 |
+
# Manually carry over any narrowing from hasattr() from inner frames. This is
|
| 400 |
+
# a bit ad-hoc, but our handling of hasattr() is on best effort basis anyway.
|
| 401 |
+
or isinstance(p_type := get_proper_type(type), Instance)
|
| 402 |
+
and p_type.extra_attrs
|
| 403 |
+
):
|
| 404 |
+
self._put(key, type, from_assignment=True)
|
| 405 |
+
if current_value is not None or extract_var_from_literal_hash(key) is None:
|
| 406 |
+
# We definitely learned something new
|
| 407 |
+
changed = True
|
| 408 |
+
elif not changed:
|
| 409 |
+
# If there is no current value compare with the declaration. This prevents
|
| 410 |
+
# reporting false changes in cases like this:
|
| 411 |
+
# x: int
|
| 412 |
+
# if foo():
|
| 413 |
+
# x = 1
|
| 414 |
+
# else:
|
| 415 |
+
# x = 2
|
| 416 |
+
# We check partial types and widening in accept_loop() separately, so
|
| 417 |
+
# this should be safe.
|
| 418 |
+
changed = declaration_type is not None and not is_same_type(
|
| 419 |
+
type, declaration_type
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
self.frames[-1].unreachable = not frames
|
| 423 |
+
|
| 424 |
+
return changed
|
| 425 |
+
|
| 426 |
+
def pop_frame(self, can_skip: bool, fall_through: int, *, discard: bool = False) -> Frame:
|
| 427 |
+
"""Pop a frame and return it.
|
| 428 |
+
|
| 429 |
+
See frame_context() for documentation of fall_through and discard.
|
| 430 |
+
"""
|
| 431 |
+
|
| 432 |
+
if fall_through > 0:
|
| 433 |
+
self.allow_jump(-fall_through)
|
| 434 |
+
|
| 435 |
+
result = self.frames.pop()
|
| 436 |
+
options = self.options_on_return.pop()
|
| 437 |
+
|
| 438 |
+
if discard:
|
| 439 |
+
self.last_pop_changed = False
|
| 440 |
+
return result
|
| 441 |
+
|
| 442 |
+
if can_skip:
|
| 443 |
+
options.insert(0, self.frames[-1])
|
| 444 |
+
|
| 445 |
+
self.last_pop_changed = self.update_from_options(options)
|
| 446 |
+
|
| 447 |
+
return result
|
| 448 |
+
|
| 449 |
+
@contextmanager
|
| 450 |
+
def accumulate_type_assignments(self) -> Iterator[Assigns]:
|
| 451 |
+
"""Push a new map to collect assigned types in multiassign from union.
|
| 452 |
+
|
| 453 |
+
If this map is not None, actual binding is deferred until all items in
|
| 454 |
+
the union are processed (a union of collected items is later bound
|
| 455 |
+
manually by the caller).
|
| 456 |
+
"""
|
| 457 |
+
old_assignments = None
|
| 458 |
+
if self.type_assignments is not None:
|
| 459 |
+
old_assignments = self.type_assignments
|
| 460 |
+
self.type_assignments = defaultdict(list)
|
| 461 |
+
yield self.type_assignments
|
| 462 |
+
self.type_assignments = old_assignments
|
| 463 |
+
|
| 464 |
+
def assign_type(self, expr: Expression, type: Type, declared_type: Type | None) -> None:
|
| 465 |
+
"""Narrow type of expression through an assignment.
|
| 466 |
+
|
| 467 |
+
Do nothing if the expression doesn't support narrowing.
|
| 468 |
+
|
| 469 |
+
When not narrowing though an assignment (isinstance() etc.), use put()
|
| 470 |
+
directly. This omits some special-casing logic for assignments.
|
| 471 |
+
"""
|
| 472 |
+
# We should erase last known value in binder, because if we are using it,
|
| 473 |
+
# it means that the target is not final, and therefore can't hold a literal.
|
| 474 |
+
type = remove_instance_last_known_values(type)
|
| 475 |
+
|
| 476 |
+
if self.type_assignments is not None:
|
| 477 |
+
# We are in a multiassign from union, defer the actual binding,
|
| 478 |
+
# just collect the types.
|
| 479 |
+
self.type_assignments[expr].append((type, declared_type))
|
| 480 |
+
return
|
| 481 |
+
if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)):
|
| 482 |
+
return
|
| 483 |
+
if not literal(expr):
|
| 484 |
+
return
|
| 485 |
+
self.invalidate_dependencies(expr)
|
| 486 |
+
|
| 487 |
+
if declared_type is None:
|
| 488 |
+
# Not sure why this happens. It seems to mainly happen in
|
| 489 |
+
# member initialization.
|
| 490 |
+
return
|
| 491 |
+
if not is_subtype(type, declared_type):
|
| 492 |
+
# Pretty sure this is only happens when there's a type error.
|
| 493 |
+
|
| 494 |
+
# Ideally this function wouldn't be called if the
|
| 495 |
+
# expression has a type error, though -- do other kinds of
|
| 496 |
+
# errors cause this function to get called at invalid
|
| 497 |
+
# times?
|
| 498 |
+
return
|
| 499 |
+
|
| 500 |
+
p_declared = get_proper_type(declared_type)
|
| 501 |
+
p_type = get_proper_type(type)
|
| 502 |
+
if isinstance(p_type, AnyType):
|
| 503 |
+
# Any type requires some special casing, for both historical reasons,
|
| 504 |
+
# and to optimise user experience without sacrificing correctness too much.
|
| 505 |
+
if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred:
|
| 506 |
+
# First case: a local/global variable without explicit annotation,
|
| 507 |
+
# in this case we just assign Any (essentially following the SSA logic).
|
| 508 |
+
self.put(expr, type)
|
| 509 |
+
elif isinstance(p_declared, UnionType):
|
| 510 |
+
all_items = flatten_nested_unions(p_declared.items)
|
| 511 |
+
if any(isinstance(get_proper_type(item), NoneType) for item in all_items):
|
| 512 |
+
# Second case: explicit optional type, in this case we optimize for
|
| 513 |
+
# a common pattern when an untyped value used as a fallback replacing None.
|
| 514 |
+
new_items = [
|
| 515 |
+
type if isinstance(get_proper_type(item), NoneType) else item
|
| 516 |
+
for item in all_items
|
| 517 |
+
]
|
| 518 |
+
self.put(expr, UnionType(new_items))
|
| 519 |
+
elif any(isinstance(get_proper_type(item), AnyType) for item in all_items):
|
| 520 |
+
# Third case: a union already containing Any (most likely from
|
| 521 |
+
# an un-imported name), in this case we allow assigning Any as well.
|
| 522 |
+
self.put(expr, type)
|
| 523 |
+
else:
|
| 524 |
+
# In all other cases we don't narrow to Any to minimize false negatives.
|
| 525 |
+
self.put(expr, declared_type)
|
| 526 |
+
else:
|
| 527 |
+
self.put(expr, declared_type)
|
| 528 |
+
elif isinstance(p_declared, AnyType):
|
| 529 |
+
# Mirroring the first case above, we don't narrow to a precise type if the variable
|
| 530 |
+
# has an explicit `Any` type annotation.
|
| 531 |
+
if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred:
|
| 532 |
+
self.put(expr, type)
|
| 533 |
+
else:
|
| 534 |
+
self.put(expr, declared_type)
|
| 535 |
+
else:
|
| 536 |
+
self.put(expr, type)
|
| 537 |
+
|
| 538 |
+
for i in self.try_frames:
|
| 539 |
+
# XXX This should probably not copy the entire frame, but
|
| 540 |
+
# just copy this variable into a single stored frame.
|
| 541 |
+
self.allow_jump(i)
|
| 542 |
+
|
| 543 |
+
def invalidate_dependencies(self, expr: BindableExpression) -> None:
|
| 544 |
+
"""Invalidate knowledge of types that include expr, but not expr itself.
|
| 545 |
+
|
| 546 |
+
For example, when expr is foo.bar, invalidate foo.bar.baz.
|
| 547 |
+
|
| 548 |
+
It is overly conservative: it invalidates globally, including
|
| 549 |
+
in code paths unreachable from here.
|
| 550 |
+
"""
|
| 551 |
+
key = literal_hash(expr)
|
| 552 |
+
assert key is not None
|
| 553 |
+
for dep in self.dependencies.get(key, set()):
|
| 554 |
+
self._cleanse_key(dep)
|
| 555 |
+
|
| 556 |
+
def allow_jump(self, index: int) -> None:
|
| 557 |
+
# self.frames and self.options_on_return have different lengths
|
| 558 |
+
# so make sure the index is positive
|
| 559 |
+
if index < 0:
|
| 560 |
+
index += len(self.options_on_return)
|
| 561 |
+
frame = Frame(self._get_id())
|
| 562 |
+
for f in self.frames[index + 1 :]:
|
| 563 |
+
frame.types.update(f.types)
|
| 564 |
+
if f.unreachable:
|
| 565 |
+
frame.unreachable = True
|
| 566 |
+
self.options_on_return[index].append(frame)
|
| 567 |
+
|
| 568 |
+
def handle_break(self) -> None:
|
| 569 |
+
self.allow_jump(self.break_frames[-1])
|
| 570 |
+
self.unreachable()
|
| 571 |
+
|
| 572 |
+
def handle_continue(self) -> None:
|
| 573 |
+
self.allow_jump(self.continue_frames[-1])
|
| 574 |
+
self.unreachable()
|
| 575 |
+
|
| 576 |
+
def frame_context(
|
| 577 |
+
self,
|
| 578 |
+
*,
|
| 579 |
+
can_skip: bool,
|
| 580 |
+
fall_through: int = 1,
|
| 581 |
+
break_frame: int = 0,
|
| 582 |
+
continue_frame: int = 0,
|
| 583 |
+
conditional_frame: bool = False,
|
| 584 |
+
try_frame: bool = False,
|
| 585 |
+
discard: bool = False,
|
| 586 |
+
) -> FrameContext:
|
| 587 |
+
"""Return a context manager that pushes/pops frames on enter/exit.
|
| 588 |
+
|
| 589 |
+
If can_skip is True, control flow is allowed to bypass the
|
| 590 |
+
newly-created frame.
|
| 591 |
+
|
| 592 |
+
If fall_through > 0, then it will allow control flow that
|
| 593 |
+
falls off the end of the frame to escape to its ancestor
|
| 594 |
+
`fall_through` levels higher. Otherwise, control flow ends
|
| 595 |
+
at the end of the frame.
|
| 596 |
+
|
| 597 |
+
If break_frame > 0, then 'break' statements within this frame
|
| 598 |
+
will jump out to the frame break_frame levels higher than the
|
| 599 |
+
frame created by this call to frame_context. Similarly, for
|
| 600 |
+
continue_frame and 'continue' statements.
|
| 601 |
+
|
| 602 |
+
If try_frame is true, then execution is allowed to jump at any
|
| 603 |
+
point within the newly created frame (or its descendants) to
|
| 604 |
+
its parent (i.e., to the frame that was on top before this
|
| 605 |
+
call to frame_context).
|
| 606 |
+
|
| 607 |
+
If discard is True, then this is a temporary throw-away frame
|
| 608 |
+
(used e.g. for isolation) and its effect will be discarded on pop.
|
| 609 |
+
|
| 610 |
+
After the context manager exits, self.last_pop_changed indicates
|
| 611 |
+
whether any types changed in the newly-topmost frame as a result
|
| 612 |
+
of popping this frame.
|
| 613 |
+
"""
|
| 614 |
+
return FrameContext(
|
| 615 |
+
self,
|
| 616 |
+
can_skip=can_skip,
|
| 617 |
+
fall_through=fall_through,
|
| 618 |
+
break_frame=break_frame,
|
| 619 |
+
continue_frame=continue_frame,
|
| 620 |
+
conditional_frame=conditional_frame,
|
| 621 |
+
try_frame=try_frame,
|
| 622 |
+
discard=discard,
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
@contextmanager
|
| 626 |
+
def top_frame_context(self) -> Iterator[Frame]:
|
| 627 |
+
"""A variant of frame_context for use at the top level of
|
| 628 |
+
a namespace (module, function, or class).
|
| 629 |
+
"""
|
| 630 |
+
assert len(self.frames) == 1
|
| 631 |
+
yield self.push_frame()
|
| 632 |
+
self.pop_frame(True, 0)
|
| 633 |
+
assert len(self.frames) == 1
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def get_declaration(expr: BindableExpression) -> Type | None:
|
| 637 |
+
"""Get the declared or inferred type of a RefExpr expression.
|
| 638 |
+
|
| 639 |
+
Return None if there is no type or the expression is not a RefExpr.
|
| 640 |
+
This can return None if the type hasn't been inferred yet.
|
| 641 |
+
"""
|
| 642 |
+
if isinstance(expr, RefExpr):
|
| 643 |
+
if isinstance(expr.node, Var):
|
| 644 |
+
type = expr.node.type
|
| 645 |
+
if not isinstance(get_proper_type(type), PartialType):
|
| 646 |
+
return type
|
| 647 |
+
elif isinstance(expr.node, TypeInfo):
|
| 648 |
+
return TypeType(fill_typevars_with_any(expr.node))
|
| 649 |
+
return None
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def collapse_variadic_union(typ: UnionType) -> Type:
|
| 653 |
+
"""Simplify a union involving variadic tuple if possible.
|
| 654 |
+
|
| 655 |
+
This will collapse a type like e.g.
|
| 656 |
+
tuple[X, Z] | tuple[X, Y, Z] | tuple[X, Y, Y, *tuple[Y, ...], Z]
|
| 657 |
+
back to
|
| 658 |
+
tuple[X, *tuple[Y, ...], Z]
|
| 659 |
+
which is equivalent, but much simpler form of the same type.
|
| 660 |
+
"""
|
| 661 |
+
tuple_items = []
|
| 662 |
+
other_items = []
|
| 663 |
+
for t in typ.items:
|
| 664 |
+
p_t = get_proper_type(t)
|
| 665 |
+
if isinstance(p_t, TupleType):
|
| 666 |
+
tuple_items.append(p_t)
|
| 667 |
+
else:
|
| 668 |
+
other_items.append(t)
|
| 669 |
+
if len(tuple_items) <= 1:
|
| 670 |
+
# This type cannot be simplified further.
|
| 671 |
+
return typ
|
| 672 |
+
tuple_items = sorted(tuple_items, key=lambda t: len(t.items))
|
| 673 |
+
first = tuple_items[0]
|
| 674 |
+
last = tuple_items[-1]
|
| 675 |
+
unpack_index = find_unpack_in_list(last.items)
|
| 676 |
+
if unpack_index is None:
|
| 677 |
+
return typ
|
| 678 |
+
unpack = last.items[unpack_index]
|
| 679 |
+
assert isinstance(unpack, UnpackType)
|
| 680 |
+
unpacked = get_proper_type(unpack.type)
|
| 681 |
+
if not isinstance(unpacked, Instance):
|
| 682 |
+
return typ
|
| 683 |
+
assert unpacked.type.fullname == "builtins.tuple"
|
| 684 |
+
suffix = last.items[unpack_index + 1 :]
|
| 685 |
+
|
| 686 |
+
# Check that first item matches the expected pattern and infer prefix.
|
| 687 |
+
if len(first.items) < len(suffix):
|
| 688 |
+
return typ
|
| 689 |
+
if suffix and first.items[-len(suffix) :] != suffix:
|
| 690 |
+
return typ
|
| 691 |
+
if suffix:
|
| 692 |
+
prefix = first.items[: -len(suffix)]
|
| 693 |
+
else:
|
| 694 |
+
prefix = first.items
|
| 695 |
+
|
| 696 |
+
# Check that all middle types match the expected pattern as well.
|
| 697 |
+
arg = unpacked.args[0]
|
| 698 |
+
for i, it in enumerate(tuple_items[1:-1]):
|
| 699 |
+
if it.items != prefix + [arg] * (i + 1) + suffix:
|
| 700 |
+
return typ
|
| 701 |
+
|
| 702 |
+
# Check the last item (the one with unpack), and choose an appropriate simplified type.
|
| 703 |
+
if last.items != prefix + [arg] * (len(typ.items) - 1) + [unpack] + suffix:
|
| 704 |
+
return typ
|
| 705 |
+
if len(first.items) == 0:
|
| 706 |
+
simplified: Type = unpacked.copy_modified()
|
| 707 |
+
else:
|
| 708 |
+
simplified = TupleType(prefix + [unpack] + suffix, fallback=last.partial_fallback)
|
| 709 |
+
return UnionType.make_union([simplified] + other_items)
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/bogus_type.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A Bogus[T] type alias for marking when we subvert the type system
|
| 2 |
+
|
| 3 |
+
We need this for compiling with mypyc, which inserts runtime
|
| 4 |
+
typechecks that cause problems when we subvert the type system. So
|
| 5 |
+
when compiling with mypyc, we turn those places into Any, while
|
| 6 |
+
keeping the types around for normal typechecks.
|
| 7 |
+
|
| 8 |
+
Since this causes the runtime types to be Any, this is best used
|
| 9 |
+
in places where efficient access to properties is not important.
|
| 10 |
+
For those cases some other technique should be used.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from typing import Any, TypeVar
|
| 16 |
+
|
| 17 |
+
from mypy_extensions import FlexibleAlias
|
| 18 |
+
|
| 19 |
+
T = TypeVar("T")
|
| 20 |
+
|
| 21 |
+
# This won't ever be true at runtime, but we consider it true during
|
| 22 |
+
# mypyc compilations.
|
| 23 |
+
MYPYC = False
|
| 24 |
+
if MYPYC:
|
| 25 |
+
Bogus = FlexibleAlias[T, Any]
|
| 26 |
+
else:
|
| 27 |
+
Bogus = FlexibleAlias[T, T]
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/build.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/cache.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module contains high-level logic for fixed format serialization.
|
| 3 |
+
|
| 4 |
+
Lower-level parts are implemented in C in mypyc/lib-rt/internal/librt_internal.c
|
| 5 |
+
Short summary of low-level functionality:
|
| 6 |
+
* integers are automatically serialized as 1, 2, or 4 bytes, or arbitrary length.
|
| 7 |
+
* str/bytes are serialized as size (1, 2, or 4 bytes) followed by bytes buffer.
|
| 8 |
+
* floats are serialized as C doubles.
|
| 9 |
+
|
| 10 |
+
At high-level we add type tags as needed so that our format is self-descriptive.
|
| 11 |
+
More precisely:
|
| 12 |
+
* False, True, and None are stored as just a tag: 0, 1, 2 correspondingly.
|
| 13 |
+
* builtin primitives like int/str/bytes/float are stored as their type tag followed
|
| 14 |
+
by bare (low-level) representation of the value. Reserved tag range for primitives is
|
| 15 |
+
3 ... 19.
|
| 16 |
+
* generic (heterogeneous) list are stored as tag, followed by bare size, followed by
|
| 17 |
+
sequence of tagged values.
|
| 18 |
+
* homogeneous lists of primitives are stored as tag, followed by bare size, followed
|
| 19 |
+
by sequence of bare values.
|
| 20 |
+
* reserved tag range for sequence-like builtins is 20 ... 29
|
| 21 |
+
* currently we have only one mapping-like format: string-keyed dictionary with heterogeneous
|
| 22 |
+
values. It is stored as tag, followed by bare size, followed by sequence of pairs: bare
|
| 23 |
+
string key followed by tagged value.
|
| 24 |
+
* reserved tag range for mapping-like builtins is 30 ... 39
|
| 25 |
+
* there is an additional reserved tag range 40 ... 49 for any other builtin collections.
|
| 26 |
+
* custom classes (like types, symbols etc.) are stored as tag, followed by a sequence of
|
| 27 |
+
tagged field values, followed by a special end tag 255. Names of class fields are
|
| 28 |
+
*not* stored, the caller should know the field names and order for the given class tag.
|
| 29 |
+
* reserved tag range for symbols (TypeInfo, Var, etc) is 50 ... 79.
|
| 30 |
+
* class Instance is the only exception from the above format (since it is the most common one).
|
| 31 |
+
It has two extra formats: few most common instances like "builtins.object" are stored as
|
| 32 |
+
instance tag followed by a secondary tag, other plain non-generic instances are stored as
|
| 33 |
+
instance tag followed by secondary tag followed by fullname as bare string. All generic
|
| 34 |
+
readers must handle these.
|
| 35 |
+
* reserved tag range for Instance type formats is 80 ... 99, for other types it is 100 ... 149.
|
| 36 |
+
* tag 254 is reserved for if we would ever need to extend the tag range to indicated second tag
|
| 37 |
+
page. Tags 150 ... 253 are free for everything else (e.g. AST nodes etc).
|
| 38 |
+
|
| 39 |
+
General convention is that custom classes implement write() and read() methods for FF
|
| 40 |
+
serialization. The write method should write both class tag and end tag. The read method
|
| 41 |
+
conventionally *does not* read the start tag (to simplify logic for unions). Known exceptions
|
| 42 |
+
are MypyFile.read() and SymbolTableNode.read(), since those two never appear in a union.
|
| 43 |
+
|
| 44 |
+
If any of these details change, or if the structure of CacheMeta changes please
|
| 45 |
+
bump CACHE_VERSION below.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
from __future__ import annotations
|
| 49 |
+
|
| 50 |
+
from collections.abc import Sequence
|
| 51 |
+
from typing import Any, Final, TypeAlias as _TypeAlias
|
| 52 |
+
|
| 53 |
+
from librt.internal import (
|
| 54 |
+
ReadBuffer as ReadBuffer,
|
| 55 |
+
WriteBuffer as WriteBuffer,
|
| 56 |
+
read_bool as read_bool,
|
| 57 |
+
read_bytes as read_bytes_bare,
|
| 58 |
+
read_float as read_float_bare,
|
| 59 |
+
read_int as read_int_bare,
|
| 60 |
+
read_str as read_str_bare,
|
| 61 |
+
read_tag as read_tag,
|
| 62 |
+
write_bool as write_bool,
|
| 63 |
+
write_bytes as write_bytes_bare,
|
| 64 |
+
write_float as write_float_bare,
|
| 65 |
+
write_int as write_int_bare,
|
| 66 |
+
write_str as write_str_bare,
|
| 67 |
+
write_tag as write_tag,
|
| 68 |
+
)
|
| 69 |
+
from mypy_extensions import u8
|
| 70 |
+
|
| 71 |
+
# High-level cache layout format
|
| 72 |
+
CACHE_VERSION: Final = 7
|
| 73 |
+
|
| 74 |
+
# Type used internally to represent errors:
|
| 75 |
+
# (path, line, column, end_line, end_column, severity, message, code)
|
| 76 |
+
ErrorTuple: _TypeAlias = tuple[str | None, int, int, int, int, str, str, str | None]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class CacheMeta:
|
| 80 |
+
"""Class representing cache metadata for a module."""
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
*,
|
| 85 |
+
id: str,
|
| 86 |
+
path: str,
|
| 87 |
+
mtime: int,
|
| 88 |
+
size: int,
|
| 89 |
+
hash: str,
|
| 90 |
+
dependencies: list[str],
|
| 91 |
+
data_mtime: int,
|
| 92 |
+
data_file: str,
|
| 93 |
+
suppressed: list[str],
|
| 94 |
+
imports_ignored: dict[int, list[str]],
|
| 95 |
+
options: dict[str, object],
|
| 96 |
+
suppressed_deps_opts: bytes,
|
| 97 |
+
dep_prios: list[int],
|
| 98 |
+
dep_lines: list[int],
|
| 99 |
+
dep_hashes: list[bytes],
|
| 100 |
+
interface_hash: bytes,
|
| 101 |
+
trans_dep_hash: bytes,
|
| 102 |
+
version_id: str,
|
| 103 |
+
ignore_all: bool,
|
| 104 |
+
plugin_data: Any,
|
| 105 |
+
) -> None:
|
| 106 |
+
self.id = id
|
| 107 |
+
self.path = path
|
| 108 |
+
self.mtime = mtime # source file mtime
|
| 109 |
+
self.size = size # source file size
|
| 110 |
+
self.hash = hash # source file hash (as a hex string for historical reasons)
|
| 111 |
+
self.dependencies = dependencies # names of imported modules
|
| 112 |
+
self.data_mtime = data_mtime # mtime of data_file
|
| 113 |
+
self.data_file = data_file # path of <id>.data.json or <id>.data.ff
|
| 114 |
+
self.suppressed = suppressed # dependencies that weren't imported
|
| 115 |
+
self.imports_ignored = imports_ignored # type ignore codes by line
|
| 116 |
+
self.options = options # build options snapshot
|
| 117 |
+
self.suppressed_deps_opts = suppressed_deps_opts # hash of import-related options
|
| 118 |
+
# dep_prios and dep_lines are both aligned with dependencies + suppressed
|
| 119 |
+
self.dep_prios = dep_prios
|
| 120 |
+
self.dep_lines = dep_lines
|
| 121 |
+
# dep_hashes list is aligned with dependencies only
|
| 122 |
+
self.dep_hashes = dep_hashes # list of interface_hash for dependencies
|
| 123 |
+
self.interface_hash = interface_hash # hash representing the public interface
|
| 124 |
+
self.trans_dep_hash = trans_dep_hash # hash of import structure (transitive)
|
| 125 |
+
self.version_id = version_id # mypy version for cache invalidation
|
| 126 |
+
self.ignore_all = ignore_all # if errors were ignored
|
| 127 |
+
self.plugin_data = plugin_data # config data from plugins
|
| 128 |
+
|
| 129 |
+
def serialize(self) -> dict[str, Any]:
|
| 130 |
+
return {
|
| 131 |
+
"id": self.id,
|
| 132 |
+
"path": self.path,
|
| 133 |
+
"mtime": self.mtime,
|
| 134 |
+
"size": self.size,
|
| 135 |
+
"hash": self.hash,
|
| 136 |
+
"data_mtime": self.data_mtime,
|
| 137 |
+
"dependencies": self.dependencies,
|
| 138 |
+
"suppressed": self.suppressed,
|
| 139 |
+
"imports_ignored": {str(line): codes for line, codes in self.imports_ignored.items()},
|
| 140 |
+
"options": self.options,
|
| 141 |
+
"suppressed_deps_opts": self.suppressed_deps_opts.hex(),
|
| 142 |
+
"dep_prios": self.dep_prios,
|
| 143 |
+
"dep_lines": self.dep_lines,
|
| 144 |
+
"dep_hashes": [dep.hex() for dep in self.dep_hashes],
|
| 145 |
+
"interface_hash": self.interface_hash.hex(),
|
| 146 |
+
"trans_dep_hash": self.trans_dep_hash.hex(),
|
| 147 |
+
"version_id": self.version_id,
|
| 148 |
+
"ignore_all": self.ignore_all,
|
| 149 |
+
"plugin_data": self.plugin_data,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def deserialize(cls, meta: dict[str, Any], data_file: str) -> CacheMeta | None:
|
| 154 |
+
try:
|
| 155 |
+
return CacheMeta(
|
| 156 |
+
id=meta["id"],
|
| 157 |
+
path=meta["path"],
|
| 158 |
+
mtime=meta["mtime"],
|
| 159 |
+
size=meta["size"],
|
| 160 |
+
hash=meta["hash"],
|
| 161 |
+
dependencies=meta["dependencies"],
|
| 162 |
+
data_mtime=meta["data_mtime"],
|
| 163 |
+
data_file=data_file,
|
| 164 |
+
suppressed=meta["suppressed"],
|
| 165 |
+
imports_ignored={
|
| 166 |
+
int(line): codes for line, codes in meta["imports_ignored"].items()
|
| 167 |
+
},
|
| 168 |
+
options=meta["options"],
|
| 169 |
+
suppressed_deps_opts=bytes.fromhex(meta["suppressed_deps_opts"]),
|
| 170 |
+
dep_prios=meta["dep_prios"],
|
| 171 |
+
dep_lines=meta["dep_lines"],
|
| 172 |
+
dep_hashes=[bytes.fromhex(dep) for dep in meta["dep_hashes"]],
|
| 173 |
+
interface_hash=bytes.fromhex(meta["interface_hash"]),
|
| 174 |
+
trans_dep_hash=bytes.fromhex(meta["trans_dep_hash"]),
|
| 175 |
+
version_id=meta["version_id"],
|
| 176 |
+
ignore_all=meta["ignore_all"],
|
| 177 |
+
plugin_data=meta["plugin_data"],
|
| 178 |
+
)
|
| 179 |
+
except (KeyError, ValueError):
|
| 180 |
+
return None
|
| 181 |
+
|
| 182 |
+
def write(self, data: WriteBuffer) -> None:
|
| 183 |
+
write_str(data, self.id)
|
| 184 |
+
write_str(data, self.path)
|
| 185 |
+
write_int(data, self.mtime)
|
| 186 |
+
write_int(data, self.size)
|
| 187 |
+
write_str(data, self.hash)
|
| 188 |
+
write_str_list(data, self.dependencies)
|
| 189 |
+
write_int(data, self.data_mtime)
|
| 190 |
+
write_str_list(data, self.suppressed)
|
| 191 |
+
write_int_bare(data, len(self.imports_ignored))
|
| 192 |
+
for line, codes in self.imports_ignored.items():
|
| 193 |
+
write_int(data, line)
|
| 194 |
+
write_str_list(data, codes)
|
| 195 |
+
write_json(data, self.options)
|
| 196 |
+
write_bytes(data, self.suppressed_deps_opts)
|
| 197 |
+
write_int_list(data, self.dep_prios)
|
| 198 |
+
write_int_list(data, self.dep_lines)
|
| 199 |
+
write_bytes_list(data, self.dep_hashes)
|
| 200 |
+
write_bytes(data, self.interface_hash)
|
| 201 |
+
write_bytes(data, self.trans_dep_hash)
|
| 202 |
+
write_str(data, self.version_id)
|
| 203 |
+
write_bool(data, self.ignore_all)
|
| 204 |
+
# Plugin data may be not a dictionary, so we use
|
| 205 |
+
# a more generic write_json_value() here.
|
| 206 |
+
write_json_value(data, self.plugin_data)
|
| 207 |
+
|
| 208 |
+
@classmethod
|
| 209 |
+
def read(cls, data: ReadBuffer, data_file: str) -> CacheMeta | None:
|
| 210 |
+
try:
|
| 211 |
+
return CacheMeta(
|
| 212 |
+
id=read_str(data),
|
| 213 |
+
path=read_str(data),
|
| 214 |
+
mtime=read_int(data),
|
| 215 |
+
size=read_int(data),
|
| 216 |
+
hash=read_str(data),
|
| 217 |
+
dependencies=read_str_list(data),
|
| 218 |
+
data_mtime=read_int(data),
|
| 219 |
+
data_file=data_file,
|
| 220 |
+
suppressed=read_str_list(data),
|
| 221 |
+
imports_ignored={
|
| 222 |
+
read_int(data): read_str_list(data) for _ in range(read_int_bare(data))
|
| 223 |
+
},
|
| 224 |
+
options=read_json(data),
|
| 225 |
+
suppressed_deps_opts=read_bytes(data),
|
| 226 |
+
dep_prios=read_int_list(data),
|
| 227 |
+
dep_lines=read_int_list(data),
|
| 228 |
+
dep_hashes=read_bytes_list(data),
|
| 229 |
+
interface_hash=read_bytes(data),
|
| 230 |
+
trans_dep_hash=read_bytes(data),
|
| 231 |
+
version_id=read_str(data),
|
| 232 |
+
ignore_all=read_bool(data),
|
| 233 |
+
plugin_data=read_json_value(data),
|
| 234 |
+
)
|
| 235 |
+
except (ValueError, AssertionError):
|
| 236 |
+
return None
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# Always use this type alias to refer to type tags.
|
| 240 |
+
Tag = u8
|
| 241 |
+
|
| 242 |
+
# Primitives.
|
| 243 |
+
LITERAL_FALSE: Final[Tag] = 0
|
| 244 |
+
LITERAL_TRUE: Final[Tag] = 1
|
| 245 |
+
LITERAL_NONE: Final[Tag] = 2
|
| 246 |
+
LITERAL_INT: Final[Tag] = 3
|
| 247 |
+
LITERAL_STR: Final[Tag] = 4
|
| 248 |
+
LITERAL_BYTES: Final[Tag] = 5
|
| 249 |
+
LITERAL_FLOAT: Final[Tag] = 6
|
| 250 |
+
LITERAL_COMPLEX: Final[Tag] = 7
|
| 251 |
+
|
| 252 |
+
# Collections.
|
| 253 |
+
LIST_GEN: Final[Tag] = 20
|
| 254 |
+
LIST_INT: Final[Tag] = 21
|
| 255 |
+
LIST_STR: Final[Tag] = 22
|
| 256 |
+
LIST_BYTES: Final[Tag] = 23
|
| 257 |
+
TUPLE_GEN: Final[Tag] = 24
|
| 258 |
+
DICT_STR_GEN: Final[Tag] = 30
|
| 259 |
+
DICT_INT_GEN: Final[Tag] = 31
|
| 260 |
+
|
| 261 |
+
# Misc classes.
|
| 262 |
+
EXTRA_ATTRS: Final[Tag] = 150
|
| 263 |
+
DT_SPEC: Final[Tag] = 151
|
| 264 |
+
# Four integers representing source file (line, column) range.
|
| 265 |
+
LOCATION: Final[Tag] = 152
|
| 266 |
+
|
| 267 |
+
END_TAG: Final[Tag] = 255
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def read_literal(data: ReadBuffer, tag: Tag) -> int | str | bool | float:
|
| 271 |
+
if tag == LITERAL_INT:
|
| 272 |
+
return read_int_bare(data)
|
| 273 |
+
elif tag == LITERAL_STR:
|
| 274 |
+
return read_str_bare(data)
|
| 275 |
+
elif tag == LITERAL_FALSE:
|
| 276 |
+
return False
|
| 277 |
+
elif tag == LITERAL_TRUE:
|
| 278 |
+
return True
|
| 279 |
+
elif tag == LITERAL_FLOAT:
|
| 280 |
+
return read_float_bare(data)
|
| 281 |
+
assert False, f"Unknown literal tag {tag}"
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
# There is an intentional asymmetry between read and write for literals because
|
| 285 |
+
# None and/or complex values are only allowed in some contexts but not in others.
|
| 286 |
+
def write_literal(data: WriteBuffer, value: int | str | bool | float | complex | None) -> None:
|
| 287 |
+
if isinstance(value, bool):
|
| 288 |
+
write_bool(data, value)
|
| 289 |
+
elif isinstance(value, int):
|
| 290 |
+
write_tag(data, LITERAL_INT)
|
| 291 |
+
write_int_bare(data, value)
|
| 292 |
+
elif isinstance(value, str):
|
| 293 |
+
write_tag(data, LITERAL_STR)
|
| 294 |
+
write_str_bare(data, value)
|
| 295 |
+
elif isinstance(value, float):
|
| 296 |
+
write_tag(data, LITERAL_FLOAT)
|
| 297 |
+
write_float_bare(data, value)
|
| 298 |
+
elif isinstance(value, complex):
|
| 299 |
+
write_tag(data, LITERAL_COMPLEX)
|
| 300 |
+
write_float_bare(data, value.real)
|
| 301 |
+
write_float_bare(data, value.imag)
|
| 302 |
+
else:
|
| 303 |
+
write_tag(data, LITERAL_NONE)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def read_int(data: ReadBuffer) -> int:
|
| 307 |
+
assert read_tag(data) == LITERAL_INT
|
| 308 |
+
return read_int_bare(data)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def write_int(data: WriteBuffer, value: int) -> None:
|
| 312 |
+
write_tag(data, LITERAL_INT)
|
| 313 |
+
write_int_bare(data, value)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def read_str(data: ReadBuffer) -> str:
|
| 317 |
+
assert read_tag(data) == LITERAL_STR
|
| 318 |
+
return read_str_bare(data)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def write_str(data: WriteBuffer, value: str) -> None:
|
| 322 |
+
write_tag(data, LITERAL_STR)
|
| 323 |
+
write_str_bare(data, value)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def read_bytes(data: ReadBuffer) -> bytes:
|
| 327 |
+
assert read_tag(data) == LITERAL_BYTES
|
| 328 |
+
return read_bytes_bare(data)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def write_bytes(data: WriteBuffer, value: bytes) -> None:
|
| 332 |
+
write_tag(data, LITERAL_BYTES)
|
| 333 |
+
write_bytes_bare(data, value)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def read_int_opt(data: ReadBuffer) -> int | None:
|
| 337 |
+
tag = read_tag(data)
|
| 338 |
+
if tag == LITERAL_NONE:
|
| 339 |
+
return None
|
| 340 |
+
assert tag == LITERAL_INT
|
| 341 |
+
return read_int_bare(data)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def write_int_opt(data: WriteBuffer, value: int | None) -> None:
|
| 345 |
+
if value is not None:
|
| 346 |
+
write_tag(data, LITERAL_INT)
|
| 347 |
+
write_int_bare(data, value)
|
| 348 |
+
else:
|
| 349 |
+
write_tag(data, LITERAL_NONE)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def read_str_opt(data: ReadBuffer) -> str | None:
|
| 353 |
+
tag = read_tag(data)
|
| 354 |
+
if tag == LITERAL_NONE:
|
| 355 |
+
return None
|
| 356 |
+
assert tag == LITERAL_STR
|
| 357 |
+
return read_str_bare(data)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def write_str_opt(data: WriteBuffer, value: str | None) -> None:
|
| 361 |
+
if value is not None:
|
| 362 |
+
write_tag(data, LITERAL_STR)
|
| 363 |
+
write_str_bare(data, value)
|
| 364 |
+
else:
|
| 365 |
+
write_tag(data, LITERAL_NONE)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def read_int_list(data: ReadBuffer) -> list[int]:
|
| 369 |
+
assert read_tag(data) == LIST_INT
|
| 370 |
+
size = read_int_bare(data)
|
| 371 |
+
return [read_int_bare(data) for _ in range(size)]
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def write_int_list(data: WriteBuffer, value: list[int]) -> None:
|
| 375 |
+
write_tag(data, LIST_INT)
|
| 376 |
+
write_int_bare(data, len(value))
|
| 377 |
+
for item in value:
|
| 378 |
+
write_int_bare(data, item)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def read_str_list(data: ReadBuffer) -> list[str]:
|
| 382 |
+
assert read_tag(data) == LIST_STR
|
| 383 |
+
size = read_int_bare(data)
|
| 384 |
+
return [read_str_bare(data) for _ in range(size)]
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def write_str_list(data: WriteBuffer, value: Sequence[str]) -> None:
|
| 388 |
+
write_tag(data, LIST_STR)
|
| 389 |
+
write_int_bare(data, len(value))
|
| 390 |
+
for item in value:
|
| 391 |
+
write_str_bare(data, item)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def read_bytes_list(data: ReadBuffer) -> list[bytes]:
|
| 395 |
+
assert read_tag(data) == LIST_BYTES
|
| 396 |
+
size = read_int_bare(data)
|
| 397 |
+
return [read_bytes_bare(data) for _ in range(size)]
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def write_bytes_list(data: WriteBuffer, value: Sequence[bytes]) -> None:
|
| 401 |
+
write_tag(data, LIST_BYTES)
|
| 402 |
+
write_int_bare(data, len(value))
|
| 403 |
+
for item in value:
|
| 404 |
+
write_bytes_bare(data, item)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def read_str_opt_list(data: ReadBuffer) -> list[str | None]:
|
| 408 |
+
assert read_tag(data) == LIST_GEN
|
| 409 |
+
size = read_int_bare(data)
|
| 410 |
+
return [read_str_opt(data) for _ in range(size)]
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def write_str_opt_list(data: WriteBuffer, value: list[str | None]) -> None:
|
| 414 |
+
write_tag(data, LIST_GEN)
|
| 415 |
+
write_int_bare(data, len(value))
|
| 416 |
+
for item in value:
|
| 417 |
+
write_str_opt(data, item)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
Value: _TypeAlias = None | int | str | bool
|
| 421 |
+
|
| 422 |
+
# Our JSON format is somewhat non-standard as we distinguish lists and tuples.
|
| 423 |
+
# This is convenient for some internal things, like mypyc plugin and error serialization.
|
| 424 |
+
JsonValue: _TypeAlias = (
|
| 425 |
+
Value | list["JsonValue"] | dict[str, "JsonValue"] | tuple["JsonValue", ...]
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def read_json_value(data: ReadBuffer) -> JsonValue:
|
| 430 |
+
tag = read_tag(data)
|
| 431 |
+
if tag == LITERAL_NONE:
|
| 432 |
+
return None
|
| 433 |
+
if tag == LITERAL_FALSE:
|
| 434 |
+
return False
|
| 435 |
+
if tag == LITERAL_TRUE:
|
| 436 |
+
return True
|
| 437 |
+
if tag == LITERAL_INT:
|
| 438 |
+
return read_int_bare(data)
|
| 439 |
+
if tag == LITERAL_STR:
|
| 440 |
+
return read_str_bare(data)
|
| 441 |
+
if tag == LIST_GEN:
|
| 442 |
+
size = read_int_bare(data)
|
| 443 |
+
return [read_json_value(data) for _ in range(size)]
|
| 444 |
+
if tag == TUPLE_GEN:
|
| 445 |
+
size = read_int_bare(data)
|
| 446 |
+
return tuple(read_json_value(data) for _ in range(size))
|
| 447 |
+
if tag == DICT_STR_GEN:
|
| 448 |
+
size = read_int_bare(data)
|
| 449 |
+
return {read_str_bare(data): read_json_value(data) for _ in range(size)}
|
| 450 |
+
assert False, f"Invalid JSON tag: {tag}"
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def write_json_value(data: WriteBuffer, value: JsonValue) -> None:
|
| 454 |
+
if value is None:
|
| 455 |
+
write_tag(data, LITERAL_NONE)
|
| 456 |
+
elif isinstance(value, bool):
|
| 457 |
+
write_bool(data, value)
|
| 458 |
+
elif isinstance(value, int):
|
| 459 |
+
write_tag(data, LITERAL_INT)
|
| 460 |
+
write_int_bare(data, value)
|
| 461 |
+
elif isinstance(value, str):
|
| 462 |
+
write_tag(data, LITERAL_STR)
|
| 463 |
+
write_str_bare(data, value)
|
| 464 |
+
elif isinstance(value, list):
|
| 465 |
+
write_tag(data, LIST_GEN)
|
| 466 |
+
write_int_bare(data, len(value))
|
| 467 |
+
for val in value:
|
| 468 |
+
write_json_value(data, val)
|
| 469 |
+
elif isinstance(value, tuple):
|
| 470 |
+
write_tag(data, TUPLE_GEN)
|
| 471 |
+
write_int_bare(data, len(value))
|
| 472 |
+
for val in value:
|
| 473 |
+
write_json_value(data, val)
|
| 474 |
+
elif isinstance(value, dict):
|
| 475 |
+
write_tag(data, DICT_STR_GEN)
|
| 476 |
+
write_int_bare(data, len(value))
|
| 477 |
+
for key in sorted(value):
|
| 478 |
+
write_str_bare(data, key)
|
| 479 |
+
write_json_value(data, value[key])
|
| 480 |
+
else:
|
| 481 |
+
assert False, f"Invalid JSON value: {value}"
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
# These are functions for JSON *dictionaries* specifically. Unfortunately, we
|
| 485 |
+
# must use imprecise types here, because the callers use imprecise types.
|
| 486 |
+
def read_json(data: ReadBuffer) -> dict[str, Any]:
|
| 487 |
+
assert read_tag(data) == DICT_STR_GEN
|
| 488 |
+
size = read_int_bare(data)
|
| 489 |
+
return {read_str_bare(data): read_json_value(data) for _ in range(size)}
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def write_json(data: WriteBuffer, value: dict[str, Any]) -> None:
|
| 493 |
+
write_tag(data, DICT_STR_GEN)
|
| 494 |
+
write_int_bare(data, len(value))
|
| 495 |
+
for key in sorted(value):
|
| 496 |
+
write_str_bare(data, key)
|
| 497 |
+
write_json_value(data, value[key])
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def write_errors(data: WriteBuffer, errs: list[ErrorTuple]) -> None:
|
| 501 |
+
write_tag(data, LIST_GEN)
|
| 502 |
+
write_int_bare(data, len(errs))
|
| 503 |
+
for path, line, column, end_line, end_column, severity, message, code in errs:
|
| 504 |
+
write_tag(data, TUPLE_GEN)
|
| 505 |
+
write_str_opt(data, path)
|
| 506 |
+
write_int(data, line)
|
| 507 |
+
write_int(data, column)
|
| 508 |
+
write_int(data, end_line)
|
| 509 |
+
write_int(data, end_column)
|
| 510 |
+
write_str(data, severity)
|
| 511 |
+
write_str(data, message)
|
| 512 |
+
write_str_opt(data, code)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def read_errors(data: ReadBuffer) -> list[ErrorTuple]:
|
| 516 |
+
assert read_tag(data) == LIST_GEN
|
| 517 |
+
result = []
|
| 518 |
+
for _ in range(read_int_bare(data)):
|
| 519 |
+
assert read_tag(data) == TUPLE_GEN
|
| 520 |
+
result.append(
|
| 521 |
+
(
|
| 522 |
+
read_str_opt(data),
|
| 523 |
+
read_int(data),
|
| 524 |
+
read_int(data),
|
| 525 |
+
read_int(data),
|
| 526 |
+
read_int(data),
|
| 527 |
+
read_str(data),
|
| 528 |
+
read_str(data),
|
| 529 |
+
read_str_opt(data),
|
| 530 |
+
)
|
| 531 |
+
)
|
| 532 |
+
return result
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared definitions used by different parts of type checker."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from abc import abstractmethod
|
| 6 |
+
from collections.abc import Iterator, Sequence, Set as AbstractSet
|
| 7 |
+
from contextlib import contextmanager
|
| 8 |
+
from typing import NamedTuple, overload
|
| 9 |
+
|
| 10 |
+
from mypy_extensions import trait
|
| 11 |
+
|
| 12 |
+
from mypy.errorcodes import ErrorCode
|
| 13 |
+
from mypy.errors import ErrorWatcher
|
| 14 |
+
from mypy.message_registry import ErrorMessage
|
| 15 |
+
from mypy.nodes import (
|
| 16 |
+
ArgKind,
|
| 17 |
+
Context,
|
| 18 |
+
Expression,
|
| 19 |
+
FuncItem,
|
| 20 |
+
LambdaExpr,
|
| 21 |
+
MypyFile,
|
| 22 |
+
Node,
|
| 23 |
+
RefExpr,
|
| 24 |
+
SymbolNode,
|
| 25 |
+
TypeInfo,
|
| 26 |
+
Var,
|
| 27 |
+
)
|
| 28 |
+
from mypy.plugin import CheckerPluginInterface, Plugin
|
| 29 |
+
from mypy.types import (
|
| 30 |
+
CallableType,
|
| 31 |
+
Instance,
|
| 32 |
+
LiteralValue,
|
| 33 |
+
Overloaded,
|
| 34 |
+
PartialType,
|
| 35 |
+
TupleType,
|
| 36 |
+
Type,
|
| 37 |
+
TypedDictType,
|
| 38 |
+
TypeType,
|
| 39 |
+
)
|
| 40 |
+
from mypy.typevars import fill_typevars
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# An object that represents either a precise type or a type with an upper bound;
|
| 44 |
+
# it is important for correct type inference with isinstance.
|
| 45 |
+
class TypeRange(NamedTuple):
|
| 46 |
+
item: Type
|
| 47 |
+
is_upper_bound: bool # False => precise type
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@trait
|
| 51 |
+
class ExpressionCheckerSharedApi:
|
| 52 |
+
@abstractmethod
|
| 53 |
+
def accept(
|
| 54 |
+
self,
|
| 55 |
+
node: Expression,
|
| 56 |
+
type_context: Type | None = None,
|
| 57 |
+
allow_none_return: bool = False,
|
| 58 |
+
always_allow_any: bool = False,
|
| 59 |
+
is_callee: bool = False,
|
| 60 |
+
) -> Type:
|
| 61 |
+
raise NotImplementedError
|
| 62 |
+
|
| 63 |
+
@abstractmethod
|
| 64 |
+
def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:
|
| 65 |
+
raise NotImplementedError
|
| 66 |
+
|
| 67 |
+
@abstractmethod
|
| 68 |
+
def check_call(
|
| 69 |
+
self,
|
| 70 |
+
callee: Type,
|
| 71 |
+
args: list[Expression],
|
| 72 |
+
arg_kinds: list[ArgKind],
|
| 73 |
+
context: Context,
|
| 74 |
+
arg_names: Sequence[str | None] | None = None,
|
| 75 |
+
callable_node: Expression | None = None,
|
| 76 |
+
callable_name: str | None = None,
|
| 77 |
+
object_type: Type | None = None,
|
| 78 |
+
original_type: Type | None = None,
|
| 79 |
+
) -> tuple[Type, Type]:
|
| 80 |
+
raise NotImplementedError
|
| 81 |
+
|
| 82 |
+
@abstractmethod
|
| 83 |
+
def transform_callee_type(
|
| 84 |
+
self,
|
| 85 |
+
callable_name: str | None,
|
| 86 |
+
callee: Type,
|
| 87 |
+
args: list[Expression],
|
| 88 |
+
arg_kinds: list[ArgKind],
|
| 89 |
+
context: Context,
|
| 90 |
+
arg_names: Sequence[str | None] | None = None,
|
| 91 |
+
object_type: Type | None = None,
|
| 92 |
+
) -> Type:
|
| 93 |
+
raise NotImplementedError
|
| 94 |
+
|
| 95 |
+
@abstractmethod
|
| 96 |
+
def method_fullname(self, object_type: Type, method_name: str) -> str | None:
|
| 97 |
+
raise NotImplementedError
|
| 98 |
+
|
| 99 |
+
@abstractmethod
|
| 100 |
+
def check_method_call_by_name(
|
| 101 |
+
self,
|
| 102 |
+
method: str,
|
| 103 |
+
base_type: Type,
|
| 104 |
+
args: list[Expression],
|
| 105 |
+
arg_kinds: list[ArgKind],
|
| 106 |
+
context: Context,
|
| 107 |
+
original_type: Type | None = None,
|
| 108 |
+
) -> tuple[Type, Type]:
|
| 109 |
+
raise NotImplementedError
|
| 110 |
+
|
| 111 |
+
@abstractmethod
|
| 112 |
+
def visit_typeddict_index_expr(
|
| 113 |
+
self, td_type: TypedDictType, index: Expression, setitem: bool = False
|
| 114 |
+
) -> tuple[Type, set[str]]:
|
| 115 |
+
raise NotImplementedError
|
| 116 |
+
|
| 117 |
+
@abstractmethod
|
| 118 |
+
def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type:
|
| 119 |
+
raise NotImplementedError
|
| 120 |
+
|
| 121 |
+
@abstractmethod
|
| 122 |
+
def analyze_static_reference(
|
| 123 |
+
self,
|
| 124 |
+
node: SymbolNode,
|
| 125 |
+
ctx: Context,
|
| 126 |
+
is_lvalue: bool,
|
| 127 |
+
*,
|
| 128 |
+
include_modules: bool = True,
|
| 129 |
+
suppress_errors: bool = False,
|
| 130 |
+
) -> Type:
|
| 131 |
+
raise NotImplementedError
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@trait
|
| 135 |
+
class TypeCheckerSharedApi(CheckerPluginInterface):
|
| 136 |
+
plugin: Plugin
|
| 137 |
+
module_refs: set[str]
|
| 138 |
+
scope: CheckerScope
|
| 139 |
+
checking_missing_await: bool
|
| 140 |
+
allow_constructor_cache: bool
|
| 141 |
+
|
| 142 |
+
@property
|
| 143 |
+
@abstractmethod
|
| 144 |
+
def expr_checker(self) -> ExpressionCheckerSharedApi:
|
| 145 |
+
raise NotImplementedError
|
| 146 |
+
|
| 147 |
+
@abstractmethod
|
| 148 |
+
def named_type(self, name: str) -> Instance:
|
| 149 |
+
raise NotImplementedError
|
| 150 |
+
|
| 151 |
+
@abstractmethod
|
| 152 |
+
def lookup_typeinfo(self, fullname: str) -> TypeInfo:
|
| 153 |
+
raise NotImplementedError
|
| 154 |
+
|
| 155 |
+
@abstractmethod
|
| 156 |
+
def lookup_type(self, node: Expression) -> Type:
|
| 157 |
+
raise NotImplementedError
|
| 158 |
+
|
| 159 |
+
@abstractmethod
|
| 160 |
+
def handle_cannot_determine_type(self, name: str, context: Context) -> None:
|
| 161 |
+
raise NotImplementedError
|
| 162 |
+
|
| 163 |
+
@abstractmethod
|
| 164 |
+
def handle_partial_var_type(
|
| 165 |
+
self, typ: PartialType, is_lvalue: bool, node: Var, context: Context
|
| 166 |
+
) -> Type:
|
| 167 |
+
raise NotImplementedError
|
| 168 |
+
|
| 169 |
+
@overload
|
| 170 |
+
@abstractmethod
|
| 171 |
+
def check_subtype(
|
| 172 |
+
self,
|
| 173 |
+
subtype: Type,
|
| 174 |
+
supertype: Type,
|
| 175 |
+
context: Context,
|
| 176 |
+
msg: str,
|
| 177 |
+
subtype_label: str | None = None,
|
| 178 |
+
supertype_label: str | None = None,
|
| 179 |
+
*,
|
| 180 |
+
notes: list[str] | None = None,
|
| 181 |
+
code: ErrorCode | None = None,
|
| 182 |
+
outer_context: Context | None = None,
|
| 183 |
+
) -> bool: ...
|
| 184 |
+
|
| 185 |
+
@overload
|
| 186 |
+
@abstractmethod
|
| 187 |
+
def check_subtype(
|
| 188 |
+
self,
|
| 189 |
+
subtype: Type,
|
| 190 |
+
supertype: Type,
|
| 191 |
+
context: Context,
|
| 192 |
+
msg: ErrorMessage,
|
| 193 |
+
subtype_label: str | None = None,
|
| 194 |
+
supertype_label: str | None = None,
|
| 195 |
+
*,
|
| 196 |
+
notes: list[str] | None = None,
|
| 197 |
+
outer_context: Context | None = None,
|
| 198 |
+
) -> bool: ...
|
| 199 |
+
|
| 200 |
+
# Unfortunately, mypyc doesn't support abstract overloads yet.
|
| 201 |
+
@abstractmethod
|
| 202 |
+
def check_subtype(
|
| 203 |
+
self,
|
| 204 |
+
subtype: Type,
|
| 205 |
+
supertype: Type,
|
| 206 |
+
context: Context,
|
| 207 |
+
msg: str | ErrorMessage,
|
| 208 |
+
subtype_label: str | None = None,
|
| 209 |
+
supertype_label: str | None = None,
|
| 210 |
+
*,
|
| 211 |
+
notes: list[str] | None = None,
|
| 212 |
+
code: ErrorCode | None = None,
|
| 213 |
+
outer_context: Context | None = None,
|
| 214 |
+
) -> bool:
|
| 215 |
+
raise NotImplementedError
|
| 216 |
+
|
| 217 |
+
@abstractmethod
|
| 218 |
+
def get_final_context(self) -> bool:
|
| 219 |
+
raise NotImplementedError
|
| 220 |
+
|
| 221 |
+
@overload
|
| 222 |
+
@abstractmethod
|
| 223 |
+
def conditional_types_with_intersection(
|
| 224 |
+
self,
|
| 225 |
+
expr_type: Type,
|
| 226 |
+
type_ranges: list[TypeRange] | None,
|
| 227 |
+
ctx: Context,
|
| 228 |
+
default: None = None,
|
| 229 |
+
) -> tuple[Type | None, Type | None]: ...
|
| 230 |
+
|
| 231 |
+
@overload
|
| 232 |
+
@abstractmethod
|
| 233 |
+
def conditional_types_with_intersection(
|
| 234 |
+
self, expr_type: Type, type_ranges: list[TypeRange] | None, ctx: Context, default: Type
|
| 235 |
+
) -> tuple[Type, Type]: ...
|
| 236 |
+
|
| 237 |
+
# Unfortunately, mypyc doesn't support abstract overloads yet.
|
| 238 |
+
@abstractmethod
|
| 239 |
+
def conditional_types_with_intersection(
|
| 240 |
+
self,
|
| 241 |
+
expr_type: Type,
|
| 242 |
+
type_ranges: list[TypeRange] | None,
|
| 243 |
+
ctx: Context,
|
| 244 |
+
default: Type | None = None,
|
| 245 |
+
) -> tuple[Type | None, Type | None]:
|
| 246 |
+
raise NotImplementedError
|
| 247 |
+
|
| 248 |
+
@abstractmethod
|
| 249 |
+
def narrow_type_by_identity_equality(
|
| 250 |
+
self,
|
| 251 |
+
operator: str,
|
| 252 |
+
operands: list[Expression],
|
| 253 |
+
operand_types: list[Type],
|
| 254 |
+
expr_indices: list[int],
|
| 255 |
+
narrowable_indices: AbstractSet[int],
|
| 256 |
+
) -> tuple[dict[Expression, Type] | None, dict[Expression, Type] | None]:
|
| 257 |
+
raise NotImplementedError
|
| 258 |
+
|
| 259 |
+
@abstractmethod
|
| 260 |
+
def check_deprecated(self, node: Node | None, context: Context) -> None:
|
| 261 |
+
raise NotImplementedError
|
| 262 |
+
|
| 263 |
+
@abstractmethod
|
| 264 |
+
def warn_deprecated(self, node: Node | None, context: Context) -> None:
|
| 265 |
+
raise NotImplementedError
|
| 266 |
+
|
| 267 |
+
@abstractmethod
|
| 268 |
+
def type_is_iterable(self, type: Type) -> bool:
|
| 269 |
+
raise NotImplementedError
|
| 270 |
+
|
| 271 |
+
@abstractmethod
|
| 272 |
+
def iterable_item_type(
|
| 273 |
+
self, it: Instance | CallableType | TypeType | Overloaded, context: Context
|
| 274 |
+
) -> Type:
|
| 275 |
+
raise NotImplementedError
|
| 276 |
+
|
| 277 |
+
@abstractmethod
|
| 278 |
+
@contextmanager
|
| 279 |
+
def checking_await_set(self) -> Iterator[None]:
|
| 280 |
+
raise NotImplementedError
|
| 281 |
+
|
| 282 |
+
@abstractmethod
|
| 283 |
+
def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None:
|
| 284 |
+
raise NotImplementedError
|
| 285 |
+
|
| 286 |
+
@abstractmethod
|
| 287 |
+
def add_any_attribute_to_type(self, typ: Type, name: str) -> Type:
|
| 288 |
+
raise NotImplementedError
|
| 289 |
+
|
| 290 |
+
@abstractmethod
|
| 291 |
+
def is_defined_in_stub(self, typ: Instance, /) -> bool:
|
| 292 |
+
raise NotImplementedError
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class CheckerScope:
|
| 296 |
+
# We keep two stacks combined, to maintain the relative order
|
| 297 |
+
stack: list[TypeInfo | FuncItem | MypyFile]
|
| 298 |
+
|
| 299 |
+
def __init__(self, module: MypyFile) -> None:
|
| 300 |
+
self.stack = [module]
|
| 301 |
+
|
| 302 |
+
def current_function(self) -> FuncItem | None:
|
| 303 |
+
for e in reversed(self.stack):
|
| 304 |
+
if isinstance(e, FuncItem):
|
| 305 |
+
return e
|
| 306 |
+
return None
|
| 307 |
+
|
| 308 |
+
def top_level_function(self) -> FuncItem | None:
|
| 309 |
+
"""Return top-level non-lambda function."""
|
| 310 |
+
for e in self.stack:
|
| 311 |
+
if isinstance(e, FuncItem) and not isinstance(e, LambdaExpr):
|
| 312 |
+
return e
|
| 313 |
+
return None
|
| 314 |
+
|
| 315 |
+
def active_class(self) -> TypeInfo | None:
|
| 316 |
+
if isinstance(self.stack[-1], TypeInfo):
|
| 317 |
+
return self.stack[-1]
|
| 318 |
+
return None
|
| 319 |
+
|
| 320 |
+
def enclosing_class(self, func: FuncItem | None = None) -> TypeInfo | None:
|
| 321 |
+
"""Is there a class *directly* enclosing this function?"""
|
| 322 |
+
func = func or self.current_function()
|
| 323 |
+
assert func, "This method must be called from inside a function"
|
| 324 |
+
index = self.stack.index(func)
|
| 325 |
+
assert index, "CheckerScope stack must always start with a module"
|
| 326 |
+
enclosing = self.stack[index - 1]
|
| 327 |
+
if isinstance(enclosing, TypeInfo):
|
| 328 |
+
return enclosing
|
| 329 |
+
return None
|
| 330 |
+
|
| 331 |
+
def active_self_type(self) -> Instance | TupleType | None:
|
| 332 |
+
"""An instance or tuple type representing the current class.
|
| 333 |
+
|
| 334 |
+
This returns None unless we are in class body or in a method.
|
| 335 |
+
In particular, inside a function nested in method this returns None.
|
| 336 |
+
"""
|
| 337 |
+
info = self.active_class()
|
| 338 |
+
if not info and self.current_function():
|
| 339 |
+
info = self.enclosing_class()
|
| 340 |
+
if info:
|
| 341 |
+
return fill_typevars(info)
|
| 342 |
+
return None
|
| 343 |
+
|
| 344 |
+
def current_self_type(self) -> Instance | TupleType | None:
|
| 345 |
+
"""Same as active_self_type() but handle functions nested in methods."""
|
| 346 |
+
for item in reversed(self.stack):
|
| 347 |
+
if isinstance(item, TypeInfo):
|
| 348 |
+
return fill_typevars(item)
|
| 349 |
+
return None
|
| 350 |
+
|
| 351 |
+
def is_top_level(self) -> bool:
|
| 352 |
+
"""Is current scope top-level (no classes or functions)?"""
|
| 353 |
+
return len(self.stack) == 1
|
| 354 |
+
|
| 355 |
+
@contextmanager
|
| 356 |
+
def push_function(self, item: FuncItem) -> Iterator[None]:
|
| 357 |
+
self.stack.append(item)
|
| 358 |
+
yield
|
| 359 |
+
self.stack.pop()
|
| 360 |
+
|
| 361 |
+
@contextmanager
|
| 362 |
+
def push_class(self, info: TypeInfo) -> Iterator[None]:
|
| 363 |
+
self.stack.append(info)
|
| 364 |
+
yield
|
| 365 |
+
self.stack.pop()
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checker_state.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Iterator
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from typing import Final
|
| 6 |
+
|
| 7 |
+
from mypy.checker_shared import TypeCheckerSharedApi
|
| 8 |
+
|
| 9 |
+
# This is global mutable state. Don't add anything here unless there's a very
|
| 10 |
+
# good reason.
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TypeCheckerState:
|
| 14 |
+
# Wrap this in a class since it's faster that using a module-level attribute.
|
| 15 |
+
|
| 16 |
+
def __init__(self, type_checker: TypeCheckerSharedApi | None) -> None:
|
| 17 |
+
# Value varies by file being processed
|
| 18 |
+
self.type_checker = type_checker
|
| 19 |
+
|
| 20 |
+
@contextmanager
|
| 21 |
+
def set(self, value: TypeCheckerSharedApi) -> Iterator[None]:
|
| 22 |
+
saved = self.type_checker
|
| 23 |
+
self.type_checker = value
|
| 24 |
+
try:
|
| 25 |
+
yield
|
| 26 |
+
finally:
|
| 27 |
+
self.type_checker = saved
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
checker_state: Final = TypeCheckerState(type_checker=None)
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkexpr.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkmember.py
ADDED
|
@@ -0,0 +1,1588 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Type checking of attribute access"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable, Sequence
|
| 6 |
+
from typing import TypeVar, cast
|
| 7 |
+
|
| 8 |
+
from mypy import message_registry, state
|
| 9 |
+
from mypy.checker_shared import TypeCheckerSharedApi
|
| 10 |
+
from mypy.erasetype import erase_typevars
|
| 11 |
+
from mypy.expandtype import (
|
| 12 |
+
expand_self_type,
|
| 13 |
+
expand_type_by_instance,
|
| 14 |
+
freshen_all_functions_type_vars,
|
| 15 |
+
)
|
| 16 |
+
from mypy.maptype import map_instance_to_supertype
|
| 17 |
+
from mypy.meet import is_overlapping_types
|
| 18 |
+
from mypy.messages import MessageBuilder
|
| 19 |
+
from mypy.nodes import (
|
| 20 |
+
ARG_POS,
|
| 21 |
+
ARG_STAR,
|
| 22 |
+
ARG_STAR2,
|
| 23 |
+
EXCLUDED_ENUM_ATTRIBUTES,
|
| 24 |
+
SYMBOL_FUNCBASE_TYPES,
|
| 25 |
+
Context,
|
| 26 |
+
Decorator,
|
| 27 |
+
Expression,
|
| 28 |
+
FuncBase,
|
| 29 |
+
FuncDef,
|
| 30 |
+
IndexExpr,
|
| 31 |
+
MypyFile,
|
| 32 |
+
NameExpr,
|
| 33 |
+
OverloadedFuncDef,
|
| 34 |
+
SymbolTable,
|
| 35 |
+
TempNode,
|
| 36 |
+
TypeAlias,
|
| 37 |
+
TypeInfo,
|
| 38 |
+
TypeVarLikeExpr,
|
| 39 |
+
Var,
|
| 40 |
+
is_final_node,
|
| 41 |
+
)
|
| 42 |
+
from mypy.plugin import AttributeContext
|
| 43 |
+
from mypy.subtypes import is_subtype
|
| 44 |
+
from mypy.typeops import (
|
| 45 |
+
bind_self,
|
| 46 |
+
erase_to_bound,
|
| 47 |
+
freeze_all_type_vars,
|
| 48 |
+
function_type,
|
| 49 |
+
get_all_type_vars,
|
| 50 |
+
make_simplified_union,
|
| 51 |
+
supported_self_type,
|
| 52 |
+
tuple_fallback,
|
| 53 |
+
)
|
| 54 |
+
from mypy.types import (
|
| 55 |
+
AnyType,
|
| 56 |
+
CallableType,
|
| 57 |
+
DeletedType,
|
| 58 |
+
FunctionLike,
|
| 59 |
+
Instance,
|
| 60 |
+
LiteralType,
|
| 61 |
+
NoneType,
|
| 62 |
+
Overloaded,
|
| 63 |
+
ParamSpecType,
|
| 64 |
+
PartialType,
|
| 65 |
+
ProperType,
|
| 66 |
+
TupleType,
|
| 67 |
+
Type,
|
| 68 |
+
TypedDictType,
|
| 69 |
+
TypeOfAny,
|
| 70 |
+
TypeType,
|
| 71 |
+
TypeVarLikeType,
|
| 72 |
+
TypeVarTupleType,
|
| 73 |
+
TypeVarType,
|
| 74 |
+
UninhabitedType,
|
| 75 |
+
UnionType,
|
| 76 |
+
get_proper_type,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class MemberContext:
|
| 81 |
+
"""Information and objects needed to type check attribute access.
|
| 82 |
+
|
| 83 |
+
Look at the docstring of analyze_member_access for more information.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
*,
|
| 89 |
+
is_lvalue: bool,
|
| 90 |
+
is_super: bool,
|
| 91 |
+
is_operator: bool,
|
| 92 |
+
original_type: Type,
|
| 93 |
+
context: Context,
|
| 94 |
+
chk: TypeCheckerSharedApi,
|
| 95 |
+
self_type: Type | None = None,
|
| 96 |
+
module_symbol_table: SymbolTable | None = None,
|
| 97 |
+
no_deferral: bool = False,
|
| 98 |
+
is_self: bool = False,
|
| 99 |
+
rvalue: Expression | None = None,
|
| 100 |
+
suppress_errors: bool = False,
|
| 101 |
+
preserve_type_var_ids: bool = False,
|
| 102 |
+
) -> None:
|
| 103 |
+
self.is_lvalue = is_lvalue
|
| 104 |
+
self.is_super = is_super
|
| 105 |
+
self.is_operator = is_operator
|
| 106 |
+
self.original_type = original_type
|
| 107 |
+
self.self_type = self_type or original_type
|
| 108 |
+
self.context = context # Error context
|
| 109 |
+
self.chk = chk
|
| 110 |
+
self.msg = chk.msg
|
| 111 |
+
self.module_symbol_table = module_symbol_table
|
| 112 |
+
self.no_deferral = no_deferral
|
| 113 |
+
self.is_self = is_self
|
| 114 |
+
if rvalue is not None:
|
| 115 |
+
assert is_lvalue
|
| 116 |
+
self.rvalue = rvalue
|
| 117 |
+
self.suppress_errors = suppress_errors
|
| 118 |
+
# This attribute is only used to preserve old protocol member access logic.
|
| 119 |
+
# It is needed to avoid infinite recursion in cases involving self-referential
|
| 120 |
+
# generic methods, see find_member() for details. Do not use for other purposes!
|
| 121 |
+
self.preserve_type_var_ids = preserve_type_var_ids
|
| 122 |
+
|
| 123 |
+
def named_type(self, name: str) -> Instance:
|
| 124 |
+
return self.chk.named_type(name)
|
| 125 |
+
|
| 126 |
+
def not_ready_callback(self, name: str, context: Context) -> None:
|
| 127 |
+
self.chk.handle_cannot_determine_type(name, context)
|
| 128 |
+
|
| 129 |
+
def fail(self, msg: str) -> None:
|
| 130 |
+
if not self.suppress_errors:
|
| 131 |
+
self.msg.fail(msg, self.context)
|
| 132 |
+
|
| 133 |
+
def copy_modified(
|
| 134 |
+
self,
|
| 135 |
+
*,
|
| 136 |
+
self_type: Type | None = None,
|
| 137 |
+
is_lvalue: bool | None = None,
|
| 138 |
+
original_type: Type | None = None,
|
| 139 |
+
) -> MemberContext:
|
| 140 |
+
mx = MemberContext(
|
| 141 |
+
is_lvalue=self.is_lvalue,
|
| 142 |
+
is_super=self.is_super,
|
| 143 |
+
is_operator=self.is_operator,
|
| 144 |
+
original_type=self.original_type,
|
| 145 |
+
context=self.context,
|
| 146 |
+
chk=self.chk,
|
| 147 |
+
self_type=self.self_type,
|
| 148 |
+
module_symbol_table=self.module_symbol_table,
|
| 149 |
+
no_deferral=self.no_deferral,
|
| 150 |
+
rvalue=self.rvalue,
|
| 151 |
+
suppress_errors=self.suppress_errors,
|
| 152 |
+
preserve_type_var_ids=self.preserve_type_var_ids,
|
| 153 |
+
)
|
| 154 |
+
if self_type is not None:
|
| 155 |
+
mx.self_type = self_type
|
| 156 |
+
if is_lvalue is not None:
|
| 157 |
+
mx.is_lvalue = is_lvalue
|
| 158 |
+
if original_type is not None:
|
| 159 |
+
mx.original_type = original_type
|
| 160 |
+
return mx
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def analyze_member_access(
|
| 164 |
+
name: str,
|
| 165 |
+
typ: Type,
|
| 166 |
+
context: Context,
|
| 167 |
+
*,
|
| 168 |
+
is_lvalue: bool,
|
| 169 |
+
is_super: bool,
|
| 170 |
+
is_operator: bool,
|
| 171 |
+
original_type: Type,
|
| 172 |
+
chk: TypeCheckerSharedApi,
|
| 173 |
+
override_info: TypeInfo | None = None,
|
| 174 |
+
in_literal_context: bool = False,
|
| 175 |
+
self_type: Type | None = None,
|
| 176 |
+
module_symbol_table: SymbolTable | None = None,
|
| 177 |
+
no_deferral: bool = False,
|
| 178 |
+
is_self: bool = False,
|
| 179 |
+
rvalue: Expression | None = None,
|
| 180 |
+
suppress_errors: bool = False,
|
| 181 |
+
) -> Type:
|
| 182 |
+
"""Return the type of attribute 'name' of 'typ'.
|
| 183 |
+
|
| 184 |
+
The actual implementation is in '_analyze_member_access' and this docstring
|
| 185 |
+
also applies to it.
|
| 186 |
+
|
| 187 |
+
This is a general operation that supports various different variations:
|
| 188 |
+
|
| 189 |
+
1. lvalue or non-lvalue access (setter or getter access)
|
| 190 |
+
2. supertype access when using super() (is_super == True and
|
| 191 |
+
'override_info' should refer to the supertype)
|
| 192 |
+
|
| 193 |
+
'original_type' is the most precise inferred or declared type of the base object
|
| 194 |
+
that we have available. When looking for an attribute of 'typ', we may perform
|
| 195 |
+
recursive calls targeting the fallback type, and 'typ' may become some supertype
|
| 196 |
+
of 'original_type'. 'original_type' is always preserved as the 'typ' type used in
|
| 197 |
+
the initial, non-recursive call. The 'self_type' is a component of 'original_type'
|
| 198 |
+
to which generic self should be bound (a narrower type that has a fallback to instance).
|
| 199 |
+
Currently, this is used only for union types.
|
| 200 |
+
|
| 201 |
+
'module_symbol_table' is passed to this function if 'typ' is actually a module,
|
| 202 |
+
and we want to keep track of the available attributes of the module (since they
|
| 203 |
+
are not available via the type object directly)
|
| 204 |
+
|
| 205 |
+
'rvalue' can be provided optionally to infer better setter type when is_lvalue is True,
|
| 206 |
+
most notably this helps for descriptors with overloaded __set__() method.
|
| 207 |
+
|
| 208 |
+
'suppress_errors' will skip any logic that is only needed to generate error messages.
|
| 209 |
+
Note that this more of a performance optimization, one should not rely on this to not
|
| 210 |
+
show any messages, as some may be show e.g. by callbacks called here,
|
| 211 |
+
use msg.filter_errors(), if needed.
|
| 212 |
+
"""
|
| 213 |
+
mx = MemberContext(
|
| 214 |
+
is_lvalue=is_lvalue,
|
| 215 |
+
is_super=is_super,
|
| 216 |
+
is_operator=is_operator,
|
| 217 |
+
original_type=original_type,
|
| 218 |
+
context=context,
|
| 219 |
+
chk=chk,
|
| 220 |
+
self_type=self_type,
|
| 221 |
+
module_symbol_table=module_symbol_table,
|
| 222 |
+
no_deferral=no_deferral,
|
| 223 |
+
is_self=is_self,
|
| 224 |
+
rvalue=rvalue,
|
| 225 |
+
suppress_errors=suppress_errors,
|
| 226 |
+
)
|
| 227 |
+
result = _analyze_member_access(name, typ, mx, override_info)
|
| 228 |
+
possible_literal = get_proper_type(result)
|
| 229 |
+
if (
|
| 230 |
+
in_literal_context
|
| 231 |
+
and isinstance(possible_literal, Instance)
|
| 232 |
+
and possible_literal.last_known_value is not None
|
| 233 |
+
):
|
| 234 |
+
return possible_literal.last_known_value
|
| 235 |
+
else:
|
| 236 |
+
return result
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _analyze_member_access(
|
| 240 |
+
name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None
|
| 241 |
+
) -> Type:
|
| 242 |
+
typ = get_proper_type(typ)
|
| 243 |
+
if isinstance(typ, Instance):
|
| 244 |
+
return analyze_instance_member_access(name, typ, mx, override_info)
|
| 245 |
+
elif isinstance(typ, AnyType):
|
| 246 |
+
# The base object has dynamic type.
|
| 247 |
+
return AnyType(TypeOfAny.from_another_any, source_any=typ)
|
| 248 |
+
elif isinstance(typ, UnionType):
|
| 249 |
+
return analyze_union_member_access(name, typ, mx)
|
| 250 |
+
elif isinstance(typ, FunctionLike) and typ.is_type_obj():
|
| 251 |
+
return analyze_type_callable_member_access(name, typ, mx)
|
| 252 |
+
elif isinstance(typ, TypeType):
|
| 253 |
+
return analyze_type_type_member_access(name, typ, mx, override_info)
|
| 254 |
+
elif isinstance(typ, TupleType):
|
| 255 |
+
# Actually look up from the fallback instance type.
|
| 256 |
+
return _analyze_member_access(name, tuple_fallback(typ), mx, override_info)
|
| 257 |
+
elif isinstance(typ, (LiteralType, FunctionLike)):
|
| 258 |
+
# Actually look up from the fallback instance type.
|
| 259 |
+
return _analyze_member_access(name, typ.fallback, mx, override_info)
|
| 260 |
+
elif isinstance(typ, TypedDictType):
|
| 261 |
+
return analyze_typeddict_access(name, typ, mx, override_info)
|
| 262 |
+
elif isinstance(typ, NoneType):
|
| 263 |
+
return analyze_none_member_access(name, typ, mx)
|
| 264 |
+
elif isinstance(typ, TypeVarLikeType):
|
| 265 |
+
if isinstance(typ, TypeVarType) and typ.values:
|
| 266 |
+
return _analyze_member_access(
|
| 267 |
+
name, make_simplified_union(typ.values), mx, override_info
|
| 268 |
+
)
|
| 269 |
+
return _analyze_member_access(name, typ.upper_bound, mx, override_info)
|
| 270 |
+
elif isinstance(typ, DeletedType):
|
| 271 |
+
if not mx.suppress_errors:
|
| 272 |
+
mx.msg.deleted_as_rvalue(typ, mx.context)
|
| 273 |
+
return AnyType(TypeOfAny.from_error)
|
| 274 |
+
elif isinstance(typ, UninhabitedType):
|
| 275 |
+
attr_type = UninhabitedType()
|
| 276 |
+
attr_type.ambiguous = typ.ambiguous
|
| 277 |
+
return attr_type
|
| 278 |
+
return report_missing_attribute(mx.original_type, typ, name, mx)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def may_be_awaitable_attribute(
|
| 282 |
+
name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None
|
| 283 |
+
) -> bool:
|
| 284 |
+
"""Check if the given type has the attribute when awaited."""
|
| 285 |
+
if mx.chk.checking_missing_await:
|
| 286 |
+
# Avoid infinite recursion.
|
| 287 |
+
return False
|
| 288 |
+
with mx.chk.checking_await_set(), mx.msg.filter_errors() as local_errors:
|
| 289 |
+
aw_type = mx.chk.get_precise_awaitable_type(typ, local_errors)
|
| 290 |
+
if aw_type is None:
|
| 291 |
+
return False
|
| 292 |
+
_ = _analyze_member_access(
|
| 293 |
+
name, aw_type, mx.copy_modified(self_type=aw_type), override_info
|
| 294 |
+
)
|
| 295 |
+
return not local_errors.has_new_errors()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def report_missing_attribute(
|
| 299 |
+
original_type: Type,
|
| 300 |
+
typ: Type,
|
| 301 |
+
name: str,
|
| 302 |
+
mx: MemberContext,
|
| 303 |
+
override_info: TypeInfo | None = None,
|
| 304 |
+
) -> Type:
|
| 305 |
+
if mx.suppress_errors:
|
| 306 |
+
return AnyType(TypeOfAny.from_error)
|
| 307 |
+
error_code = mx.msg.has_no_attr(original_type, typ, name, mx.context, mx.module_symbol_table)
|
| 308 |
+
if not mx.msg.prefer_simple_messages():
|
| 309 |
+
if may_be_awaitable_attribute(name, typ, mx, override_info):
|
| 310 |
+
mx.msg.possible_missing_await(mx.context, error_code)
|
| 311 |
+
return AnyType(TypeOfAny.from_error)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# The several functions that follow implement analyze_member_access for various
|
| 315 |
+
# types and aren't documented individually.
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def analyze_instance_member_access(
|
| 319 |
+
name: str, typ: Instance, mx: MemberContext, override_info: TypeInfo | None
|
| 320 |
+
) -> Type:
|
| 321 |
+
info = typ.type
|
| 322 |
+
if override_info:
|
| 323 |
+
info = override_info
|
| 324 |
+
|
| 325 |
+
method = info.get_method(name)
|
| 326 |
+
|
| 327 |
+
if name == "__init__" and not mx.is_super and not info.is_final:
|
| 328 |
+
if not method or not method.is_final:
|
| 329 |
+
# Accessing __init__ in statically typed code would compromise
|
| 330 |
+
# type safety unless used via super() or the method/class is final.
|
| 331 |
+
mx.fail(message_registry.CANNOT_ACCESS_INIT)
|
| 332 |
+
return AnyType(TypeOfAny.from_error)
|
| 333 |
+
|
| 334 |
+
# The base object has an instance type.
|
| 335 |
+
|
| 336 |
+
if (
|
| 337 |
+
state.find_occurrences
|
| 338 |
+
and info.name == state.find_occurrences[0]
|
| 339 |
+
and name == state.find_occurrences[1]
|
| 340 |
+
and not mx.suppress_errors
|
| 341 |
+
):
|
| 342 |
+
mx.msg.note("Occurrence of '{}.{}'".format(*state.find_occurrences), mx.context)
|
| 343 |
+
|
| 344 |
+
# Look up the member. First look up the method dictionary.
|
| 345 |
+
if method and not isinstance(method, Decorator):
|
| 346 |
+
if mx.is_super and not mx.suppress_errors:
|
| 347 |
+
validate_super_call(method, mx)
|
| 348 |
+
|
| 349 |
+
if method.is_property:
|
| 350 |
+
assert isinstance(method, OverloadedFuncDef)
|
| 351 |
+
getter = method.items[0]
|
| 352 |
+
assert isinstance(getter, Decorator)
|
| 353 |
+
if mx.is_lvalue and getter.var.is_settable_property:
|
| 354 |
+
mx.chk.warn_deprecated(method.setter, mx.context)
|
| 355 |
+
return analyze_var(name, getter.var, typ, mx)
|
| 356 |
+
|
| 357 |
+
if mx.is_lvalue and not mx.suppress_errors:
|
| 358 |
+
mx.msg.cant_assign_to_method(mx.context)
|
| 359 |
+
if not isinstance(method, OverloadedFuncDef):
|
| 360 |
+
signature = function_type(method, mx.named_type("builtins.function"))
|
| 361 |
+
else:
|
| 362 |
+
if method.type is None:
|
| 363 |
+
# Overloads may be not ready if they are decorated. Handle this in same
|
| 364 |
+
# manner as we would handle a regular decorated function: defer if possible.
|
| 365 |
+
if not mx.no_deferral and method.items:
|
| 366 |
+
mx.not_ready_callback(method.name, mx.context)
|
| 367 |
+
return AnyType(TypeOfAny.special_form)
|
| 368 |
+
assert isinstance(method.type, Overloaded)
|
| 369 |
+
signature = method.type
|
| 370 |
+
if not mx.preserve_type_var_ids:
|
| 371 |
+
signature = freshen_all_functions_type_vars(signature)
|
| 372 |
+
if not method.is_static:
|
| 373 |
+
if isinstance(method, (FuncDef, OverloadedFuncDef)) and method.is_trivial_self:
|
| 374 |
+
signature = bind_self_fast(signature, mx.self_type)
|
| 375 |
+
else:
|
| 376 |
+
signature = check_self_arg(
|
| 377 |
+
signature, mx.self_type, method.is_class, mx.context, name, mx.msg
|
| 378 |
+
)
|
| 379 |
+
signature = bind_self(signature, mx.self_type, is_classmethod=method.is_class)
|
| 380 |
+
typ = map_instance_to_supertype(typ, method.info)
|
| 381 |
+
member_type = expand_type_by_instance(signature, typ)
|
| 382 |
+
freeze_all_type_vars(member_type)
|
| 383 |
+
return member_type
|
| 384 |
+
else:
|
| 385 |
+
# Not a method.
|
| 386 |
+
return analyze_member_var_access(name, typ, info, mx)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def validate_super_call(node: FuncBase, mx: MemberContext) -> None:
|
| 390 |
+
unsafe_super = False
|
| 391 |
+
if isinstance(node, FuncDef) and node.is_trivial_body:
|
| 392 |
+
unsafe_super = True
|
| 393 |
+
elif isinstance(node, OverloadedFuncDef):
|
| 394 |
+
if node.impl:
|
| 395 |
+
impl = node.impl if isinstance(node.impl, FuncDef) else node.impl.func
|
| 396 |
+
unsafe_super = impl.is_trivial_body
|
| 397 |
+
elif not node.is_property and node.items:
|
| 398 |
+
assert isinstance(node.items[0], Decorator)
|
| 399 |
+
unsafe_super = node.items[0].func.is_trivial_body
|
| 400 |
+
if unsafe_super:
|
| 401 |
+
mx.msg.unsafe_super(node.name, node.info.name, mx.context)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def analyze_type_callable_member_access(name: str, typ: FunctionLike, mx: MemberContext) -> Type:
|
| 405 |
+
# Class attribute.
|
| 406 |
+
# TODO super?
|
| 407 |
+
ret_type = typ.items[0].ret_type
|
| 408 |
+
assert isinstance(ret_type, ProperType)
|
| 409 |
+
if isinstance(ret_type, TupleType):
|
| 410 |
+
ret_type = tuple_fallback(ret_type)
|
| 411 |
+
if isinstance(ret_type, TypedDictType):
|
| 412 |
+
ret_type = ret_type.fallback
|
| 413 |
+
if isinstance(ret_type, LiteralType):
|
| 414 |
+
ret_type = ret_type.fallback
|
| 415 |
+
if isinstance(ret_type, Instance):
|
| 416 |
+
if not mx.is_operator:
|
| 417 |
+
# When Python sees an operator (eg `3 == 4`), it automatically translates that
|
| 418 |
+
# into something like `int.__eq__(3, 4)` instead of `(3).__eq__(4)` as an
|
| 419 |
+
# optimization.
|
| 420 |
+
#
|
| 421 |
+
# While it normally it doesn't matter which of the two versions are used, it
|
| 422 |
+
# does cause inconsistencies when working with classes. For example, translating
|
| 423 |
+
# `int == int` to `int.__eq__(int)` would not work since `int.__eq__` is meant to
|
| 424 |
+
# compare two int _instances_. What we really want is `type(int).__eq__`, which
|
| 425 |
+
# is meant to compare two types or classes.
|
| 426 |
+
#
|
| 427 |
+
# This check makes sure that when we encounter an operator, we skip looking up
|
| 428 |
+
# the corresponding method in the current instance to avoid this edge case.
|
| 429 |
+
# See https://github.com/python/mypy/pull/1787 for more info.
|
| 430 |
+
# TODO: do not rely on same type variables being present in all constructor overloads.
|
| 431 |
+
result = analyze_class_attribute_access(
|
| 432 |
+
ret_type, name, mx, original_vars=typ.items[0].variables, mcs_fallback=typ.fallback
|
| 433 |
+
)
|
| 434 |
+
if result:
|
| 435 |
+
return result
|
| 436 |
+
# Look up from the 'type' type.
|
| 437 |
+
return _analyze_member_access(name, typ.fallback, mx)
|
| 438 |
+
else:
|
| 439 |
+
assert False, f"Unexpected type {ret_type!r}"
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def analyze_type_type_member_access(
|
| 443 |
+
name: str, typ: TypeType, mx: MemberContext, override_info: TypeInfo | None
|
| 444 |
+
) -> Type:
|
| 445 |
+
# Similar to analyze_type_callable_attribute_access.
|
| 446 |
+
item = None
|
| 447 |
+
fallback = mx.named_type("builtins.type")
|
| 448 |
+
if isinstance(typ.item, Instance):
|
| 449 |
+
item = typ.item
|
| 450 |
+
elif isinstance(typ.item, AnyType):
|
| 451 |
+
with mx.msg.filter_errors():
|
| 452 |
+
return _analyze_member_access(name, fallback, mx, override_info)
|
| 453 |
+
elif isinstance(typ.item, TypeVarType):
|
| 454 |
+
upper_bound = get_proper_type(typ.item.upper_bound)
|
| 455 |
+
if isinstance(upper_bound, Instance):
|
| 456 |
+
item = upper_bound
|
| 457 |
+
elif isinstance(upper_bound, UnionType):
|
| 458 |
+
return _analyze_member_access(
|
| 459 |
+
name,
|
| 460 |
+
TypeType.make_normalized(upper_bound, line=typ.line, column=typ.column),
|
| 461 |
+
mx,
|
| 462 |
+
override_info,
|
| 463 |
+
)
|
| 464 |
+
elif isinstance(upper_bound, TupleType):
|
| 465 |
+
item = tuple_fallback(upper_bound)
|
| 466 |
+
elif isinstance(upper_bound, AnyType):
|
| 467 |
+
with mx.msg.filter_errors():
|
| 468 |
+
return _analyze_member_access(name, fallback, mx, override_info)
|
| 469 |
+
elif isinstance(typ.item, TupleType):
|
| 470 |
+
item = tuple_fallback(typ.item)
|
| 471 |
+
elif isinstance(typ.item, FunctionLike) and typ.item.is_type_obj():
|
| 472 |
+
item = typ.item.fallback
|
| 473 |
+
elif isinstance(typ.item, TypeType):
|
| 474 |
+
# Access member on metaclass object via Type[Type[C]]
|
| 475 |
+
if isinstance(typ.item.item, Instance):
|
| 476 |
+
item = typ.item.item.type.metaclass_type
|
| 477 |
+
ignore_messages = False
|
| 478 |
+
|
| 479 |
+
if item is not None:
|
| 480 |
+
fallback = item.type.metaclass_type or fallback
|
| 481 |
+
|
| 482 |
+
if item and not mx.is_operator:
|
| 483 |
+
# See comment above for why operators are skipped
|
| 484 |
+
result = analyze_class_attribute_access(
|
| 485 |
+
item, name, mx, mcs_fallback=fallback, override_info=override_info
|
| 486 |
+
)
|
| 487 |
+
if result:
|
| 488 |
+
if not (isinstance(get_proper_type(result), AnyType) and item.type.fallback_to_any):
|
| 489 |
+
return result
|
| 490 |
+
else:
|
| 491 |
+
# We don't want errors on metaclass lookup for classes with Any fallback
|
| 492 |
+
ignore_messages = True
|
| 493 |
+
|
| 494 |
+
with mx.msg.filter_errors(filter_errors=ignore_messages):
|
| 495 |
+
return _analyze_member_access(name, fallback, mx, override_info)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def analyze_union_member_access(name: str, typ: UnionType, mx: MemberContext) -> Type:
|
| 499 |
+
with mx.msg.disable_type_names():
|
| 500 |
+
results = []
|
| 501 |
+
for subtype in typ.relevant_items():
|
| 502 |
+
# Self types should be bound to every individual item of a union.
|
| 503 |
+
item_mx = mx.copy_modified(self_type=subtype)
|
| 504 |
+
results.append(_analyze_member_access(name, subtype, item_mx))
|
| 505 |
+
return make_simplified_union(results)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def analyze_none_member_access(name: str, typ: NoneType, mx: MemberContext) -> Type:
|
| 509 |
+
if name == "__bool__":
|
| 510 |
+
literal_false = LiteralType(False, fallback=mx.named_type("builtins.bool"))
|
| 511 |
+
return CallableType(
|
| 512 |
+
arg_types=[],
|
| 513 |
+
arg_kinds=[],
|
| 514 |
+
arg_names=[],
|
| 515 |
+
ret_type=literal_false,
|
| 516 |
+
fallback=mx.named_type("builtins.function"),
|
| 517 |
+
)
|
| 518 |
+
else:
|
| 519 |
+
return _analyze_member_access(name, mx.named_type("builtins.object"), mx)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def analyze_member_var_access(
|
| 523 |
+
name: str, itype: Instance, info: TypeInfo, mx: MemberContext
|
| 524 |
+
) -> Type:
|
| 525 |
+
"""Analyse attribute access that does not target a method.
|
| 526 |
+
|
| 527 |
+
This is logically part of analyze_member_access and the arguments are similar.
|
| 528 |
+
|
| 529 |
+
original_type is the type of E in the expression E.var
|
| 530 |
+
"""
|
| 531 |
+
# It was not a method. Try looking up a variable.
|
| 532 |
+
node = info.get(name)
|
| 533 |
+
v = node.node if node else None
|
| 534 |
+
|
| 535 |
+
mx.chk.warn_deprecated(v, mx.context)
|
| 536 |
+
|
| 537 |
+
vv = v
|
| 538 |
+
is_trivial_self = False
|
| 539 |
+
if isinstance(vv, Decorator):
|
| 540 |
+
# The associated Var node of a decorator contains the type.
|
| 541 |
+
v = vv.var
|
| 542 |
+
is_trivial_self = vv.func.is_trivial_self and not vv.decorators
|
| 543 |
+
if mx.is_super and not mx.suppress_errors:
|
| 544 |
+
validate_super_call(vv.func, mx)
|
| 545 |
+
if isinstance(v, FuncDef):
|
| 546 |
+
assert False, "Did not expect a function"
|
| 547 |
+
if isinstance(v, MypyFile):
|
| 548 |
+
# Special case: accessing module on instances is allowed, but will not
|
| 549 |
+
# be recorded by semantic analyzer.
|
| 550 |
+
mx.chk.module_refs.add(v.fullname)
|
| 551 |
+
|
| 552 |
+
if isinstance(vv, (TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)):
|
| 553 |
+
# If the associated variable is a TypeInfo synthesize a Var node for
|
| 554 |
+
# the purposes of type checking. This enables us to type check things
|
| 555 |
+
# like accessing class attributes on an inner class. Similar we allow
|
| 556 |
+
# using qualified type aliases in runtime context. For example:
|
| 557 |
+
# class C:
|
| 558 |
+
# A = List[int]
|
| 559 |
+
# x = C.A() <- this is OK
|
| 560 |
+
typ = mx.chk.expr_checker.analyze_static_reference(vv, mx.context, mx.is_lvalue)
|
| 561 |
+
v = Var(name, type=typ)
|
| 562 |
+
v.info = info
|
| 563 |
+
|
| 564 |
+
if isinstance(v, Var):
|
| 565 |
+
implicit = info[name].implicit
|
| 566 |
+
|
| 567 |
+
# An assignment to final attribute is always an error,
|
| 568 |
+
# independently of types.
|
| 569 |
+
if mx.is_lvalue and not mx.chk.get_final_context():
|
| 570 |
+
check_final_member(name, info, mx.msg, mx.context)
|
| 571 |
+
|
| 572 |
+
return analyze_var(name, v, itype, mx, implicit=implicit, is_trivial_self=is_trivial_self)
|
| 573 |
+
elif (
|
| 574 |
+
not v
|
| 575 |
+
and name not in ["__getattr__", "__setattr__", "__getattribute__"]
|
| 576 |
+
and not mx.is_operator
|
| 577 |
+
and mx.module_symbol_table is None
|
| 578 |
+
):
|
| 579 |
+
# Above we skip ModuleType.__getattr__ etc. if we have a
|
| 580 |
+
# module symbol table, since the symbol table allows precise
|
| 581 |
+
# checking.
|
| 582 |
+
if not mx.is_lvalue:
|
| 583 |
+
for method_name in ("__getattribute__", "__getattr__"):
|
| 584 |
+
method = info.get_method(method_name)
|
| 585 |
+
|
| 586 |
+
# __getattribute__ is defined on builtins.object and returns Any, so without
|
| 587 |
+
# the guard this search will always find object.__getattribute__ and conclude
|
| 588 |
+
# that the attribute exists
|
| 589 |
+
if method and method.info.fullname != "builtins.object":
|
| 590 |
+
bound_method = analyze_decorator_or_funcbase_access(
|
| 591 |
+
defn=method, itype=itype, name=method_name, mx=mx
|
| 592 |
+
)
|
| 593 |
+
typ = map_instance_to_supertype(itype, method.info)
|
| 594 |
+
getattr_type = get_proper_type(expand_type_by_instance(bound_method, typ))
|
| 595 |
+
if isinstance(getattr_type, CallableType):
|
| 596 |
+
result = getattr_type.ret_type
|
| 597 |
+
else:
|
| 598 |
+
result = getattr_type
|
| 599 |
+
|
| 600 |
+
# Call the attribute hook before returning.
|
| 601 |
+
fullname = f"{method.info.fullname}.{name}"
|
| 602 |
+
hook = mx.chk.plugin.get_attribute_hook(fullname)
|
| 603 |
+
if hook:
|
| 604 |
+
result = hook(
|
| 605 |
+
AttributeContext(
|
| 606 |
+
get_proper_type(mx.original_type),
|
| 607 |
+
result,
|
| 608 |
+
mx.is_lvalue,
|
| 609 |
+
mx.context,
|
| 610 |
+
mx.chk,
|
| 611 |
+
)
|
| 612 |
+
)
|
| 613 |
+
return result
|
| 614 |
+
else:
|
| 615 |
+
setattr_meth = info.get_method("__setattr__")
|
| 616 |
+
if setattr_meth and setattr_meth.info.fullname != "builtins.object":
|
| 617 |
+
bound_type = analyze_decorator_or_funcbase_access(
|
| 618 |
+
defn=setattr_meth,
|
| 619 |
+
itype=itype,
|
| 620 |
+
name="__setattr__",
|
| 621 |
+
mx=mx.copy_modified(is_lvalue=False),
|
| 622 |
+
)
|
| 623 |
+
typ = map_instance_to_supertype(itype, setattr_meth.info)
|
| 624 |
+
setattr_type = get_proper_type(expand_type_by_instance(bound_type, typ))
|
| 625 |
+
if isinstance(setattr_type, CallableType) and len(setattr_type.arg_types) > 0:
|
| 626 |
+
return setattr_type.arg_types[-1]
|
| 627 |
+
|
| 628 |
+
if itype.type.fallback_to_any:
|
| 629 |
+
return AnyType(TypeOfAny.special_form)
|
| 630 |
+
|
| 631 |
+
# Could not find the member.
|
| 632 |
+
if itype.extra_attrs and name in itype.extra_attrs.attrs:
|
| 633 |
+
# For modules use direct symbol table lookup.
|
| 634 |
+
if not itype.extra_attrs.mod_name:
|
| 635 |
+
return itype.extra_attrs.attrs[name]
|
| 636 |
+
|
| 637 |
+
if mx.is_super and not mx.suppress_errors:
|
| 638 |
+
mx.msg.undefined_in_superclass(name, mx.context)
|
| 639 |
+
return AnyType(TypeOfAny.from_error)
|
| 640 |
+
else:
|
| 641 |
+
ret = report_missing_attribute(mx.original_type, itype, name, mx)
|
| 642 |
+
# Avoid paying double jeopardy if we can't find the member due to --no-implicit-reexport
|
| 643 |
+
if (
|
| 644 |
+
mx.module_symbol_table is not None
|
| 645 |
+
and name in mx.module_symbol_table
|
| 646 |
+
and not mx.module_symbol_table[name].module_public
|
| 647 |
+
):
|
| 648 |
+
v = mx.module_symbol_table[name].node
|
| 649 |
+
e = NameExpr(name)
|
| 650 |
+
e.set_line(mx.context)
|
| 651 |
+
e.node = v
|
| 652 |
+
return mx.chk.expr_checker.analyze_ref_expr(e, lvalue=mx.is_lvalue)
|
| 653 |
+
return ret
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def check_final_member(name: str, info: TypeInfo, msg: MessageBuilder, ctx: Context) -> None:
|
| 657 |
+
"""Give an error if the name being assigned was declared as final."""
|
| 658 |
+
for base in info.mro:
|
| 659 |
+
sym = base.names.get(name)
|
| 660 |
+
if sym and is_final_node(sym.node):
|
| 661 |
+
msg.cant_assign_to_final(name, attr_assign=True, ctx=ctx)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def analyze_descriptor_access(descriptor_type: Type, mx: MemberContext) -> Type:
|
| 665 |
+
"""Type check descriptor access.
|
| 666 |
+
|
| 667 |
+
Arguments:
|
| 668 |
+
descriptor_type: The type of the descriptor attribute being accessed
|
| 669 |
+
(the type of ``f`` in ``a.f`` when ``f`` is a descriptor).
|
| 670 |
+
mx: The current member access context.
|
| 671 |
+
Return:
|
| 672 |
+
The return type of the appropriate ``__get__/__set__`` overload for the descriptor.
|
| 673 |
+
"""
|
| 674 |
+
instance_type = get_proper_type(mx.self_type)
|
| 675 |
+
orig_descriptor_type = descriptor_type
|
| 676 |
+
descriptor_type = get_proper_type(descriptor_type)
|
| 677 |
+
|
| 678 |
+
if isinstance(descriptor_type, UnionType):
|
| 679 |
+
# Map the access over union types
|
| 680 |
+
return make_simplified_union(
|
| 681 |
+
[analyze_descriptor_access(typ, mx) for typ in descriptor_type.items]
|
| 682 |
+
)
|
| 683 |
+
elif not isinstance(descriptor_type, Instance):
|
| 684 |
+
return orig_descriptor_type
|
| 685 |
+
|
| 686 |
+
if not mx.is_lvalue and not descriptor_type.type.has_readable_member("__get__"):
|
| 687 |
+
return orig_descriptor_type
|
| 688 |
+
|
| 689 |
+
# We do this check first to accommodate for descriptors with only __set__ method.
|
| 690 |
+
# If there is no __set__, we type-check that the assigned value matches
|
| 691 |
+
# the return type of __get__. This doesn't match the python semantics,
|
| 692 |
+
# (which allow you to override the descriptor with any value), but preserves
|
| 693 |
+
# the type of accessing the attribute (even after the override).
|
| 694 |
+
if mx.is_lvalue and descriptor_type.type.has_readable_member("__set__"):
|
| 695 |
+
return analyze_descriptor_assign(descriptor_type, mx)
|
| 696 |
+
|
| 697 |
+
if mx.is_lvalue and not descriptor_type.type.has_readable_member("__get__"):
|
| 698 |
+
# This turned out to be not a descriptor after all.
|
| 699 |
+
return orig_descriptor_type
|
| 700 |
+
|
| 701 |
+
dunder_get = descriptor_type.type.get_method("__get__")
|
| 702 |
+
if dunder_get is None:
|
| 703 |
+
mx.fail(
|
| 704 |
+
message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(
|
| 705 |
+
descriptor_type.str_with_options(mx.msg.options)
|
| 706 |
+
)
|
| 707 |
+
)
|
| 708 |
+
return AnyType(TypeOfAny.from_error)
|
| 709 |
+
|
| 710 |
+
bound_method = analyze_decorator_or_funcbase_access(
|
| 711 |
+
defn=dunder_get,
|
| 712 |
+
itype=descriptor_type,
|
| 713 |
+
name="__get__",
|
| 714 |
+
mx=mx.copy_modified(self_type=descriptor_type),
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
typ = map_instance_to_supertype(descriptor_type, dunder_get.info)
|
| 718 |
+
dunder_get_type = expand_type_by_instance(bound_method, typ)
|
| 719 |
+
|
| 720 |
+
if isinstance(instance_type, FunctionLike) and instance_type.is_type_obj():
|
| 721 |
+
owner_type = instance_type.items[0].ret_type
|
| 722 |
+
instance_type = NoneType()
|
| 723 |
+
elif isinstance(instance_type, TypeType):
|
| 724 |
+
owner_type = instance_type.item
|
| 725 |
+
instance_type = NoneType()
|
| 726 |
+
else:
|
| 727 |
+
owner_type = instance_type
|
| 728 |
+
|
| 729 |
+
callable_name = mx.chk.expr_checker.method_fullname(descriptor_type, "__get__")
|
| 730 |
+
dunder_get_type = mx.chk.expr_checker.transform_callee_type(
|
| 731 |
+
callable_name,
|
| 732 |
+
dunder_get_type,
|
| 733 |
+
[
|
| 734 |
+
TempNode(instance_type, context=mx.context),
|
| 735 |
+
TempNode(TypeType.make_normalized(owner_type), context=mx.context),
|
| 736 |
+
],
|
| 737 |
+
[ARG_POS, ARG_POS],
|
| 738 |
+
mx.context,
|
| 739 |
+
object_type=descriptor_type,
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
_, inferred_dunder_get_type = mx.chk.expr_checker.check_call(
|
| 743 |
+
dunder_get_type,
|
| 744 |
+
[
|
| 745 |
+
TempNode(instance_type, context=mx.context),
|
| 746 |
+
TempNode(TypeType.make_normalized(owner_type), context=mx.context),
|
| 747 |
+
],
|
| 748 |
+
[ARG_POS, ARG_POS],
|
| 749 |
+
mx.context,
|
| 750 |
+
object_type=descriptor_type,
|
| 751 |
+
callable_name=callable_name,
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
# Search for possible deprecations:
|
| 755 |
+
mx.chk.warn_deprecated(dunder_get, mx.context)
|
| 756 |
+
|
| 757 |
+
inferred_dunder_get_type = get_proper_type(inferred_dunder_get_type)
|
| 758 |
+
if isinstance(inferred_dunder_get_type, AnyType):
|
| 759 |
+
# check_call failed, and will have reported an error
|
| 760 |
+
return inferred_dunder_get_type
|
| 761 |
+
|
| 762 |
+
if not isinstance(inferred_dunder_get_type, CallableType):
|
| 763 |
+
mx.fail(
|
| 764 |
+
message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(
|
| 765 |
+
descriptor_type.str_with_options(mx.msg.options)
|
| 766 |
+
)
|
| 767 |
+
)
|
| 768 |
+
return AnyType(TypeOfAny.from_error)
|
| 769 |
+
|
| 770 |
+
return inferred_dunder_get_type.ret_type
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def analyze_descriptor_assign(descriptor_type: Instance, mx: MemberContext) -> Type:
|
| 774 |
+
instance_type = get_proper_type(mx.self_type)
|
| 775 |
+
dunder_set = descriptor_type.type.get_method("__set__")
|
| 776 |
+
if dunder_set is None:
|
| 777 |
+
mx.fail(
|
| 778 |
+
message_registry.DESCRIPTOR_SET_NOT_CALLABLE.format(
|
| 779 |
+
descriptor_type.str_with_options(mx.msg.options)
|
| 780 |
+
).value
|
| 781 |
+
)
|
| 782 |
+
return AnyType(TypeOfAny.from_error)
|
| 783 |
+
|
| 784 |
+
bound_method = analyze_decorator_or_funcbase_access(
|
| 785 |
+
defn=dunder_set,
|
| 786 |
+
itype=descriptor_type,
|
| 787 |
+
name="__set__",
|
| 788 |
+
mx=mx.copy_modified(is_lvalue=False, self_type=descriptor_type),
|
| 789 |
+
)
|
| 790 |
+
typ = map_instance_to_supertype(descriptor_type, dunder_set.info)
|
| 791 |
+
dunder_set_type = expand_type_by_instance(bound_method, typ)
|
| 792 |
+
|
| 793 |
+
callable_name = mx.chk.expr_checker.method_fullname(descriptor_type, "__set__")
|
| 794 |
+
rvalue = mx.rvalue or TempNode(AnyType(TypeOfAny.special_form), context=mx.context)
|
| 795 |
+
dunder_set_type = mx.chk.expr_checker.transform_callee_type(
|
| 796 |
+
callable_name,
|
| 797 |
+
dunder_set_type,
|
| 798 |
+
[TempNode(instance_type, context=mx.context), rvalue],
|
| 799 |
+
[ARG_POS, ARG_POS],
|
| 800 |
+
mx.context,
|
| 801 |
+
object_type=descriptor_type,
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
# For non-overloaded setters, the result should be type-checked like a regular assignment.
|
| 805 |
+
# Hence, we first only try to infer the type by using the rvalue as type context.
|
| 806 |
+
type_context = rvalue
|
| 807 |
+
with mx.msg.filter_errors():
|
| 808 |
+
_, inferred_dunder_set_type = mx.chk.expr_checker.check_call(
|
| 809 |
+
dunder_set_type,
|
| 810 |
+
[TempNode(instance_type, context=mx.context), type_context],
|
| 811 |
+
[ARG_POS, ARG_POS],
|
| 812 |
+
mx.context,
|
| 813 |
+
object_type=descriptor_type,
|
| 814 |
+
callable_name=callable_name,
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
# And now we in fact type check the call, to show errors related to wrong arguments
|
| 818 |
+
# count, etc., replacing the type context for non-overloaded setters only.
|
| 819 |
+
inferred_dunder_set_type = get_proper_type(inferred_dunder_set_type)
|
| 820 |
+
if isinstance(inferred_dunder_set_type, CallableType):
|
| 821 |
+
type_context = TempNode(AnyType(TypeOfAny.special_form), context=mx.context)
|
| 822 |
+
mx.chk.expr_checker.check_call(
|
| 823 |
+
dunder_set_type,
|
| 824 |
+
[TempNode(instance_type, context=mx.context), type_context],
|
| 825 |
+
[ARG_POS, ARG_POS],
|
| 826 |
+
mx.context,
|
| 827 |
+
object_type=descriptor_type,
|
| 828 |
+
callable_name=callable_name,
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
# Search for possible deprecations:
|
| 832 |
+
mx.chk.warn_deprecated(dunder_set, mx.context)
|
| 833 |
+
|
| 834 |
+
# In the following cases, a message already will have been recorded in check_call.
|
| 835 |
+
if (not isinstance(inferred_dunder_set_type, CallableType)) or (
|
| 836 |
+
len(inferred_dunder_set_type.arg_types) < 2
|
| 837 |
+
):
|
| 838 |
+
return AnyType(TypeOfAny.from_error)
|
| 839 |
+
return inferred_dunder_set_type.arg_types[1]
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def is_instance_var(var: Var) -> bool:
|
| 843 |
+
"""Return if var is an instance variable according to PEP 526."""
|
| 844 |
+
return (
|
| 845 |
+
# check the type_info node is the var (not a decorated function, etc.)
|
| 846 |
+
var.name in var.info.names
|
| 847 |
+
and var.info.names[var.name].node is var
|
| 848 |
+
and not var.is_classvar
|
| 849 |
+
# variables without annotations are treated as classvar
|
| 850 |
+
and not var.is_inferred
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
def analyze_var(
|
| 855 |
+
name: str,
|
| 856 |
+
var: Var,
|
| 857 |
+
itype: Instance,
|
| 858 |
+
mx: MemberContext,
|
| 859 |
+
*,
|
| 860 |
+
implicit: bool = False,
|
| 861 |
+
is_trivial_self: bool = False,
|
| 862 |
+
) -> Type:
|
| 863 |
+
"""Analyze access to an attribute via a Var node.
|
| 864 |
+
|
| 865 |
+
This is conceptually part of analyze_member_access and the arguments are similar.
|
| 866 |
+
itype is the instance type in which attribute should be looked up
|
| 867 |
+
original_type is the type of E in the expression E.var
|
| 868 |
+
if implicit is True, the original Var was created as an assignment to self
|
| 869 |
+
if is_trivial_self is True, we can use fast path for bind_self().
|
| 870 |
+
"""
|
| 871 |
+
# Found a member variable.
|
| 872 |
+
original_itype = itype
|
| 873 |
+
itype = map_instance_to_supertype(itype, var.info)
|
| 874 |
+
if var.is_settable_property and mx.is_lvalue:
|
| 875 |
+
typ: Type | None = var.setter_type
|
| 876 |
+
if typ is None and var.is_ready:
|
| 877 |
+
# Existing synthetic properties may not set setter type. Fall back to getter.
|
| 878 |
+
typ = var.type
|
| 879 |
+
else:
|
| 880 |
+
typ = var.type
|
| 881 |
+
if typ:
|
| 882 |
+
if isinstance(typ, PartialType):
|
| 883 |
+
return mx.chk.handle_partial_var_type(typ, mx.is_lvalue, var, mx.context)
|
| 884 |
+
if mx.is_lvalue and not mx.suppress_errors:
|
| 885 |
+
if var.is_property and not var.is_settable_property:
|
| 886 |
+
mx.msg.read_only_property(name, itype.type, mx.context)
|
| 887 |
+
if var.is_classvar:
|
| 888 |
+
mx.msg.cant_assign_to_classvar(name, mx.context)
|
| 889 |
+
# This is the most common case for variables, so start with this.
|
| 890 |
+
result = expand_without_binding(typ, var, itype, original_itype, mx)
|
| 891 |
+
|
| 892 |
+
# A non-None value indicates that we should actually bind self for this variable.
|
| 893 |
+
call_type: ProperType | None = None
|
| 894 |
+
if var.is_initialized_in_class and (not is_instance_var(var) or mx.is_operator):
|
| 895 |
+
typ = get_proper_type(typ)
|
| 896 |
+
if isinstance(typ, FunctionLike) and not typ.is_type_obj():
|
| 897 |
+
call_type = typ
|
| 898 |
+
elif var.is_property:
|
| 899 |
+
deco_mx = mx.copy_modified(original_type=typ, self_type=typ, is_lvalue=False)
|
| 900 |
+
call_type = get_proper_type(_analyze_member_access("__call__", typ, deco_mx))
|
| 901 |
+
else:
|
| 902 |
+
call_type = typ
|
| 903 |
+
|
| 904 |
+
# Bound variables with callable types are treated like methods
|
| 905 |
+
# (these are usually method aliases like __rmul__ = __mul__).
|
| 906 |
+
if isinstance(call_type, FunctionLike) and not call_type.is_type_obj():
|
| 907 |
+
if mx.is_lvalue and not var.is_property and not mx.suppress_errors:
|
| 908 |
+
mx.msg.cant_assign_to_method(mx.context)
|
| 909 |
+
|
| 910 |
+
# Bind the self type for each callable component (when needed).
|
| 911 |
+
if call_type and not var.is_staticmethod:
|
| 912 |
+
bound_items = []
|
| 913 |
+
for ct in call_type.items if isinstance(call_type, UnionType) else [call_type]:
|
| 914 |
+
p_ct = get_proper_type(ct)
|
| 915 |
+
if isinstance(p_ct, FunctionLike) and (not p_ct.bound() or var.is_property):
|
| 916 |
+
item = expand_and_bind_callable(p_ct, var, itype, name, mx, is_trivial_self)
|
| 917 |
+
else:
|
| 918 |
+
item = expand_without_binding(ct, var, itype, original_itype, mx)
|
| 919 |
+
bound_items.append(item)
|
| 920 |
+
result = UnionType.make_union(bound_items)
|
| 921 |
+
else:
|
| 922 |
+
if not var.is_ready and not mx.no_deferral:
|
| 923 |
+
mx.not_ready_callback(var.name, mx.context)
|
| 924 |
+
# Implicit 'Any' type.
|
| 925 |
+
result = AnyType(TypeOfAny.special_form)
|
| 926 |
+
fullname = f"{var.info.fullname}.{name}"
|
| 927 |
+
hook = mx.chk.plugin.get_attribute_hook(fullname)
|
| 928 |
+
|
| 929 |
+
if var.info.is_enum and not mx.is_lvalue:
|
| 930 |
+
if name in var.info.enum_members and name not in {"name", "value"}:
|
| 931 |
+
enum_literal = LiteralType(name, fallback=itype)
|
| 932 |
+
result = itype.copy_modified(last_known_value=enum_literal)
|
| 933 |
+
elif (
|
| 934 |
+
isinstance(p_result := get_proper_type(result), Instance)
|
| 935 |
+
and p_result.type.fullname == "enum.nonmember"
|
| 936 |
+
and p_result.args
|
| 937 |
+
):
|
| 938 |
+
# Unwrap nonmember similar to class-level access
|
| 939 |
+
result = p_result.args[0]
|
| 940 |
+
if result and not (implicit or var.info.is_protocol and is_instance_var(var)):
|
| 941 |
+
result = analyze_descriptor_access(result, mx)
|
| 942 |
+
if hook:
|
| 943 |
+
result = hook(
|
| 944 |
+
AttributeContext(
|
| 945 |
+
get_proper_type(mx.original_type), result, mx.is_lvalue, mx.context, mx.chk
|
| 946 |
+
)
|
| 947 |
+
)
|
| 948 |
+
return result
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def expand_without_binding(
|
| 952 |
+
typ: Type, var: Var, itype: Instance, original_itype: Instance, mx: MemberContext
|
| 953 |
+
) -> Type:
|
| 954 |
+
if not mx.preserve_type_var_ids:
|
| 955 |
+
typ = freshen_all_functions_type_vars(typ)
|
| 956 |
+
typ = expand_self_type_if_needed(typ, mx, var, original_itype)
|
| 957 |
+
expanded = expand_type_by_instance(typ, itype)
|
| 958 |
+
freeze_all_type_vars(expanded)
|
| 959 |
+
return expanded
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
def expand_and_bind_callable(
|
| 963 |
+
functype: FunctionLike,
|
| 964 |
+
var: Var,
|
| 965 |
+
itype: Instance,
|
| 966 |
+
name: str,
|
| 967 |
+
mx: MemberContext,
|
| 968 |
+
is_trivial_self: bool,
|
| 969 |
+
) -> Type:
|
| 970 |
+
if not mx.preserve_type_var_ids:
|
| 971 |
+
functype = freshen_all_functions_type_vars(functype)
|
| 972 |
+
typ = get_proper_type(expand_self_type(var, functype, mx.self_type))
|
| 973 |
+
assert isinstance(typ, FunctionLike)
|
| 974 |
+
if is_trivial_self:
|
| 975 |
+
typ = bind_self_fast(typ, mx.self_type)
|
| 976 |
+
else:
|
| 977 |
+
typ = check_self_arg(typ, mx.self_type, var.is_classmethod, mx.context, name, mx.msg)
|
| 978 |
+
typ = bind_self(typ, mx.self_type, var.is_classmethod)
|
| 979 |
+
expanded = expand_type_by_instance(typ, itype)
|
| 980 |
+
freeze_all_type_vars(expanded)
|
| 981 |
+
if not var.is_property:
|
| 982 |
+
return expanded
|
| 983 |
+
if isinstance(expanded, Overloaded):
|
| 984 |
+
# Legacy way to store settable properties is with overloads. Also in case it is
|
| 985 |
+
# an actual overloaded property, selecting first item that passed check_self_arg()
|
| 986 |
+
# is a good approximation, long-term we should use check_call() inference below.
|
| 987 |
+
if not expanded.items:
|
| 988 |
+
# A broken overload, error should be already reported.
|
| 989 |
+
return AnyType(TypeOfAny.from_error)
|
| 990 |
+
expanded = expanded.items[0]
|
| 991 |
+
assert isinstance(expanded, CallableType), expanded
|
| 992 |
+
if var.is_settable_property and mx.is_lvalue and var.setter_type is not None:
|
| 993 |
+
if expanded.variables:
|
| 994 |
+
type_ctx = mx.rvalue or TempNode(AnyType(TypeOfAny.special_form), context=mx.context)
|
| 995 |
+
_, inferred_expanded = mx.chk.expr_checker.check_call(
|
| 996 |
+
expanded, [type_ctx], [ARG_POS], mx.context
|
| 997 |
+
)
|
| 998 |
+
expanded = get_proper_type(inferred_expanded)
|
| 999 |
+
assert isinstance(expanded, CallableType)
|
| 1000 |
+
if not expanded.arg_types:
|
| 1001 |
+
# This can happen when accessing invalid property from its own body,
|
| 1002 |
+
# error will be reported elsewhere.
|
| 1003 |
+
return AnyType(TypeOfAny.from_error)
|
| 1004 |
+
return expanded.arg_types[0]
|
| 1005 |
+
else:
|
| 1006 |
+
return expanded.ret_type
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def expand_self_type_if_needed(
|
| 1010 |
+
t: Type, mx: MemberContext, var: Var, itype: Instance, is_class: bool = False
|
| 1011 |
+
) -> Type:
|
| 1012 |
+
"""Expand special Self type in a backwards compatible manner.
|
| 1013 |
+
|
| 1014 |
+
This should ensure that mixing old-style and new-style self-types work
|
| 1015 |
+
seamlessly. Also, re-bind new style self-types in subclasses if needed.
|
| 1016 |
+
"""
|
| 1017 |
+
original = get_proper_type(mx.self_type)
|
| 1018 |
+
if not (mx.is_self or mx.is_super):
|
| 1019 |
+
repl = mx.self_type
|
| 1020 |
+
if is_class:
|
| 1021 |
+
if isinstance(original, TypeType):
|
| 1022 |
+
repl = original.item
|
| 1023 |
+
elif isinstance(original, CallableType):
|
| 1024 |
+
# Problematic access errors should have been already reported.
|
| 1025 |
+
repl = erase_typevars(original.ret_type)
|
| 1026 |
+
else:
|
| 1027 |
+
repl = itype
|
| 1028 |
+
return expand_self_type(var, t, repl)
|
| 1029 |
+
elif supported_self_type(
|
| 1030 |
+
# Support compatibility with plain old style T -> T and Type[T] -> T only.
|
| 1031 |
+
get_proper_type(mx.self_type),
|
| 1032 |
+
allow_instances=False,
|
| 1033 |
+
allow_callable=False,
|
| 1034 |
+
):
|
| 1035 |
+
repl = mx.self_type
|
| 1036 |
+
if is_class and isinstance(original, TypeType):
|
| 1037 |
+
repl = original.item
|
| 1038 |
+
return expand_self_type(var, t, repl)
|
| 1039 |
+
elif (
|
| 1040 |
+
mx.is_self
|
| 1041 |
+
and itype.type != var.info
|
| 1042 |
+
# If an attribute with Self-type was defined in a supertype, we need to
|
| 1043 |
+
# rebind the Self type variable to Self type variable of current class...
|
| 1044 |
+
and itype.type.self_type is not None
|
| 1045 |
+
# ...unless `self` has an explicit non-trivial annotation.
|
| 1046 |
+
and itype == mx.chk.scope.active_self_type()
|
| 1047 |
+
):
|
| 1048 |
+
return expand_self_type(var, t, itype.type.self_type)
|
| 1049 |
+
else:
|
| 1050 |
+
return t
|
| 1051 |
+
|
| 1052 |
+
|
| 1053 |
+
def check_self_arg(
|
| 1054 |
+
functype: FunctionLike,
|
| 1055 |
+
dispatched_arg_type: Type,
|
| 1056 |
+
is_classmethod: bool,
|
| 1057 |
+
context: Context,
|
| 1058 |
+
name: str,
|
| 1059 |
+
msg: MessageBuilder,
|
| 1060 |
+
) -> FunctionLike:
|
| 1061 |
+
"""Check that an instance has a valid type for a method with annotated 'self'.
|
| 1062 |
+
|
| 1063 |
+
For example if the method is defined as:
|
| 1064 |
+
class A:
|
| 1065 |
+
def f(self: S) -> T: ...
|
| 1066 |
+
then for 'x.f' we check that type(x) <: S. If the method is overloaded, we select
|
| 1067 |
+
only overloads items that satisfy this requirement. If there are no matching
|
| 1068 |
+
overloads, an error is generated.
|
| 1069 |
+
"""
|
| 1070 |
+
items = functype.items
|
| 1071 |
+
if not items:
|
| 1072 |
+
return functype
|
| 1073 |
+
new_items = []
|
| 1074 |
+
if is_classmethod:
|
| 1075 |
+
dispatched_arg_type = TypeType.make_normalized(dispatched_arg_type)
|
| 1076 |
+
p_dispatched_arg_type = get_proper_type(dispatched_arg_type)
|
| 1077 |
+
|
| 1078 |
+
for item in items:
|
| 1079 |
+
if not item.arg_types or item.arg_kinds[0] not in (ARG_POS, ARG_STAR):
|
| 1080 |
+
# No positional first (self) argument (*args is okay).
|
| 1081 |
+
msg.no_formal_self(name, item, context)
|
| 1082 |
+
# This is pretty bad, so just return the original signature if
|
| 1083 |
+
# there is at least one such error.
|
| 1084 |
+
return functype
|
| 1085 |
+
selfarg = get_proper_type(item.arg_types[0])
|
| 1086 |
+
if isinstance(selfarg, Instance) and isinstance(p_dispatched_arg_type, Instance):
|
| 1087 |
+
if selfarg.type is p_dispatched_arg_type.type and selfarg.args:
|
| 1088 |
+
if not is_overlapping_types(p_dispatched_arg_type, selfarg):
|
| 1089 |
+
# This special casing is needed since `actual <: erased(template)`
|
| 1090 |
+
# logic below doesn't always work, and a more correct approach may
|
| 1091 |
+
# be tricky.
|
| 1092 |
+
continue
|
| 1093 |
+
new_items.append(item)
|
| 1094 |
+
|
| 1095 |
+
if new_items:
|
| 1096 |
+
items = new_items
|
| 1097 |
+
new_items = []
|
| 1098 |
+
|
| 1099 |
+
for item in items:
|
| 1100 |
+
selfarg = get_proper_type(item.arg_types[0])
|
| 1101 |
+
# This matches similar special-casing in bind_self(), see more details there.
|
| 1102 |
+
self_callable = name == "__call__" and isinstance(selfarg, CallableType)
|
| 1103 |
+
if self_callable or is_subtype(
|
| 1104 |
+
dispatched_arg_type,
|
| 1105 |
+
# This level of erasure matches the one in checker.check_func_def(),
|
| 1106 |
+
# better keep these two checks consistent.
|
| 1107 |
+
erase_typevars(erase_to_bound(selfarg)),
|
| 1108 |
+
# This is to work around the fact that erased ParamSpec and TypeVarTuple
|
| 1109 |
+
# callables are not always compatible with non-erased ones both ways.
|
| 1110 |
+
always_covariant=any(
|
| 1111 |
+
not isinstance(tv, TypeVarType) for tv in get_all_type_vars(selfarg)
|
| 1112 |
+
),
|
| 1113 |
+
ignore_pos_arg_names=True,
|
| 1114 |
+
):
|
| 1115 |
+
new_items.append(item)
|
| 1116 |
+
elif isinstance(selfarg, ParamSpecType):
|
| 1117 |
+
# TODO: This is not always right. What's the most reasonable thing to do here?
|
| 1118 |
+
new_items.append(item)
|
| 1119 |
+
elif isinstance(selfarg, TypeVarTupleType):
|
| 1120 |
+
raise NotImplementedError
|
| 1121 |
+
if not new_items:
|
| 1122 |
+
# Choose first item for the message (it may be not very helpful for overloads).
|
| 1123 |
+
msg.incompatible_self_argument(
|
| 1124 |
+
name, dispatched_arg_type, items[0], is_classmethod, context
|
| 1125 |
+
)
|
| 1126 |
+
return functype
|
| 1127 |
+
if len(new_items) == 1:
|
| 1128 |
+
return new_items[0]
|
| 1129 |
+
return Overloaded(new_items)
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
def analyze_class_attribute_access(
|
| 1133 |
+
itype: Instance,
|
| 1134 |
+
name: str,
|
| 1135 |
+
mx: MemberContext,
|
| 1136 |
+
*,
|
| 1137 |
+
mcs_fallback: Instance,
|
| 1138 |
+
override_info: TypeInfo | None = None,
|
| 1139 |
+
original_vars: Sequence[TypeVarLikeType] | None = None,
|
| 1140 |
+
) -> Type | None:
|
| 1141 |
+
"""Analyze access to an attribute on a class object.
|
| 1142 |
+
|
| 1143 |
+
itype is the return type of the class object callable, original_type is the type
|
| 1144 |
+
of E in the expression E.var, original_vars are type variables of the class callable
|
| 1145 |
+
(for generic classes).
|
| 1146 |
+
"""
|
| 1147 |
+
info = itype.type
|
| 1148 |
+
if override_info:
|
| 1149 |
+
info = override_info
|
| 1150 |
+
|
| 1151 |
+
fullname = f"{info.fullname}.{name}"
|
| 1152 |
+
hook = mx.chk.plugin.get_class_attribute_hook(fullname)
|
| 1153 |
+
|
| 1154 |
+
node = info.get(name)
|
| 1155 |
+
if not node:
|
| 1156 |
+
if itype.extra_attrs and name in itype.extra_attrs.attrs:
|
| 1157 |
+
# For modules use direct symbol table lookup.
|
| 1158 |
+
if not itype.extra_attrs.mod_name:
|
| 1159 |
+
return itype.extra_attrs.attrs[name]
|
| 1160 |
+
if info.fallback_to_any or info.meta_fallback_to_any:
|
| 1161 |
+
return apply_class_attr_hook(mx, hook, AnyType(TypeOfAny.special_form))
|
| 1162 |
+
return None
|
| 1163 |
+
|
| 1164 |
+
if (
|
| 1165 |
+
isinstance(node.node, Var)
|
| 1166 |
+
and not node.node.is_classvar
|
| 1167 |
+
and not hook
|
| 1168 |
+
and mcs_fallback.type.get(name)
|
| 1169 |
+
):
|
| 1170 |
+
# If the same attribute is declared on the metaclass and the class but with different types,
|
| 1171 |
+
# and the attribute on the class is not a ClassVar,
|
| 1172 |
+
# the type of the attribute on the metaclass should take priority
|
| 1173 |
+
# over the type of the attribute on the class,
|
| 1174 |
+
# when the attribute is being accessed from the class object itself.
|
| 1175 |
+
#
|
| 1176 |
+
# Return `None` here to signify that the name should be looked up
|
| 1177 |
+
# on the class object itself rather than the instance.
|
| 1178 |
+
return None
|
| 1179 |
+
|
| 1180 |
+
mx.chk.warn_deprecated(node.node, mx.context)
|
| 1181 |
+
|
| 1182 |
+
is_decorated = isinstance(node.node, Decorator)
|
| 1183 |
+
is_method = is_decorated or isinstance(node.node, FuncBase)
|
| 1184 |
+
if mx.is_lvalue and not mx.suppress_errors:
|
| 1185 |
+
if is_method:
|
| 1186 |
+
mx.msg.cant_assign_to_method(mx.context)
|
| 1187 |
+
if isinstance(node.node, TypeInfo):
|
| 1188 |
+
mx.fail(message_registry.CANNOT_ASSIGN_TO_TYPE)
|
| 1189 |
+
|
| 1190 |
+
# Refuse class attribute access if slot defined
|
| 1191 |
+
if info.slots and name in info.slots:
|
| 1192 |
+
mx.fail(message_registry.CLASS_VAR_CONFLICTS_SLOTS.format(name))
|
| 1193 |
+
|
| 1194 |
+
if node.implicit and isinstance(node.node, Var):
|
| 1195 |
+
if node.node.is_final:
|
| 1196 |
+
# If a final attribute was declared on `self` in `__init__`, then it
|
| 1197 |
+
# can't be accessed on the class object.
|
| 1198 |
+
mx.fail(message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR.format(node.node.name))
|
| 1199 |
+
elif not mx.is_lvalue and not defined_in_superclass(info, name):
|
| 1200 |
+
mx.fail(message_registry.CANNOT_ACCESS_INSTANCE_ONLY_ATTR.format(node.node.name))
|
| 1201 |
+
|
| 1202 |
+
# An assignment to final attribute on class object is also always an error,
|
| 1203 |
+
# independently of types.
|
| 1204 |
+
if mx.is_lvalue and not mx.chk.get_final_context():
|
| 1205 |
+
check_final_member(name, info, mx.msg, mx.context)
|
| 1206 |
+
|
| 1207 |
+
if info.is_enum and not (mx.is_lvalue or is_decorated or is_method):
|
| 1208 |
+
enum_class_attribute_type = analyze_enum_class_attribute_access(itype, name, mx)
|
| 1209 |
+
if enum_class_attribute_type:
|
| 1210 |
+
return apply_class_attr_hook(mx, hook, enum_class_attribute_type)
|
| 1211 |
+
|
| 1212 |
+
t = node.type
|
| 1213 |
+
if t:
|
| 1214 |
+
if isinstance(t, PartialType):
|
| 1215 |
+
symnode = node.node
|
| 1216 |
+
assert isinstance(symnode, Var)
|
| 1217 |
+
return apply_class_attr_hook(
|
| 1218 |
+
mx, hook, mx.chk.handle_partial_var_type(t, mx.is_lvalue, symnode, mx.context)
|
| 1219 |
+
)
|
| 1220 |
+
|
| 1221 |
+
# Find the class where method/variable was defined.
|
| 1222 |
+
if isinstance(node.node, Decorator):
|
| 1223 |
+
super_info: TypeInfo | None = node.node.var.info
|
| 1224 |
+
elif isinstance(node.node, (Var, SYMBOL_FUNCBASE_TYPES)):
|
| 1225 |
+
super_info = node.node.info
|
| 1226 |
+
else:
|
| 1227 |
+
super_info = None
|
| 1228 |
+
|
| 1229 |
+
# Map the type to how it would look as a defining class. For example:
|
| 1230 |
+
# class C(Generic[T]): ...
|
| 1231 |
+
# class D(C[Tuple[T, S]]): ...
|
| 1232 |
+
# D[int, str].method()
|
| 1233 |
+
# Here itype is D[int, str], isuper is C[Tuple[int, str]].
|
| 1234 |
+
if not super_info:
|
| 1235 |
+
isuper = None
|
| 1236 |
+
else:
|
| 1237 |
+
isuper = map_instance_to_supertype(itype, super_info)
|
| 1238 |
+
|
| 1239 |
+
if isinstance(node.node, Var):
|
| 1240 |
+
assert isuper is not None
|
| 1241 |
+
object_type = get_proper_type(mx.self_type)
|
| 1242 |
+
# Check if original variable type has type variables. For example:
|
| 1243 |
+
# class C(Generic[T]):
|
| 1244 |
+
# x: T
|
| 1245 |
+
# C.x # Error, ambiguous access
|
| 1246 |
+
# C[int].x # Also an error, since C[int] is same as C at runtime
|
| 1247 |
+
# Exception is Self type wrapped in ClassVar, that is safe.
|
| 1248 |
+
prohibit_self = not node.node.is_classvar
|
| 1249 |
+
def_vars = set(node.node.info.defn.type_vars)
|
| 1250 |
+
if prohibit_self and node.node.info.self_type:
|
| 1251 |
+
def_vars.add(node.node.info.self_type)
|
| 1252 |
+
# Exception: access on Type[...], including first argument of class methods is OK.
|
| 1253 |
+
prohibit_generic = not isinstance(object_type, TypeType) or node.implicit
|
| 1254 |
+
if prohibit_generic and def_vars & set(get_all_type_vars(t)):
|
| 1255 |
+
if node.node.is_classvar:
|
| 1256 |
+
message = message_registry.GENERIC_CLASS_VAR_ACCESS
|
| 1257 |
+
else:
|
| 1258 |
+
message = message_registry.GENERIC_INSTANCE_VAR_CLASS_ACCESS
|
| 1259 |
+
mx.fail(message)
|
| 1260 |
+
t = expand_self_type_if_needed(t, mx, node.node, itype, is_class=True)
|
| 1261 |
+
t = expand_type_by_instance(t, isuper)
|
| 1262 |
+
# Erase non-mapped variables, but keep mapped ones, even if there is an error.
|
| 1263 |
+
# In the above example this means that we infer following types:
|
| 1264 |
+
# C.x -> Any
|
| 1265 |
+
# C[int].x -> int
|
| 1266 |
+
if prohibit_generic:
|
| 1267 |
+
erase_vars = set(itype.type.defn.type_vars)
|
| 1268 |
+
if prohibit_self and itype.type.self_type:
|
| 1269 |
+
erase_vars.add(itype.type.self_type)
|
| 1270 |
+
t = erase_typevars(t, {tv.id for tv in erase_vars})
|
| 1271 |
+
|
| 1272 |
+
is_classmethod = (
|
| 1273 |
+
(is_decorated and cast(Decorator, node.node).func.is_class)
|
| 1274 |
+
or (isinstance(node.node, SYMBOL_FUNCBASE_TYPES) and node.node.is_class)
|
| 1275 |
+
or isinstance(node.node, Var)
|
| 1276 |
+
and node.node.is_classmethod
|
| 1277 |
+
)
|
| 1278 |
+
t = get_proper_type(t)
|
| 1279 |
+
is_trivial_self = False
|
| 1280 |
+
if isinstance(node.node, Decorator):
|
| 1281 |
+
# Use fast path if there are trivial decorators like @classmethod or @property
|
| 1282 |
+
is_trivial_self = node.node.func.is_trivial_self and not node.node.decorators
|
| 1283 |
+
elif isinstance(node.node, (FuncDef, OverloadedFuncDef)):
|
| 1284 |
+
is_trivial_self = node.node.is_trivial_self
|
| 1285 |
+
if (
|
| 1286 |
+
isinstance(t, FunctionLike)
|
| 1287 |
+
and is_classmethod
|
| 1288 |
+
and not is_trivial_self
|
| 1289 |
+
and not t.bound()
|
| 1290 |
+
):
|
| 1291 |
+
t = check_self_arg(t, mx.self_type, False, mx.context, name, mx.msg)
|
| 1292 |
+
t = add_class_tvars(
|
| 1293 |
+
t,
|
| 1294 |
+
isuper,
|
| 1295 |
+
is_classmethod,
|
| 1296 |
+
mx,
|
| 1297 |
+
original_vars=original_vars,
|
| 1298 |
+
is_trivial_self=is_trivial_self,
|
| 1299 |
+
)
|
| 1300 |
+
if is_decorated:
|
| 1301 |
+
t = expand_self_type_if_needed(
|
| 1302 |
+
t, mx, cast(Decorator, node.node).var, itype, is_class=is_classmethod
|
| 1303 |
+
)
|
| 1304 |
+
|
| 1305 |
+
result = t
|
| 1306 |
+
# __set__ is not called on class objects.
|
| 1307 |
+
if not mx.is_lvalue:
|
| 1308 |
+
result = analyze_descriptor_access(result, mx)
|
| 1309 |
+
|
| 1310 |
+
return apply_class_attr_hook(mx, hook, result)
|
| 1311 |
+
elif isinstance(node.node, Var):
|
| 1312 |
+
mx.not_ready_callback(name, mx.context)
|
| 1313 |
+
return AnyType(TypeOfAny.special_form)
|
| 1314 |
+
|
| 1315 |
+
if isinstance(node.node, (TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)):
|
| 1316 |
+
# TODO: should we apply class plugin here (similar to instance access)?
|
| 1317 |
+
return mx.chk.expr_checker.analyze_static_reference(node.node, mx.context, mx.is_lvalue)
|
| 1318 |
+
|
| 1319 |
+
if is_decorated:
|
| 1320 |
+
assert isinstance(node.node, Decorator)
|
| 1321 |
+
if node.node.type:
|
| 1322 |
+
return apply_class_attr_hook(mx, hook, node.node.type)
|
| 1323 |
+
else:
|
| 1324 |
+
mx.not_ready_callback(name, mx.context)
|
| 1325 |
+
return AnyType(TypeOfAny.from_error)
|
| 1326 |
+
else:
|
| 1327 |
+
assert isinstance(node.node, SYMBOL_FUNCBASE_TYPES)
|
| 1328 |
+
typ = function_type(node.node, mx.named_type("builtins.function"))
|
| 1329 |
+
# Note: if we are accessing class method on class object, the cls argument is bound.
|
| 1330 |
+
# Annotated and/or explicit class methods go through other code paths above, for
|
| 1331 |
+
# unannotated implicit class methods we do this here.
|
| 1332 |
+
if node.node.is_class:
|
| 1333 |
+
typ = bind_self_fast(typ)
|
| 1334 |
+
return apply_class_attr_hook(mx, hook, typ)
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
def apply_class_attr_hook(
|
| 1338 |
+
mx: MemberContext, hook: Callable[[AttributeContext], Type] | None, result: Type
|
| 1339 |
+
) -> Type | None:
|
| 1340 |
+
if hook:
|
| 1341 |
+
result = hook(
|
| 1342 |
+
AttributeContext(
|
| 1343 |
+
get_proper_type(mx.original_type), result, mx.is_lvalue, mx.context, mx.chk
|
| 1344 |
+
)
|
| 1345 |
+
)
|
| 1346 |
+
return result
|
| 1347 |
+
|
| 1348 |
+
|
| 1349 |
+
def analyze_enum_class_attribute_access(
|
| 1350 |
+
itype: Instance, name: str, mx: MemberContext
|
| 1351 |
+
) -> Type | None:
|
| 1352 |
+
# Skip these since Enum will remove it
|
| 1353 |
+
if name in EXCLUDED_ENUM_ATTRIBUTES:
|
| 1354 |
+
return report_missing_attribute(mx.original_type, itype, name, mx)
|
| 1355 |
+
|
| 1356 |
+
node = itype.type.get(name)
|
| 1357 |
+
if node and node.type:
|
| 1358 |
+
proper = get_proper_type(node.type)
|
| 1359 |
+
# Support `A = nonmember(1)` function call and decorator.
|
| 1360 |
+
if (
|
| 1361 |
+
isinstance(proper, Instance)
|
| 1362 |
+
and proper.type.fullname == "enum.nonmember"
|
| 1363 |
+
and proper.args
|
| 1364 |
+
):
|
| 1365 |
+
return proper.args[0]
|
| 1366 |
+
|
| 1367 |
+
if name not in itype.type.enum_members:
|
| 1368 |
+
return None
|
| 1369 |
+
|
| 1370 |
+
enum_literal = LiteralType(name, fallback=itype)
|
| 1371 |
+
return itype.copy_modified(last_known_value=enum_literal)
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
def analyze_typeddict_access(
|
| 1375 |
+
name: str, typ: TypedDictType, mx: MemberContext, override_info: TypeInfo | None
|
| 1376 |
+
) -> Type:
|
| 1377 |
+
if name == "__setitem__":
|
| 1378 |
+
if isinstance(mx.context, IndexExpr):
|
| 1379 |
+
# Since we can get this during `a['key'] = ...`
|
| 1380 |
+
# it is safe to assume that the context is `IndexExpr`.
|
| 1381 |
+
item_type, key_names = mx.chk.expr_checker.visit_typeddict_index_expr(
|
| 1382 |
+
typ, mx.context.index, setitem=True
|
| 1383 |
+
)
|
| 1384 |
+
assigned_readonly_keys = typ.readonly_keys & key_names
|
| 1385 |
+
if assigned_readonly_keys and not mx.suppress_errors:
|
| 1386 |
+
mx.msg.readonly_keys_mutated(assigned_readonly_keys, context=mx.context)
|
| 1387 |
+
else:
|
| 1388 |
+
# It can also be `a.__setitem__(...)` direct call.
|
| 1389 |
+
# In this case `item_type` can be `Any`,
|
| 1390 |
+
# because we don't have args available yet.
|
| 1391 |
+
# TODO: check in `default` plugin that `__setitem__` is correct.
|
| 1392 |
+
item_type = AnyType(TypeOfAny.implementation_artifact)
|
| 1393 |
+
return CallableType(
|
| 1394 |
+
arg_types=[mx.chk.named_type("builtins.str"), item_type],
|
| 1395 |
+
arg_kinds=[ARG_POS, ARG_POS],
|
| 1396 |
+
arg_names=[None, None],
|
| 1397 |
+
ret_type=NoneType(),
|
| 1398 |
+
fallback=mx.chk.named_type("builtins.function"),
|
| 1399 |
+
name=name,
|
| 1400 |
+
)
|
| 1401 |
+
elif name == "__delitem__":
|
| 1402 |
+
return CallableType(
|
| 1403 |
+
arg_types=[mx.chk.named_type("builtins.str")],
|
| 1404 |
+
arg_kinds=[ARG_POS],
|
| 1405 |
+
arg_names=[None],
|
| 1406 |
+
ret_type=NoneType(),
|
| 1407 |
+
fallback=mx.chk.named_type("builtins.function"),
|
| 1408 |
+
name=name,
|
| 1409 |
+
)
|
| 1410 |
+
return _analyze_member_access(name, typ.fallback, mx, override_info)
|
| 1411 |
+
|
| 1412 |
+
|
| 1413 |
+
def add_class_tvars(
|
| 1414 |
+
t: ProperType,
|
| 1415 |
+
isuper: Instance | None,
|
| 1416 |
+
is_classmethod: bool,
|
| 1417 |
+
mx: MemberContext,
|
| 1418 |
+
original_vars: Sequence[TypeVarLikeType] | None = None,
|
| 1419 |
+
is_trivial_self: bool = False,
|
| 1420 |
+
) -> Type:
|
| 1421 |
+
"""Instantiate type variables during analyze_class_attribute_access,
|
| 1422 |
+
e.g T and Q in the following:
|
| 1423 |
+
|
| 1424 |
+
class A(Generic[T]):
|
| 1425 |
+
@classmethod
|
| 1426 |
+
def foo(cls: Type[Q]) -> Tuple[T, Q]: ...
|
| 1427 |
+
|
| 1428 |
+
class B(A[str]): pass
|
| 1429 |
+
B.foo()
|
| 1430 |
+
|
| 1431 |
+
Args:
|
| 1432 |
+
t: Declared type of the method (or property)
|
| 1433 |
+
isuper: Current instance mapped to the superclass where method was defined, this
|
| 1434 |
+
is usually done by map_instance_to_supertype()
|
| 1435 |
+
is_classmethod: True if this method is decorated with @classmethod
|
| 1436 |
+
original_vars: Type variables of the class callable on which the method was accessed
|
| 1437 |
+
is_trivial_self: if True, we can use fast path for bind_self().
|
| 1438 |
+
Returns:
|
| 1439 |
+
Expanded method type with added type variables (when needed).
|
| 1440 |
+
"""
|
| 1441 |
+
# TODO: verify consistency between Q and T
|
| 1442 |
+
|
| 1443 |
+
# We add class type variables if the class method is accessed on class object
|
| 1444 |
+
# without applied type arguments, this matches the behavior of __init__().
|
| 1445 |
+
# For example (continuing the example in docstring):
|
| 1446 |
+
# A # The type of callable is def [T] () -> A[T], _not_ def () -> A[Any]
|
| 1447 |
+
# A[int] # The type of callable is def () -> A[int]
|
| 1448 |
+
# and
|
| 1449 |
+
# A.foo # The type is generic def [T] () -> Tuple[T, A[T]]
|
| 1450 |
+
# A[int].foo # The type is non-generic def () -> Tuple[int, A[int]]
|
| 1451 |
+
#
|
| 1452 |
+
# This behaviour is useful for defining alternative constructors for generic classes.
|
| 1453 |
+
# To achieve such behaviour, we add the class type variables that are still free
|
| 1454 |
+
# (i.e. appear in the return type of the class object on which the method was accessed).
|
| 1455 |
+
if isinstance(t, CallableType):
|
| 1456 |
+
tvars = original_vars if original_vars is not None else []
|
| 1457 |
+
if not mx.preserve_type_var_ids:
|
| 1458 |
+
t = freshen_all_functions_type_vars(t)
|
| 1459 |
+
if is_classmethod and not t.is_bound:
|
| 1460 |
+
if is_trivial_self:
|
| 1461 |
+
t = bind_self_fast(t, mx.self_type)
|
| 1462 |
+
else:
|
| 1463 |
+
t = bind_self(t, mx.self_type, is_classmethod=True)
|
| 1464 |
+
if isuper is not None:
|
| 1465 |
+
t = expand_type_by_instance(t, isuper)
|
| 1466 |
+
freeze_all_type_vars(t)
|
| 1467 |
+
return t.copy_modified(variables=list(tvars) + list(t.variables))
|
| 1468 |
+
elif isinstance(t, Overloaded):
|
| 1469 |
+
return Overloaded(
|
| 1470 |
+
[
|
| 1471 |
+
cast(
|
| 1472 |
+
CallableType,
|
| 1473 |
+
add_class_tvars(item, isuper, is_classmethod, mx, original_vars=original_vars),
|
| 1474 |
+
)
|
| 1475 |
+
for item in t.items
|
| 1476 |
+
]
|
| 1477 |
+
)
|
| 1478 |
+
if isuper is not None:
|
| 1479 |
+
t = expand_type_by_instance(t, isuper)
|
| 1480 |
+
return t
|
| 1481 |
+
|
| 1482 |
+
|
| 1483 |
+
def analyze_decorator_or_funcbase_access(
|
| 1484 |
+
defn: Decorator | FuncBase, itype: Instance, name: str, mx: MemberContext
|
| 1485 |
+
) -> Type:
|
| 1486 |
+
"""Analyzes the type behind method access.
|
| 1487 |
+
|
| 1488 |
+
The function itself can possibly be decorated.
|
| 1489 |
+
See: https://github.com/python/mypy/issues/10409
|
| 1490 |
+
"""
|
| 1491 |
+
if isinstance(defn, Decorator):
|
| 1492 |
+
return analyze_var(name, defn.var, itype, mx)
|
| 1493 |
+
typ = function_type(defn, mx.chk.named_type("builtins.function"))
|
| 1494 |
+
if isinstance(defn, (FuncDef, OverloadedFuncDef)) and defn.is_trivial_self:
|
| 1495 |
+
return bind_self_fast(typ, mx.self_type)
|
| 1496 |
+
typ = check_self_arg(typ, mx.self_type, defn.is_class, mx.context, name, mx.msg)
|
| 1497 |
+
return bind_self(typ, original_type=mx.self_type, is_classmethod=defn.is_class)
|
| 1498 |
+
|
| 1499 |
+
|
| 1500 |
+
F = TypeVar("F", bound=FunctionLike)
|
| 1501 |
+
|
| 1502 |
+
|
| 1503 |
+
def bind_self_fast(method: F, original_type: Type | None = None) -> F:
|
| 1504 |
+
"""Return a copy of `method`, with the type of its first parameter (usually
|
| 1505 |
+
self or cls) bound to original_type.
|
| 1506 |
+
|
| 1507 |
+
This is a faster version of mypy.typeops.bind_self() that can be used for methods
|
| 1508 |
+
with trivial self/cls annotations.
|
| 1509 |
+
"""
|
| 1510 |
+
if isinstance(method, Overloaded):
|
| 1511 |
+
items = [bind_self_fast(c, original_type) for c in method.items]
|
| 1512 |
+
return cast(F, Overloaded(items))
|
| 1513 |
+
assert isinstance(method, CallableType)
|
| 1514 |
+
if not method.arg_types:
|
| 1515 |
+
# Invalid method, return something.
|
| 1516 |
+
return method
|
| 1517 |
+
if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2):
|
| 1518 |
+
# See typeops.py for details.
|
| 1519 |
+
return method
|
| 1520 |
+
return method.copy_modified(
|
| 1521 |
+
arg_types=method.arg_types[1:],
|
| 1522 |
+
arg_kinds=method.arg_kinds[1:],
|
| 1523 |
+
arg_names=method.arg_names[1:],
|
| 1524 |
+
is_bound=True,
|
| 1525 |
+
)
|
| 1526 |
+
|
| 1527 |
+
|
| 1528 |
+
def has_operator(typ: Type, op_method: str, named_type: Callable[[str], Instance]) -> bool:
|
| 1529 |
+
"""Does type have operator with the given name?
|
| 1530 |
+
|
| 1531 |
+
Note: this follows the rules for operator access, in particular:
|
| 1532 |
+
* __getattr__ is not considered
|
| 1533 |
+
* for class objects we only look in metaclass
|
| 1534 |
+
* instance level attributes (i.e. extra_attrs) are not considered
|
| 1535 |
+
"""
|
| 1536 |
+
# This is much faster than analyze_member_access, and so using
|
| 1537 |
+
# it first as a filter is important for performance. This is mostly relevant
|
| 1538 |
+
# in situations where we can't expect that method is likely present,
|
| 1539 |
+
# e.g. for __OP__ vs __rOP__.
|
| 1540 |
+
typ = get_proper_type(typ)
|
| 1541 |
+
|
| 1542 |
+
if isinstance(typ, TypeVarLikeType):
|
| 1543 |
+
typ = typ.values_or_bound()
|
| 1544 |
+
if isinstance(typ, AnyType):
|
| 1545 |
+
return True
|
| 1546 |
+
if isinstance(typ, UnionType):
|
| 1547 |
+
return all(has_operator(x, op_method, named_type) for x in typ.relevant_items())
|
| 1548 |
+
if isinstance(typ, FunctionLike) and typ.is_type_obj():
|
| 1549 |
+
return typ.fallback.type.has_readable_member(op_method)
|
| 1550 |
+
if isinstance(typ, TypeType):
|
| 1551 |
+
# Type[Union[X, ...]] is always normalized to Union[Type[X], ...],
|
| 1552 |
+
# so we don't need to care about unions here, but we need to care about
|
| 1553 |
+
# Type[T], where upper bound of T is a union.
|
| 1554 |
+
item = typ.item
|
| 1555 |
+
if isinstance(item, TypeVarType):
|
| 1556 |
+
item = item.values_or_bound()
|
| 1557 |
+
if isinstance(item, UnionType):
|
| 1558 |
+
return all(meta_has_operator(x, op_method, named_type) for x in item.relevant_items())
|
| 1559 |
+
return meta_has_operator(item, op_method, named_type)
|
| 1560 |
+
return instance_fallback(typ, named_type).type.has_readable_member(op_method)
|
| 1561 |
+
|
| 1562 |
+
|
| 1563 |
+
def instance_fallback(typ: ProperType, named_type: Callable[[str], Instance]) -> Instance:
|
| 1564 |
+
if isinstance(typ, Instance):
|
| 1565 |
+
return typ
|
| 1566 |
+
if isinstance(typ, TupleType):
|
| 1567 |
+
return tuple_fallback(typ)
|
| 1568 |
+
if isinstance(typ, (LiteralType, TypedDictType)):
|
| 1569 |
+
return typ.fallback
|
| 1570 |
+
return named_type("builtins.object")
|
| 1571 |
+
|
| 1572 |
+
|
| 1573 |
+
def meta_has_operator(item: Type, op_method: str, named_type: Callable[[str], Instance]) -> bool:
|
| 1574 |
+
item = get_proper_type(item)
|
| 1575 |
+
if isinstance(item, AnyType):
|
| 1576 |
+
return True
|
| 1577 |
+
item = instance_fallback(item, named_type)
|
| 1578 |
+
meta = item.type.metaclass_type or named_type("builtins.type")
|
| 1579 |
+
return meta.type.has_readable_member(op_method)
|
| 1580 |
+
|
| 1581 |
+
|
| 1582 |
+
def defined_in_superclass(info: TypeInfo, name: str) -> bool:
|
| 1583 |
+
"""Check if a variable has an explicit value at class level in any of superclasses."""
|
| 1584 |
+
for base in info.mro[1:]:
|
| 1585 |
+
if (node := base.names.get(name)) is not None:
|
| 1586 |
+
if not node.implicit and isinstance(node.node, Var) and node.node.has_explicit_value:
|
| 1587 |
+
return True
|
| 1588 |
+
return False
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkpattern.py
ADDED
|
@@ -0,0 +1,885 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pattern checker. This file is conceptually part of TypeChecker."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from typing import Final, NamedTuple
|
| 7 |
+
|
| 8 |
+
from mypy import message_registry
|
| 9 |
+
from mypy.checker_shared import TypeCheckerSharedApi, TypeRange
|
| 10 |
+
from mypy.checkmember import analyze_member_access
|
| 11 |
+
from mypy.expandtype import expand_type_by_instance
|
| 12 |
+
from mypy.join import join_types
|
| 13 |
+
from mypy.literals import literal_hash
|
| 14 |
+
from mypy.maptype import map_instance_to_supertype
|
| 15 |
+
from mypy.meet import narrow_declared_type
|
| 16 |
+
from mypy.messages import MessageBuilder
|
| 17 |
+
from mypy.nodes import ARG_POS, Expression, NameExpr, TempNode, TypeAlias, Var
|
| 18 |
+
from mypy.options import Options
|
| 19 |
+
from mypy.patterns import (
|
| 20 |
+
AsPattern,
|
| 21 |
+
ClassPattern,
|
| 22 |
+
MappingPattern,
|
| 23 |
+
OrPattern,
|
| 24 |
+
Pattern,
|
| 25 |
+
SequencePattern,
|
| 26 |
+
SingletonPattern,
|
| 27 |
+
StarredPattern,
|
| 28 |
+
ValuePattern,
|
| 29 |
+
)
|
| 30 |
+
from mypy.plugin import Plugin
|
| 31 |
+
from mypy.subtypes import is_subtype
|
| 32 |
+
from mypy.typeops import (
|
| 33 |
+
coerce_to_literal,
|
| 34 |
+
make_simplified_union,
|
| 35 |
+
try_getting_str_literals_from_type,
|
| 36 |
+
tuple_fallback,
|
| 37 |
+
)
|
| 38 |
+
from mypy.types import (
|
| 39 |
+
AnyType,
|
| 40 |
+
FunctionLike,
|
| 41 |
+
Instance,
|
| 42 |
+
NoneType,
|
| 43 |
+
ProperType,
|
| 44 |
+
TupleType,
|
| 45 |
+
Type,
|
| 46 |
+
TypedDictType,
|
| 47 |
+
TypeOfAny,
|
| 48 |
+
TypeType,
|
| 49 |
+
TypeVarTupleType,
|
| 50 |
+
TypeVarType,
|
| 51 |
+
UninhabitedType,
|
| 52 |
+
UnionType,
|
| 53 |
+
UnpackType,
|
| 54 |
+
callable_with_ellipsis,
|
| 55 |
+
find_unpack_in_list,
|
| 56 |
+
get_proper_type,
|
| 57 |
+
split_with_prefix_and_suffix,
|
| 58 |
+
)
|
| 59 |
+
from mypy.typevars import fill_typevars, fill_typevars_with_any
|
| 60 |
+
from mypy.visitor import PatternVisitor
|
| 61 |
+
|
| 62 |
+
self_match_type_names: Final = [
|
| 63 |
+
"builtins.bool",
|
| 64 |
+
"builtins.bytearray",
|
| 65 |
+
"builtins.bytes",
|
| 66 |
+
"builtins.dict",
|
| 67 |
+
"builtins.float",
|
| 68 |
+
"builtins.frozenset",
|
| 69 |
+
"builtins.int",
|
| 70 |
+
"builtins.list",
|
| 71 |
+
"builtins.set",
|
| 72 |
+
"builtins.str",
|
| 73 |
+
"builtins.tuple",
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
non_sequence_match_type_names: Final = ["builtins.str", "builtins.bytes", "builtins.bytearray"]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# For every Pattern a PatternType can be calculated. This requires recursively calculating
|
| 80 |
+
# the PatternTypes of the sub-patterns first.
|
| 81 |
+
# Using the data in the PatternType the match subject and captured names can be narrowed/inferred.
|
| 82 |
+
class PatternType(NamedTuple):
|
| 83 |
+
type: Type # The type the match subject can be narrowed to
|
| 84 |
+
rest_type: Type # The remaining type if the pattern didn't match
|
| 85 |
+
captures: dict[Expression, Type] # The variables captured by the pattern
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class PatternChecker(PatternVisitor[PatternType]):
|
| 89 |
+
"""Pattern checker.
|
| 90 |
+
|
| 91 |
+
This class checks if a pattern can match a type, what the type can be narrowed to, and what
|
| 92 |
+
type capture patterns should be inferred as.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
# Some services are provided by a TypeChecker instance.
|
| 96 |
+
chk: TypeCheckerSharedApi
|
| 97 |
+
# This is shared with TypeChecker, but stored also here for convenience.
|
| 98 |
+
msg: MessageBuilder
|
| 99 |
+
# Currently unused
|
| 100 |
+
plugin: Plugin
|
| 101 |
+
# The expression being matched against the pattern
|
| 102 |
+
subject: Expression
|
| 103 |
+
|
| 104 |
+
subject_type: Type
|
| 105 |
+
# Type of the subject to check the (sub)pattern against
|
| 106 |
+
type_context: list[Type]
|
| 107 |
+
# Types that match against self instead of their __match_args__ if used as a class pattern
|
| 108 |
+
# Filled in from self_match_type_names
|
| 109 |
+
self_match_types: list[Type]
|
| 110 |
+
# Types that are sequences, but don't match sequence patterns. Filled in from
|
| 111 |
+
# non_sequence_match_type_names
|
| 112 |
+
non_sequence_match_types: list[Type]
|
| 113 |
+
|
| 114 |
+
options: Options
|
| 115 |
+
|
| 116 |
+
def __init__(
|
| 117 |
+
self, chk: TypeCheckerSharedApi, msg: MessageBuilder, plugin: Plugin, options: Options
|
| 118 |
+
) -> None:
|
| 119 |
+
self.chk = chk
|
| 120 |
+
self.msg = msg
|
| 121 |
+
self.plugin = plugin
|
| 122 |
+
|
| 123 |
+
self.type_context = []
|
| 124 |
+
self.self_match_types = self.generate_types_from_names(self_match_type_names)
|
| 125 |
+
self.non_sequence_match_types = self.generate_types_from_names(
|
| 126 |
+
non_sequence_match_type_names
|
| 127 |
+
)
|
| 128 |
+
self.options = options
|
| 129 |
+
|
| 130 |
+
def accept(self, o: Pattern, type_context: Type) -> PatternType:
|
| 131 |
+
self.type_context.append(type_context)
|
| 132 |
+
result = o.accept(self)
|
| 133 |
+
self.type_context.pop()
|
| 134 |
+
|
| 135 |
+
return result
|
| 136 |
+
|
| 137 |
+
def visit_as_pattern(self, o: AsPattern) -> PatternType:
|
| 138 |
+
current_type = self.type_context[-1]
|
| 139 |
+
if o.pattern is not None:
|
| 140 |
+
pattern_type = self.accept(o.pattern, current_type)
|
| 141 |
+
typ, rest_type, type_map = pattern_type
|
| 142 |
+
else:
|
| 143 |
+
typ, rest_type, type_map = current_type, UninhabitedType(), {}
|
| 144 |
+
|
| 145 |
+
if not is_uninhabited(typ) and o.name is not None:
|
| 146 |
+
typ, _ = self.chk.conditional_types_with_intersection(
|
| 147 |
+
current_type, [get_type_range(typ)], o, default=current_type
|
| 148 |
+
)
|
| 149 |
+
if not is_uninhabited(typ):
|
| 150 |
+
type_map[o.name] = typ
|
| 151 |
+
|
| 152 |
+
return PatternType(typ, rest_type, type_map)
|
| 153 |
+
|
| 154 |
+
def visit_or_pattern(self, o: OrPattern) -> PatternType:
|
| 155 |
+
current_type = self.type_context[-1]
|
| 156 |
+
|
| 157 |
+
#
|
| 158 |
+
# Check all the subpatterns
|
| 159 |
+
#
|
| 160 |
+
pattern_types = []
|
| 161 |
+
for pattern in o.patterns:
|
| 162 |
+
pattern_type = self.accept(pattern, current_type)
|
| 163 |
+
pattern_types.append(pattern_type)
|
| 164 |
+
if not is_uninhabited(pattern_type.type):
|
| 165 |
+
current_type = pattern_type.rest_type
|
| 166 |
+
|
| 167 |
+
#
|
| 168 |
+
# Collect the final type
|
| 169 |
+
#
|
| 170 |
+
types = []
|
| 171 |
+
for pattern_type in pattern_types:
|
| 172 |
+
if not is_uninhabited(pattern_type.type):
|
| 173 |
+
types.append(pattern_type.type)
|
| 174 |
+
|
| 175 |
+
#
|
| 176 |
+
# Check the capture types
|
| 177 |
+
#
|
| 178 |
+
capture_types: dict[Var, list[tuple[Expression, Type]]] = defaultdict(list)
|
| 179 |
+
# Collect captures from the first subpattern
|
| 180 |
+
for expr, typ in pattern_types[0].captures.items():
|
| 181 |
+
node = get_var(expr)
|
| 182 |
+
capture_types[node].append((expr, typ))
|
| 183 |
+
|
| 184 |
+
# Check if other subpatterns capture the same names
|
| 185 |
+
for i, pattern_type in enumerate(pattern_types[1:]):
|
| 186 |
+
vars = {get_var(expr) for expr, _ in pattern_type.captures.items()}
|
| 187 |
+
if capture_types.keys() != vars:
|
| 188 |
+
self.msg.fail(message_registry.OR_PATTERN_ALTERNATIVE_NAMES, o.patterns[i])
|
| 189 |
+
for expr, typ in pattern_type.captures.items():
|
| 190 |
+
node = get_var(expr)
|
| 191 |
+
capture_types[node].append((expr, typ))
|
| 192 |
+
|
| 193 |
+
captures: dict[Expression, Type] = {}
|
| 194 |
+
for capture_list in capture_types.values():
|
| 195 |
+
typ = UninhabitedType()
|
| 196 |
+
for _, other in capture_list:
|
| 197 |
+
typ = make_simplified_union([typ, other])
|
| 198 |
+
|
| 199 |
+
captures[capture_list[0][0]] = typ
|
| 200 |
+
|
| 201 |
+
union_type = make_simplified_union(types)
|
| 202 |
+
return PatternType(union_type, current_type, captures)
|
| 203 |
+
|
| 204 |
+
def visit_value_pattern(self, o: ValuePattern) -> PatternType:
|
| 205 |
+
current_type = self.type_context[-1]
|
| 206 |
+
typ = self.chk.expr_checker.accept(o.expr)
|
| 207 |
+
typ = coerce_to_literal(typ)
|
| 208 |
+
node = TempNode(current_type)
|
| 209 |
+
# Value patterns are essentially a syntactic sugar on top of `if x == Value`.
|
| 210 |
+
# They should be treated equivalently.
|
| 211 |
+
ok_map, rest_map = self.chk.narrow_type_by_identity_equality(
|
| 212 |
+
"==", [node, TempNode(typ)], [current_type, typ], [0, 1], {0}
|
| 213 |
+
)
|
| 214 |
+
ok_type = ok_map.get(node, current_type) if ok_map is not None else UninhabitedType()
|
| 215 |
+
rest_type = rest_map.get(node, current_type) if rest_map is not None else UninhabitedType()
|
| 216 |
+
return PatternType(ok_type, rest_type, {})
|
| 217 |
+
|
| 218 |
+
def visit_singleton_pattern(self, o: SingletonPattern) -> PatternType:
|
| 219 |
+
current_type = self.type_context[-1]
|
| 220 |
+
value: bool | None = o.value
|
| 221 |
+
if isinstance(value, bool):
|
| 222 |
+
typ = self.chk.expr_checker.infer_literal_expr_type(value, "builtins.bool")
|
| 223 |
+
elif value is None:
|
| 224 |
+
typ = NoneType()
|
| 225 |
+
else:
|
| 226 |
+
assert False
|
| 227 |
+
|
| 228 |
+
narrowed_type, rest_type = self.chk.conditional_types_with_intersection(
|
| 229 |
+
current_type, [get_type_range(typ)], o, default=current_type
|
| 230 |
+
)
|
| 231 |
+
return PatternType(narrowed_type, rest_type, {})
|
| 232 |
+
|
| 233 |
+
def visit_sequence_pattern(self, o: SequencePattern) -> PatternType:
|
| 234 |
+
#
|
| 235 |
+
# Step 1. Check for existence of a starred pattern
|
| 236 |
+
#
|
| 237 |
+
current_type = get_proper_type(self.type_context[-1])
|
| 238 |
+
if not self.can_match_sequence(current_type):
|
| 239 |
+
return self.early_non_match()
|
| 240 |
+
|
| 241 |
+
star_positions = [i for i, p in enumerate(o.patterns) if isinstance(p, StarredPattern)]
|
| 242 |
+
star_position: int | None = None
|
| 243 |
+
if len(star_positions) == 1:
|
| 244 |
+
star_position = star_positions[0]
|
| 245 |
+
elif len(star_positions) >= 2:
|
| 246 |
+
assert False, "Parser should prevent multiple starred patterns"
|
| 247 |
+
required_patterns = len(o.patterns)
|
| 248 |
+
if star_position is not None:
|
| 249 |
+
required_patterns -= 1
|
| 250 |
+
|
| 251 |
+
#
|
| 252 |
+
# Step 2. If we have a union, recurse and return the combined result
|
| 253 |
+
#
|
| 254 |
+
if isinstance(current_type, UnionType):
|
| 255 |
+
match_types: list[Type] = []
|
| 256 |
+
rest_types: list[Type] = []
|
| 257 |
+
captures_list: dict[Expression, list[Type]] = {}
|
| 258 |
+
|
| 259 |
+
if star_position is not None:
|
| 260 |
+
star_pattern = o.patterns[star_position]
|
| 261 |
+
assert isinstance(star_pattern, StarredPattern)
|
| 262 |
+
star_expr = star_pattern.capture
|
| 263 |
+
else:
|
| 264 |
+
star_expr = None
|
| 265 |
+
|
| 266 |
+
for t in current_type.items:
|
| 267 |
+
match_type, rest_type, captures = self.accept(o, t)
|
| 268 |
+
match_types.append(match_type)
|
| 269 |
+
rest_types.append(rest_type)
|
| 270 |
+
if not is_uninhabited(match_type):
|
| 271 |
+
for expr, typ in captures.items():
|
| 272 |
+
p_typ = get_proper_type(typ)
|
| 273 |
+
if expr not in captures_list:
|
| 274 |
+
captures_list[expr] = []
|
| 275 |
+
# Avoid adding in a list[Never] for empty list captures
|
| 276 |
+
if (
|
| 277 |
+
expr == star_expr
|
| 278 |
+
and isinstance(p_typ, Instance)
|
| 279 |
+
and p_typ.type.fullname == "builtins.list"
|
| 280 |
+
and is_uninhabited(p_typ.args[0])
|
| 281 |
+
):
|
| 282 |
+
continue
|
| 283 |
+
captures_list[expr].append(typ)
|
| 284 |
+
|
| 285 |
+
return PatternType(
|
| 286 |
+
make_simplified_union(match_types),
|
| 287 |
+
make_simplified_union(rest_types),
|
| 288 |
+
{expr: make_simplified_union(types) for expr, types in captures_list.items()},
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
#
|
| 292 |
+
# Step 3. Get inner types of original type
|
| 293 |
+
#
|
| 294 |
+
unpack_index = None
|
| 295 |
+
if isinstance(current_type, TupleType):
|
| 296 |
+
inner_types: list[Type] = current_type.items
|
| 297 |
+
unpack_index = find_unpack_in_list(inner_types)
|
| 298 |
+
if unpack_index is None:
|
| 299 |
+
size_diff = len(inner_types) - required_patterns
|
| 300 |
+
if size_diff < 0:
|
| 301 |
+
return self.early_non_match()
|
| 302 |
+
elif size_diff > 0 and star_position is None:
|
| 303 |
+
return self.early_non_match()
|
| 304 |
+
else:
|
| 305 |
+
normalized_inner_types = []
|
| 306 |
+
for it in inner_types:
|
| 307 |
+
# Unfortunately, it is not possible to "split" the TypeVarTuple
|
| 308 |
+
# into individual items, so we just use its upper bound for the whole
|
| 309 |
+
# analysis instead.
|
| 310 |
+
if isinstance(it, UnpackType) and isinstance(it.type, TypeVarTupleType):
|
| 311 |
+
it = UnpackType(it.type.upper_bound)
|
| 312 |
+
normalized_inner_types.append(it)
|
| 313 |
+
inner_types = normalized_inner_types
|
| 314 |
+
current_type = current_type.copy_modified(items=normalized_inner_types)
|
| 315 |
+
if len(inner_types) - 1 > required_patterns and star_position is None:
|
| 316 |
+
return self.early_non_match()
|
| 317 |
+
elif isinstance(current_type, AnyType):
|
| 318 |
+
inner_type = AnyType(TypeOfAny.from_another_any, current_type)
|
| 319 |
+
inner_types = [inner_type] * len(o.patterns)
|
| 320 |
+
elif isinstance(current_type, Instance) and self.chk.type_is_iterable(current_type):
|
| 321 |
+
inner_type = self.chk.iterable_item_type(current_type, o)
|
| 322 |
+
inner_types = [inner_type] * len(o.patterns)
|
| 323 |
+
else:
|
| 324 |
+
inner_type = self.chk.named_type("builtins.object")
|
| 325 |
+
inner_types = [inner_type] * len(o.patterns)
|
| 326 |
+
|
| 327 |
+
#
|
| 328 |
+
# Step 4. Match inner patterns
|
| 329 |
+
#
|
| 330 |
+
contracted_new_inner_types: list[Type] = []
|
| 331 |
+
contracted_rest_inner_types: list[Type] = []
|
| 332 |
+
captures = {} # dict[Expression, Type]
|
| 333 |
+
|
| 334 |
+
contracted_inner_types = self.contract_starred_pattern_types(
|
| 335 |
+
inner_types, star_position, required_patterns
|
| 336 |
+
)
|
| 337 |
+
for p, t in zip(o.patterns, contracted_inner_types):
|
| 338 |
+
pattern_type = self.accept(p, t)
|
| 339 |
+
typ, rest, type_map = pattern_type
|
| 340 |
+
contracted_new_inner_types.append(typ)
|
| 341 |
+
contracted_rest_inner_types.append(rest)
|
| 342 |
+
self.update_type_map(captures, type_map)
|
| 343 |
+
|
| 344 |
+
new_inner_types = self.expand_starred_pattern_types(
|
| 345 |
+
contracted_new_inner_types, star_position, len(inner_types), unpack_index is not None
|
| 346 |
+
)
|
| 347 |
+
rest_inner_types = self.expand_starred_pattern_types(
|
| 348 |
+
contracted_rest_inner_types, star_position, len(inner_types), unpack_index is not None
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
#
|
| 352 |
+
# Step 5. Calculate new type
|
| 353 |
+
#
|
| 354 |
+
new_type: Type
|
| 355 |
+
rest_type = current_type
|
| 356 |
+
if isinstance(current_type, TupleType) and unpack_index is None:
|
| 357 |
+
if any(is_uninhabited(typ) for typ in new_inner_types):
|
| 358 |
+
new_type = UninhabitedType()
|
| 359 |
+
else:
|
| 360 |
+
new_type = TupleType(new_inner_types, current_type.partial_fallback)
|
| 361 |
+
|
| 362 |
+
num_always_match = sum(is_uninhabited(typ) for typ in rest_inner_types)
|
| 363 |
+
if num_always_match == len(rest_inner_types):
|
| 364 |
+
# All subpatterns always match, so we can apply negative narrowing
|
| 365 |
+
rest_type = UninhabitedType()
|
| 366 |
+
elif num_always_match == len(rest_inner_types) - 1:
|
| 367 |
+
# Exactly one subpattern may conditionally match, the rest always match.
|
| 368 |
+
# We can apply negative narrowing to this one position.
|
| 369 |
+
rest_type = TupleType(
|
| 370 |
+
[
|
| 371 |
+
curr if is_uninhabited(rest) else rest
|
| 372 |
+
for curr, rest in zip(inner_types, rest_inner_types)
|
| 373 |
+
],
|
| 374 |
+
current_type.partial_fallback,
|
| 375 |
+
)
|
| 376 |
+
elif isinstance(current_type, TupleType):
|
| 377 |
+
# For variadic tuples it is too tricky to match individual items like for fixed
|
| 378 |
+
# tuples, so we instead try to narrow the entire type.
|
| 379 |
+
# TODO: use more precise narrowing when possible (e.g. for identical shapes).
|
| 380 |
+
new_tuple_type = TupleType(new_inner_types, current_type.partial_fallback)
|
| 381 |
+
new_type, _ = self.chk.conditional_types_with_intersection(
|
| 382 |
+
new_tuple_type, [get_type_range(current_type)], o, default=new_tuple_type
|
| 383 |
+
)
|
| 384 |
+
if (
|
| 385 |
+
star_position is not None
|
| 386 |
+
and required_patterns <= len(inner_types) - 1
|
| 387 |
+
and all(is_uninhabited(rest) for rest in rest_inner_types)
|
| 388 |
+
):
|
| 389 |
+
rest_type = UninhabitedType()
|
| 390 |
+
else:
|
| 391 |
+
new_inner_type = UninhabitedType()
|
| 392 |
+
for typ in new_inner_types:
|
| 393 |
+
new_inner_type = join_types(new_inner_type, typ)
|
| 394 |
+
new_type = self.construct_sequence_child(current_type, new_inner_type)
|
| 395 |
+
new_type, possible_rest_type = self.chk.conditional_types_with_intersection(
|
| 396 |
+
current_type, [get_type_range(new_type)], o, default=current_type
|
| 397 |
+
)
|
| 398 |
+
if star_position is not None and len(o.patterns) == 1:
|
| 399 |
+
# Match cannot be refuted, so narrow the remaining type
|
| 400 |
+
rest_type = possible_rest_type
|
| 401 |
+
|
| 402 |
+
return PatternType(new_type, rest_type, captures)
|
| 403 |
+
|
| 404 |
+
def contract_starred_pattern_types(
|
| 405 |
+
self, types: list[Type], star_pos: int | None, num_patterns: int
|
| 406 |
+
) -> list[Type]:
|
| 407 |
+
"""
|
| 408 |
+
Contracts a list of types in a sequence pattern depending on the position of a starred
|
| 409 |
+
capture pattern.
|
| 410 |
+
|
| 411 |
+
For example if the sequence pattern [a, *b, c] is matched against types [bool, int, str,
|
| 412 |
+
bytes] the contracted types are [bool, Union[int, str], bytes].
|
| 413 |
+
|
| 414 |
+
If star_pos in None the types are returned unchanged.
|
| 415 |
+
"""
|
| 416 |
+
unpack_index = find_unpack_in_list(types)
|
| 417 |
+
if unpack_index is not None:
|
| 418 |
+
# Variadic tuples require "re-shaping" to match the requested pattern.
|
| 419 |
+
unpack = types[unpack_index]
|
| 420 |
+
assert isinstance(unpack, UnpackType)
|
| 421 |
+
unpacked = get_proper_type(unpack.type)
|
| 422 |
+
# This should be guaranteed by the normalization in the caller.
|
| 423 |
+
assert isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple"
|
| 424 |
+
if star_pos is None:
|
| 425 |
+
missing = num_patterns - len(types) + 1
|
| 426 |
+
new_types = types[:unpack_index]
|
| 427 |
+
new_types += [unpacked.args[0]] * missing
|
| 428 |
+
new_types += types[unpack_index + 1 :]
|
| 429 |
+
return new_types
|
| 430 |
+
prefix, middle, suffix = split_with_prefix_and_suffix(
|
| 431 |
+
tuple([UnpackType(unpacked) if isinstance(t, UnpackType) else t for t in types]),
|
| 432 |
+
star_pos,
|
| 433 |
+
num_patterns - star_pos,
|
| 434 |
+
)
|
| 435 |
+
new_middle = []
|
| 436 |
+
for m in middle:
|
| 437 |
+
# The existing code expects the star item type, rather than the type of
|
| 438 |
+
# the whole tuple "slice".
|
| 439 |
+
if isinstance(m, UnpackType):
|
| 440 |
+
new_middle.append(unpacked.args[0])
|
| 441 |
+
else:
|
| 442 |
+
new_middle.append(m)
|
| 443 |
+
return list(prefix) + [make_simplified_union(new_middle)] + list(suffix)
|
| 444 |
+
else:
|
| 445 |
+
if star_pos is None:
|
| 446 |
+
return types
|
| 447 |
+
new_types = types[:star_pos]
|
| 448 |
+
star_length = len(types) - num_patterns
|
| 449 |
+
new_types.append(make_simplified_union(types[star_pos : star_pos + star_length]))
|
| 450 |
+
new_types += types[star_pos + star_length :]
|
| 451 |
+
return new_types
|
| 452 |
+
|
| 453 |
+
def expand_starred_pattern_types(
|
| 454 |
+
self, types: list[Type], star_pos: int | None, num_types: int, original_unpack: bool
|
| 455 |
+
) -> list[Type]:
|
| 456 |
+
"""Undoes the contraction done by contract_starred_pattern_types.
|
| 457 |
+
|
| 458 |
+
For example if the sequence pattern is [a, *b, c] and types [bool, int, str] are extended
|
| 459 |
+
to length 4 the result is [bool, int, int, str].
|
| 460 |
+
"""
|
| 461 |
+
if star_pos is None:
|
| 462 |
+
return types
|
| 463 |
+
if original_unpack:
|
| 464 |
+
# In the case where original tuple type has an unpack item, it is not practical
|
| 465 |
+
# to coerce pattern type back to the original shape (and may not even be possible),
|
| 466 |
+
# so we only restore the type of the star item.
|
| 467 |
+
res = []
|
| 468 |
+
for i, t in enumerate(types):
|
| 469 |
+
if i != star_pos or is_uninhabited(t):
|
| 470 |
+
res.append(t)
|
| 471 |
+
else:
|
| 472 |
+
res.append(UnpackType(self.chk.named_generic_type("builtins.tuple", [t])))
|
| 473 |
+
return res
|
| 474 |
+
new_types = types[:star_pos]
|
| 475 |
+
star_length = num_types - len(types) + 1
|
| 476 |
+
new_types += [types[star_pos]] * star_length
|
| 477 |
+
new_types += types[star_pos + 1 :]
|
| 478 |
+
|
| 479 |
+
return new_types
|
| 480 |
+
|
| 481 |
+
def visit_starred_pattern(self, o: StarredPattern) -> PatternType:
|
| 482 |
+
captures: dict[Expression, Type] = {}
|
| 483 |
+
if o.capture is not None:
|
| 484 |
+
list_type = self.chk.named_generic_type("builtins.list", [self.type_context[-1]])
|
| 485 |
+
captures[o.capture] = list_type
|
| 486 |
+
return PatternType(self.type_context[-1], UninhabitedType(), captures)
|
| 487 |
+
|
| 488 |
+
def visit_mapping_pattern(self, o: MappingPattern) -> PatternType:
|
| 489 |
+
current_type = get_proper_type(self.type_context[-1])
|
| 490 |
+
can_match = True
|
| 491 |
+
captures: dict[Expression, Type] = {}
|
| 492 |
+
for key, value in zip(o.keys, o.values):
|
| 493 |
+
inner_type = self.get_mapping_item_type(o, current_type, key)
|
| 494 |
+
if inner_type is None:
|
| 495 |
+
can_match = False
|
| 496 |
+
inner_type = self.chk.named_type("builtins.object")
|
| 497 |
+
pattern_type = self.accept(value, inner_type)
|
| 498 |
+
if is_uninhabited(pattern_type.type):
|
| 499 |
+
can_match = False
|
| 500 |
+
else:
|
| 501 |
+
self.update_type_map(captures, pattern_type.captures)
|
| 502 |
+
|
| 503 |
+
if o.rest is not None:
|
| 504 |
+
mapping = self.chk.named_type("typing.Mapping")
|
| 505 |
+
if is_subtype(current_type, mapping) and isinstance(current_type, Instance):
|
| 506 |
+
mapping_inst = map_instance_to_supertype(current_type, mapping.type)
|
| 507 |
+
dict_typeinfo = self.chk.lookup_typeinfo("builtins.dict")
|
| 508 |
+
rest_type = Instance(dict_typeinfo, mapping_inst.args)
|
| 509 |
+
else:
|
| 510 |
+
object_type = self.chk.named_type("builtins.object")
|
| 511 |
+
rest_type = self.chk.named_generic_type(
|
| 512 |
+
"builtins.dict", [object_type, object_type]
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
captures[o.rest] = rest_type
|
| 516 |
+
|
| 517 |
+
else_type = current_type
|
| 518 |
+
if can_match:
|
| 519 |
+
# We can't narrow the type here, as Mapping key is invariant.
|
| 520 |
+
new_type = self.type_context[-1]
|
| 521 |
+
if not o.keys:
|
| 522 |
+
# Match cannot be refuted, so narrow the remaining type
|
| 523 |
+
mapping = self.chk.named_type("typing.Mapping")
|
| 524 |
+
if_type, else_type = self.chk.conditional_types_with_intersection(
|
| 525 |
+
current_type,
|
| 526 |
+
[TypeRange(mapping, is_upper_bound=False)],
|
| 527 |
+
o,
|
| 528 |
+
default=current_type,
|
| 529 |
+
)
|
| 530 |
+
if not isinstance(current_type, AnyType):
|
| 531 |
+
new_type = if_type
|
| 532 |
+
else:
|
| 533 |
+
new_type = UninhabitedType()
|
| 534 |
+
return PatternType(new_type, else_type, captures)
|
| 535 |
+
|
| 536 |
+
def get_mapping_item_type(
|
| 537 |
+
self, pattern: MappingPattern, mapping_type: Type, key: Expression
|
| 538 |
+
) -> Type | None:
|
| 539 |
+
mapping_type = get_proper_type(mapping_type)
|
| 540 |
+
if isinstance(mapping_type, TypedDictType):
|
| 541 |
+
with self.msg.filter_errors() as local_errors:
|
| 542 |
+
result: Type | None = self.chk.expr_checker.visit_typeddict_index_expr(
|
| 543 |
+
mapping_type, key
|
| 544 |
+
)[0]
|
| 545 |
+
has_local_errors = local_errors.has_new_errors()
|
| 546 |
+
# If we can't determine the type statically fall back to treating it as a normal
|
| 547 |
+
# mapping
|
| 548 |
+
if has_local_errors:
|
| 549 |
+
with self.msg.filter_errors() as local_errors:
|
| 550 |
+
result = self.get_simple_mapping_item_type(pattern, mapping_type, key)
|
| 551 |
+
|
| 552 |
+
if local_errors.has_new_errors():
|
| 553 |
+
result = None
|
| 554 |
+
else:
|
| 555 |
+
with self.msg.filter_errors():
|
| 556 |
+
result = self.get_simple_mapping_item_type(pattern, mapping_type, key)
|
| 557 |
+
return result
|
| 558 |
+
|
| 559 |
+
def get_simple_mapping_item_type(
|
| 560 |
+
self, pattern: MappingPattern, mapping_type: Type, key: Expression
|
| 561 |
+
) -> Type:
|
| 562 |
+
result, _ = self.chk.expr_checker.check_method_call_by_name(
|
| 563 |
+
"__getitem__", mapping_type, [key], [ARG_POS], pattern
|
| 564 |
+
)
|
| 565 |
+
return result
|
| 566 |
+
|
| 567 |
+
def visit_class_pattern(self, o: ClassPattern) -> PatternType:
|
| 568 |
+
current_type = get_proper_type(self.type_context[-1])
|
| 569 |
+
|
| 570 |
+
#
|
| 571 |
+
# Check class type
|
| 572 |
+
#
|
| 573 |
+
type_info = o.class_ref.node
|
| 574 |
+
if isinstance(type_info, TypeAlias) and not type_info.no_args:
|
| 575 |
+
self.msg.fail(message_registry.CLASS_PATTERN_GENERIC_TYPE_ALIAS, o)
|
| 576 |
+
return self.early_non_match()
|
| 577 |
+
|
| 578 |
+
typ = self.chk.expr_checker.accept(o.class_ref)
|
| 579 |
+
type_ranges = self.get_class_pattern_type_ranges(typ, o)
|
| 580 |
+
if type_ranges is None:
|
| 581 |
+
return self.early_non_match()
|
| 582 |
+
typ = UnionType.make_union([t.item for t in type_ranges])
|
| 583 |
+
|
| 584 |
+
new_type, rest_type = self.chk.conditional_types_with_intersection(
|
| 585 |
+
current_type, type_ranges, o, default=current_type
|
| 586 |
+
)
|
| 587 |
+
if is_uninhabited(new_type):
|
| 588 |
+
return self.early_non_match()
|
| 589 |
+
# TODO: Do I need this?
|
| 590 |
+
narrowed_type = narrow_declared_type(current_type, new_type)
|
| 591 |
+
|
| 592 |
+
#
|
| 593 |
+
# Convert positional to keyword patterns
|
| 594 |
+
#
|
| 595 |
+
keyword_pairs: list[tuple[str | None, Pattern]] = []
|
| 596 |
+
match_arg_set: set[str] = set()
|
| 597 |
+
|
| 598 |
+
captures: dict[Expression, Type] = {}
|
| 599 |
+
|
| 600 |
+
if len(o.positionals) != 0:
|
| 601 |
+
if self.should_self_match(typ):
|
| 602 |
+
if len(o.positionals) > 1:
|
| 603 |
+
self.msg.fail(message_registry.CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS, o)
|
| 604 |
+
pattern_type = self.accept(o.positionals[0], narrowed_type)
|
| 605 |
+
if not is_uninhabited(pattern_type.type):
|
| 606 |
+
return PatternType(
|
| 607 |
+
pattern_type.type,
|
| 608 |
+
join_types(rest_type, pattern_type.rest_type),
|
| 609 |
+
pattern_type.captures,
|
| 610 |
+
)
|
| 611 |
+
captures = pattern_type.captures
|
| 612 |
+
else:
|
| 613 |
+
with self.msg.filter_errors() as local_errors:
|
| 614 |
+
match_args_type = analyze_member_access(
|
| 615 |
+
"__match_args__",
|
| 616 |
+
typ,
|
| 617 |
+
o,
|
| 618 |
+
is_lvalue=False,
|
| 619 |
+
is_super=False,
|
| 620 |
+
is_operator=False,
|
| 621 |
+
original_type=typ,
|
| 622 |
+
chk=self.chk,
|
| 623 |
+
)
|
| 624 |
+
has_local_errors = local_errors.has_new_errors()
|
| 625 |
+
if has_local_errors:
|
| 626 |
+
self.msg.fail(
|
| 627 |
+
message_registry.MISSING_MATCH_ARGS.format(
|
| 628 |
+
typ.str_with_options(self.options)
|
| 629 |
+
),
|
| 630 |
+
o,
|
| 631 |
+
)
|
| 632 |
+
return self.early_non_match()
|
| 633 |
+
|
| 634 |
+
proper_match_args_type = get_proper_type(match_args_type)
|
| 635 |
+
if isinstance(proper_match_args_type, TupleType):
|
| 636 |
+
match_arg_names = get_match_arg_names(proper_match_args_type)
|
| 637 |
+
|
| 638 |
+
if len(o.positionals) > len(match_arg_names):
|
| 639 |
+
self.msg.fail(message_registry.CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS, o)
|
| 640 |
+
return self.early_non_match()
|
| 641 |
+
else:
|
| 642 |
+
match_arg_names = [None] * len(o.positionals)
|
| 643 |
+
|
| 644 |
+
for arg_name, pos in zip(match_arg_names, o.positionals):
|
| 645 |
+
keyword_pairs.append((arg_name, pos))
|
| 646 |
+
if arg_name is not None:
|
| 647 |
+
match_arg_set.add(arg_name)
|
| 648 |
+
|
| 649 |
+
#
|
| 650 |
+
# Check for duplicate patterns
|
| 651 |
+
#
|
| 652 |
+
keyword_arg_set = set()
|
| 653 |
+
has_duplicates = False
|
| 654 |
+
for key, value in zip(o.keyword_keys, o.keyword_values):
|
| 655 |
+
keyword_pairs.append((key, value))
|
| 656 |
+
if key in match_arg_set:
|
| 657 |
+
self.msg.fail(
|
| 658 |
+
message_registry.CLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL.format(key), value
|
| 659 |
+
)
|
| 660 |
+
has_duplicates = True
|
| 661 |
+
elif key in keyword_arg_set:
|
| 662 |
+
self.msg.fail(
|
| 663 |
+
message_registry.CLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN.format(key), value
|
| 664 |
+
)
|
| 665 |
+
has_duplicates = True
|
| 666 |
+
keyword_arg_set.add(key)
|
| 667 |
+
|
| 668 |
+
if has_duplicates:
|
| 669 |
+
return self.early_non_match()
|
| 670 |
+
|
| 671 |
+
#
|
| 672 |
+
# Check keyword patterns
|
| 673 |
+
#
|
| 674 |
+
can_match = True
|
| 675 |
+
for keyword, pattern in keyword_pairs:
|
| 676 |
+
key_type: Type | None = None
|
| 677 |
+
with self.msg.filter_errors() as local_errors:
|
| 678 |
+
if keyword is not None:
|
| 679 |
+
key_type = analyze_member_access(
|
| 680 |
+
keyword,
|
| 681 |
+
narrowed_type,
|
| 682 |
+
pattern,
|
| 683 |
+
is_lvalue=False,
|
| 684 |
+
is_super=False,
|
| 685 |
+
is_operator=False,
|
| 686 |
+
original_type=new_type,
|
| 687 |
+
chk=self.chk,
|
| 688 |
+
)
|
| 689 |
+
else:
|
| 690 |
+
key_type = AnyType(TypeOfAny.from_error)
|
| 691 |
+
has_local_errors = local_errors.has_new_errors()
|
| 692 |
+
if has_local_errors or key_type is None:
|
| 693 |
+
key_type = AnyType(TypeOfAny.from_error)
|
| 694 |
+
if not (type_info and type_info.fullname == "builtins.object"):
|
| 695 |
+
self.msg.fail(
|
| 696 |
+
message_registry.CLASS_PATTERN_UNKNOWN_KEYWORD.format(
|
| 697 |
+
typ.str_with_options(self.options), keyword
|
| 698 |
+
),
|
| 699 |
+
pattern,
|
| 700 |
+
)
|
| 701 |
+
elif keyword is not None:
|
| 702 |
+
new_type = self.chk.add_any_attribute_to_type(new_type, keyword)
|
| 703 |
+
|
| 704 |
+
inner_type, inner_rest_type, inner_captures = self.accept(pattern, key_type)
|
| 705 |
+
if is_uninhabited(inner_type):
|
| 706 |
+
can_match = False
|
| 707 |
+
else:
|
| 708 |
+
self.update_type_map(captures, inner_captures)
|
| 709 |
+
if not is_uninhabited(inner_rest_type):
|
| 710 |
+
rest_type = current_type
|
| 711 |
+
|
| 712 |
+
if not can_match:
|
| 713 |
+
new_type = UninhabitedType()
|
| 714 |
+
return PatternType(new_type, rest_type, captures)
|
| 715 |
+
|
| 716 |
+
def get_class_pattern_type_ranges(self, typ: Type, o: ClassPattern) -> list[TypeRange] | None:
|
| 717 |
+
p_typ = get_proper_type(typ)
|
| 718 |
+
|
| 719 |
+
if isinstance(p_typ, UnionType):
|
| 720 |
+
type_ranges = []
|
| 721 |
+
for item in p_typ.items:
|
| 722 |
+
type_range = self.get_class_pattern_type_ranges(item, o)
|
| 723 |
+
if type_range is not None:
|
| 724 |
+
type_ranges.extend(type_range)
|
| 725 |
+
if not type_ranges:
|
| 726 |
+
return None
|
| 727 |
+
return type_ranges
|
| 728 |
+
|
| 729 |
+
if isinstance(p_typ, FunctionLike) and p_typ.is_type_obj():
|
| 730 |
+
typ = fill_typevars_with_any(p_typ.type_object())
|
| 731 |
+
return [TypeRange(typ, is_upper_bound=False)]
|
| 732 |
+
if (
|
| 733 |
+
isinstance(o.class_ref.node, Var)
|
| 734 |
+
and o.class_ref.node.type is not None
|
| 735 |
+
and o.class_ref.node.fullname == "typing.Callable"
|
| 736 |
+
):
|
| 737 |
+
# Create a `Callable[..., Any]`
|
| 738 |
+
fallback = self.chk.named_type("builtins.function")
|
| 739 |
+
any_type = AnyType(TypeOfAny.unannotated)
|
| 740 |
+
typ = callable_with_ellipsis(any_type, ret_type=any_type, fallback=fallback)
|
| 741 |
+
return [TypeRange(typ, is_upper_bound=False)]
|
| 742 |
+
if isinstance(p_typ, TypeType):
|
| 743 |
+
typ = p_typ.item
|
| 744 |
+
return [TypeRange(p_typ.item, is_upper_bound=True)]
|
| 745 |
+
if isinstance(p_typ, AnyType):
|
| 746 |
+
return [TypeRange(p_typ, is_upper_bound=False)]
|
| 747 |
+
|
| 748 |
+
self.msg.fail(
|
| 749 |
+
message_registry.CLASS_PATTERN_TYPE_REQUIRED.format(
|
| 750 |
+
typ.str_with_options(self.options)
|
| 751 |
+
),
|
| 752 |
+
o,
|
| 753 |
+
)
|
| 754 |
+
return None
|
| 755 |
+
|
| 756 |
+
def should_self_match(self, typ: Type) -> bool:
|
| 757 |
+
typ = get_proper_type(typ)
|
| 758 |
+
if isinstance(typ, TupleType):
|
| 759 |
+
typ = typ.partial_fallback
|
| 760 |
+
if isinstance(typ, AnyType):
|
| 761 |
+
return False
|
| 762 |
+
if isinstance(typ, Instance) and typ.type.get("__match_args__") is not None:
|
| 763 |
+
# Named tuples and other subtypes of builtins that define __match_args__
|
| 764 |
+
# should not self match.
|
| 765 |
+
return False
|
| 766 |
+
for other in self.self_match_types:
|
| 767 |
+
if is_subtype(typ, other):
|
| 768 |
+
return True
|
| 769 |
+
return False
|
| 770 |
+
|
| 771 |
+
def can_match_sequence(self, typ: ProperType) -> bool:
|
| 772 |
+
if isinstance(typ, AnyType):
|
| 773 |
+
return True
|
| 774 |
+
if isinstance(typ, UnionType):
|
| 775 |
+
return any(self.can_match_sequence(get_proper_type(item)) for item in typ.items)
|
| 776 |
+
for other in self.non_sequence_match_types:
|
| 777 |
+
# We have to ignore promotions, as memoryview should match, but bytes,
|
| 778 |
+
# which it can be promoted to, shouldn't
|
| 779 |
+
if is_subtype(typ, other, ignore_promotions=True):
|
| 780 |
+
return False
|
| 781 |
+
sequence = self.chk.named_type("typing.Sequence")
|
| 782 |
+
# If the static type is more general than sequence the actual type could still match
|
| 783 |
+
return is_subtype(typ, sequence) or is_subtype(sequence, typ)
|
| 784 |
+
|
| 785 |
+
def generate_types_from_names(self, type_names: list[str]) -> list[Type]:
|
| 786 |
+
types: list[Type] = []
|
| 787 |
+
for name in type_names:
|
| 788 |
+
try:
|
| 789 |
+
types.append(self.chk.named_type(name))
|
| 790 |
+
except KeyError as e:
|
| 791 |
+
# Some built in types are not defined in all test cases
|
| 792 |
+
if not name.startswith("builtins."):
|
| 793 |
+
raise e
|
| 794 |
+
return types
|
| 795 |
+
|
| 796 |
+
def update_type_map(
|
| 797 |
+
self, original_type_map: dict[Expression, Type], extra_type_map: dict[Expression, Type]
|
| 798 |
+
) -> None:
|
| 799 |
+
# Calculating this would not be needed if TypeMap directly used literal hashes instead of
|
| 800 |
+
# expressions, as suggested in the TODO above it's definition
|
| 801 |
+
already_captured = {literal_hash(expr) for expr in original_type_map}
|
| 802 |
+
for expr, typ in extra_type_map.items():
|
| 803 |
+
if literal_hash(expr) in already_captured:
|
| 804 |
+
node = get_var(expr)
|
| 805 |
+
self.msg.fail(
|
| 806 |
+
message_registry.MULTIPLE_ASSIGNMENTS_IN_PATTERN.format(node.name), expr
|
| 807 |
+
)
|
| 808 |
+
else:
|
| 809 |
+
original_type_map[expr] = typ
|
| 810 |
+
|
| 811 |
+
def construct_sequence_child(self, outer_type: Type, inner_type: Type) -> Type:
|
| 812 |
+
"""
|
| 813 |
+
If outer_type is a child class of typing.Sequence returns a new instance of
|
| 814 |
+
outer_type, that is a Sequence of inner_type. If outer_type is not a child class of
|
| 815 |
+
typing.Sequence just returns a Sequence of inner_type
|
| 816 |
+
|
| 817 |
+
For example:
|
| 818 |
+
construct_sequence_child(List[int], str) = List[str]
|
| 819 |
+
|
| 820 |
+
TODO: this doesn't make sense. For example if one has class S(Sequence[int], Generic[T])
|
| 821 |
+
or class T(Sequence[Tuple[T, T]]), there is no way any of those can map to Sequence[str].
|
| 822 |
+
"""
|
| 823 |
+
proper_type = get_proper_type(outer_type)
|
| 824 |
+
if isinstance(proper_type, TypeVarType):
|
| 825 |
+
new_bound = self.construct_sequence_child(proper_type.upper_bound, inner_type)
|
| 826 |
+
return proper_type.copy_modified(upper_bound=new_bound)
|
| 827 |
+
if isinstance(proper_type, AnyType):
|
| 828 |
+
return outer_type
|
| 829 |
+
if isinstance(proper_type, UnionType):
|
| 830 |
+
types = [
|
| 831 |
+
self.construct_sequence_child(item, inner_type)
|
| 832 |
+
for item in proper_type.items
|
| 833 |
+
if self.can_match_sequence(get_proper_type(item))
|
| 834 |
+
]
|
| 835 |
+
return make_simplified_union(types)
|
| 836 |
+
sequence = self.chk.named_generic_type("typing.Sequence", [inner_type])
|
| 837 |
+
if is_subtype(outer_type, self.chk.named_type("typing.Sequence")):
|
| 838 |
+
if isinstance(proper_type, TupleType):
|
| 839 |
+
proper_type = tuple_fallback(proper_type)
|
| 840 |
+
assert isinstance(proper_type, Instance)
|
| 841 |
+
empty_type = fill_typevars(proper_type.type)
|
| 842 |
+
partial_type = expand_type_by_instance(empty_type, sequence)
|
| 843 |
+
return expand_type_by_instance(partial_type, proper_type)
|
| 844 |
+
else:
|
| 845 |
+
return sequence
|
| 846 |
+
|
| 847 |
+
def early_non_match(self) -> PatternType:
|
| 848 |
+
return PatternType(UninhabitedType(), self.type_context[-1], {})
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def get_match_arg_names(typ: TupleType) -> list[str | None]:
|
| 852 |
+
args: list[str | None] = []
|
| 853 |
+
for item in typ.items:
|
| 854 |
+
values = try_getting_str_literals_from_type(item)
|
| 855 |
+
if values is None or len(values) != 1:
|
| 856 |
+
args.append(None)
|
| 857 |
+
else:
|
| 858 |
+
args.append(values[0])
|
| 859 |
+
return args
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def get_var(expr: Expression) -> Var:
|
| 863 |
+
"""
|
| 864 |
+
Warning: this in only true for expressions captured by a match statement.
|
| 865 |
+
Don't call it from anywhere else
|
| 866 |
+
"""
|
| 867 |
+
assert isinstance(expr, NameExpr), expr
|
| 868 |
+
node = expr.node
|
| 869 |
+
assert isinstance(node, Var), node
|
| 870 |
+
return node
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def get_type_range(typ: Type) -> TypeRange:
|
| 874 |
+
typ = get_proper_type(typ)
|
| 875 |
+
if (
|
| 876 |
+
isinstance(typ, Instance)
|
| 877 |
+
and typ.last_known_value
|
| 878 |
+
and isinstance(typ.last_known_value.value, bool)
|
| 879 |
+
):
|
| 880 |
+
typ = typ.last_known_value
|
| 881 |
+
return TypeRange(typ, is_upper_bound=False)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def is_uninhabited(typ: Type) -> bool:
|
| 885 |
+
return isinstance(get_proper_type(typ), UninhabitedType)
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/checkstrformat.py
ADDED
|
@@ -0,0 +1,1099 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Format expression type checker.
|
| 3 |
+
|
| 4 |
+
This file is conceptually part of ExpressionChecker and TypeChecker. Main functionality
|
| 5 |
+
is located in StringFormatterChecker.check_str_format_call() for '{}'.format(), and in
|
| 6 |
+
StringFormatterChecker.check_str_interpolation() for printf-style % interpolation.
|
| 7 |
+
|
| 8 |
+
Note that although at runtime format strings are parsed using custom parsers,
|
| 9 |
+
here we use a regexp-based approach. This way we 99% match runtime behaviour while keeping
|
| 10 |
+
implementation simple.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import re
|
| 16 |
+
from collections.abc import Callable
|
| 17 |
+
from re import Match, Pattern
|
| 18 |
+
from typing import Final, TypeAlias as _TypeAlias, cast
|
| 19 |
+
|
| 20 |
+
import mypy.errorcodes as codes
|
| 21 |
+
from mypy import message_registry
|
| 22 |
+
from mypy.checker_shared import TypeCheckerSharedApi
|
| 23 |
+
from mypy.errors import Errors
|
| 24 |
+
from mypy.maptype import map_instance_to_supertype
|
| 25 |
+
from mypy.messages import MessageBuilder
|
| 26 |
+
from mypy.nodes import (
|
| 27 |
+
ARG_NAMED,
|
| 28 |
+
ARG_POS,
|
| 29 |
+
ARG_STAR,
|
| 30 |
+
ARG_STAR2,
|
| 31 |
+
BytesExpr,
|
| 32 |
+
CallExpr,
|
| 33 |
+
Context,
|
| 34 |
+
DictExpr,
|
| 35 |
+
Expression,
|
| 36 |
+
ExpressionStmt,
|
| 37 |
+
IndexExpr,
|
| 38 |
+
IntExpr,
|
| 39 |
+
MemberExpr,
|
| 40 |
+
MypyFile,
|
| 41 |
+
NameExpr,
|
| 42 |
+
Node,
|
| 43 |
+
StarExpr,
|
| 44 |
+
StrExpr,
|
| 45 |
+
TempNode,
|
| 46 |
+
TupleExpr,
|
| 47 |
+
)
|
| 48 |
+
from mypy.parse import parse
|
| 49 |
+
from mypy.subtypes import is_subtype
|
| 50 |
+
from mypy.typeops import custom_special_method
|
| 51 |
+
from mypy.types import (
|
| 52 |
+
AnyType,
|
| 53 |
+
Instance,
|
| 54 |
+
LiteralType,
|
| 55 |
+
TupleType,
|
| 56 |
+
Type,
|
| 57 |
+
TypeOfAny,
|
| 58 |
+
TypeVarTupleType,
|
| 59 |
+
TypeVarType,
|
| 60 |
+
UnionType,
|
| 61 |
+
UnpackType,
|
| 62 |
+
find_unpack_in_list,
|
| 63 |
+
get_proper_type,
|
| 64 |
+
get_proper_types,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
FormatStringExpr: _TypeAlias = StrExpr | BytesExpr
|
| 68 |
+
Checkers: _TypeAlias = tuple[Callable[[Expression], None], Callable[[Type], bool]]
|
| 69 |
+
MatchMap: _TypeAlias = dict[tuple[int, int], Match[str]] # span -> match
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def compile_format_re() -> Pattern[str]:
|
| 73 |
+
"""Construct regexp to match format conversion specifiers in % interpolation.
|
| 74 |
+
|
| 75 |
+
See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
|
| 76 |
+
The regexp is intentionally a bit wider to report better errors.
|
| 77 |
+
"""
|
| 78 |
+
key_re = r"(\((?P<key>[^)]*)\))?" # (optional) parenthesised sequence of characters.
|
| 79 |
+
flags_re = r"(?P<flags>[#0\-+ ]*)" # (optional) sequence of flags.
|
| 80 |
+
width_re = r"(?P<width>[1-9][0-9]*|\*)?" # (optional) minimum field width (* or numbers).
|
| 81 |
+
precision_re = r"(?:\.(?P<precision>\*|[0-9]+)?)?" # (optional) . followed by * of numbers.
|
| 82 |
+
length_mod_re = r"[hlL]?" # (optional) length modifier (unused).
|
| 83 |
+
type_re = r"(?P<type>.)?" # conversion type.
|
| 84 |
+
format_re = "%" + key_re + flags_re + width_re + precision_re + length_mod_re + type_re
|
| 85 |
+
return re.compile(format_re)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def compile_new_format_re(custom_spec: bool) -> Pattern[str]:
|
| 89 |
+
"""Construct regexps to match format conversion specifiers in str.format() calls.
|
| 90 |
+
|
| 91 |
+
See After https://docs.python.org/3/library/string.html#formatspec for
|
| 92 |
+
specifications. The regexps are intentionally wider, to report better errors,
|
| 93 |
+
instead of just not matching.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
# Field (optional) is an integer/identifier possibly followed by several .attr and [index].
|
| 97 |
+
field = r"(?P<field>(?P<key>[^.[!:]*)([^:!]+)?)"
|
| 98 |
+
|
| 99 |
+
# Conversion (optional) is ! followed by one of letters for forced repr(), str(), or ascii().
|
| 100 |
+
conversion = r"(?P<conversion>![^:])?"
|
| 101 |
+
|
| 102 |
+
# Format specification (optional) follows its own mini-language:
|
| 103 |
+
if not custom_spec:
|
| 104 |
+
# Fill and align is valid for all builtin types.
|
| 105 |
+
fill_align = r"(?P<fill_align>.?[<>=^])?"
|
| 106 |
+
# Number formatting options are only valid for int, float, complex, and Decimal,
|
| 107 |
+
# except if only width is given (it is valid for all types).
|
| 108 |
+
# This contains sign, flags (sign, # and/or 0), width, grouping (_ or ,) and precision.
|
| 109 |
+
num_spec = r"(?P<flags>[+\- ]?#?0?)(?P<width>\d+)?[_,]?(?P<precision>\.\d+)?"
|
| 110 |
+
# The last element is type.
|
| 111 |
+
conv_type = r"(?P<type>.)?" # only some are supported, but we want to give a better error
|
| 112 |
+
format_spec = r"(?P<format_spec>:" + fill_align + num_spec + conv_type + r")?"
|
| 113 |
+
else:
|
| 114 |
+
# Custom types can define their own form_spec using __format__().
|
| 115 |
+
format_spec = r"(?P<format_spec>:.*)?"
|
| 116 |
+
|
| 117 |
+
return re.compile(field + conversion + format_spec)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
FORMAT_RE: Final = compile_format_re()
|
| 121 |
+
FORMAT_RE_NEW: Final = compile_new_format_re(False)
|
| 122 |
+
FORMAT_RE_NEW_CUSTOM: Final = compile_new_format_re(True)
|
| 123 |
+
DUMMY_FIELD_NAME: Final = "__dummy_name__"
|
| 124 |
+
|
| 125 |
+
# Types that require either int or float.
|
| 126 |
+
NUMERIC_TYPES_OLD: Final = {"d", "i", "o", "u", "x", "X", "e", "E", "f", "F", "g", "G"}
|
| 127 |
+
NUMERIC_TYPES_NEW: Final = {"b", "d", "o", "e", "E", "f", "F", "g", "G", "n", "x", "X", "%"}
|
| 128 |
+
|
| 129 |
+
# These types accept _only_ int.
|
| 130 |
+
REQUIRE_INT_OLD: Final = {"o", "x", "X"}
|
| 131 |
+
REQUIRE_INT_NEW: Final = {"b", "d", "o", "x", "X"}
|
| 132 |
+
|
| 133 |
+
# These types fall back to SupportsFloat with % (other fall back to SupportsInt)
|
| 134 |
+
FLOAT_TYPES: Final = {"e", "E", "f", "F", "g", "G"}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class ConversionSpecifier:
|
| 138 |
+
def __init__(
|
| 139 |
+
self, match: Match[str], start_pos: int = -1, non_standard_format_spec: bool = False
|
| 140 |
+
) -> None:
|
| 141 |
+
self.whole_seq = match.group()
|
| 142 |
+
self.start_pos = start_pos
|
| 143 |
+
|
| 144 |
+
m_dict = match.groupdict()
|
| 145 |
+
self.key = m_dict.get("key")
|
| 146 |
+
|
| 147 |
+
# Replace unmatched optional groups with empty matches (for convenience).
|
| 148 |
+
self.conv_type = m_dict.get("type") or ""
|
| 149 |
+
self.flags = m_dict.get("flags") or ""
|
| 150 |
+
self.width = m_dict.get("width") or ""
|
| 151 |
+
self.precision = m_dict.get("precision") or ""
|
| 152 |
+
|
| 153 |
+
# Used only for str.format() calls (it may be custom for types with __format__()).
|
| 154 |
+
self.format_spec = m_dict.get("format_spec")
|
| 155 |
+
self.non_standard_format_spec = non_standard_format_spec
|
| 156 |
+
# Used only for str.format() calls.
|
| 157 |
+
self.conversion = m_dict.get("conversion")
|
| 158 |
+
# Full formatted expression (i.e. key plus following attributes and/or indexes).
|
| 159 |
+
# Used only for str.format() calls.
|
| 160 |
+
self.field = m_dict.get("field")
|
| 161 |
+
|
| 162 |
+
def has_key(self) -> bool:
|
| 163 |
+
return self.key is not None
|
| 164 |
+
|
| 165 |
+
def has_star(self) -> bool:
|
| 166 |
+
return self.width == "*" or self.precision == "*"
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def parse_conversion_specifiers(format_str: str) -> list[ConversionSpecifier]:
|
| 170 |
+
"""Parse c-printf-style format string into list of conversion specifiers."""
|
| 171 |
+
specifiers: list[ConversionSpecifier] = []
|
| 172 |
+
for m in re.finditer(FORMAT_RE, format_str):
|
| 173 |
+
specifiers.append(ConversionSpecifier(m, start_pos=m.start()))
|
| 174 |
+
return specifiers
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def parse_format_value(
|
| 178 |
+
format_value: str, ctx: Context, msg: MessageBuilder, nested: bool = False
|
| 179 |
+
) -> list[ConversionSpecifier] | None:
|
| 180 |
+
"""Parse format string into list of conversion specifiers.
|
| 181 |
+
|
| 182 |
+
The specifiers may be nested (two levels maximum), in this case they are ordered as
|
| 183 |
+
'{0:{1}}, {2:{3}{4}}'. Return None in case of an error.
|
| 184 |
+
"""
|
| 185 |
+
top_targets = find_non_escaped_targets(format_value, ctx, msg)
|
| 186 |
+
if top_targets is None:
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
+
result: list[ConversionSpecifier] = []
|
| 190 |
+
for target, start_pos in top_targets:
|
| 191 |
+
match = FORMAT_RE_NEW.fullmatch(target)
|
| 192 |
+
if match:
|
| 193 |
+
conv_spec = ConversionSpecifier(match, start_pos=start_pos)
|
| 194 |
+
else:
|
| 195 |
+
custom_match = FORMAT_RE_NEW_CUSTOM.fullmatch(target)
|
| 196 |
+
if custom_match:
|
| 197 |
+
conv_spec = ConversionSpecifier(
|
| 198 |
+
custom_match, start_pos=start_pos, non_standard_format_spec=True
|
| 199 |
+
)
|
| 200 |
+
else:
|
| 201 |
+
msg.fail(
|
| 202 |
+
"Invalid conversion specifier in format string",
|
| 203 |
+
ctx,
|
| 204 |
+
code=codes.STRING_FORMATTING,
|
| 205 |
+
)
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
if conv_spec.key and ("{" in conv_spec.key or "}" in conv_spec.key):
|
| 209 |
+
msg.fail("Conversion value must not contain { or }", ctx, code=codes.STRING_FORMATTING)
|
| 210 |
+
return None
|
| 211 |
+
result.append(conv_spec)
|
| 212 |
+
|
| 213 |
+
# Parse nested conversions that are allowed in format specifier.
|
| 214 |
+
if (
|
| 215 |
+
conv_spec.format_spec
|
| 216 |
+
and conv_spec.non_standard_format_spec
|
| 217 |
+
and ("{" in conv_spec.format_spec or "}" in conv_spec.format_spec)
|
| 218 |
+
):
|
| 219 |
+
if nested:
|
| 220 |
+
msg.fail(
|
| 221 |
+
"Formatting nesting must be at most two levels deep",
|
| 222 |
+
ctx,
|
| 223 |
+
code=codes.STRING_FORMATTING,
|
| 224 |
+
)
|
| 225 |
+
return None
|
| 226 |
+
sub_conv_specs = parse_format_value(conv_spec.format_spec, ctx, msg, nested=True)
|
| 227 |
+
if sub_conv_specs is None:
|
| 228 |
+
return None
|
| 229 |
+
result.extend(sub_conv_specs)
|
| 230 |
+
return result
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def find_non_escaped_targets(
|
| 234 |
+
format_value: str, ctx: Context, msg: MessageBuilder
|
| 235 |
+
) -> list[tuple[str, int]] | None:
|
| 236 |
+
"""Return list of raw (un-parsed) format specifiers in format string.
|
| 237 |
+
|
| 238 |
+
Format specifiers don't include enclosing braces. We don't use regexp for
|
| 239 |
+
this because they don't work well with nested/repeated patterns
|
| 240 |
+
(both greedy and non-greedy), and these are heavily used internally for
|
| 241 |
+
representation of f-strings.
|
| 242 |
+
|
| 243 |
+
Return None in case of an error.
|
| 244 |
+
"""
|
| 245 |
+
result = []
|
| 246 |
+
next_spec = ""
|
| 247 |
+
pos = 0
|
| 248 |
+
nesting = 0
|
| 249 |
+
while pos < len(format_value):
|
| 250 |
+
c = format_value[pos]
|
| 251 |
+
if not nesting:
|
| 252 |
+
# Skip any paired '{{' and '}}', enter nesting on '{', report error on '}'.
|
| 253 |
+
if c == "{":
|
| 254 |
+
if pos < len(format_value) - 1 and format_value[pos + 1] == "{":
|
| 255 |
+
pos += 1
|
| 256 |
+
else:
|
| 257 |
+
nesting = 1
|
| 258 |
+
if c == "}":
|
| 259 |
+
if pos < len(format_value) - 1 and format_value[pos + 1] == "}":
|
| 260 |
+
pos += 1
|
| 261 |
+
else:
|
| 262 |
+
msg.fail(
|
| 263 |
+
"Invalid conversion specifier in format string: unexpected }",
|
| 264 |
+
ctx,
|
| 265 |
+
code=codes.STRING_FORMATTING,
|
| 266 |
+
)
|
| 267 |
+
return None
|
| 268 |
+
else:
|
| 269 |
+
# Adjust nesting level, then either continue adding chars or move on.
|
| 270 |
+
if c == "{":
|
| 271 |
+
nesting += 1
|
| 272 |
+
if c == "}":
|
| 273 |
+
nesting -= 1
|
| 274 |
+
if nesting:
|
| 275 |
+
next_spec += c
|
| 276 |
+
else:
|
| 277 |
+
result.append((next_spec, pos - len(next_spec)))
|
| 278 |
+
next_spec = ""
|
| 279 |
+
pos += 1
|
| 280 |
+
if nesting:
|
| 281 |
+
msg.fail(
|
| 282 |
+
"Invalid conversion specifier in format string: unmatched {",
|
| 283 |
+
ctx,
|
| 284 |
+
code=codes.STRING_FORMATTING,
|
| 285 |
+
)
|
| 286 |
+
return None
|
| 287 |
+
return result
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class StringFormatterChecker:
|
| 291 |
+
"""String interpolation/formatter type checker.
|
| 292 |
+
|
| 293 |
+
This class works closely together with checker.ExpressionChecker.
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
# Some services are provided by a TypeChecker instance.
|
| 297 |
+
chk: TypeCheckerSharedApi
|
| 298 |
+
# This is shared with TypeChecker, but stored also here for convenience.
|
| 299 |
+
msg: MessageBuilder
|
| 300 |
+
|
| 301 |
+
def __init__(self, chk: TypeCheckerSharedApi, msg: MessageBuilder) -> None:
|
| 302 |
+
"""Construct an expression type checker."""
|
| 303 |
+
self.chk = chk
|
| 304 |
+
self.msg = msg
|
| 305 |
+
|
| 306 |
+
def check_str_format_call(self, call: CallExpr, format_value: str) -> None:
|
| 307 |
+
"""Perform more precise checks for str.format() calls when possible.
|
| 308 |
+
|
| 309 |
+
Currently the checks are performed for:
|
| 310 |
+
* Actual string literals
|
| 311 |
+
* Literal types with string values
|
| 312 |
+
* Final names with string values
|
| 313 |
+
|
| 314 |
+
The checks that we currently perform:
|
| 315 |
+
* Check generic validity (e.g. unmatched { or }, and {} in invalid positions)
|
| 316 |
+
* Check consistency of specifiers' auto-numbering
|
| 317 |
+
* Verify that replacements can be found for all conversion specifiers,
|
| 318 |
+
and all arguments were used
|
| 319 |
+
* Non-standard format specs are only allowed for types with custom __format__
|
| 320 |
+
* Type check replacements with accessors applied (if any).
|
| 321 |
+
* Verify that specifier type is known and matches replacement type
|
| 322 |
+
* Perform special checks for some specifier types:
|
| 323 |
+
- 'c' requires a single character string
|
| 324 |
+
- 's' must not accept bytes
|
| 325 |
+
- non-empty flags are only allowed for numeric types
|
| 326 |
+
"""
|
| 327 |
+
conv_specs = parse_format_value(format_value, call, self.msg)
|
| 328 |
+
if conv_specs is None:
|
| 329 |
+
return
|
| 330 |
+
if not self.auto_generate_keys(conv_specs, call):
|
| 331 |
+
return
|
| 332 |
+
self.check_specs_in_format_call(call, conv_specs, format_value)
|
| 333 |
+
|
| 334 |
+
def check_specs_in_format_call(
|
| 335 |
+
self, call: CallExpr, specs: list[ConversionSpecifier], format_value: str
|
| 336 |
+
) -> None:
|
| 337 |
+
"""Perform pairwise checks for conversion specifiers vs their replacements.
|
| 338 |
+
|
| 339 |
+
The core logic for format checking is implemented in this method.
|
| 340 |
+
"""
|
| 341 |
+
assert all(s.key for s in specs), "Keys must be auto-generated first!"
|
| 342 |
+
replacements = self.find_replacements_in_call(call, [cast(str, s.key) for s in specs])
|
| 343 |
+
assert len(replacements) == len(specs)
|
| 344 |
+
for spec, repl in zip(specs, replacements):
|
| 345 |
+
repl = self.apply_field_accessors(spec, repl, ctx=call)
|
| 346 |
+
actual_type = repl.type if isinstance(repl, TempNode) else self.chk.lookup_type(repl)
|
| 347 |
+
assert actual_type is not None
|
| 348 |
+
|
| 349 |
+
# Special case custom formatting.
|
| 350 |
+
if (
|
| 351 |
+
spec.format_spec
|
| 352 |
+
and spec.non_standard_format_spec
|
| 353 |
+
and
|
| 354 |
+
# Exclude "dynamic" specifiers (i.e. containing nested formatting).
|
| 355 |
+
not ("{" in spec.format_spec or "}" in spec.format_spec)
|
| 356 |
+
):
|
| 357 |
+
if (
|
| 358 |
+
not custom_special_method(actual_type, "__format__", check_all=True)
|
| 359 |
+
or spec.conversion
|
| 360 |
+
):
|
| 361 |
+
# TODO: add support for some custom specs like datetime?
|
| 362 |
+
self.msg.fail(
|
| 363 |
+
f'Unrecognized format specification "{spec.format_spec[1:]}"',
|
| 364 |
+
call,
|
| 365 |
+
code=codes.STRING_FORMATTING,
|
| 366 |
+
)
|
| 367 |
+
continue
|
| 368 |
+
# Adjust expected and actual types.
|
| 369 |
+
if not spec.conv_type:
|
| 370 |
+
expected_type: Type | None = AnyType(TypeOfAny.special_form)
|
| 371 |
+
else:
|
| 372 |
+
assert isinstance(call.callee, MemberExpr)
|
| 373 |
+
if isinstance(call.callee.expr, StrExpr):
|
| 374 |
+
format_str = call.callee.expr
|
| 375 |
+
else:
|
| 376 |
+
format_str = StrExpr(format_value)
|
| 377 |
+
expected_type = self.conversion_type(
|
| 378 |
+
spec.conv_type, call, format_str, format_call=True
|
| 379 |
+
)
|
| 380 |
+
if spec.conversion is not None:
|
| 381 |
+
# If the explicit conversion is given, then explicit conversion is called _first_.
|
| 382 |
+
if spec.conversion[1] not in "rsa":
|
| 383 |
+
self.msg.fail(
|
| 384 |
+
(
|
| 385 |
+
f'Invalid conversion type "{spec.conversion[1]}", '
|
| 386 |
+
f'must be one of "r", "s" or "a"'
|
| 387 |
+
),
|
| 388 |
+
call,
|
| 389 |
+
code=codes.STRING_FORMATTING,
|
| 390 |
+
)
|
| 391 |
+
actual_type = self.named_type("builtins.str")
|
| 392 |
+
|
| 393 |
+
# Perform the checks for given types.
|
| 394 |
+
if expected_type is None:
|
| 395 |
+
continue
|
| 396 |
+
|
| 397 |
+
a_type = get_proper_type(actual_type)
|
| 398 |
+
actual_items = (
|
| 399 |
+
get_proper_types(a_type.items) if isinstance(a_type, UnionType) else [a_type]
|
| 400 |
+
)
|
| 401 |
+
for a_type in actual_items:
|
| 402 |
+
if custom_special_method(a_type, "__format__"):
|
| 403 |
+
continue
|
| 404 |
+
self.check_placeholder_type(a_type, expected_type, call)
|
| 405 |
+
self.perform_special_format_checks(spec, call, repl, a_type, expected_type)
|
| 406 |
+
|
| 407 |
+
def perform_special_format_checks(
|
| 408 |
+
self,
|
| 409 |
+
spec: ConversionSpecifier,
|
| 410 |
+
call: CallExpr,
|
| 411 |
+
repl: Expression,
|
| 412 |
+
actual_type: Type,
|
| 413 |
+
expected_type: Type,
|
| 414 |
+
) -> None:
|
| 415 |
+
# TODO: try refactoring to combine this logic with % formatting.
|
| 416 |
+
if spec.conv_type == "c":
|
| 417 |
+
if isinstance(repl, (StrExpr, BytesExpr)) and len(repl.value) != 1:
|
| 418 |
+
self.msg.requires_int_or_char(call, format_call=True)
|
| 419 |
+
c_typ = get_proper_type(self.chk.lookup_type(repl))
|
| 420 |
+
if isinstance(c_typ, Instance) and c_typ.last_known_value:
|
| 421 |
+
c_typ = c_typ.last_known_value
|
| 422 |
+
if isinstance(c_typ, LiteralType) and isinstance(c_typ.value, str):
|
| 423 |
+
if len(c_typ.value) != 1:
|
| 424 |
+
self.msg.requires_int_or_char(call, format_call=True)
|
| 425 |
+
if (not spec.conv_type or spec.conv_type == "s") and not spec.conversion:
|
| 426 |
+
if has_type_component(actual_type, "builtins.bytes") and not custom_special_method(
|
| 427 |
+
actual_type, "__str__"
|
| 428 |
+
):
|
| 429 |
+
self.msg.fail(
|
| 430 |
+
'If x = b\'abc\' then f"{x}" or "{}".format(x) produces "b\'abc\'", '
|
| 431 |
+
'not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). '
|
| 432 |
+
"Otherwise, decode the bytes",
|
| 433 |
+
call,
|
| 434 |
+
code=codes.STR_BYTES_PY3,
|
| 435 |
+
)
|
| 436 |
+
if spec.flags:
|
| 437 |
+
numeric_types = UnionType(
|
| 438 |
+
[self.named_type("builtins.int"), self.named_type("builtins.float")]
|
| 439 |
+
)
|
| 440 |
+
if (
|
| 441 |
+
spec.conv_type
|
| 442 |
+
and spec.conv_type not in NUMERIC_TYPES_NEW
|
| 443 |
+
or not spec.conv_type
|
| 444 |
+
and not is_subtype(actual_type, numeric_types)
|
| 445 |
+
and not custom_special_method(actual_type, "__format__")
|
| 446 |
+
):
|
| 447 |
+
self.msg.fail(
|
| 448 |
+
"Numeric flags are only allowed for numeric types",
|
| 449 |
+
call,
|
| 450 |
+
code=codes.STRING_FORMATTING,
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
def find_replacements_in_call(self, call: CallExpr, keys: list[str]) -> list[Expression]:
|
| 454 |
+
"""Find replacement expression for every specifier in str.format() call.
|
| 455 |
+
|
| 456 |
+
In case of an error use TempNode(AnyType).
|
| 457 |
+
"""
|
| 458 |
+
result: list[Expression] = []
|
| 459 |
+
used: set[Expression] = set()
|
| 460 |
+
for key in keys:
|
| 461 |
+
if key.isdecimal():
|
| 462 |
+
expr = self.get_expr_by_position(int(key), call)
|
| 463 |
+
if not expr:
|
| 464 |
+
self.msg.fail(
|
| 465 |
+
f"Cannot find replacement for positional format specifier {key}",
|
| 466 |
+
call,
|
| 467 |
+
code=codes.STRING_FORMATTING,
|
| 468 |
+
)
|
| 469 |
+
expr = TempNode(AnyType(TypeOfAny.from_error))
|
| 470 |
+
else:
|
| 471 |
+
expr = self.get_expr_by_name(key, call)
|
| 472 |
+
if not expr:
|
| 473 |
+
self.msg.fail(
|
| 474 |
+
f'Cannot find replacement for named format specifier "{key}"',
|
| 475 |
+
call,
|
| 476 |
+
code=codes.STRING_FORMATTING,
|
| 477 |
+
)
|
| 478 |
+
expr = TempNode(AnyType(TypeOfAny.from_error))
|
| 479 |
+
result.append(expr)
|
| 480 |
+
if not isinstance(expr, TempNode):
|
| 481 |
+
used.add(expr)
|
| 482 |
+
# Strictly speaking not using all replacements is not a type error, but most likely
|
| 483 |
+
# a typo in user code, so we show an error like we do for % formatting.
|
| 484 |
+
total_explicit = len([kind for kind in call.arg_kinds if kind in (ARG_POS, ARG_NAMED)])
|
| 485 |
+
if len(used) < total_explicit:
|
| 486 |
+
self.msg.too_many_string_formatting_arguments(call)
|
| 487 |
+
return result
|
| 488 |
+
|
| 489 |
+
def get_expr_by_position(self, pos: int, call: CallExpr) -> Expression | None:
|
| 490 |
+
"""Get positional replacement expression from '{0}, {1}'.format(x, y, ...) call.
|
| 491 |
+
|
| 492 |
+
If the type is from *args, return TempNode(<item type>). Return None in case of
|
| 493 |
+
an error.
|
| 494 |
+
"""
|
| 495 |
+
pos_args = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_POS]
|
| 496 |
+
if pos < len(pos_args):
|
| 497 |
+
return pos_args[pos]
|
| 498 |
+
star_args = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_STAR]
|
| 499 |
+
if not star_args:
|
| 500 |
+
return None
|
| 501 |
+
|
| 502 |
+
# Fall back to *args when present in call.
|
| 503 |
+
star_arg = star_args[0]
|
| 504 |
+
varargs_type = get_proper_type(self.chk.lookup_type(star_arg))
|
| 505 |
+
if not isinstance(varargs_type, Instance) or not varargs_type.type.has_base(
|
| 506 |
+
"typing.Sequence"
|
| 507 |
+
):
|
| 508 |
+
# Error should be already reported.
|
| 509 |
+
return TempNode(AnyType(TypeOfAny.special_form))
|
| 510 |
+
iter_info = self.chk.named_generic_type(
|
| 511 |
+
"typing.Sequence", [AnyType(TypeOfAny.special_form)]
|
| 512 |
+
).type
|
| 513 |
+
return TempNode(map_instance_to_supertype(varargs_type, iter_info).args[0])
|
| 514 |
+
|
| 515 |
+
def get_expr_by_name(self, key: str, call: CallExpr) -> Expression | None:
|
| 516 |
+
"""Get named replacement expression from '{name}'.format(name=...) call.
|
| 517 |
+
|
| 518 |
+
If the type is from **kwargs, return TempNode(<item type>). Return None in case of
|
| 519 |
+
an error.
|
| 520 |
+
"""
|
| 521 |
+
named_args = [
|
| 522 |
+
arg
|
| 523 |
+
for arg, kind, name in zip(call.args, call.arg_kinds, call.arg_names)
|
| 524 |
+
if kind == ARG_NAMED and name == key
|
| 525 |
+
]
|
| 526 |
+
if named_args:
|
| 527 |
+
return named_args[0]
|
| 528 |
+
star_args_2 = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_STAR2]
|
| 529 |
+
if not star_args_2:
|
| 530 |
+
return None
|
| 531 |
+
star_arg_2 = star_args_2[0]
|
| 532 |
+
kwargs_type = get_proper_type(self.chk.lookup_type(star_arg_2))
|
| 533 |
+
if not isinstance(kwargs_type, Instance) or not kwargs_type.type.has_base(
|
| 534 |
+
"typing.Mapping"
|
| 535 |
+
):
|
| 536 |
+
# Error should be already reported.
|
| 537 |
+
return TempNode(AnyType(TypeOfAny.special_form))
|
| 538 |
+
any_type = AnyType(TypeOfAny.special_form)
|
| 539 |
+
mapping_info = self.chk.named_generic_type("typing.Mapping", [any_type, any_type]).type
|
| 540 |
+
return TempNode(map_instance_to_supertype(kwargs_type, mapping_info).args[1])
|
| 541 |
+
|
| 542 |
+
def auto_generate_keys(self, all_specs: list[ConversionSpecifier], ctx: Context) -> bool:
|
| 543 |
+
"""Translate '{} {name} {}' to '{0} {name} {1}'.
|
| 544 |
+
|
| 545 |
+
Return True if generation was successful, otherwise report an error and return false.
|
| 546 |
+
"""
|
| 547 |
+
some_defined = any(s.key and s.key.isdecimal() for s in all_specs)
|
| 548 |
+
all_defined = all(bool(s.key) for s in all_specs)
|
| 549 |
+
if some_defined and not all_defined:
|
| 550 |
+
self.msg.fail(
|
| 551 |
+
"Cannot combine automatic field numbering and manual field specification",
|
| 552 |
+
ctx,
|
| 553 |
+
code=codes.STRING_FORMATTING,
|
| 554 |
+
)
|
| 555 |
+
return False
|
| 556 |
+
if all_defined:
|
| 557 |
+
return True
|
| 558 |
+
next_index = 0
|
| 559 |
+
for spec in all_specs:
|
| 560 |
+
if not spec.key:
|
| 561 |
+
str_index = str(next_index)
|
| 562 |
+
spec.key = str_index
|
| 563 |
+
# Update also the full field (i.e. turn {.x} into {0.x}).
|
| 564 |
+
if not spec.field:
|
| 565 |
+
spec.field = str_index
|
| 566 |
+
else:
|
| 567 |
+
spec.field = str_index + spec.field
|
| 568 |
+
next_index += 1
|
| 569 |
+
return True
|
| 570 |
+
|
| 571 |
+
def apply_field_accessors(
|
| 572 |
+
self, spec: ConversionSpecifier, repl: Expression, ctx: Context
|
| 573 |
+
) -> Expression:
|
| 574 |
+
"""Transform and validate expr in '{.attr[item]}'.format(expr) into expr.attr['item'].
|
| 575 |
+
|
| 576 |
+
If validation fails, return TempNode(AnyType).
|
| 577 |
+
"""
|
| 578 |
+
assert spec.key, "Keys must be auto-generated first!"
|
| 579 |
+
if spec.field == spec.key:
|
| 580 |
+
return repl
|
| 581 |
+
assert spec.field
|
| 582 |
+
|
| 583 |
+
temp_errors = Errors(self.chk.options)
|
| 584 |
+
dummy = DUMMY_FIELD_NAME + spec.field[len(spec.key) :]
|
| 585 |
+
temp_ast: Node = parse(
|
| 586 |
+
dummy, fnam="<format>", module=None, options=self.chk.options, errors=temp_errors
|
| 587 |
+
)
|
| 588 |
+
if temp_errors.is_errors():
|
| 589 |
+
self.msg.fail(
|
| 590 |
+
f'Syntax error in format specifier "{spec.field}"',
|
| 591 |
+
ctx,
|
| 592 |
+
code=codes.STRING_FORMATTING,
|
| 593 |
+
)
|
| 594 |
+
return TempNode(AnyType(TypeOfAny.from_error))
|
| 595 |
+
|
| 596 |
+
# These asserts are guaranteed by the original regexp.
|
| 597 |
+
assert isinstance(temp_ast, MypyFile)
|
| 598 |
+
temp_ast = temp_ast.defs[0]
|
| 599 |
+
assert isinstance(temp_ast, ExpressionStmt)
|
| 600 |
+
temp_ast = temp_ast.expr
|
| 601 |
+
if not self.validate_and_transform_accessors(temp_ast, repl, spec, ctx=ctx):
|
| 602 |
+
return TempNode(AnyType(TypeOfAny.from_error))
|
| 603 |
+
|
| 604 |
+
# Check if there are any other errors (like missing members).
|
| 605 |
+
# TODO: fix column to point to actual start of the format specifier _within_ string.
|
| 606 |
+
temp_ast.line = ctx.line
|
| 607 |
+
temp_ast.column = ctx.column
|
| 608 |
+
self.chk.expr_checker.accept(temp_ast)
|
| 609 |
+
return temp_ast
|
| 610 |
+
|
| 611 |
+
def validate_and_transform_accessors(
|
| 612 |
+
self,
|
| 613 |
+
temp_ast: Expression,
|
| 614 |
+
original_repl: Expression,
|
| 615 |
+
spec: ConversionSpecifier,
|
| 616 |
+
ctx: Context,
|
| 617 |
+
) -> bool:
|
| 618 |
+
"""Validate and transform (in-place) format field accessors.
|
| 619 |
+
|
| 620 |
+
On error, report it and return False. The transformations include replacing the dummy
|
| 621 |
+
variable with actual replacement expression and translating any name expressions in an
|
| 622 |
+
index into strings, so that this will work:
|
| 623 |
+
|
| 624 |
+
class User(TypedDict):
|
| 625 |
+
name: str
|
| 626 |
+
id: int
|
| 627 |
+
u: User
|
| 628 |
+
'{[id]:d} -> {[name]}'.format(u)
|
| 629 |
+
"""
|
| 630 |
+
if not isinstance(temp_ast, (MemberExpr, IndexExpr)):
|
| 631 |
+
self.msg.fail(
|
| 632 |
+
"Only index and member expressions are allowed in"
|
| 633 |
+
' format field accessors; got "{}"'.format(spec.field),
|
| 634 |
+
ctx,
|
| 635 |
+
code=codes.STRING_FORMATTING,
|
| 636 |
+
)
|
| 637 |
+
return False
|
| 638 |
+
if isinstance(temp_ast, MemberExpr):
|
| 639 |
+
node = temp_ast.expr
|
| 640 |
+
else:
|
| 641 |
+
node = temp_ast.base
|
| 642 |
+
if not isinstance(temp_ast.index, (NameExpr, IntExpr)):
|
| 643 |
+
assert spec.key, "Call this method only after auto-generating keys!"
|
| 644 |
+
assert spec.field
|
| 645 |
+
self.msg.fail(
|
| 646 |
+
'Invalid index expression in format field accessor "{}"'.format(
|
| 647 |
+
spec.field[len(spec.key) :]
|
| 648 |
+
),
|
| 649 |
+
ctx,
|
| 650 |
+
code=codes.STRING_FORMATTING,
|
| 651 |
+
)
|
| 652 |
+
return False
|
| 653 |
+
if isinstance(temp_ast.index, NameExpr):
|
| 654 |
+
temp_ast.index = StrExpr(temp_ast.index.name)
|
| 655 |
+
if isinstance(node, NameExpr) and node.name == DUMMY_FIELD_NAME:
|
| 656 |
+
# Replace it with the actual replacement expression.
|
| 657 |
+
assert isinstance(temp_ast, (IndexExpr, MemberExpr)) # XXX: this is redundant
|
| 658 |
+
if isinstance(temp_ast, IndexExpr):
|
| 659 |
+
temp_ast.base = original_repl
|
| 660 |
+
else:
|
| 661 |
+
temp_ast.expr = original_repl
|
| 662 |
+
return True
|
| 663 |
+
node.line = ctx.line
|
| 664 |
+
node.column = ctx.column
|
| 665 |
+
return self.validate_and_transform_accessors(
|
| 666 |
+
node, original_repl=original_repl, spec=spec, ctx=ctx
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
# TODO: In Python 3, the bytes formatting has a more restricted set of options
|
| 670 |
+
# compared to string formatting.
|
| 671 |
+
def check_str_interpolation(self, expr: FormatStringExpr, replacements: Expression) -> Type:
|
| 672 |
+
"""Check the types of the 'replacements' in a string interpolation
|
| 673 |
+
expression: str % replacements.
|
| 674 |
+
"""
|
| 675 |
+
self.chk.expr_checker.accept(expr)
|
| 676 |
+
specifiers = parse_conversion_specifiers(expr.value)
|
| 677 |
+
has_mapping_keys = self.analyze_conversion_specifiers(specifiers, expr)
|
| 678 |
+
if has_mapping_keys is None:
|
| 679 |
+
pass # Error was reported
|
| 680 |
+
elif has_mapping_keys:
|
| 681 |
+
self.check_mapping_str_interpolation(specifiers, replacements, expr)
|
| 682 |
+
else:
|
| 683 |
+
self.check_simple_str_interpolation(specifiers, replacements, expr)
|
| 684 |
+
|
| 685 |
+
if isinstance(expr, BytesExpr):
|
| 686 |
+
return self.named_type("builtins.bytes")
|
| 687 |
+
elif isinstance(expr, StrExpr):
|
| 688 |
+
return self.named_type("builtins.str")
|
| 689 |
+
else:
|
| 690 |
+
assert False
|
| 691 |
+
|
| 692 |
+
def analyze_conversion_specifiers(
|
| 693 |
+
self, specifiers: list[ConversionSpecifier], context: Context
|
| 694 |
+
) -> bool | None:
|
| 695 |
+
has_star = any(specifier.has_star() for specifier in specifiers)
|
| 696 |
+
has_key = any(specifier.has_key() for specifier in specifiers)
|
| 697 |
+
all_have_keys = all(
|
| 698 |
+
specifier.has_key() or specifier.conv_type == "%" for specifier in specifiers
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
if has_key and has_star:
|
| 702 |
+
self.msg.string_interpolation_with_star_and_key(context)
|
| 703 |
+
return None
|
| 704 |
+
if has_key and not all_have_keys:
|
| 705 |
+
self.msg.string_interpolation_mixing_key_and_non_keys(context)
|
| 706 |
+
return None
|
| 707 |
+
return has_key
|
| 708 |
+
|
| 709 |
+
def check_simple_str_interpolation(
|
| 710 |
+
self,
|
| 711 |
+
specifiers: list[ConversionSpecifier],
|
| 712 |
+
replacements: Expression,
|
| 713 |
+
expr: FormatStringExpr,
|
| 714 |
+
) -> None:
|
| 715 |
+
"""Check % string interpolation with positional specifiers '%s, %d' % ('yes, 42')."""
|
| 716 |
+
checkers = self.build_replacement_checkers(specifiers, replacements, expr)
|
| 717 |
+
if checkers is None:
|
| 718 |
+
return
|
| 719 |
+
|
| 720 |
+
rhs_type = get_proper_type(self.accept(replacements))
|
| 721 |
+
rep_types: list[Type] = []
|
| 722 |
+
if isinstance(rhs_type, TupleType):
|
| 723 |
+
rep_types = rhs_type.items
|
| 724 |
+
unpack_index = find_unpack_in_list(rep_types)
|
| 725 |
+
if unpack_index is not None:
|
| 726 |
+
# TODO: we should probably warn about potentially short tuple.
|
| 727 |
+
# However, without special-casing for tuple(f(i) for in other_tuple)
|
| 728 |
+
# this causes false positive on mypy self-check in report.py.
|
| 729 |
+
extras = max(0, len(checkers) - len(rep_types) + 1)
|
| 730 |
+
unpacked = rep_types[unpack_index]
|
| 731 |
+
assert isinstance(unpacked, UnpackType)
|
| 732 |
+
unpacked = get_proper_type(unpacked.type)
|
| 733 |
+
if isinstance(unpacked, TypeVarTupleType):
|
| 734 |
+
unpacked = get_proper_type(unpacked.upper_bound)
|
| 735 |
+
assert (
|
| 736 |
+
isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple"
|
| 737 |
+
)
|
| 738 |
+
unpack_items = [unpacked.args[0]] * extras
|
| 739 |
+
rep_types = rep_types[:unpack_index] + unpack_items + rep_types[unpack_index + 1 :]
|
| 740 |
+
elif isinstance(rhs_type, AnyType):
|
| 741 |
+
return
|
| 742 |
+
elif isinstance(rhs_type, Instance) and rhs_type.type.fullname == "builtins.tuple":
|
| 743 |
+
# Assume that an arbitrary-length tuple has the right number of items.
|
| 744 |
+
rep_types = [rhs_type.args[0]] * len(checkers)
|
| 745 |
+
elif isinstance(rhs_type, UnionType):
|
| 746 |
+
for typ in rhs_type.relevant_items():
|
| 747 |
+
temp_node = TempNode(typ)
|
| 748 |
+
temp_node.line = replacements.line
|
| 749 |
+
self.check_simple_str_interpolation(specifiers, temp_node, expr)
|
| 750 |
+
return
|
| 751 |
+
else:
|
| 752 |
+
rep_types = [rhs_type]
|
| 753 |
+
|
| 754 |
+
if len(checkers) > len(rep_types):
|
| 755 |
+
# Only check the fix-length Tuple type. Other Iterable types would skip.
|
| 756 |
+
if is_subtype(rhs_type, self.chk.named_type("typing.Iterable")) and not isinstance(
|
| 757 |
+
rhs_type, TupleType
|
| 758 |
+
):
|
| 759 |
+
return
|
| 760 |
+
else:
|
| 761 |
+
self.msg.too_few_string_formatting_arguments(replacements)
|
| 762 |
+
elif len(checkers) < len(rep_types):
|
| 763 |
+
self.msg.too_many_string_formatting_arguments(replacements)
|
| 764 |
+
else:
|
| 765 |
+
if len(checkers) == 1:
|
| 766 |
+
check_node, check_type = checkers[0]
|
| 767 |
+
if isinstance(rhs_type, TupleType) and len(rhs_type.items) == 1:
|
| 768 |
+
check_type(rhs_type.items[0])
|
| 769 |
+
else:
|
| 770 |
+
check_node(replacements)
|
| 771 |
+
elif isinstance(replacements, TupleExpr) and not any(
|
| 772 |
+
isinstance(item, StarExpr) for item in replacements.items
|
| 773 |
+
):
|
| 774 |
+
for checks, rep_node in zip(checkers, replacements.items):
|
| 775 |
+
check_node, check_type = checks
|
| 776 |
+
check_node(rep_node)
|
| 777 |
+
else:
|
| 778 |
+
for checks, rep_type in zip(checkers, rep_types):
|
| 779 |
+
check_node, check_type = checks
|
| 780 |
+
check_type(rep_type)
|
| 781 |
+
|
| 782 |
+
def check_mapping_str_interpolation(
|
| 783 |
+
self,
|
| 784 |
+
specifiers: list[ConversionSpecifier],
|
| 785 |
+
replacements: Expression,
|
| 786 |
+
expr: FormatStringExpr,
|
| 787 |
+
) -> None:
|
| 788 |
+
"""Check % string interpolation with names specifiers '%(name)s' % {'name': 'John'}."""
|
| 789 |
+
if isinstance(replacements, DictExpr) and all(
|
| 790 |
+
isinstance(k, (StrExpr, BytesExpr)) for k, v in replacements.items
|
| 791 |
+
):
|
| 792 |
+
mapping: dict[str, Type] = {}
|
| 793 |
+
for k, v in replacements.items:
|
| 794 |
+
if isinstance(expr, BytesExpr):
|
| 795 |
+
# Special case: for bytes formatting keys must be bytes.
|
| 796 |
+
if not isinstance(k, BytesExpr):
|
| 797 |
+
self.msg.fail(
|
| 798 |
+
"Dictionary keys in bytes formatting must be bytes, not strings",
|
| 799 |
+
expr,
|
| 800 |
+
code=codes.STRING_FORMATTING,
|
| 801 |
+
)
|
| 802 |
+
key_str = cast(FormatStringExpr, k).value
|
| 803 |
+
mapping[key_str] = self.accept(v)
|
| 804 |
+
|
| 805 |
+
for specifier in specifiers:
|
| 806 |
+
if specifier.conv_type == "%":
|
| 807 |
+
# %% is allowed in mappings, no checking is required
|
| 808 |
+
continue
|
| 809 |
+
assert specifier.key is not None
|
| 810 |
+
if specifier.key not in mapping:
|
| 811 |
+
self.msg.key_not_in_mapping(specifier.key, replacements)
|
| 812 |
+
return
|
| 813 |
+
rep_type = mapping[specifier.key]
|
| 814 |
+
assert specifier.conv_type is not None
|
| 815 |
+
expected_type = self.conversion_type(specifier.conv_type, replacements, expr)
|
| 816 |
+
if expected_type is None:
|
| 817 |
+
return
|
| 818 |
+
self.chk.check_subtype(
|
| 819 |
+
rep_type,
|
| 820 |
+
expected_type,
|
| 821 |
+
replacements,
|
| 822 |
+
message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,
|
| 823 |
+
"expression has type",
|
| 824 |
+
f"placeholder with key '{specifier.key}' has type",
|
| 825 |
+
code=codes.STRING_FORMATTING,
|
| 826 |
+
)
|
| 827 |
+
if specifier.conv_type == "s":
|
| 828 |
+
self.check_s_special_cases(expr, rep_type, expr)
|
| 829 |
+
else:
|
| 830 |
+
rep_type = self.accept(replacements)
|
| 831 |
+
dict_type = self.build_dict_type(expr)
|
| 832 |
+
self.chk.check_subtype(
|
| 833 |
+
rep_type,
|
| 834 |
+
dict_type,
|
| 835 |
+
replacements,
|
| 836 |
+
message_registry.FORMAT_REQUIRES_MAPPING,
|
| 837 |
+
"expression has type",
|
| 838 |
+
"expected type for mapping is",
|
| 839 |
+
code=codes.STRING_FORMATTING,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
def build_dict_type(self, expr: FormatStringExpr) -> Type:
|
| 843 |
+
"""Build expected mapping type for right operand in % formatting."""
|
| 844 |
+
any_type = AnyType(TypeOfAny.special_form)
|
| 845 |
+
if isinstance(expr, BytesExpr):
|
| 846 |
+
bytes_type = self.chk.named_generic_type("builtins.bytes", [])
|
| 847 |
+
return self.chk.named_generic_type(
|
| 848 |
+
"_typeshed.SupportsKeysAndGetItem", [bytes_type, any_type]
|
| 849 |
+
)
|
| 850 |
+
elif isinstance(expr, StrExpr):
|
| 851 |
+
str_type = self.chk.named_generic_type("builtins.str", [])
|
| 852 |
+
return self.chk.named_generic_type(
|
| 853 |
+
"_typeshed.SupportsKeysAndGetItem", [str_type, any_type]
|
| 854 |
+
)
|
| 855 |
+
else:
|
| 856 |
+
assert False, "Unreachable"
|
| 857 |
+
|
| 858 |
+
def build_replacement_checkers(
|
| 859 |
+
self, specifiers: list[ConversionSpecifier], context: Context, expr: FormatStringExpr
|
| 860 |
+
) -> list[Checkers] | None:
|
| 861 |
+
checkers: list[Checkers] = []
|
| 862 |
+
for specifier in specifiers:
|
| 863 |
+
checker = self.replacement_checkers(specifier, context, expr)
|
| 864 |
+
if checker is None:
|
| 865 |
+
return None
|
| 866 |
+
checkers.extend(checker)
|
| 867 |
+
return checkers
|
| 868 |
+
|
| 869 |
+
def replacement_checkers(
|
| 870 |
+
self, specifier: ConversionSpecifier, context: Context, expr: FormatStringExpr
|
| 871 |
+
) -> list[Checkers] | None:
|
| 872 |
+
"""Returns a list of tuples of two functions that check whether a replacement is
|
| 873 |
+
of the right type for the specifier. The first function takes a node and checks
|
| 874 |
+
its type in the right type context. The second function just checks a type.
|
| 875 |
+
"""
|
| 876 |
+
checkers: list[Checkers] = []
|
| 877 |
+
|
| 878 |
+
if specifier.width == "*":
|
| 879 |
+
checkers.append(self.checkers_for_star(context))
|
| 880 |
+
if specifier.precision == "*":
|
| 881 |
+
checkers.append(self.checkers_for_star(context))
|
| 882 |
+
|
| 883 |
+
if specifier.conv_type == "c":
|
| 884 |
+
c = self.checkers_for_c_type(specifier.conv_type, context, expr)
|
| 885 |
+
if c is None:
|
| 886 |
+
return None
|
| 887 |
+
checkers.append(c)
|
| 888 |
+
elif specifier.conv_type is not None and specifier.conv_type != "%":
|
| 889 |
+
c = self.checkers_for_regular_type(specifier.conv_type, context, expr)
|
| 890 |
+
if c is None:
|
| 891 |
+
return None
|
| 892 |
+
checkers.append(c)
|
| 893 |
+
return checkers
|
| 894 |
+
|
| 895 |
+
def checkers_for_star(self, context: Context) -> Checkers:
|
| 896 |
+
"""Returns a tuple of check functions that check whether, respectively,
|
| 897 |
+
a node or a type is compatible with a star in a conversion specifier.
|
| 898 |
+
"""
|
| 899 |
+
expected = self.named_type("builtins.int")
|
| 900 |
+
|
| 901 |
+
def check_type(type: Type) -> bool:
|
| 902 |
+
expected = self.named_type("builtins.int")
|
| 903 |
+
return self.chk.check_subtype(
|
| 904 |
+
type, expected, context, "* wants int", code=codes.STRING_FORMATTING
|
| 905 |
+
)
|
| 906 |
+
|
| 907 |
+
def check_expr(expr: Expression) -> None:
|
| 908 |
+
type = self.accept(expr, expected)
|
| 909 |
+
check_type(type)
|
| 910 |
+
|
| 911 |
+
return check_expr, check_type
|
| 912 |
+
|
| 913 |
+
def check_placeholder_type(self, typ: Type, expected_type: Type, context: Context) -> bool:
|
| 914 |
+
return self.chk.check_subtype(
|
| 915 |
+
typ,
|
| 916 |
+
expected_type,
|
| 917 |
+
context,
|
| 918 |
+
message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,
|
| 919 |
+
"expression has type",
|
| 920 |
+
"placeholder has type",
|
| 921 |
+
code=codes.STRING_FORMATTING,
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
def checkers_for_regular_type(
|
| 925 |
+
self, conv_type: str, context: Context, expr: FormatStringExpr
|
| 926 |
+
) -> Checkers | None:
|
| 927 |
+
"""Returns a tuple of check functions that check whether, respectively,
|
| 928 |
+
a node or a type is compatible with 'type'. Return None in case of an error.
|
| 929 |
+
"""
|
| 930 |
+
expected_type = self.conversion_type(conv_type, context, expr)
|
| 931 |
+
if expected_type is None:
|
| 932 |
+
return None
|
| 933 |
+
|
| 934 |
+
def check_type(typ: Type) -> bool:
|
| 935 |
+
assert expected_type is not None
|
| 936 |
+
ret = self.check_placeholder_type(typ, expected_type, context)
|
| 937 |
+
if ret and conv_type == "s":
|
| 938 |
+
ret = self.check_s_special_cases(expr, typ, context)
|
| 939 |
+
return ret
|
| 940 |
+
|
| 941 |
+
def check_expr(expr: Expression) -> None:
|
| 942 |
+
type = self.accept(expr, expected_type)
|
| 943 |
+
check_type(type)
|
| 944 |
+
|
| 945 |
+
return check_expr, check_type
|
| 946 |
+
|
| 947 |
+
def check_s_special_cases(self, expr: FormatStringExpr, typ: Type, context: Context) -> bool:
|
| 948 |
+
"""Additional special cases for %s in bytes vs string context."""
|
| 949 |
+
if isinstance(expr, StrExpr):
|
| 950 |
+
# Couple special cases for string formatting.
|
| 951 |
+
if has_type_component(typ, "builtins.bytes"):
|
| 952 |
+
self.msg.fail(
|
| 953 |
+
'If x = b\'abc\' then "%s" % x produces "b\'abc\'", not "abc". '
|
| 954 |
+
'If this is desired behavior use "%r" % x. Otherwise, decode the bytes',
|
| 955 |
+
context,
|
| 956 |
+
code=codes.STR_BYTES_PY3,
|
| 957 |
+
)
|
| 958 |
+
return False
|
| 959 |
+
if isinstance(expr, BytesExpr):
|
| 960 |
+
# A special case for bytes formatting: b'%s' actually requires bytes on Python 3.
|
| 961 |
+
if has_type_component(typ, "builtins.str"):
|
| 962 |
+
self.msg.fail(
|
| 963 |
+
"On Python 3 b'%s' requires bytes, not string",
|
| 964 |
+
context,
|
| 965 |
+
code=codes.STRING_FORMATTING,
|
| 966 |
+
)
|
| 967 |
+
return False
|
| 968 |
+
return True
|
| 969 |
+
|
| 970 |
+
def checkers_for_c_type(
|
| 971 |
+
self, type: str, context: Context, format_expr: FormatStringExpr
|
| 972 |
+
) -> Checkers | None:
|
| 973 |
+
"""Returns a tuple of check functions that check whether, respectively,
|
| 974 |
+
a node or a type is compatible with 'type' that is a character type.
|
| 975 |
+
"""
|
| 976 |
+
expected_type = self.conversion_type(type, context, format_expr)
|
| 977 |
+
if expected_type is None:
|
| 978 |
+
return None
|
| 979 |
+
|
| 980 |
+
def check_type(type: Type) -> bool:
|
| 981 |
+
assert expected_type is not None
|
| 982 |
+
if isinstance(format_expr, BytesExpr):
|
| 983 |
+
err_msg = '"%c" requires an integer in range(256) or a single byte'
|
| 984 |
+
else:
|
| 985 |
+
err_msg = '"%c" requires int or char'
|
| 986 |
+
return self.chk.check_subtype(
|
| 987 |
+
type,
|
| 988 |
+
expected_type,
|
| 989 |
+
context,
|
| 990 |
+
err_msg,
|
| 991 |
+
"expression has type",
|
| 992 |
+
code=codes.STRING_FORMATTING,
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
def check_expr(expr: Expression) -> None:
|
| 996 |
+
"""int, or str with length 1"""
|
| 997 |
+
type = self.accept(expr, expected_type)
|
| 998 |
+
# We need further check with expr to make sure that
|
| 999 |
+
# it has exact one char or one single byte.
|
| 1000 |
+
if check_type(type):
|
| 1001 |
+
# Python 3 doesn't support b'%c' % str
|
| 1002 |
+
if (
|
| 1003 |
+
isinstance(format_expr, BytesExpr)
|
| 1004 |
+
and isinstance(expr, BytesExpr)
|
| 1005 |
+
and len(expr.value) != 1
|
| 1006 |
+
):
|
| 1007 |
+
self.msg.requires_int_or_single_byte(context)
|
| 1008 |
+
elif isinstance(expr, (StrExpr, BytesExpr)) and len(expr.value) != 1:
|
| 1009 |
+
self.msg.requires_int_or_char(context)
|
| 1010 |
+
|
| 1011 |
+
return check_expr, check_type
|
| 1012 |
+
|
| 1013 |
+
def conversion_type(
|
| 1014 |
+
self, p: str, context: Context, expr: FormatStringExpr, format_call: bool = False
|
| 1015 |
+
) -> Type | None:
|
| 1016 |
+
"""Return the type that is accepted for a string interpolation conversion specifier type.
|
| 1017 |
+
|
| 1018 |
+
Note that both Python's float (e.g. %f) and integer (e.g. %d)
|
| 1019 |
+
specifier types accept both float and integers.
|
| 1020 |
+
|
| 1021 |
+
The 'format_call' argument indicates whether this type came from % interpolation or from
|
| 1022 |
+
a str.format() call, the meaning of few formatting types are different.
|
| 1023 |
+
"""
|
| 1024 |
+
NUMERIC_TYPES = NUMERIC_TYPES_NEW if format_call else NUMERIC_TYPES_OLD
|
| 1025 |
+
INT_TYPES = REQUIRE_INT_NEW if format_call else REQUIRE_INT_OLD
|
| 1026 |
+
if p == "b" and not format_call:
|
| 1027 |
+
if not isinstance(expr, BytesExpr):
|
| 1028 |
+
self.msg.fail(
|
| 1029 |
+
'Format character "b" is only supported on bytes patterns',
|
| 1030 |
+
context,
|
| 1031 |
+
code=codes.STRING_FORMATTING,
|
| 1032 |
+
)
|
| 1033 |
+
return None
|
| 1034 |
+
return self.named_type("builtins.bytes")
|
| 1035 |
+
elif p == "a":
|
| 1036 |
+
# TODO: return type object?
|
| 1037 |
+
return AnyType(TypeOfAny.special_form)
|
| 1038 |
+
elif p in ["s", "r"]:
|
| 1039 |
+
return AnyType(TypeOfAny.special_form)
|
| 1040 |
+
elif p in NUMERIC_TYPES:
|
| 1041 |
+
if p in INT_TYPES:
|
| 1042 |
+
numeric_types = [self.named_type("builtins.int")]
|
| 1043 |
+
else:
|
| 1044 |
+
numeric_types = [
|
| 1045 |
+
self.named_type("builtins.int"),
|
| 1046 |
+
self.named_type("builtins.float"),
|
| 1047 |
+
]
|
| 1048 |
+
if not format_call:
|
| 1049 |
+
if p in FLOAT_TYPES:
|
| 1050 |
+
numeric_types.append(self.named_type("typing.SupportsFloat"))
|
| 1051 |
+
else:
|
| 1052 |
+
numeric_types.append(self.named_type("typing.SupportsInt"))
|
| 1053 |
+
return UnionType.make_union(numeric_types)
|
| 1054 |
+
elif p in ["c"]:
|
| 1055 |
+
if isinstance(expr, BytesExpr):
|
| 1056 |
+
return UnionType(
|
| 1057 |
+
[self.named_type("builtins.int"), self.named_type("builtins.bytes")]
|
| 1058 |
+
)
|
| 1059 |
+
else:
|
| 1060 |
+
return UnionType(
|
| 1061 |
+
[self.named_type("builtins.int"), self.named_type("builtins.str")]
|
| 1062 |
+
)
|
| 1063 |
+
else:
|
| 1064 |
+
self.msg.unsupported_placeholder(p, context)
|
| 1065 |
+
return None
|
| 1066 |
+
|
| 1067 |
+
#
|
| 1068 |
+
# Helpers
|
| 1069 |
+
#
|
| 1070 |
+
|
| 1071 |
+
def named_type(self, name: str) -> Instance:
|
| 1072 |
+
"""Return an instance type with type given by the name and no type
|
| 1073 |
+
arguments. Alias for TypeChecker.named_type.
|
| 1074 |
+
"""
|
| 1075 |
+
return self.chk.named_type(name)
|
| 1076 |
+
|
| 1077 |
+
def accept(self, expr: Expression, context: Type | None = None) -> Type:
|
| 1078 |
+
"""Type check a node. Alias for TypeChecker.accept."""
|
| 1079 |
+
return self.chk.expr_checker.accept(expr, context)
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
def has_type_component(typ: Type, fullname: str) -> bool:
|
| 1083 |
+
"""Is this a specific instance type, or a union that contains it?
|
| 1084 |
+
|
| 1085 |
+
We use this ad-hoc function instead of a proper visitor or subtype check
|
| 1086 |
+
because some str vs bytes errors are strictly speaking not runtime errors,
|
| 1087 |
+
but rather highly counter-intuitive behavior. This is similar to what is used for
|
| 1088 |
+
--strict-equality.
|
| 1089 |
+
"""
|
| 1090 |
+
typ = get_proper_type(typ)
|
| 1091 |
+
if isinstance(typ, Instance):
|
| 1092 |
+
return typ.type.has_base(fullname)
|
| 1093 |
+
elif isinstance(typ, TypeVarType):
|
| 1094 |
+
return has_type_component(typ.upper_bound, fullname) or any(
|
| 1095 |
+
has_type_component(v, fullname) for v in typ.values
|
| 1096 |
+
)
|
| 1097 |
+
elif isinstance(typ, UnionType):
|
| 1098 |
+
return any(has_type_component(t, fullname) for t in typ.relevant_items())
|
| 1099 |
+
return False
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/config_parser.py
ADDED
|
@@ -0,0 +1,734 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import configparser
|
| 5 |
+
import glob as fileglob
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
from io import StringIO
|
| 10 |
+
|
| 11 |
+
if sys.version_info >= (3, 11):
|
| 12 |
+
import tomllib
|
| 13 |
+
else:
|
| 14 |
+
import tomli as tomllib
|
| 15 |
+
|
| 16 |
+
from collections.abc import Callable, Mapping, MutableMapping, Sequence
|
| 17 |
+
from typing import Any, Final, TextIO, TypeAlias
|
| 18 |
+
from typing_extensions import Never
|
| 19 |
+
|
| 20 |
+
from mypy import defaults
|
| 21 |
+
from mypy.options import PER_MODULE_OPTIONS, Options
|
| 22 |
+
|
| 23 |
+
_CONFIG_VALUE_TYPES: TypeAlias = (
|
| 24 |
+
str | bool | int | float | dict[str, str] | list[str] | tuple[int, int]
|
| 25 |
+
)
|
| 26 |
+
_INI_PARSER_CALLABLE: TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class VersionTypeError(argparse.ArgumentTypeError):
|
| 30 |
+
"""Provide a fallback value if the Python version is unsupported."""
|
| 31 |
+
|
| 32 |
+
def __init__(self, *args: Any, fallback: tuple[int, int]) -> None:
|
| 33 |
+
self.fallback = fallback
|
| 34 |
+
super().__init__(*args)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def parse_version(v: str | float) -> tuple[int, int]:
|
| 38 |
+
m = re.match(r"\A(\d)\.(\d+)\Z", str(v))
|
| 39 |
+
if not m:
|
| 40 |
+
raise argparse.ArgumentTypeError(f"Invalid python version '{v}' (expected format: 'x.y')")
|
| 41 |
+
major, minor = int(m.group(1)), int(m.group(2))
|
| 42 |
+
if major == 2 and minor == 7:
|
| 43 |
+
pass # Error raised elsewhere
|
| 44 |
+
elif major == 3:
|
| 45 |
+
if minor < defaults.PYTHON3_VERSION_MIN[1]:
|
| 46 |
+
msg = "Python 3.{} is not supported (must be {}.{} or higher)".format(
|
| 47 |
+
minor, *defaults.PYTHON3_VERSION_MIN
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
if isinstance(v, float):
|
| 51 |
+
msg += ". You may need to put quotes around your Python version"
|
| 52 |
+
|
| 53 |
+
raise VersionTypeError(msg, fallback=defaults.PYTHON3_VERSION_MIN)
|
| 54 |
+
else:
|
| 55 |
+
raise argparse.ArgumentTypeError(
|
| 56 |
+
f"Python major version '{major}' out of range (must be 3)"
|
| 57 |
+
)
|
| 58 |
+
return major, minor
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def try_split(v: str | Sequence[str] | object, split_regex: str = ",") -> list[str]:
|
| 62 |
+
"""Split and trim a str or sequence (eg: list) of str into a list of str.
|
| 63 |
+
If an element of the input is not str, a type error will be raised."""
|
| 64 |
+
|
| 65 |
+
def complain(x: object, additional_info: str = "") -> Never:
|
| 66 |
+
raise argparse.ArgumentTypeError(
|
| 67 |
+
f"Expected a list or a stringified version thereof, but got: '{x}', of type {type(x).__name__}.{additional_info}"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
if isinstance(v, str):
|
| 71 |
+
items = [p.strip() for p in re.split(split_regex, v)]
|
| 72 |
+
if items and items[-1] == "":
|
| 73 |
+
items.pop(-1)
|
| 74 |
+
return items
|
| 75 |
+
elif isinstance(v, Sequence):
|
| 76 |
+
return [
|
| 77 |
+
(
|
| 78 |
+
p.strip()
|
| 79 |
+
if isinstance(p, str)
|
| 80 |
+
else complain(p, additional_info=" (As an element of the list.)")
|
| 81 |
+
)
|
| 82 |
+
for p in v
|
| 83 |
+
]
|
| 84 |
+
else:
|
| 85 |
+
complain(v)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def validate_package_allow_list(allow_list: list[str]) -> list[str]:
|
| 89 |
+
for p in allow_list:
|
| 90 |
+
msg = f"Invalid allow list entry: {p}"
|
| 91 |
+
if "*" in p:
|
| 92 |
+
raise argparse.ArgumentTypeError(
|
| 93 |
+
f"{msg} (entries are already prefixes so must not contain *)"
|
| 94 |
+
)
|
| 95 |
+
if "\\" in p or "/" in p:
|
| 96 |
+
raise argparse.ArgumentTypeError(
|
| 97 |
+
f"{msg} (entries must be packages like foo.bar not directories or files)"
|
| 98 |
+
)
|
| 99 |
+
return allow_list
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def expand_path(path: str) -> str:
|
| 103 |
+
"""Expand the user home directory and any environment variables contained within
|
| 104 |
+
the provided path.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
return os.path.expandvars(os.path.expanduser(path))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def str_or_array_as_list(v: str | Sequence[str]) -> list[str]:
|
| 111 |
+
if isinstance(v, str):
|
| 112 |
+
return [v.strip()] if v.strip() else []
|
| 113 |
+
return [p.strip() for p in v if p.strip()]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def split_and_match_files_list(paths: Sequence[str]) -> list[str]:
|
| 117 |
+
"""Take a list of files/directories (with support for globbing through the glob library).
|
| 118 |
+
|
| 119 |
+
Where a path/glob matches no file, we still include the raw path in the resulting list.
|
| 120 |
+
|
| 121 |
+
Returns a list of file paths
|
| 122 |
+
"""
|
| 123 |
+
expanded_paths = []
|
| 124 |
+
|
| 125 |
+
for path in paths:
|
| 126 |
+
path = expand_path(path.strip())
|
| 127 |
+
globbed_files = fileglob.glob(path, recursive=True)
|
| 128 |
+
if globbed_files:
|
| 129 |
+
expanded_paths.extend(globbed_files)
|
| 130 |
+
else:
|
| 131 |
+
expanded_paths.append(path)
|
| 132 |
+
|
| 133 |
+
return expanded_paths
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def split_and_match_files(paths: str) -> list[str]:
|
| 137 |
+
"""Take a string representing a list of files/directories (with support for globbing
|
| 138 |
+
through the glob library).
|
| 139 |
+
|
| 140 |
+
Where a path/glob matches no file, we still include the raw path in the resulting list.
|
| 141 |
+
|
| 142 |
+
Returns a list of file paths
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
return split_and_match_files_list(split_commas(paths))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def check_follow_imports(choice: str) -> str:
|
| 149 |
+
choices = ["normal", "silent", "skip", "error"]
|
| 150 |
+
if choice not in choices:
|
| 151 |
+
raise argparse.ArgumentTypeError(
|
| 152 |
+
"invalid choice '{}' (choose from {})".format(
|
| 153 |
+
choice, ", ".join(f"'{x}'" for x in choices)
|
| 154 |
+
)
|
| 155 |
+
)
|
| 156 |
+
return choice
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def check_junit_format(choice: str) -> str:
|
| 160 |
+
choices = ["global", "per_file"]
|
| 161 |
+
if choice not in choices:
|
| 162 |
+
raise argparse.ArgumentTypeError(
|
| 163 |
+
"invalid choice '{}' (choose from {})".format(
|
| 164 |
+
choice, ", ".join(f"'{x}'" for x in choices)
|
| 165 |
+
)
|
| 166 |
+
)
|
| 167 |
+
return choice
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def split_commas(value: str) -> list[str]:
|
| 171 |
+
# Uses a bit smarter technique to allow last trailing comma
|
| 172 |
+
# and to remove last `""` item from the split.
|
| 173 |
+
items = value.split(",")
|
| 174 |
+
if items and items[-1] == "":
|
| 175 |
+
items.pop(-1)
|
| 176 |
+
return items
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# For most options, the type of the default value set in options.py is
|
| 180 |
+
# sufficient, and we don't have to do anything here. This table
|
| 181 |
+
# exists to specify types for values initialized to None or container
|
| 182 |
+
# types.
|
| 183 |
+
ini_config_types: Final[dict[str, _INI_PARSER_CALLABLE]] = {
|
| 184 |
+
"python_version": parse_version,
|
| 185 |
+
"custom_typing_module": str,
|
| 186 |
+
"custom_typeshed_dir": expand_path,
|
| 187 |
+
"mypy_path": lambda s: [expand_path(p.strip()) for p in re.split("[,:]", s)],
|
| 188 |
+
"files": split_and_match_files,
|
| 189 |
+
"quickstart_file": expand_path,
|
| 190 |
+
"junit_xml": expand_path,
|
| 191 |
+
"junit_format": check_junit_format,
|
| 192 |
+
"follow_imports": check_follow_imports,
|
| 193 |
+
"no_site_packages": bool,
|
| 194 |
+
"plugins": lambda s: [p.strip() for p in split_commas(s)],
|
| 195 |
+
"always_true": lambda s: [p.strip() for p in split_commas(s)],
|
| 196 |
+
"always_false": lambda s: [p.strip() for p in split_commas(s)],
|
| 197 |
+
"untyped_calls_exclude": lambda s: validate_package_allow_list(
|
| 198 |
+
[p.strip() for p in split_commas(s)]
|
| 199 |
+
),
|
| 200 |
+
"enable_incomplete_feature": lambda s: [p.strip() for p in split_commas(s)],
|
| 201 |
+
"disable_error_code": lambda s: [p.strip() for p in split_commas(s)],
|
| 202 |
+
"enable_error_code": lambda s: [p.strip() for p in split_commas(s)],
|
| 203 |
+
"package_root": lambda s: [p.strip() for p in split_commas(s)],
|
| 204 |
+
"cache_dir": expand_path,
|
| 205 |
+
"python_executable": expand_path,
|
| 206 |
+
"strict": bool,
|
| 207 |
+
"exclude": lambda s: [s.strip()],
|
| 208 |
+
"packages": try_split,
|
| 209 |
+
"modules": try_split,
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
# Reuse the ini_config_types and overwrite the diff
|
| 213 |
+
toml_config_types: Final[dict[str, _INI_PARSER_CALLABLE]] = ini_config_types.copy()
|
| 214 |
+
toml_config_types.update(
|
| 215 |
+
{
|
| 216 |
+
"python_version": parse_version,
|
| 217 |
+
"mypy_path": lambda s: [expand_path(p) for p in try_split(s, "[,:]")],
|
| 218 |
+
"files": lambda s: split_and_match_files_list(try_split(s)),
|
| 219 |
+
"junit_format": lambda s: check_junit_format(str(s)),
|
| 220 |
+
"follow_imports": lambda s: check_follow_imports(str(s)),
|
| 221 |
+
"plugins": try_split,
|
| 222 |
+
"always_true": try_split,
|
| 223 |
+
"always_false": try_split,
|
| 224 |
+
"untyped_calls_exclude": lambda s: validate_package_allow_list(try_split(s)),
|
| 225 |
+
"enable_incomplete_feature": try_split,
|
| 226 |
+
"disable_error_code": lambda s: try_split(s),
|
| 227 |
+
"enable_error_code": lambda s: try_split(s),
|
| 228 |
+
"package_root": try_split,
|
| 229 |
+
"exclude": str_or_array_as_list,
|
| 230 |
+
"packages": try_split,
|
| 231 |
+
"modules": try_split,
|
| 232 |
+
}
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _parse_individual_file(
|
| 237 |
+
config_file: str, stderr: TextIO | None = None
|
| 238 |
+
) -> tuple[MutableMapping[str, Any], dict[str, _INI_PARSER_CALLABLE], str] | None:
|
| 239 |
+
|
| 240 |
+
if not os.path.exists(config_file):
|
| 241 |
+
return None
|
| 242 |
+
|
| 243 |
+
parser: MutableMapping[str, Any]
|
| 244 |
+
try:
|
| 245 |
+
if is_toml(config_file):
|
| 246 |
+
with open(config_file, "rb") as f:
|
| 247 |
+
toml_data = tomllib.load(f)
|
| 248 |
+
# Filter down to just mypy relevant toml keys
|
| 249 |
+
toml_data = toml_data.get("tool", {})
|
| 250 |
+
if "mypy" not in toml_data:
|
| 251 |
+
return None
|
| 252 |
+
toml_data = {"mypy": toml_data["mypy"]}
|
| 253 |
+
parser = destructure_overrides(toml_data)
|
| 254 |
+
config_types = toml_config_types
|
| 255 |
+
else:
|
| 256 |
+
parser = configparser.RawConfigParser()
|
| 257 |
+
parser.read(config_file)
|
| 258 |
+
config_types = ini_config_types
|
| 259 |
+
|
| 260 |
+
except (tomllib.TOMLDecodeError, configparser.Error, ConfigTOMLValueError) as err:
|
| 261 |
+
print(f"{config_file}: {err}", file=stderr)
|
| 262 |
+
return None
|
| 263 |
+
|
| 264 |
+
if os.path.basename(config_file) in defaults.SHARED_CONFIG_NAMES and "mypy" not in parser:
|
| 265 |
+
return None
|
| 266 |
+
|
| 267 |
+
return parser, config_types, config_file
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _find_config_file(
|
| 271 |
+
stderr: TextIO | None = None,
|
| 272 |
+
) -> tuple[MutableMapping[str, Any], dict[str, _INI_PARSER_CALLABLE], str] | None:
|
| 273 |
+
|
| 274 |
+
current_dir = os.path.abspath(os.getcwd())
|
| 275 |
+
|
| 276 |
+
while True:
|
| 277 |
+
for name in defaults.CONFIG_NAMES + defaults.SHARED_CONFIG_NAMES:
|
| 278 |
+
config_file = os.path.relpath(os.path.join(current_dir, name))
|
| 279 |
+
ret = _parse_individual_file(config_file, stderr)
|
| 280 |
+
if ret is None:
|
| 281 |
+
continue
|
| 282 |
+
return ret
|
| 283 |
+
|
| 284 |
+
if any(
|
| 285 |
+
os.path.exists(os.path.join(current_dir, cvs_root)) for cvs_root in (".git", ".hg")
|
| 286 |
+
):
|
| 287 |
+
break
|
| 288 |
+
parent_dir = os.path.dirname(current_dir)
|
| 289 |
+
if parent_dir == current_dir:
|
| 290 |
+
break
|
| 291 |
+
current_dir = parent_dir
|
| 292 |
+
|
| 293 |
+
for config_file in defaults.USER_CONFIG_FILES:
|
| 294 |
+
ret = _parse_individual_file(config_file, stderr)
|
| 295 |
+
if ret is None:
|
| 296 |
+
continue
|
| 297 |
+
return ret
|
| 298 |
+
|
| 299 |
+
return None
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def parse_config_file(
|
| 303 |
+
options: Options,
|
| 304 |
+
set_strict_flags: Callable[[], None],
|
| 305 |
+
filename: str | None,
|
| 306 |
+
stdout: TextIO | None = None,
|
| 307 |
+
stderr: TextIO | None = None,
|
| 308 |
+
) -> None:
|
| 309 |
+
"""Parse a config file into an Options object.
|
| 310 |
+
|
| 311 |
+
Errors are written to stderr but are not fatal.
|
| 312 |
+
|
| 313 |
+
If filename is None, fall back to default config files.
|
| 314 |
+
"""
|
| 315 |
+
stdout = stdout or sys.stdout
|
| 316 |
+
stderr = stderr or sys.stderr
|
| 317 |
+
|
| 318 |
+
ret = (
|
| 319 |
+
_parse_individual_file(filename, stderr)
|
| 320 |
+
if filename is not None
|
| 321 |
+
else _find_config_file(stderr)
|
| 322 |
+
)
|
| 323 |
+
if ret is None:
|
| 324 |
+
return
|
| 325 |
+
parser, config_types, file_read = ret
|
| 326 |
+
|
| 327 |
+
options.config_file = file_read
|
| 328 |
+
os.environ["MYPY_CONFIG_FILE_DIR"] = os.path.dirname(os.path.abspath(file_read))
|
| 329 |
+
|
| 330 |
+
if "mypy" not in parser:
|
| 331 |
+
if filename or os.path.basename(file_read) not in defaults.SHARED_CONFIG_NAMES:
|
| 332 |
+
print(f"{file_read}: No [mypy] section in config file", file=stderr)
|
| 333 |
+
else:
|
| 334 |
+
section = parser["mypy"]
|
| 335 |
+
prefix = f"{file_read}: [mypy]: "
|
| 336 |
+
updates, report_dirs = parse_section(
|
| 337 |
+
prefix, options, set_strict_flags, section, config_types, stderr
|
| 338 |
+
)
|
| 339 |
+
for k, v in updates.items():
|
| 340 |
+
setattr(options, k, v)
|
| 341 |
+
options.report_dirs.update(report_dirs)
|
| 342 |
+
|
| 343 |
+
for name, section in parser.items():
|
| 344 |
+
if name.startswith("mypy-"):
|
| 345 |
+
prefix = get_prefix(file_read, name)
|
| 346 |
+
updates, report_dirs = parse_section(
|
| 347 |
+
prefix, options, set_strict_flags, section, config_types, stderr
|
| 348 |
+
)
|
| 349 |
+
if report_dirs:
|
| 350 |
+
print(
|
| 351 |
+
prefix,
|
| 352 |
+
"Per-module sections should not specify reports ({})".format(
|
| 353 |
+
", ".join(s + "_report" for s in sorted(report_dirs))
|
| 354 |
+
),
|
| 355 |
+
file=stderr,
|
| 356 |
+
)
|
| 357 |
+
if set(updates) - PER_MODULE_OPTIONS:
|
| 358 |
+
print(
|
| 359 |
+
prefix,
|
| 360 |
+
"Per-module sections should only specify per-module flags ({})".format(
|
| 361 |
+
", ".join(sorted(set(updates) - PER_MODULE_OPTIONS))
|
| 362 |
+
),
|
| 363 |
+
file=stderr,
|
| 364 |
+
)
|
| 365 |
+
updates = {k: v for k, v in updates.items() if k in PER_MODULE_OPTIONS}
|
| 366 |
+
|
| 367 |
+
globs = name[5:]
|
| 368 |
+
for glob in globs.split(","):
|
| 369 |
+
# For backwards compatibility, replace (back)slashes with dots.
|
| 370 |
+
glob = glob.replace(os.sep, ".")
|
| 371 |
+
if os.altsep:
|
| 372 |
+
glob = glob.replace(os.altsep, ".")
|
| 373 |
+
|
| 374 |
+
if any(c in glob for c in "?[]!") or any(
|
| 375 |
+
"*" in x and x != "*" for x in glob.split(".")
|
| 376 |
+
):
|
| 377 |
+
print(
|
| 378 |
+
prefix,
|
| 379 |
+
"Patterns must be fully-qualified module names, optionally "
|
| 380 |
+
"with '*' in some components (e.g spam.*.eggs.*)",
|
| 381 |
+
file=stderr,
|
| 382 |
+
)
|
| 383 |
+
else:
|
| 384 |
+
options.per_module_options[glob] = updates
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def get_prefix(file_read: str, name: str) -> str:
|
| 388 |
+
if is_toml(file_read):
|
| 389 |
+
module_name_str = 'module = "%s"' % "-".join(name.split("-")[1:])
|
| 390 |
+
else:
|
| 391 |
+
module_name_str = name
|
| 392 |
+
|
| 393 |
+
return f"{file_read}: [{module_name_str}]:"
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def is_toml(filename: str) -> bool:
|
| 397 |
+
return filename.lower().endswith(".toml")
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def destructure_overrides(toml_data: dict[str, Any]) -> dict[str, Any]:
|
| 401 |
+
"""Take the new [[tool.mypy.overrides]] section array in the pyproject.toml file,
|
| 402 |
+
and convert it back to a flatter structure that the existing config_parser can handle.
|
| 403 |
+
|
| 404 |
+
E.g. the following pyproject.toml file:
|
| 405 |
+
|
| 406 |
+
[[tool.mypy.overrides]]
|
| 407 |
+
module = [
|
| 408 |
+
"a.b",
|
| 409 |
+
"b.*"
|
| 410 |
+
]
|
| 411 |
+
disallow_untyped_defs = true
|
| 412 |
+
|
| 413 |
+
[[tool.mypy.overrides]]
|
| 414 |
+
module = 'c'
|
| 415 |
+
disallow_untyped_defs = false
|
| 416 |
+
|
| 417 |
+
Would map to the following config dict that it would have gotten from parsing an equivalent
|
| 418 |
+
ini file:
|
| 419 |
+
|
| 420 |
+
{
|
| 421 |
+
"mypy-a.b": {
|
| 422 |
+
disallow_untyped_defs = true,
|
| 423 |
+
},
|
| 424 |
+
"mypy-b.*": {
|
| 425 |
+
disallow_untyped_defs = true,
|
| 426 |
+
},
|
| 427 |
+
"mypy-c": {
|
| 428 |
+
disallow_untyped_defs: false,
|
| 429 |
+
},
|
| 430 |
+
}
|
| 431 |
+
"""
|
| 432 |
+
if "overrides" not in toml_data["mypy"]:
|
| 433 |
+
return toml_data
|
| 434 |
+
|
| 435 |
+
if not isinstance(toml_data["mypy"]["overrides"], list):
|
| 436 |
+
raise ConfigTOMLValueError(
|
| 437 |
+
"tool.mypy.overrides sections must be an array. Please make "
|
| 438 |
+
"sure you are using double brackets like so: [[tool.mypy.overrides]]"
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
result = toml_data.copy()
|
| 442 |
+
for override in result["mypy"]["overrides"]:
|
| 443 |
+
if "module" not in override:
|
| 444 |
+
raise ConfigTOMLValueError(
|
| 445 |
+
"toml config file contains a [[tool.mypy.overrides]] "
|
| 446 |
+
"section, but no module to override was specified."
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
if isinstance(override["module"], str):
|
| 450 |
+
modules = [override["module"]]
|
| 451 |
+
elif isinstance(override["module"], list):
|
| 452 |
+
modules = override["module"]
|
| 453 |
+
else:
|
| 454 |
+
raise ConfigTOMLValueError(
|
| 455 |
+
"toml config file contains a [[tool.mypy.overrides]] "
|
| 456 |
+
"section with a module value that is not a string or a list of "
|
| 457 |
+
"strings"
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
for module in modules:
|
| 461 |
+
module_overrides = override.copy()
|
| 462 |
+
del module_overrides["module"]
|
| 463 |
+
old_config_name = f"mypy-{module}"
|
| 464 |
+
if old_config_name not in result:
|
| 465 |
+
result[old_config_name] = module_overrides
|
| 466 |
+
else:
|
| 467 |
+
for new_key, new_value in module_overrides.items():
|
| 468 |
+
if (
|
| 469 |
+
new_key in result[old_config_name]
|
| 470 |
+
and result[old_config_name][new_key] != new_value
|
| 471 |
+
):
|
| 472 |
+
raise ConfigTOMLValueError(
|
| 473 |
+
"toml config file contains "
|
| 474 |
+
"[[tool.mypy.overrides]] sections with conflicting "
|
| 475 |
+
f"values. Module '{module}' has two different values for '{new_key}'"
|
| 476 |
+
)
|
| 477 |
+
result[old_config_name][new_key] = new_value
|
| 478 |
+
|
| 479 |
+
del result["mypy"]["overrides"]
|
| 480 |
+
return result
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def parse_section(
|
| 484 |
+
prefix: str,
|
| 485 |
+
template: Options,
|
| 486 |
+
set_strict_flags: Callable[[], None],
|
| 487 |
+
section: Mapping[str, Any],
|
| 488 |
+
config_types: dict[str, Any],
|
| 489 |
+
stderr: TextIO = sys.stderr,
|
| 490 |
+
) -> tuple[dict[str, object], dict[str, str]]:
|
| 491 |
+
"""Parse one section of a config file.
|
| 492 |
+
|
| 493 |
+
Returns a dict of option values encountered, and a dict of report directories.
|
| 494 |
+
"""
|
| 495 |
+
results: dict[str, object] = {}
|
| 496 |
+
report_dirs: dict[str, str] = {}
|
| 497 |
+
|
| 498 |
+
# Because these fields exist on Options, without proactive checking, we would accept them
|
| 499 |
+
# and crash later
|
| 500 |
+
invalid_options = {
|
| 501 |
+
"enabled_error_codes": "enable_error_code",
|
| 502 |
+
"disabled_error_codes": "disable_error_code",
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
for key in section:
|
| 506 |
+
invert = False
|
| 507 |
+
# Here we use `key` for original config section key, and `options_key` for
|
| 508 |
+
# the corresponding Options attribute.
|
| 509 |
+
options_key = key
|
| 510 |
+
# Match aliasing for command line flag.
|
| 511 |
+
if key.endswith("allow_redefinition"):
|
| 512 |
+
options_key += "_old"
|
| 513 |
+
if key in config_types:
|
| 514 |
+
ct = config_types[key]
|
| 515 |
+
elif key in invalid_options:
|
| 516 |
+
print(
|
| 517 |
+
f"{prefix}Unrecognized option: {key} = {section[key]}"
|
| 518 |
+
f" (did you mean {invalid_options[key]}?)",
|
| 519 |
+
file=stderr,
|
| 520 |
+
)
|
| 521 |
+
continue
|
| 522 |
+
else:
|
| 523 |
+
dv = getattr(template, options_key, None)
|
| 524 |
+
if dv is None:
|
| 525 |
+
if key.endswith("_report"):
|
| 526 |
+
report_type = key[:-7].replace("_", "-")
|
| 527 |
+
if report_type in defaults.REPORTER_NAMES:
|
| 528 |
+
report_dirs[report_type] = str(section[key])
|
| 529 |
+
else:
|
| 530 |
+
print(f"{prefix}Unrecognized report type: {key}", file=stderr)
|
| 531 |
+
continue
|
| 532 |
+
if key.startswith("x_"):
|
| 533 |
+
pass # Don't complain about `x_blah` flags
|
| 534 |
+
elif key.startswith("no_") and hasattr(template, options_key[3:]):
|
| 535 |
+
options_key = options_key[3:]
|
| 536 |
+
invert = True
|
| 537 |
+
elif key.startswith("allow") and hasattr(template, "dis" + options_key):
|
| 538 |
+
options_key = "dis" + options_key
|
| 539 |
+
invert = True
|
| 540 |
+
elif key.startswith("disallow") and hasattr(template, options_key[3:]):
|
| 541 |
+
options_key = options_key[3:]
|
| 542 |
+
invert = True
|
| 543 |
+
elif key.startswith("show_") and hasattr(template, "hide_" + options_key[5:]):
|
| 544 |
+
options_key = "hide_" + options_key[5:]
|
| 545 |
+
invert = True
|
| 546 |
+
elif key == "strict":
|
| 547 |
+
pass # Special handling below
|
| 548 |
+
else:
|
| 549 |
+
print(f"{prefix}Unrecognized option: {key} = {section[key]}", file=stderr)
|
| 550 |
+
if invert:
|
| 551 |
+
dv = getattr(template, options_key, None)
|
| 552 |
+
else:
|
| 553 |
+
continue
|
| 554 |
+
ct = type(dv) if dv is not None else None
|
| 555 |
+
v: Any = None
|
| 556 |
+
try:
|
| 557 |
+
if ct is bool:
|
| 558 |
+
if isinstance(section, dict):
|
| 559 |
+
v = convert_to_boolean(section.get(key))
|
| 560 |
+
else:
|
| 561 |
+
v = section.getboolean(key) # type: ignore[attr-defined] # Until better stub
|
| 562 |
+
if invert:
|
| 563 |
+
v = not v
|
| 564 |
+
elif callable(ct):
|
| 565 |
+
if invert:
|
| 566 |
+
print(f"{prefix}Can not invert non-boolean key {options_key}", file=stderr)
|
| 567 |
+
continue
|
| 568 |
+
try:
|
| 569 |
+
v = ct(section.get(key))
|
| 570 |
+
except VersionTypeError as err_version:
|
| 571 |
+
print(f"{prefix}{key}: {err_version}", file=stderr)
|
| 572 |
+
v = err_version.fallback
|
| 573 |
+
except argparse.ArgumentTypeError as err:
|
| 574 |
+
print(f"{prefix}{key}: {err}", file=stderr)
|
| 575 |
+
continue
|
| 576 |
+
else:
|
| 577 |
+
print(f"{prefix}Don't know what type {key} should have", file=stderr)
|
| 578 |
+
continue
|
| 579 |
+
except ValueError as err:
|
| 580 |
+
print(f"{prefix}{key}: {err}", file=stderr)
|
| 581 |
+
continue
|
| 582 |
+
if key == "strict":
|
| 583 |
+
if v:
|
| 584 |
+
set_strict_flags()
|
| 585 |
+
continue
|
| 586 |
+
results[options_key] = v
|
| 587 |
+
|
| 588 |
+
# These two flags act as per-module overrides, so store the empty defaults.
|
| 589 |
+
if "disable_error_code" not in results:
|
| 590 |
+
results["disable_error_code"] = []
|
| 591 |
+
if "enable_error_code" not in results:
|
| 592 |
+
results["enable_error_code"] = []
|
| 593 |
+
|
| 594 |
+
return results, report_dirs
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def convert_to_boolean(value: Any | None) -> bool:
|
| 598 |
+
"""Return a boolean value translating from other types if necessary."""
|
| 599 |
+
if isinstance(value, bool):
|
| 600 |
+
return value
|
| 601 |
+
if not isinstance(value, str):
|
| 602 |
+
value = str(value)
|
| 603 |
+
if value.lower() not in configparser.RawConfigParser.BOOLEAN_STATES:
|
| 604 |
+
raise ValueError(f"Not a boolean: {value}")
|
| 605 |
+
return configparser.RawConfigParser.BOOLEAN_STATES[value.lower()]
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def split_directive(s: str) -> tuple[list[str], list[str]]:
|
| 609 |
+
"""Split s on commas, except during quoted sections.
|
| 610 |
+
|
| 611 |
+
Returns the parts and a list of error messages."""
|
| 612 |
+
parts = []
|
| 613 |
+
cur: list[str] = []
|
| 614 |
+
errors = []
|
| 615 |
+
i = 0
|
| 616 |
+
while i < len(s):
|
| 617 |
+
if s[i] == ",":
|
| 618 |
+
parts.append("".join(cur).strip())
|
| 619 |
+
cur = []
|
| 620 |
+
elif s[i] == '"':
|
| 621 |
+
i += 1
|
| 622 |
+
while i < len(s) and s[i] != '"':
|
| 623 |
+
cur.append(s[i])
|
| 624 |
+
i += 1
|
| 625 |
+
if i == len(s):
|
| 626 |
+
errors.append("Unterminated quote in configuration comment")
|
| 627 |
+
cur.clear()
|
| 628 |
+
else:
|
| 629 |
+
cur.append(s[i])
|
| 630 |
+
i += 1
|
| 631 |
+
if cur:
|
| 632 |
+
parts.append("".join(cur).strip())
|
| 633 |
+
|
| 634 |
+
return parts, errors
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def mypy_comments_to_config_map(line: str, template: Options) -> tuple[dict[str, str], list[str]]:
|
| 638 |
+
"""Rewrite the mypy comment syntax into ini file syntax."""
|
| 639 |
+
options = {}
|
| 640 |
+
entries, errors = split_directive(line)
|
| 641 |
+
for entry in entries:
|
| 642 |
+
if "=" not in entry:
|
| 643 |
+
name = entry
|
| 644 |
+
value = None
|
| 645 |
+
else:
|
| 646 |
+
name, value = (x.strip() for x in entry.split("=", 1))
|
| 647 |
+
|
| 648 |
+
name = name.replace("-", "_")
|
| 649 |
+
if value is None:
|
| 650 |
+
value = "True"
|
| 651 |
+
options[name] = value
|
| 652 |
+
|
| 653 |
+
return options, errors
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def parse_mypy_comments(
|
| 657 |
+
args: list[tuple[int, str]], template: Options
|
| 658 |
+
) -> tuple[dict[str, object], list[tuple[int, str]]]:
|
| 659 |
+
"""Parse a collection of inline mypy: configuration comments.
|
| 660 |
+
|
| 661 |
+
Returns a dictionary of options to be applied and a list of error messages
|
| 662 |
+
generated.
|
| 663 |
+
"""
|
| 664 |
+
errors: list[tuple[int, str]] = []
|
| 665 |
+
sections: dict[str, object] = {"enable_error_code": [], "disable_error_code": []}
|
| 666 |
+
|
| 667 |
+
for lineno, line in args:
|
| 668 |
+
# In order to easily match the behavior for bools, we abuse configparser.
|
| 669 |
+
# Oddly, the only way to get the SectionProxy object with the getboolean
|
| 670 |
+
# method is to create a config parser.
|
| 671 |
+
parser = configparser.RawConfigParser()
|
| 672 |
+
options, parse_errors = mypy_comments_to_config_map(line, template)
|
| 673 |
+
if "python_version" in options:
|
| 674 |
+
errors.append((lineno, "python_version not supported in inline configuration"))
|
| 675 |
+
del options["python_version"]
|
| 676 |
+
|
| 677 |
+
parser["dummy"] = options
|
| 678 |
+
errors.extend((lineno, x) for x in parse_errors)
|
| 679 |
+
|
| 680 |
+
stderr = StringIO()
|
| 681 |
+
strict_found = False
|
| 682 |
+
|
| 683 |
+
def set_strict_flags() -> None:
|
| 684 |
+
nonlocal strict_found
|
| 685 |
+
strict_found = True
|
| 686 |
+
|
| 687 |
+
new_sections, reports = parse_section(
|
| 688 |
+
"", template, set_strict_flags, parser["dummy"], ini_config_types, stderr=stderr
|
| 689 |
+
)
|
| 690 |
+
errors.extend((lineno, x) for x in stderr.getvalue().strip().split("\n") if x)
|
| 691 |
+
if reports:
|
| 692 |
+
errors.append((lineno, "Reports not supported in inline configuration"))
|
| 693 |
+
if strict_found:
|
| 694 |
+
errors.append(
|
| 695 |
+
(
|
| 696 |
+
lineno,
|
| 697 |
+
'Setting "strict" not supported in inline configuration: specify it in '
|
| 698 |
+
"a configuration file instead, or set individual inline flags "
|
| 699 |
+
'(see "mypy -h" for the list of flags enabled in strict mode)',
|
| 700 |
+
)
|
| 701 |
+
)
|
| 702 |
+
# Because this is currently special-cased
|
| 703 |
+
# (the new_sections for an inline config *always* includes 'disable_error_code' and
|
| 704 |
+
# 'enable_error_code' fields, usually empty, which overwrite the old ones),
|
| 705 |
+
# we have to manipulate them specially.
|
| 706 |
+
# This could use a refactor, but so could the whole subsystem.
|
| 707 |
+
if (
|
| 708 |
+
"enable_error_code" in new_sections
|
| 709 |
+
and isinstance(neec := new_sections["enable_error_code"], list)
|
| 710 |
+
and isinstance(eec := sections.get("enable_error_code", []), list)
|
| 711 |
+
):
|
| 712 |
+
new_sections["enable_error_code"] = sorted(set(neec + eec))
|
| 713 |
+
if (
|
| 714 |
+
"disable_error_code" in new_sections
|
| 715 |
+
and isinstance(ndec := new_sections["disable_error_code"], list)
|
| 716 |
+
and isinstance(dec := sections.get("disable_error_code", []), list)
|
| 717 |
+
):
|
| 718 |
+
new_sections["disable_error_code"] = sorted(set(ndec + dec))
|
| 719 |
+
sections.update(new_sections)
|
| 720 |
+
return sections, errors
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def get_config_module_names(filename: str | None, modules: list[str]) -> str:
|
| 724 |
+
if not filename or not modules:
|
| 725 |
+
return ""
|
| 726 |
+
|
| 727 |
+
if not is_toml(filename):
|
| 728 |
+
return ", ".join(f"[mypy-{module}]" for module in modules)
|
| 729 |
+
|
| 730 |
+
return "module = ['%s']" % ("', '".join(sorted(modules)))
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
class ConfigTOMLValueError(ValueError):
|
| 734 |
+
pass
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constant_fold.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Constant folding of expressions.
|
| 2 |
+
|
| 3 |
+
For example, 3 + 5 can be constant folded into 8.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import Final
|
| 9 |
+
|
| 10 |
+
from mypy.nodes import (
|
| 11 |
+
ComplexExpr,
|
| 12 |
+
Expression,
|
| 13 |
+
FloatExpr,
|
| 14 |
+
IntExpr,
|
| 15 |
+
NameExpr,
|
| 16 |
+
OpExpr,
|
| 17 |
+
StrExpr,
|
| 18 |
+
UnaryExpr,
|
| 19 |
+
Var,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# All possible result types of constant folding
|
| 23 |
+
ConstantValue = int | bool | float | complex | str
|
| 24 |
+
CONST_TYPES: Final = (int, bool, float, complex, str)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def constant_fold_expr(expr: Expression, cur_mod_id: str) -> ConstantValue | None:
|
| 28 |
+
"""Return the constant value of an expression for supported operations.
|
| 29 |
+
|
| 30 |
+
Among other things, support int arithmetic and string
|
| 31 |
+
concatenation. For example, the expression 3 + 5 has the constant
|
| 32 |
+
value 8.
|
| 33 |
+
|
| 34 |
+
Also bind simple references to final constants defined in the
|
| 35 |
+
current module (cur_mod_id). Binding to references is best effort
|
| 36 |
+
-- we don't bind references to other modules. Mypyc trusts these
|
| 37 |
+
to be correct in compiled modules, so that it can replace a
|
| 38 |
+
constant expression (or a reference to one) with the statically
|
| 39 |
+
computed value. We don't want to infer constant values based on
|
| 40 |
+
stubs, in particular, as these might not match the implementation
|
| 41 |
+
(due to version skew, for example).
|
| 42 |
+
|
| 43 |
+
Return None if unsuccessful.
|
| 44 |
+
"""
|
| 45 |
+
if isinstance(expr, IntExpr):
|
| 46 |
+
return expr.value
|
| 47 |
+
if isinstance(expr, StrExpr):
|
| 48 |
+
return expr.value
|
| 49 |
+
if isinstance(expr, FloatExpr):
|
| 50 |
+
return expr.value
|
| 51 |
+
if isinstance(expr, ComplexExpr):
|
| 52 |
+
return expr.value
|
| 53 |
+
elif isinstance(expr, NameExpr):
|
| 54 |
+
if expr.name == "True":
|
| 55 |
+
return True
|
| 56 |
+
elif expr.name == "False":
|
| 57 |
+
return False
|
| 58 |
+
node = expr.node
|
| 59 |
+
if (
|
| 60 |
+
isinstance(node, Var)
|
| 61 |
+
and node.is_final
|
| 62 |
+
and node.fullname.rsplit(".", 1)[0] == cur_mod_id
|
| 63 |
+
):
|
| 64 |
+
value = node.final_value
|
| 65 |
+
if isinstance(value, (CONST_TYPES)):
|
| 66 |
+
return value
|
| 67 |
+
elif isinstance(expr, OpExpr):
|
| 68 |
+
left = constant_fold_expr(expr.left, cur_mod_id)
|
| 69 |
+
right = constant_fold_expr(expr.right, cur_mod_id)
|
| 70 |
+
if left is not None and right is not None:
|
| 71 |
+
return constant_fold_binary_op(expr.op, left, right)
|
| 72 |
+
elif isinstance(expr, UnaryExpr):
|
| 73 |
+
value = constant_fold_expr(expr.expr, cur_mod_id)
|
| 74 |
+
if value is not None:
|
| 75 |
+
return constant_fold_unary_op(expr.op, value)
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def constant_fold_binary_op(
|
| 80 |
+
op: str, left: ConstantValue, right: ConstantValue
|
| 81 |
+
) -> ConstantValue | None:
|
| 82 |
+
if isinstance(left, int) and isinstance(right, int):
|
| 83 |
+
return constant_fold_binary_int_op(op, left, right)
|
| 84 |
+
|
| 85 |
+
# Float and mixed int/float arithmetic.
|
| 86 |
+
if isinstance(left, float) and isinstance(right, float):
|
| 87 |
+
return constant_fold_binary_float_op(op, left, right)
|
| 88 |
+
elif isinstance(left, float) and isinstance(right, int):
|
| 89 |
+
return constant_fold_binary_float_op(op, left, right)
|
| 90 |
+
elif isinstance(left, int) and isinstance(right, float):
|
| 91 |
+
return constant_fold_binary_float_op(op, left, right)
|
| 92 |
+
|
| 93 |
+
# String concatenation and multiplication.
|
| 94 |
+
if op == "+" and isinstance(left, str) and isinstance(right, str):
|
| 95 |
+
return left + right
|
| 96 |
+
elif op == "*" and isinstance(left, str) and isinstance(right, int):
|
| 97 |
+
return left * right
|
| 98 |
+
elif op == "*" and isinstance(left, int) and isinstance(right, str):
|
| 99 |
+
return left * right
|
| 100 |
+
|
| 101 |
+
# Complex construction.
|
| 102 |
+
if op == "+" and isinstance(left, (int, float)) and isinstance(right, complex):
|
| 103 |
+
return left + right
|
| 104 |
+
elif op == "+" and isinstance(left, complex) and isinstance(right, (int, float)):
|
| 105 |
+
return left + right
|
| 106 |
+
elif op == "-" and isinstance(left, (int, float)) and isinstance(right, complex):
|
| 107 |
+
return left - right
|
| 108 |
+
elif op == "-" and isinstance(left, complex) and isinstance(right, (int, float)):
|
| 109 |
+
return left - right
|
| 110 |
+
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def constant_fold_binary_int_op(op: str, left: int, right: int) -> int | float | None:
|
| 115 |
+
if op == "+":
|
| 116 |
+
return left + right
|
| 117 |
+
if op == "-":
|
| 118 |
+
return left - right
|
| 119 |
+
elif op == "*":
|
| 120 |
+
return left * right
|
| 121 |
+
elif op == "/":
|
| 122 |
+
if right != 0:
|
| 123 |
+
return left / right
|
| 124 |
+
elif op == "//":
|
| 125 |
+
if right != 0:
|
| 126 |
+
return left // right
|
| 127 |
+
elif op == "%":
|
| 128 |
+
if right != 0:
|
| 129 |
+
return left % right
|
| 130 |
+
elif op == "&":
|
| 131 |
+
return left & right
|
| 132 |
+
elif op == "|":
|
| 133 |
+
return left | right
|
| 134 |
+
elif op == "^":
|
| 135 |
+
return left ^ right
|
| 136 |
+
elif op == "<<":
|
| 137 |
+
if right >= 0:
|
| 138 |
+
return left << right
|
| 139 |
+
elif op == ">>":
|
| 140 |
+
if right >= 0:
|
| 141 |
+
return left >> right
|
| 142 |
+
elif op == "**":
|
| 143 |
+
if right >= 0:
|
| 144 |
+
ret = left**right
|
| 145 |
+
assert isinstance(ret, int)
|
| 146 |
+
return ret
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def constant_fold_binary_float_op(op: str, left: int | float, right: int | float) -> float | None:
|
| 151 |
+
assert not (isinstance(left, int) and isinstance(right, int)), (op, left, right)
|
| 152 |
+
if op == "+":
|
| 153 |
+
return left + right
|
| 154 |
+
elif op == "-":
|
| 155 |
+
return left - right
|
| 156 |
+
elif op == "*":
|
| 157 |
+
return left * right
|
| 158 |
+
elif op == "/":
|
| 159 |
+
if right != 0:
|
| 160 |
+
return left / right
|
| 161 |
+
elif op == "//":
|
| 162 |
+
if right != 0:
|
| 163 |
+
return left // right
|
| 164 |
+
elif op == "%":
|
| 165 |
+
if right != 0:
|
| 166 |
+
return left % right
|
| 167 |
+
elif op == "**":
|
| 168 |
+
if (left < 0 and isinstance(right, int)) or left > 0:
|
| 169 |
+
try:
|
| 170 |
+
ret = left**right
|
| 171 |
+
except OverflowError:
|
| 172 |
+
return None
|
| 173 |
+
else:
|
| 174 |
+
assert isinstance(ret, float), ret
|
| 175 |
+
return ret
|
| 176 |
+
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def constant_fold_unary_op(op: str, value: ConstantValue) -> int | float | None:
|
| 181 |
+
if op == "-" and isinstance(value, (int, float)):
|
| 182 |
+
return -value
|
| 183 |
+
elif op == "~" and isinstance(value, int):
|
| 184 |
+
return ~value
|
| 185 |
+
elif op == "+" and isinstance(value, (int, float)):
|
| 186 |
+
return value
|
| 187 |
+
return None
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/constraints.py
ADDED
|
@@ -0,0 +1,1687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Type inference constraints."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Iterable, Sequence
|
| 6 |
+
from typing import TYPE_CHECKING, Final, TypeGuard, cast
|
| 7 |
+
|
| 8 |
+
import mypy.subtypes
|
| 9 |
+
import mypy.typeops
|
| 10 |
+
from mypy.argmap import ArgTypeExpander
|
| 11 |
+
from mypy.erasetype import erase_typevars
|
| 12 |
+
from mypy.maptype import map_instance_to_supertype
|
| 13 |
+
from mypy.nodes import (
|
| 14 |
+
ARG_OPT,
|
| 15 |
+
ARG_POS,
|
| 16 |
+
ARG_STAR,
|
| 17 |
+
ARG_STAR2,
|
| 18 |
+
CONTRAVARIANT,
|
| 19 |
+
COVARIANT,
|
| 20 |
+
ArgKind,
|
| 21 |
+
TypeInfo,
|
| 22 |
+
)
|
| 23 |
+
from mypy.types import (
|
| 24 |
+
TUPLE_LIKE_INSTANCE_NAMES,
|
| 25 |
+
AnyType,
|
| 26 |
+
CallableType,
|
| 27 |
+
DeletedType,
|
| 28 |
+
ErasedType,
|
| 29 |
+
Instance,
|
| 30 |
+
LiteralType,
|
| 31 |
+
NoneType,
|
| 32 |
+
NormalizedCallableType,
|
| 33 |
+
Overloaded,
|
| 34 |
+
Parameters,
|
| 35 |
+
ParamSpecType,
|
| 36 |
+
PartialType,
|
| 37 |
+
ProperType,
|
| 38 |
+
TupleType,
|
| 39 |
+
Type,
|
| 40 |
+
TypeAliasType,
|
| 41 |
+
TypedDictType,
|
| 42 |
+
TypeOfAny,
|
| 43 |
+
TypeType,
|
| 44 |
+
TypeVarId,
|
| 45 |
+
TypeVarLikeType,
|
| 46 |
+
TypeVarTupleType,
|
| 47 |
+
TypeVarType,
|
| 48 |
+
TypeVisitor,
|
| 49 |
+
UnboundType,
|
| 50 |
+
UninhabitedType,
|
| 51 |
+
UnionType,
|
| 52 |
+
UnpackType,
|
| 53 |
+
find_unpack_in_list,
|
| 54 |
+
flatten_nested_tuples,
|
| 55 |
+
get_proper_type,
|
| 56 |
+
has_recursive_types,
|
| 57 |
+
has_type_vars,
|
| 58 |
+
is_named_instance,
|
| 59 |
+
split_with_prefix_and_suffix,
|
| 60 |
+
)
|
| 61 |
+
from mypy.types_utils import is_union_with_any
|
| 62 |
+
from mypy.typestate import type_state
|
| 63 |
+
|
| 64 |
+
if TYPE_CHECKING:
|
| 65 |
+
from mypy.infer import ArgumentInferContext
|
| 66 |
+
|
| 67 |
+
SUBTYPE_OF: Final = 0
|
| 68 |
+
SUPERTYPE_OF: Final = 1
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class Constraint:
|
| 72 |
+
"""A representation of a type constraint.
|
| 73 |
+
|
| 74 |
+
It can be either T <: type or T :> type (T is a type variable).
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
type_var: TypeVarId
|
| 78 |
+
op = 0 # SUBTYPE_OF or SUPERTYPE_OF
|
| 79 |
+
target: Type
|
| 80 |
+
|
| 81 |
+
def __init__(self, type_var: TypeVarLikeType, op: int, target: Type) -> None:
|
| 82 |
+
self.type_var = type_var.id
|
| 83 |
+
self.op = op
|
| 84 |
+
# TODO: should we add "assert not isinstance(target, UnpackType)"?
|
| 85 |
+
# UnpackType is a synthetic type, and is never valid as a constraint target.
|
| 86 |
+
self.target = target
|
| 87 |
+
self.origin_type_var = type_var
|
| 88 |
+
# These are additional type variables that should be solved for together with type_var.
|
| 89 |
+
# TODO: A cleaner solution may be to modify the return type of infer_constraints()
|
| 90 |
+
# to include these instead, but this is a rather big refactoring.
|
| 91 |
+
self.extra_tvars: list[TypeVarLikeType] = []
|
| 92 |
+
|
| 93 |
+
def __repr__(self) -> str:
|
| 94 |
+
op_str = "<:"
|
| 95 |
+
if self.op == SUPERTYPE_OF:
|
| 96 |
+
op_str = ":>"
|
| 97 |
+
return f"{self.type_var} {op_str} {self.target}"
|
| 98 |
+
|
| 99 |
+
def __hash__(self) -> int:
|
| 100 |
+
return hash((self.type_var, self.op, self.target))
|
| 101 |
+
|
| 102 |
+
def __eq__(self, other: object) -> bool:
|
| 103 |
+
if not isinstance(other, Constraint):
|
| 104 |
+
return False
|
| 105 |
+
return (self.type_var, self.op, self.target) == (other.type_var, other.op, other.target)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def infer_constraints_for_callable(
|
| 109 |
+
callee: CallableType,
|
| 110 |
+
arg_types: Sequence[Type | None],
|
| 111 |
+
arg_kinds: list[ArgKind],
|
| 112 |
+
arg_names: Sequence[str | None] | None,
|
| 113 |
+
formal_to_actual: list[list[int]],
|
| 114 |
+
context: ArgumentInferContext,
|
| 115 |
+
) -> list[Constraint]:
|
| 116 |
+
"""Infer type variable constraints for a callable and actual arguments.
|
| 117 |
+
|
| 118 |
+
Return a list of constraints.
|
| 119 |
+
"""
|
| 120 |
+
constraints: list[Constraint] = []
|
| 121 |
+
mapper = ArgTypeExpander(context)
|
| 122 |
+
|
| 123 |
+
param_spec = callee.param_spec()
|
| 124 |
+
param_spec_arg_types = []
|
| 125 |
+
param_spec_arg_names = []
|
| 126 |
+
param_spec_arg_kinds: list[ArgKind] = []
|
| 127 |
+
|
| 128 |
+
incomplete_star_mapping = False
|
| 129 |
+
for i, actuals in enumerate(formal_to_actual): # TODO: isn't this `enumerate(arg_types)`?
|
| 130 |
+
for actual in actuals:
|
| 131 |
+
if actual is None and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2): # type: ignore[unreachable]
|
| 132 |
+
# We can't use arguments to infer ParamSpec constraint, if only some
|
| 133 |
+
# are present in the current inference pass.
|
| 134 |
+
incomplete_star_mapping = True # type: ignore[unreachable]
|
| 135 |
+
break
|
| 136 |
+
|
| 137 |
+
for i, actuals in enumerate(formal_to_actual):
|
| 138 |
+
if isinstance(callee.arg_types[i], UnpackType):
|
| 139 |
+
unpack_type = callee.arg_types[i]
|
| 140 |
+
assert isinstance(unpack_type, UnpackType)
|
| 141 |
+
|
| 142 |
+
# In this case we are binding all the actuals to *args,
|
| 143 |
+
# and we want a constraint that the typevar tuple being unpacked
|
| 144 |
+
# is equal to a type list of all the actuals.
|
| 145 |
+
actual_types = []
|
| 146 |
+
|
| 147 |
+
unpacked_type = get_proper_type(unpack_type.type)
|
| 148 |
+
if isinstance(unpacked_type, TypeVarTupleType):
|
| 149 |
+
tuple_instance = unpacked_type.tuple_fallback
|
| 150 |
+
elif isinstance(unpacked_type, TupleType):
|
| 151 |
+
tuple_instance = unpacked_type.partial_fallback
|
| 152 |
+
else:
|
| 153 |
+
assert False, "mypy bug: unhandled constraint inference case"
|
| 154 |
+
|
| 155 |
+
for actual in actuals:
|
| 156 |
+
actual_arg_type = arg_types[actual]
|
| 157 |
+
if actual_arg_type is None:
|
| 158 |
+
continue
|
| 159 |
+
|
| 160 |
+
expanded_actual = mapper.expand_actual_type(
|
| 161 |
+
actual_arg_type,
|
| 162 |
+
arg_kinds[actual],
|
| 163 |
+
callee.arg_names[i],
|
| 164 |
+
callee.arg_kinds[i],
|
| 165 |
+
allow_unpack=True,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
if arg_kinds[actual] != ARG_STAR or isinstance(
|
| 169 |
+
get_proper_type(actual_arg_type), TupleType
|
| 170 |
+
):
|
| 171 |
+
actual_types.append(expanded_actual)
|
| 172 |
+
else:
|
| 173 |
+
# If we are expanding an iterable inside * actual, append a homogeneous item instead
|
| 174 |
+
actual_types.append(
|
| 175 |
+
UnpackType(tuple_instance.copy_modified(args=[expanded_actual]))
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
if isinstance(unpacked_type, TypeVarTupleType):
|
| 179 |
+
constraints.append(
|
| 180 |
+
Constraint(
|
| 181 |
+
unpacked_type,
|
| 182 |
+
SUPERTYPE_OF,
|
| 183 |
+
TupleType(actual_types, unpacked_type.tuple_fallback),
|
| 184 |
+
)
|
| 185 |
+
)
|
| 186 |
+
elif isinstance(unpacked_type, TupleType):
|
| 187 |
+
# Prefixes get converted to positional args, so technically the only case we
|
| 188 |
+
# should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out
|
| 189 |
+
# not to hold we can always handle the prefixes too.
|
| 190 |
+
inner_unpack = unpacked_type.items[0]
|
| 191 |
+
assert isinstance(inner_unpack, UnpackType)
|
| 192 |
+
inner_unpacked_type = get_proper_type(inner_unpack.type)
|
| 193 |
+
suffix_len = len(unpacked_type.items) - 1
|
| 194 |
+
if isinstance(inner_unpacked_type, TypeVarTupleType):
|
| 195 |
+
# Variadic item can be either *Ts...
|
| 196 |
+
constraints.append(
|
| 197 |
+
Constraint(
|
| 198 |
+
inner_unpacked_type,
|
| 199 |
+
SUPERTYPE_OF,
|
| 200 |
+
TupleType(
|
| 201 |
+
actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback
|
| 202 |
+
),
|
| 203 |
+
)
|
| 204 |
+
)
|
| 205 |
+
else:
|
| 206 |
+
# ...or it can be a homogeneous tuple.
|
| 207 |
+
assert (
|
| 208 |
+
isinstance(inner_unpacked_type, Instance)
|
| 209 |
+
and inner_unpacked_type.type.fullname == "builtins.tuple"
|
| 210 |
+
)
|
| 211 |
+
for at in actual_types[:-suffix_len]:
|
| 212 |
+
constraints.extend(
|
| 213 |
+
infer_constraints(inner_unpacked_type.args[0], at, SUPERTYPE_OF)
|
| 214 |
+
)
|
| 215 |
+
# Now handle the suffix (if any).
|
| 216 |
+
if suffix_len:
|
| 217 |
+
for tt, at in zip(unpacked_type.items[1:], actual_types[-suffix_len:]):
|
| 218 |
+
constraints.extend(infer_constraints(tt, at, SUPERTYPE_OF))
|
| 219 |
+
else:
|
| 220 |
+
assert False, "mypy bug: unhandled constraint inference case"
|
| 221 |
+
else:
|
| 222 |
+
for actual in actuals:
|
| 223 |
+
actual_arg_type = arg_types[actual]
|
| 224 |
+
if actual_arg_type is None:
|
| 225 |
+
continue
|
| 226 |
+
|
| 227 |
+
if param_spec and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):
|
| 228 |
+
# If actual arguments are mapped to ParamSpec type, we can't infer individual
|
| 229 |
+
# constraints, instead store them and infer single constraint at the end.
|
| 230 |
+
# It is impossible to map actual kind to formal kind, so use some heuristic.
|
| 231 |
+
# This inference is used as a fallback, so relying on heuristic should be OK.
|
| 232 |
+
if not incomplete_star_mapping:
|
| 233 |
+
param_spec_arg_types.append(
|
| 234 |
+
mapper.expand_actual_type(
|
| 235 |
+
actual_arg_type, arg_kinds[actual], None, arg_kinds[actual]
|
| 236 |
+
)
|
| 237 |
+
)
|
| 238 |
+
actual_kind = arg_kinds[actual]
|
| 239 |
+
param_spec_arg_kinds.append(
|
| 240 |
+
ARG_POS if actual_kind not in (ARG_STAR, ARG_STAR2) else actual_kind
|
| 241 |
+
)
|
| 242 |
+
param_spec_arg_names.append(arg_names[actual] if arg_names else None)
|
| 243 |
+
else:
|
| 244 |
+
actual_type = mapper.expand_actual_type(
|
| 245 |
+
actual_arg_type,
|
| 246 |
+
arg_kinds[actual],
|
| 247 |
+
callee.arg_names[i],
|
| 248 |
+
callee.arg_kinds[i],
|
| 249 |
+
)
|
| 250 |
+
c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF)
|
| 251 |
+
constraints.extend(c)
|
| 252 |
+
if (
|
| 253 |
+
param_spec
|
| 254 |
+
and not any(c.type_var == param_spec.id for c in constraints)
|
| 255 |
+
and not incomplete_star_mapping
|
| 256 |
+
):
|
| 257 |
+
# Use ParamSpec constraint from arguments only if there are no other constraints,
|
| 258 |
+
# since as explained above it is quite ad-hoc.
|
| 259 |
+
constraints.append(
|
| 260 |
+
Constraint(
|
| 261 |
+
param_spec,
|
| 262 |
+
SUPERTYPE_OF,
|
| 263 |
+
Parameters(
|
| 264 |
+
arg_types=param_spec_arg_types,
|
| 265 |
+
arg_kinds=param_spec_arg_kinds,
|
| 266 |
+
arg_names=param_spec_arg_names,
|
| 267 |
+
imprecise_arg_kinds=True,
|
| 268 |
+
),
|
| 269 |
+
)
|
| 270 |
+
)
|
| 271 |
+
if any(isinstance(v, ParamSpecType) for v in callee.variables):
|
| 272 |
+
# As a perf optimization filter imprecise constraints only when we can have them.
|
| 273 |
+
constraints = filter_imprecise_kinds(constraints)
|
| 274 |
+
return constraints
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def infer_constraints(
|
| 278 |
+
template: Type, actual: Type, direction: int, skip_neg_op: bool = False
|
| 279 |
+
) -> list[Constraint]:
|
| 280 |
+
"""Infer type constraints.
|
| 281 |
+
|
| 282 |
+
Match a template type, which may contain type variable references,
|
| 283 |
+
recursively against a type which does not contain (the same) type
|
| 284 |
+
variable references. The result is a list of type constrains of
|
| 285 |
+
form 'T is a supertype/subtype of x', where T is a type variable
|
| 286 |
+
present in the template and x is a type without reference to type
|
| 287 |
+
variables present in the template.
|
| 288 |
+
|
| 289 |
+
Assume T and S are type variables. Now the following results can be
|
| 290 |
+
calculated (read as '(template, actual) --> result'):
|
| 291 |
+
|
| 292 |
+
(T, X) --> T :> X
|
| 293 |
+
(X[T], X[Y]) --> T <: Y and T :> Y
|
| 294 |
+
((T, T), (X, Y)) --> T :> X and T :> Y
|
| 295 |
+
((T, S), (X, Y)) --> T :> X and S :> Y
|
| 296 |
+
(X[T], Any) --> T <: Any and T :> Any
|
| 297 |
+
|
| 298 |
+
The constraints are represented as Constraint objects. If skip_neg_op == True,
|
| 299 |
+
then skip adding reverse (polymorphic) constraints (since this is already a call
|
| 300 |
+
to infer such constraints).
|
| 301 |
+
"""
|
| 302 |
+
if any(
|
| 303 |
+
get_proper_type(template) == get_proper_type(t)
|
| 304 |
+
and get_proper_type(actual) == get_proper_type(a)
|
| 305 |
+
for (t, a) in reversed(type_state.inferring)
|
| 306 |
+
):
|
| 307 |
+
return []
|
| 308 |
+
if has_recursive_types(template) or isinstance(get_proper_type(template), Instance):
|
| 309 |
+
# This case requires special care because it may cause infinite recursion.
|
| 310 |
+
# Note that we include Instances because the may be recursive as str(Sequence[str]).
|
| 311 |
+
if not has_type_vars(template):
|
| 312 |
+
# Return early on an empty branch.
|
| 313 |
+
return []
|
| 314 |
+
type_state.inferring.append((template, actual))
|
| 315 |
+
res = _infer_constraints(template, actual, direction, skip_neg_op)
|
| 316 |
+
type_state.inferring.pop()
|
| 317 |
+
return res
|
| 318 |
+
return _infer_constraints(template, actual, direction, skip_neg_op)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _infer_constraints(
|
| 322 |
+
template: Type, actual: Type, direction: int, skip_neg_op: bool
|
| 323 |
+
) -> list[Constraint]:
|
| 324 |
+
orig_template = template
|
| 325 |
+
template = get_proper_type(template)
|
| 326 |
+
actual = get_proper_type(actual)
|
| 327 |
+
|
| 328 |
+
# Type inference shouldn't be affected by whether union types have been simplified.
|
| 329 |
+
# We however keep any ErasedType items, so that the caller will see it when using
|
| 330 |
+
# checkexpr.has_erased_component().
|
| 331 |
+
if isinstance(template, UnionType):
|
| 332 |
+
template = mypy.typeops.make_simplified_union(template.items, keep_erased=True)
|
| 333 |
+
if isinstance(actual, UnionType):
|
| 334 |
+
actual = mypy.typeops.make_simplified_union(actual.items, keep_erased=True)
|
| 335 |
+
|
| 336 |
+
# Ignore Any types from the type suggestion engine to avoid them
|
| 337 |
+
# causing us to infer Any in situations where a better job could
|
| 338 |
+
# be done otherwise. (This can produce false positives but that
|
| 339 |
+
# doesn't really matter because it is all heuristic anyway.)
|
| 340 |
+
if isinstance(actual, AnyType) and actual.type_of_any == TypeOfAny.suggestion_engine:
|
| 341 |
+
return []
|
| 342 |
+
|
| 343 |
+
# type[A | B] is always represented as type[A] | type[B] internally.
|
| 344 |
+
# This makes our constraint solver choke on type[T] <: type[A] | type[B],
|
| 345 |
+
# solving T as generic meet(A, B) which is often `object`. Force unwrap such unions
|
| 346 |
+
# if both sides are type[...] or unions thereof. See `testTypeVarType` test
|
| 347 |
+
type_type_unwrapped = False
|
| 348 |
+
if _is_type_type(template) and _is_type_type(actual):
|
| 349 |
+
type_type_unwrapped = True
|
| 350 |
+
template = _unwrap_type_type(template)
|
| 351 |
+
actual = _unwrap_type_type(actual)
|
| 352 |
+
|
| 353 |
+
# If the template is simply a type variable, emit a Constraint directly.
|
| 354 |
+
# We need to handle this case before handling Unions for two reasons:
|
| 355 |
+
# 1. "T <: Union[U1, U2]" is not equivalent to "T <: U1 or T <: U2",
|
| 356 |
+
# because T can itself be a union (notably, Union[U1, U2] itself).
|
| 357 |
+
# 2. "T :> Union[U1, U2]" is logically equivalent to "T :> U1 and
|
| 358 |
+
# T :> U2", but they are not equivalent to the constraint solver,
|
| 359 |
+
# which never introduces new Union types (it uses join() instead).
|
| 360 |
+
if isinstance(template, TypeVarType):
|
| 361 |
+
return [Constraint(template, direction, actual)]
|
| 362 |
+
|
| 363 |
+
if (
|
| 364 |
+
isinstance(actual, TypeVarType)
|
| 365 |
+
and not actual.id.is_meta_var()
|
| 366 |
+
and direction == SUPERTYPE_OF
|
| 367 |
+
):
|
| 368 |
+
# Unless template is also a type variable (or a union that contains one), using the upper
|
| 369 |
+
# bound for inference will usually give better result for actual that is a type variable.
|
| 370 |
+
if not isinstance(template, UnionType) or not any(
|
| 371 |
+
isinstance(t, TypeVarType) for t in template.items
|
| 372 |
+
):
|
| 373 |
+
actual = get_proper_type(actual.upper_bound)
|
| 374 |
+
|
| 375 |
+
# Now handle the case of either template or actual being a Union.
|
| 376 |
+
# For a Union to be a subtype of another type, every item of the Union
|
| 377 |
+
# must be a subtype of that type, so concatenate the constraints.
|
| 378 |
+
if direction == SUBTYPE_OF and isinstance(template, UnionType):
|
| 379 |
+
res = []
|
| 380 |
+
for t_item in template.items:
|
| 381 |
+
res.extend(infer_constraints(t_item, actual, direction))
|
| 382 |
+
return res
|
| 383 |
+
if direction == SUPERTYPE_OF and isinstance(actual, UnionType):
|
| 384 |
+
res = []
|
| 385 |
+
for a_item in actual.items:
|
| 386 |
+
# `orig_template` has to be preserved intact in case it's recursive.
|
| 387 |
+
# If we unwrapped ``type[...]`` previously, wrap the item back again,
|
| 388 |
+
# as ``type[...]`` can't be removed from `orig_template`.
|
| 389 |
+
if type_type_unwrapped:
|
| 390 |
+
a_item = TypeType.make_normalized(a_item)
|
| 391 |
+
res.extend(infer_constraints(orig_template, a_item, direction))
|
| 392 |
+
return res
|
| 393 |
+
|
| 394 |
+
# Now the potential subtype is known not to be a Union or a type
|
| 395 |
+
# variable that we are solving for. In that case, for a Union to
|
| 396 |
+
# be a supertype of the potential subtype, some item of the Union
|
| 397 |
+
# must be a supertype of it.
|
| 398 |
+
if direction == SUBTYPE_OF and isinstance(actual, UnionType):
|
| 399 |
+
# We infer constraints eagerly -- try to find constraints for a type
|
| 400 |
+
# variable if possible. This seems to help with some real-world
|
| 401 |
+
# use cases.
|
| 402 |
+
return any_constraints(
|
| 403 |
+
[
|
| 404 |
+
infer_constraints_if_possible(template, a_item, direction)
|
| 405 |
+
for a_item in actual.items
|
| 406 |
+
],
|
| 407 |
+
eager=True,
|
| 408 |
+
)
|
| 409 |
+
if direction == SUPERTYPE_OF and isinstance(template, UnionType):
|
| 410 |
+
# When the template is a union, we are okay with leaving some
|
| 411 |
+
# type variables indeterminate. This helps with some special
|
| 412 |
+
# cases, though this isn't very principled.
|
| 413 |
+
result = any_constraints(
|
| 414 |
+
[
|
| 415 |
+
infer_constraints_if_possible(t_item, actual, direction)
|
| 416 |
+
for t_item in template.items
|
| 417 |
+
],
|
| 418 |
+
eager=isinstance(actual, AnyType),
|
| 419 |
+
)
|
| 420 |
+
if result:
|
| 421 |
+
return result
|
| 422 |
+
elif has_recursive_types(template) and not has_recursive_types(actual):
|
| 423 |
+
return handle_recursive_union(template, actual, direction)
|
| 424 |
+
return []
|
| 425 |
+
|
| 426 |
+
# Remaining cases are handled by ConstraintBuilderVisitor.
|
| 427 |
+
return template.accept(ConstraintBuilderVisitor(actual, direction, skip_neg_op))
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def _is_type_type(tp: ProperType) -> TypeGuard[TypeType | UnionType]:
|
| 431 |
+
"""Is ``tp`` a ``type[...]`` or a union thereof?
|
| 432 |
+
|
| 433 |
+
``Type[A | B]`` is internally represented as ``type[A] | type[B]``, and this
|
| 434 |
+
troubles the solver sometimes.
|
| 435 |
+
"""
|
| 436 |
+
return (
|
| 437 |
+
isinstance(tp, TypeType)
|
| 438 |
+
or isinstance(tp, UnionType)
|
| 439 |
+
and all(isinstance(get_proper_type(o), TypeType) for o in tp.items)
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def _unwrap_type_type(tp: TypeType | UnionType) -> ProperType:
|
| 444 |
+
"""Extract the inner type from ``type[...]`` expression or a union thereof."""
|
| 445 |
+
if isinstance(tp, TypeType):
|
| 446 |
+
return tp.item
|
| 447 |
+
return UnionType.make_union([cast(TypeType, get_proper_type(o)).item for o in tp.items])
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def infer_constraints_if_possible(
|
| 451 |
+
template: Type, actual: Type, direction: int
|
| 452 |
+
) -> list[Constraint] | None:
|
| 453 |
+
"""Like infer_constraints, but return None if the input relation is
|
| 454 |
+
known to be unsatisfiable, for example if template=List[T] and actual=int.
|
| 455 |
+
(In this case infer_constraints would return [], just like it would for
|
| 456 |
+
an automatically satisfied relation like template=List[T] and actual=object.)
|
| 457 |
+
"""
|
| 458 |
+
if direction == SUBTYPE_OF and not mypy.subtypes.is_subtype(erase_typevars(template), actual):
|
| 459 |
+
return None
|
| 460 |
+
if direction == SUPERTYPE_OF and not mypy.subtypes.is_subtype(
|
| 461 |
+
actual, erase_typevars(template)
|
| 462 |
+
):
|
| 463 |
+
return None
|
| 464 |
+
if (
|
| 465 |
+
direction == SUPERTYPE_OF
|
| 466 |
+
and isinstance(template, TypeVarType)
|
| 467 |
+
and not mypy.subtypes.is_subtype(actual, erase_typevars(template.upper_bound))
|
| 468 |
+
):
|
| 469 |
+
# This is not caught by the above branch because of the erase_typevars() call,
|
| 470 |
+
# that would return 'Any' for a type variable.
|
| 471 |
+
return None
|
| 472 |
+
return infer_constraints(template, actual, direction)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def select_trivial(options: Sequence[list[Constraint] | None]) -> list[list[Constraint]]:
|
| 476 |
+
"""Select only those lists where each item is a constraint against Any."""
|
| 477 |
+
res = []
|
| 478 |
+
for option in options:
|
| 479 |
+
if option is None:
|
| 480 |
+
continue
|
| 481 |
+
if all(isinstance(get_proper_type(c.target), AnyType) for c in option):
|
| 482 |
+
res.append(option)
|
| 483 |
+
return res
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def merge_with_any(constraint: Constraint) -> Constraint:
|
| 487 |
+
"""Transform a constraint target into a union with given Any type."""
|
| 488 |
+
target = constraint.target
|
| 489 |
+
if is_union_with_any(target):
|
| 490 |
+
# Do not produce redundant unions.
|
| 491 |
+
return constraint
|
| 492 |
+
# TODO: if we will support multiple sources Any, use this here instead.
|
| 493 |
+
any_type = AnyType(TypeOfAny.implementation_artifact)
|
| 494 |
+
return Constraint(
|
| 495 |
+
constraint.origin_type_var,
|
| 496 |
+
constraint.op,
|
| 497 |
+
UnionType.make_union([target, any_type], target.line, target.column),
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def handle_recursive_union(template: UnionType, actual: Type, direction: int) -> list[Constraint]:
|
| 502 |
+
# This is a hack to special-case things like Union[T, Inst[T]] in recursive types. Although
|
| 503 |
+
# it is quite arbitrary, it is a relatively common pattern, so we should handle it well.
|
| 504 |
+
# This function may be called when inferring against such union resulted in different
|
| 505 |
+
# constraints for each item. Normally we give up in such case, but here we instead split
|
| 506 |
+
# the union in two parts, and try inferring sequentially.
|
| 507 |
+
non_type_var_items = [t for t in template.items if not isinstance(t, TypeVarType)]
|
| 508 |
+
type_var_items = [t for t in template.items if isinstance(t, TypeVarType)]
|
| 509 |
+
return infer_constraints(
|
| 510 |
+
UnionType.make_union(non_type_var_items), actual, direction
|
| 511 |
+
) or infer_constraints(UnionType.make_union(type_var_items), actual, direction)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def any_constraints(options: list[list[Constraint] | None], *, eager: bool) -> list[Constraint]:
|
| 515 |
+
"""Deduce what we can from a collection of constraint lists.
|
| 516 |
+
|
| 517 |
+
It's a given that at least one of the lists must be satisfied. A
|
| 518 |
+
None element in the list of options represents an unsatisfiable
|
| 519 |
+
constraint and is ignored. Ignore empty constraint lists if eager
|
| 520 |
+
is true -- they are always trivially satisfiable.
|
| 521 |
+
"""
|
| 522 |
+
if eager:
|
| 523 |
+
valid_options = [option for option in options if option]
|
| 524 |
+
else:
|
| 525 |
+
valid_options = [option for option in options if option is not None]
|
| 526 |
+
|
| 527 |
+
if not valid_options:
|
| 528 |
+
return []
|
| 529 |
+
|
| 530 |
+
if len(valid_options) == 1:
|
| 531 |
+
return valid_options[0]
|
| 532 |
+
|
| 533 |
+
if all(is_same_constraints(valid_options[0], c) for c in valid_options[1:]):
|
| 534 |
+
# Multiple sets of constraints that are all the same. Just pick any one of them.
|
| 535 |
+
return valid_options[0]
|
| 536 |
+
|
| 537 |
+
if all(is_similar_constraints(valid_options[0], c) for c in valid_options[1:]):
|
| 538 |
+
# All options have same structure. In this case we can merge-in trivial
|
| 539 |
+
# options (i.e. those that only have Any) and try again.
|
| 540 |
+
# TODO: More generally, if a given (variable, direction) pair appears in
|
| 541 |
+
# every option, combine the bounds with meet/join always, not just for Any.
|
| 542 |
+
trivial_options = select_trivial(valid_options)
|
| 543 |
+
if trivial_options and len(trivial_options) < len(valid_options):
|
| 544 |
+
merged_options = []
|
| 545 |
+
for option in valid_options:
|
| 546 |
+
if option in trivial_options:
|
| 547 |
+
continue
|
| 548 |
+
merged_options.append([merge_with_any(c) for c in option])
|
| 549 |
+
return any_constraints(list(merged_options), eager=eager)
|
| 550 |
+
|
| 551 |
+
# If normal logic didn't work, try excluding trivially unsatisfiable constraint (due to
|
| 552 |
+
# upper bounds) from each option, and comparing them again.
|
| 553 |
+
filtered_options = [filter_satisfiable(o) for o in options]
|
| 554 |
+
if filtered_options != options:
|
| 555 |
+
return any_constraints(filtered_options, eager=eager)
|
| 556 |
+
|
| 557 |
+
# Try harder: if that didn't work, try to strip typevars that aren't meta vars.
|
| 558 |
+
# Note this is what we would always do, but unfortunately some callers may not
|
| 559 |
+
# set the meta var status correctly (for historical reasons), so we use this as
|
| 560 |
+
# a fallback only.
|
| 561 |
+
filtered_options = [exclude_non_meta_vars(o) for o in options]
|
| 562 |
+
if filtered_options != options:
|
| 563 |
+
return any_constraints(filtered_options, eager=eager)
|
| 564 |
+
|
| 565 |
+
# Otherwise, there are either no valid options or multiple, inconsistent valid
|
| 566 |
+
# options. Give up and deduce nothing.
|
| 567 |
+
return []
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def filter_satisfiable(option: list[Constraint] | None) -> list[Constraint] | None:
|
| 571 |
+
"""Keep only constraints that can possibly be satisfied.
|
| 572 |
+
|
| 573 |
+
Currently, we filter out constraints where target is not a subtype of the upper bound.
|
| 574 |
+
Since those can be never satisfied. We may add more cases in future if it improves type
|
| 575 |
+
inference.
|
| 576 |
+
"""
|
| 577 |
+
if not option:
|
| 578 |
+
return option
|
| 579 |
+
|
| 580 |
+
satisfiable = []
|
| 581 |
+
for c in option:
|
| 582 |
+
if isinstance(c.origin_type_var, TypeVarType) and c.origin_type_var.values:
|
| 583 |
+
if any(
|
| 584 |
+
mypy.subtypes.is_subtype(c.target, value) for value in c.origin_type_var.values
|
| 585 |
+
):
|
| 586 |
+
satisfiable.append(c)
|
| 587 |
+
elif mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound):
|
| 588 |
+
satisfiable.append(c)
|
| 589 |
+
if not satisfiable:
|
| 590 |
+
return None
|
| 591 |
+
return satisfiable
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def exclude_non_meta_vars(option: list[Constraint] | None) -> list[Constraint] | None:
|
| 595 |
+
# If we had an empty list, keep it intact
|
| 596 |
+
if not option:
|
| 597 |
+
return option
|
| 598 |
+
# However, if none of the options actually references meta vars, better remove
|
| 599 |
+
# this constraint entirely.
|
| 600 |
+
return [c for c in option if c.type_var.is_meta_var()] or None
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def is_same_constraints(x: list[Constraint], y: list[Constraint]) -> bool:
|
| 604 |
+
for c1 in x:
|
| 605 |
+
if not any(is_same_constraint(c1, c2) for c2 in y):
|
| 606 |
+
return False
|
| 607 |
+
for c1 in y:
|
| 608 |
+
if not any(is_same_constraint(c1, c2) for c2 in x):
|
| 609 |
+
return False
|
| 610 |
+
return True
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def is_same_constraint(c1: Constraint, c2: Constraint) -> bool:
|
| 614 |
+
# Ignore direction when comparing constraints against Any.
|
| 615 |
+
skip_op_check = isinstance(get_proper_type(c1.target), AnyType) and isinstance(
|
| 616 |
+
get_proper_type(c2.target), AnyType
|
| 617 |
+
)
|
| 618 |
+
return (
|
| 619 |
+
c1.type_var == c2.type_var
|
| 620 |
+
and (c1.op == c2.op or skip_op_check)
|
| 621 |
+
and mypy.subtypes.is_same_type(c1.target, c2.target)
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool:
|
| 626 |
+
"""Check that two lists of constraints have similar structure.
|
| 627 |
+
|
| 628 |
+
This means that each list has same type variable plus direction pairs (i.e we
|
| 629 |
+
ignore the target). Except for constraints where target is Any type, there
|
| 630 |
+
we ignore direction as well.
|
| 631 |
+
"""
|
| 632 |
+
return _is_similar_constraints(x, y) and _is_similar_constraints(y, x)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def _is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool:
|
| 636 |
+
"""Check that every constraint in the first list has a similar one in the second.
|
| 637 |
+
|
| 638 |
+
See docstring above for definition of similarity.
|
| 639 |
+
"""
|
| 640 |
+
for c1 in x:
|
| 641 |
+
has_similar = False
|
| 642 |
+
for c2 in y:
|
| 643 |
+
# Ignore direction when either constraint is against Any.
|
| 644 |
+
skip_op_check = isinstance(get_proper_type(c1.target), AnyType) or isinstance(
|
| 645 |
+
get_proper_type(c2.target), AnyType
|
| 646 |
+
)
|
| 647 |
+
if c1.type_var == c2.type_var and (c1.op == c2.op or skip_op_check):
|
| 648 |
+
has_similar = True
|
| 649 |
+
break
|
| 650 |
+
if not has_similar:
|
| 651 |
+
return False
|
| 652 |
+
return True
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class ConstraintBuilderVisitor(TypeVisitor[list[Constraint]]):
|
| 656 |
+
"""Visitor class for inferring type constraints."""
|
| 657 |
+
|
| 658 |
+
# The type that is compared against a template
|
| 659 |
+
# TODO: The value may be None. Is that actually correct?
|
| 660 |
+
actual: ProperType
|
| 661 |
+
|
| 662 |
+
def __init__(self, actual: ProperType, direction: int, skip_neg_op: bool) -> None:
|
| 663 |
+
# Direction must be SUBTYPE_OF or SUPERTYPE_OF.
|
| 664 |
+
self.actual = actual
|
| 665 |
+
self.direction = direction
|
| 666 |
+
# Whether to skip polymorphic inference (involves inference in opposite direction)
|
| 667 |
+
# this is used to prevent infinite recursion when both template and actual are
|
| 668 |
+
# generic callables.
|
| 669 |
+
self.skip_neg_op = skip_neg_op
|
| 670 |
+
|
| 671 |
+
# Trivial leaf types
|
| 672 |
+
|
| 673 |
+
def visit_unbound_type(self, template: UnboundType) -> list[Constraint]:
|
| 674 |
+
return []
|
| 675 |
+
|
| 676 |
+
def visit_any(self, template: AnyType) -> list[Constraint]:
|
| 677 |
+
return []
|
| 678 |
+
|
| 679 |
+
def visit_none_type(self, template: NoneType) -> list[Constraint]:
|
| 680 |
+
return []
|
| 681 |
+
|
| 682 |
+
def visit_uninhabited_type(self, template: UninhabitedType) -> list[Constraint]:
|
| 683 |
+
return []
|
| 684 |
+
|
| 685 |
+
def visit_erased_type(self, template: ErasedType) -> list[Constraint]:
|
| 686 |
+
return []
|
| 687 |
+
|
| 688 |
+
def visit_deleted_type(self, template: DeletedType) -> list[Constraint]:
|
| 689 |
+
return []
|
| 690 |
+
|
| 691 |
+
def visit_literal_type(self, template: LiteralType) -> list[Constraint]:
|
| 692 |
+
return []
|
| 693 |
+
|
| 694 |
+
# Errors
|
| 695 |
+
|
| 696 |
+
def visit_partial_type(self, template: PartialType) -> list[Constraint]:
|
| 697 |
+
# We can't do anything useful with a partial type here.
|
| 698 |
+
assert False, "Internal error"
|
| 699 |
+
|
| 700 |
+
# Non-trivial leaf type
|
| 701 |
+
|
| 702 |
+
def visit_type_var(self, template: TypeVarType) -> list[Constraint]:
|
| 703 |
+
assert False, (
|
| 704 |
+
"Unexpected TypeVarType in ConstraintBuilderVisitor"
|
| 705 |
+
" (should have been handled in infer_constraints)"
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
def visit_param_spec(self, template: ParamSpecType) -> list[Constraint]:
|
| 709 |
+
# Can't infer ParamSpecs from component values (only via Callable[P, T]).
|
| 710 |
+
return []
|
| 711 |
+
|
| 712 |
+
def visit_type_var_tuple(self, template: TypeVarTupleType) -> list[Constraint]:
|
| 713 |
+
raise NotImplementedError
|
| 714 |
+
|
| 715 |
+
def visit_unpack_type(self, template: UnpackType) -> list[Constraint]:
|
| 716 |
+
raise RuntimeError("Mypy bug: unpack should be handled at a higher level.")
|
| 717 |
+
|
| 718 |
+
def visit_parameters(self, template: Parameters) -> list[Constraint]:
|
| 719 |
+
# Constraining Any against C[P] turns into infer_against_any([P], Any)
|
| 720 |
+
if isinstance(self.actual, AnyType):
|
| 721 |
+
return self.infer_against_any(template.arg_types, self.actual)
|
| 722 |
+
if type_state.infer_polymorphic and isinstance(self.actual, Parameters):
|
| 723 |
+
# For polymorphic inference we need to be able to infer secondary constraints
|
| 724 |
+
# in situations like [x: T] <: P <: [x: int].
|
| 725 |
+
return infer_callable_arguments_constraints(template, self.actual, self.direction)
|
| 726 |
+
if type_state.infer_polymorphic and isinstance(self.actual, ParamSpecType):
|
| 727 |
+
# Similar for [x: T] <: Q <: Concatenate[int, P].
|
| 728 |
+
return infer_callable_arguments_constraints(
|
| 729 |
+
template, self.actual.prefix, self.direction
|
| 730 |
+
)
|
| 731 |
+
# There also may be unpatched types after a user error, simply ignore them.
|
| 732 |
+
return []
|
| 733 |
+
|
| 734 |
+
# Non-leaf types
|
| 735 |
+
|
| 736 |
+
def visit_instance(self, template: Instance) -> list[Constraint]:
|
| 737 |
+
original_actual = actual = self.actual
|
| 738 |
+
res: list[Constraint] = []
|
| 739 |
+
if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol:
|
| 740 |
+
if "__call__" in template.type.protocol_members:
|
| 741 |
+
# Special case: a generic callback protocol
|
| 742 |
+
if not any(template == t for t in template.type.inferring):
|
| 743 |
+
template.type.inferring.append(template)
|
| 744 |
+
call = mypy.subtypes.find_member(
|
| 745 |
+
"__call__", template, actual, is_operator=True
|
| 746 |
+
)
|
| 747 |
+
assert call is not None
|
| 748 |
+
if (
|
| 749 |
+
self.direction == SUPERTYPE_OF
|
| 750 |
+
and mypy.subtypes.is_subtype(actual, erase_typevars(call))
|
| 751 |
+
or self.direction == SUBTYPE_OF
|
| 752 |
+
and mypy.subtypes.is_subtype(erase_typevars(call), actual)
|
| 753 |
+
):
|
| 754 |
+
res.extend(infer_constraints(call, actual, self.direction))
|
| 755 |
+
template.type.inferring.pop()
|
| 756 |
+
if isinstance(actual, CallableType) and actual.fallback is not None:
|
| 757 |
+
if (
|
| 758 |
+
actual.is_type_obj()
|
| 759 |
+
and template.type.is_protocol
|
| 760 |
+
and self.direction == SUPERTYPE_OF
|
| 761 |
+
):
|
| 762 |
+
ret_type = get_proper_type(actual.ret_type)
|
| 763 |
+
if isinstance(ret_type, TupleType):
|
| 764 |
+
ret_type = mypy.typeops.tuple_fallback(ret_type)
|
| 765 |
+
if isinstance(ret_type, Instance):
|
| 766 |
+
res.extend(
|
| 767 |
+
self.infer_constraints_from_protocol_members(
|
| 768 |
+
ret_type, template, ret_type, template, class_obj=True
|
| 769 |
+
)
|
| 770 |
+
)
|
| 771 |
+
actual = actual.fallback
|
| 772 |
+
if isinstance(actual, TypeType) and template.type.is_protocol:
|
| 773 |
+
if self.direction == SUPERTYPE_OF:
|
| 774 |
+
a_item = actual.item
|
| 775 |
+
if isinstance(a_item, Instance):
|
| 776 |
+
res.extend(
|
| 777 |
+
self.infer_constraints_from_protocol_members(
|
| 778 |
+
a_item, template, a_item, template, class_obj=True
|
| 779 |
+
)
|
| 780 |
+
)
|
| 781 |
+
# Infer constraints for Type[T] via metaclass of T when it makes sense.
|
| 782 |
+
if isinstance(a_item, TypeVarType):
|
| 783 |
+
a_item = get_proper_type(a_item.upper_bound)
|
| 784 |
+
if isinstance(a_item, Instance) and a_item.type.metaclass_type:
|
| 785 |
+
res.extend(
|
| 786 |
+
self.infer_constraints_from_protocol_members(
|
| 787 |
+
a_item.type.metaclass_type, template, actual, template
|
| 788 |
+
)
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
if isinstance(actual, Overloaded) and actual.fallback is not None:
|
| 792 |
+
actual = actual.fallback
|
| 793 |
+
if isinstance(actual, TypedDictType):
|
| 794 |
+
actual = actual.create_anonymous_fallback()
|
| 795 |
+
if isinstance(actual, LiteralType):
|
| 796 |
+
actual = actual.fallback
|
| 797 |
+
if isinstance(actual, Instance):
|
| 798 |
+
instance = actual
|
| 799 |
+
erased = erase_typevars(template)
|
| 800 |
+
assert isinstance(erased, Instance) # type: ignore[misc]
|
| 801 |
+
# We always try nominal inference if possible,
|
| 802 |
+
# it is much faster than the structural one.
|
| 803 |
+
if self.direction == SUBTYPE_OF and template.type.has_base(instance.type.fullname):
|
| 804 |
+
mapped = map_instance_to_supertype(template, instance.type)
|
| 805 |
+
tvars = mapped.type.defn.type_vars
|
| 806 |
+
|
| 807 |
+
if instance.type.has_type_var_tuple_type:
|
| 808 |
+
# Variadic types need special handling to map each type argument to
|
| 809 |
+
# the correct corresponding type variable.
|
| 810 |
+
assert instance.type.type_var_tuple_prefix is not None
|
| 811 |
+
assert instance.type.type_var_tuple_suffix is not None
|
| 812 |
+
prefix_len = instance.type.type_var_tuple_prefix
|
| 813 |
+
suffix_len = instance.type.type_var_tuple_suffix
|
| 814 |
+
tvt = instance.type.defn.type_vars[prefix_len]
|
| 815 |
+
assert isinstance(tvt, TypeVarTupleType)
|
| 816 |
+
fallback = tvt.tuple_fallback
|
| 817 |
+
i_prefix, i_middle, i_suffix = split_with_prefix_and_suffix(
|
| 818 |
+
instance.args, prefix_len, suffix_len
|
| 819 |
+
)
|
| 820 |
+
m_prefix, m_middle, m_suffix = split_with_prefix_and_suffix(
|
| 821 |
+
mapped.args, prefix_len, suffix_len
|
| 822 |
+
)
|
| 823 |
+
instance_args = i_prefix + (TupleType(list(i_middle), fallback),) + i_suffix
|
| 824 |
+
mapped_args = m_prefix + (TupleType(list(m_middle), fallback),) + m_suffix
|
| 825 |
+
else:
|
| 826 |
+
mapped_args = mapped.args
|
| 827 |
+
instance_args = instance.args
|
| 828 |
+
|
| 829 |
+
# N.B: We use zip instead of indexing because the lengths might have
|
| 830 |
+
# mismatches during daemon reprocessing.
|
| 831 |
+
for tvar, mapped_arg, instance_arg in zip(tvars, mapped_args, instance_args):
|
| 832 |
+
if isinstance(tvar, TypeVarType):
|
| 833 |
+
# The constraints for generic type parameters depend on variance.
|
| 834 |
+
# Include constraints from both directions if invariant.
|
| 835 |
+
if tvar.variance != CONTRAVARIANT:
|
| 836 |
+
res.extend(infer_constraints(mapped_arg, instance_arg, self.direction))
|
| 837 |
+
if tvar.variance != COVARIANT:
|
| 838 |
+
res.extend(
|
| 839 |
+
infer_constraints(mapped_arg, instance_arg, neg_op(self.direction))
|
| 840 |
+
)
|
| 841 |
+
elif isinstance(tvar, ParamSpecType) and isinstance(mapped_arg, ParamSpecType):
|
| 842 |
+
prefix = mapped_arg.prefix
|
| 843 |
+
if isinstance(instance_arg, Parameters):
|
| 844 |
+
# No such thing as variance for ParamSpecs, consider them invariant
|
| 845 |
+
# TODO: constraints between prefixes using
|
| 846 |
+
# infer_callable_arguments_constraints()
|
| 847 |
+
suffix: Type = instance_arg.copy_modified(
|
| 848 |
+
instance_arg.arg_types[len(prefix.arg_types) :],
|
| 849 |
+
instance_arg.arg_kinds[len(prefix.arg_kinds) :],
|
| 850 |
+
instance_arg.arg_names[len(prefix.arg_names) :],
|
| 851 |
+
)
|
| 852 |
+
res.append(Constraint(mapped_arg, SUBTYPE_OF, suffix))
|
| 853 |
+
res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix))
|
| 854 |
+
elif isinstance(instance_arg, ParamSpecType):
|
| 855 |
+
suffix = instance_arg.copy_modified(
|
| 856 |
+
prefix=Parameters(
|
| 857 |
+
instance_arg.prefix.arg_types[len(prefix.arg_types) :],
|
| 858 |
+
instance_arg.prefix.arg_kinds[len(prefix.arg_kinds) :],
|
| 859 |
+
instance_arg.prefix.arg_names[len(prefix.arg_names) :],
|
| 860 |
+
)
|
| 861 |
+
)
|
| 862 |
+
res.append(Constraint(mapped_arg, SUBTYPE_OF, suffix))
|
| 863 |
+
res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix))
|
| 864 |
+
elif isinstance(tvar, TypeVarTupleType):
|
| 865 |
+
# Handle variadic type variables covariantly for consistency.
|
| 866 |
+
res.extend(infer_constraints(mapped_arg, instance_arg, self.direction))
|
| 867 |
+
|
| 868 |
+
return res
|
| 869 |
+
elif self.direction == SUPERTYPE_OF and instance.type.has_base(template.type.fullname):
|
| 870 |
+
mapped = map_instance_to_supertype(instance, template.type)
|
| 871 |
+
tvars = template.type.defn.type_vars
|
| 872 |
+
if template.type.has_type_var_tuple_type:
|
| 873 |
+
# Variadic types need special handling to map each type argument to
|
| 874 |
+
# the correct corresponding type variable.
|
| 875 |
+
assert template.type.type_var_tuple_prefix is not None
|
| 876 |
+
assert template.type.type_var_tuple_suffix is not None
|
| 877 |
+
prefix_len = template.type.type_var_tuple_prefix
|
| 878 |
+
suffix_len = template.type.type_var_tuple_suffix
|
| 879 |
+
tvt = template.type.defn.type_vars[prefix_len]
|
| 880 |
+
assert isinstance(tvt, TypeVarTupleType)
|
| 881 |
+
fallback = tvt.tuple_fallback
|
| 882 |
+
t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(
|
| 883 |
+
template.args, prefix_len, suffix_len
|
| 884 |
+
)
|
| 885 |
+
m_prefix, m_middle, m_suffix = split_with_prefix_and_suffix(
|
| 886 |
+
mapped.args, prefix_len, suffix_len
|
| 887 |
+
)
|
| 888 |
+
template_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix
|
| 889 |
+
mapped_args = m_prefix + (TupleType(list(m_middle), fallback),) + m_suffix
|
| 890 |
+
else:
|
| 891 |
+
mapped_args = mapped.args
|
| 892 |
+
template_args = template.args
|
| 893 |
+
# N.B: We use zip instead of indexing because the lengths might have
|
| 894 |
+
# mismatches during daemon reprocessing.
|
| 895 |
+
for tvar, mapped_arg, template_arg in zip(tvars, mapped_args, template_args):
|
| 896 |
+
if isinstance(tvar, TypeVarType):
|
| 897 |
+
# The constraints for generic type parameters depend on variance.
|
| 898 |
+
# Include constraints from both directions if invariant.
|
| 899 |
+
if tvar.variance != CONTRAVARIANT:
|
| 900 |
+
res.extend(infer_constraints(template_arg, mapped_arg, self.direction))
|
| 901 |
+
if tvar.variance != COVARIANT:
|
| 902 |
+
res.extend(
|
| 903 |
+
infer_constraints(template_arg, mapped_arg, neg_op(self.direction))
|
| 904 |
+
)
|
| 905 |
+
elif isinstance(tvar, ParamSpecType) and isinstance(
|
| 906 |
+
template_arg, ParamSpecType
|
| 907 |
+
):
|
| 908 |
+
prefix = template_arg.prefix
|
| 909 |
+
if isinstance(mapped_arg, Parameters):
|
| 910 |
+
# No such thing as variance for ParamSpecs, consider them invariant
|
| 911 |
+
# TODO: constraints between prefixes using
|
| 912 |
+
# infer_callable_arguments_constraints()
|
| 913 |
+
suffix = mapped_arg.copy_modified(
|
| 914 |
+
mapped_arg.arg_types[len(prefix.arg_types) :],
|
| 915 |
+
mapped_arg.arg_kinds[len(prefix.arg_kinds) :],
|
| 916 |
+
mapped_arg.arg_names[len(prefix.arg_names) :],
|
| 917 |
+
)
|
| 918 |
+
res.append(Constraint(template_arg, SUBTYPE_OF, suffix))
|
| 919 |
+
res.append(Constraint(template_arg, SUPERTYPE_OF, suffix))
|
| 920 |
+
elif isinstance(mapped_arg, ParamSpecType):
|
| 921 |
+
suffix = mapped_arg.copy_modified(
|
| 922 |
+
prefix=Parameters(
|
| 923 |
+
mapped_arg.prefix.arg_types[len(prefix.arg_types) :],
|
| 924 |
+
mapped_arg.prefix.arg_kinds[len(prefix.arg_kinds) :],
|
| 925 |
+
mapped_arg.prefix.arg_names[len(prefix.arg_names) :],
|
| 926 |
+
)
|
| 927 |
+
)
|
| 928 |
+
res.append(Constraint(template_arg, SUBTYPE_OF, suffix))
|
| 929 |
+
res.append(Constraint(template_arg, SUPERTYPE_OF, suffix))
|
| 930 |
+
elif isinstance(tvar, TypeVarTupleType):
|
| 931 |
+
# Consider variadic type variables to be invariant.
|
| 932 |
+
res.extend(infer_constraints(template_arg, mapped_arg, SUBTYPE_OF))
|
| 933 |
+
res.extend(infer_constraints(template_arg, mapped_arg, SUPERTYPE_OF))
|
| 934 |
+
return res
|
| 935 |
+
if (
|
| 936 |
+
template.type.is_protocol
|
| 937 |
+
and self.direction == SUPERTYPE_OF
|
| 938 |
+
and
|
| 939 |
+
# We avoid infinite recursion for structural subtypes by checking
|
| 940 |
+
# whether this type already appeared in the inference chain.
|
| 941 |
+
# This is a conservative way to break the inference cycles.
|
| 942 |
+
# It never produces any "false" constraints but gives up soon
|
| 943 |
+
# on purely structural inference cycles, see #3829.
|
| 944 |
+
# Note that we use is_protocol_implementation instead of is_subtype
|
| 945 |
+
# because some type may be considered a subtype of a protocol
|
| 946 |
+
# due to _promote, but still not implement the protocol.
|
| 947 |
+
not any(template == t for t in reversed(template.type.inferring))
|
| 948 |
+
and mypy.subtypes.is_protocol_implementation(instance, erased, skip=["__call__"])
|
| 949 |
+
):
|
| 950 |
+
template.type.inferring.append(template)
|
| 951 |
+
res.extend(
|
| 952 |
+
self.infer_constraints_from_protocol_members(
|
| 953 |
+
instance, template, original_actual, template
|
| 954 |
+
)
|
| 955 |
+
)
|
| 956 |
+
template.type.inferring.pop()
|
| 957 |
+
return res
|
| 958 |
+
elif (
|
| 959 |
+
instance.type.is_protocol
|
| 960 |
+
and self.direction == SUBTYPE_OF
|
| 961 |
+
and
|
| 962 |
+
# We avoid infinite recursion for structural subtypes also here.
|
| 963 |
+
not any(instance == i for i in reversed(instance.type.inferring))
|
| 964 |
+
and mypy.subtypes.is_protocol_implementation(erased, instance, skip=["__call__"])
|
| 965 |
+
):
|
| 966 |
+
instance.type.inferring.append(instance)
|
| 967 |
+
res.extend(
|
| 968 |
+
self.infer_constraints_from_protocol_members(
|
| 969 |
+
instance, template, template, instance
|
| 970 |
+
)
|
| 971 |
+
)
|
| 972 |
+
instance.type.inferring.pop()
|
| 973 |
+
return res
|
| 974 |
+
if res:
|
| 975 |
+
return res
|
| 976 |
+
|
| 977 |
+
if isinstance(actual, AnyType):
|
| 978 |
+
return self.infer_against_any(template.args, actual)
|
| 979 |
+
if (
|
| 980 |
+
isinstance(actual, TupleType)
|
| 981 |
+
and is_named_instance(template, TUPLE_LIKE_INSTANCE_NAMES)
|
| 982 |
+
and self.direction == SUPERTYPE_OF
|
| 983 |
+
):
|
| 984 |
+
for item in actual.items:
|
| 985 |
+
if isinstance(item, UnpackType):
|
| 986 |
+
unpacked = get_proper_type(item.type)
|
| 987 |
+
if isinstance(unpacked, TypeVarTupleType):
|
| 988 |
+
# Cannot infer anything for T from [T, ...] <: *Ts
|
| 989 |
+
continue
|
| 990 |
+
assert (
|
| 991 |
+
isinstance(unpacked, Instance)
|
| 992 |
+
and unpacked.type.fullname == "builtins.tuple"
|
| 993 |
+
)
|
| 994 |
+
item = unpacked.args[0]
|
| 995 |
+
cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)
|
| 996 |
+
res.extend(cb)
|
| 997 |
+
return res
|
| 998 |
+
elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF:
|
| 999 |
+
return infer_constraints(template, mypy.typeops.tuple_fallback(actual), self.direction)
|
| 1000 |
+
elif isinstance(actual, TypeVarType):
|
| 1001 |
+
if not actual.values and not actual.id.is_meta_var():
|
| 1002 |
+
return infer_constraints(template, actual.upper_bound, self.direction)
|
| 1003 |
+
return []
|
| 1004 |
+
elif isinstance(actual, ParamSpecType):
|
| 1005 |
+
return infer_constraints(template, actual.upper_bound, self.direction)
|
| 1006 |
+
elif isinstance(actual, TypeVarTupleType):
|
| 1007 |
+
raise NotImplementedError
|
| 1008 |
+
else:
|
| 1009 |
+
return []
|
| 1010 |
+
|
| 1011 |
+
def infer_constraints_from_protocol_members(
|
| 1012 |
+
self,
|
| 1013 |
+
instance: Instance,
|
| 1014 |
+
template: Instance,
|
| 1015 |
+
subtype: Type,
|
| 1016 |
+
protocol: Instance,
|
| 1017 |
+
class_obj: bool = False,
|
| 1018 |
+
) -> list[Constraint]:
|
| 1019 |
+
"""Infer constraints for situations where either 'template' or 'instance' is a protocol.
|
| 1020 |
+
|
| 1021 |
+
The 'protocol' is the one of two that is an instance of protocol type, 'subtype'
|
| 1022 |
+
is the type used to bind self during inference. Currently, we just infer constrains for
|
| 1023 |
+
every protocol member type (both ways for settable members).
|
| 1024 |
+
"""
|
| 1025 |
+
res = []
|
| 1026 |
+
for member in protocol.type.protocol_members:
|
| 1027 |
+
inst = mypy.subtypes.find_member(member, instance, subtype, class_obj=class_obj)
|
| 1028 |
+
temp = mypy.subtypes.find_member(member, template, subtype)
|
| 1029 |
+
if inst is None or temp is None:
|
| 1030 |
+
if member == "__call__":
|
| 1031 |
+
continue
|
| 1032 |
+
return [] # See #11020
|
| 1033 |
+
# The above is safe since at this point we know that 'instance' is a subtype
|
| 1034 |
+
# of (erased) 'template', therefore it defines all protocol members
|
| 1035 |
+
if class_obj:
|
| 1036 |
+
# For class objects we must only infer constraints if possible, otherwise it
|
| 1037 |
+
# can lead to confusion between class and instance, for example StrEnum is
|
| 1038 |
+
# Iterable[str] for an instance, but Iterable[StrEnum] for a class object.
|
| 1039 |
+
if not mypy.subtypes.is_subtype(
|
| 1040 |
+
inst, erase_typevars(temp), ignore_pos_arg_names=True
|
| 1041 |
+
):
|
| 1042 |
+
continue
|
| 1043 |
+
# This exception matches the one in typeops.py, see PR #14121 for context.
|
| 1044 |
+
if member == "__call__" and instance.type.is_metaclass(precise=True):
|
| 1045 |
+
continue
|
| 1046 |
+
res.extend(infer_constraints(temp, inst, self.direction))
|
| 1047 |
+
if mypy.subtypes.IS_SETTABLE in mypy.subtypes.get_member_flags(member, protocol):
|
| 1048 |
+
# Settable members are invariant, add opposite constraints
|
| 1049 |
+
res.extend(infer_constraints(temp, inst, neg_op(self.direction)))
|
| 1050 |
+
return res
|
| 1051 |
+
|
| 1052 |
+
def visit_callable_type(self, template: CallableType) -> list[Constraint]:
|
| 1053 |
+
# Normalize callables before matching against each other.
|
| 1054 |
+
# Note that non-normalized callables can be created in annotations
|
| 1055 |
+
# using e.g. callback protocols.
|
| 1056 |
+
# TODO: check that callables match? Ideally we should not infer constraints
|
| 1057 |
+
# callables that can never be subtypes of one another in given direction.
|
| 1058 |
+
template = template.with_unpacked_kwargs().with_normalized_var_args()
|
| 1059 |
+
extra_tvars = False
|
| 1060 |
+
if isinstance(self.actual, CallableType):
|
| 1061 |
+
res: list[Constraint] = []
|
| 1062 |
+
cactual = self.actual.with_unpacked_kwargs().with_normalized_var_args()
|
| 1063 |
+
param_spec = template.param_spec()
|
| 1064 |
+
|
| 1065 |
+
template_ret_type, cactual_ret_type = template.ret_type, cactual.ret_type
|
| 1066 |
+
if template.type_guard is not None and cactual.type_guard is not None:
|
| 1067 |
+
template_ret_type = template.type_guard
|
| 1068 |
+
cactual_ret_type = cactual.type_guard
|
| 1069 |
+
|
| 1070 |
+
if template.type_is is not None and cactual.type_is is not None:
|
| 1071 |
+
template_ret_type = template.type_is
|
| 1072 |
+
cactual_ret_type = cactual.type_is
|
| 1073 |
+
|
| 1074 |
+
res.extend(infer_constraints(template_ret_type, cactual_ret_type, self.direction))
|
| 1075 |
+
|
| 1076 |
+
if param_spec is None:
|
| 1077 |
+
# TODO: Erase template variables if it is generic?
|
| 1078 |
+
if (
|
| 1079 |
+
type_state.infer_polymorphic
|
| 1080 |
+
and cactual.variables
|
| 1081 |
+
and not self.skip_neg_op
|
| 1082 |
+
# Technically, the correct inferred type for application of e.g.
|
| 1083 |
+
# Callable[..., T] -> Callable[..., T] (with literal ellipsis), to a generic
|
| 1084 |
+
# like U -> U, should be Callable[..., Any], but if U is a self-type, we can
|
| 1085 |
+
# allow it to leak, to be later bound to self. A bunch of existing code
|
| 1086 |
+
# depends on this old behaviour.
|
| 1087 |
+
and not (
|
| 1088 |
+
any(tv.id.is_self() for tv in cactual.variables)
|
| 1089 |
+
and template.is_ellipsis_args
|
| 1090 |
+
)
|
| 1091 |
+
):
|
| 1092 |
+
# If the actual callable is generic, infer constraints in the opposite
|
| 1093 |
+
# direction, and indicate to the solver there are extra type variables
|
| 1094 |
+
# to solve for (see more details in mypy/solve.py).
|
| 1095 |
+
res.extend(
|
| 1096 |
+
infer_constraints(
|
| 1097 |
+
cactual, template, neg_op(self.direction), skip_neg_op=True
|
| 1098 |
+
)
|
| 1099 |
+
)
|
| 1100 |
+
extra_tvars = True
|
| 1101 |
+
|
| 1102 |
+
# We can't infer constraints from arguments if the template is Callable[..., T]
|
| 1103 |
+
# (with literal '...').
|
| 1104 |
+
if not template.is_ellipsis_args:
|
| 1105 |
+
unpack_present = find_unpack_in_list(template.arg_types)
|
| 1106 |
+
# When both ParamSpec and TypeVarTuple are present, things become messy
|
| 1107 |
+
# quickly. For now, we only allow ParamSpec to "capture" TypeVarTuple,
|
| 1108 |
+
# but not vice versa.
|
| 1109 |
+
# TODO: infer more from prefixes when possible.
|
| 1110 |
+
if unpack_present is not None and not cactual.param_spec():
|
| 1111 |
+
# We need to re-normalize args to the form they appear in tuples,
|
| 1112 |
+
# for callables we always pack the suffix inside another tuple.
|
| 1113 |
+
unpack = template.arg_types[unpack_present]
|
| 1114 |
+
assert isinstance(unpack, UnpackType)
|
| 1115 |
+
tuple_type = get_tuple_fallback_from_unpack(unpack)
|
| 1116 |
+
template_types = repack_callable_args(template, tuple_type)
|
| 1117 |
+
actual_types = repack_callable_args(cactual, tuple_type)
|
| 1118 |
+
# Now we can use the same general helper as for tuple types.
|
| 1119 |
+
unpack_constraints = build_constraints_for_simple_unpack(
|
| 1120 |
+
template_types, actual_types, neg_op(self.direction)
|
| 1121 |
+
)
|
| 1122 |
+
res.extend(unpack_constraints)
|
| 1123 |
+
else:
|
| 1124 |
+
# TODO: do we need some special-casing when unpack is present in actual
|
| 1125 |
+
# callable but not in template callable?
|
| 1126 |
+
res.extend(
|
| 1127 |
+
infer_callable_arguments_constraints(template, cactual, self.direction)
|
| 1128 |
+
)
|
| 1129 |
+
else:
|
| 1130 |
+
prefix = param_spec.prefix
|
| 1131 |
+
prefix_len = len(prefix.arg_types)
|
| 1132 |
+
cactual_ps = cactual.param_spec()
|
| 1133 |
+
|
| 1134 |
+
if type_state.infer_polymorphic and cactual.variables and not self.skip_neg_op:
|
| 1135 |
+
# Similar logic to the branch above.
|
| 1136 |
+
res.extend(
|
| 1137 |
+
infer_constraints(
|
| 1138 |
+
cactual, template, neg_op(self.direction), skip_neg_op=True
|
| 1139 |
+
)
|
| 1140 |
+
)
|
| 1141 |
+
extra_tvars = True
|
| 1142 |
+
|
| 1143 |
+
# Compare prefixes as well
|
| 1144 |
+
cactual_prefix = cactual.copy_modified(
|
| 1145 |
+
arg_types=cactual.arg_types[:prefix_len],
|
| 1146 |
+
arg_kinds=cactual.arg_kinds[:prefix_len],
|
| 1147 |
+
arg_names=cactual.arg_names[:prefix_len],
|
| 1148 |
+
)
|
| 1149 |
+
res.extend(
|
| 1150 |
+
infer_callable_arguments_constraints(prefix, cactual_prefix, self.direction)
|
| 1151 |
+
)
|
| 1152 |
+
|
| 1153 |
+
param_spec_target: Type | None = None
|
| 1154 |
+
if not cactual_ps:
|
| 1155 |
+
max_prefix_len = len([k for k in cactual.arg_kinds if k in (ARG_POS, ARG_OPT)])
|
| 1156 |
+
prefix_len = min(prefix_len, max_prefix_len)
|
| 1157 |
+
param_spec_target = Parameters(
|
| 1158 |
+
arg_types=cactual.arg_types[prefix_len:],
|
| 1159 |
+
arg_kinds=cactual.arg_kinds[prefix_len:],
|
| 1160 |
+
arg_names=cactual.arg_names[prefix_len:],
|
| 1161 |
+
variables=cactual.variables if not type_state.infer_polymorphic else [],
|
| 1162 |
+
imprecise_arg_kinds=cactual.imprecise_arg_kinds,
|
| 1163 |
+
)
|
| 1164 |
+
else:
|
| 1165 |
+
if len(param_spec.prefix.arg_types) <= len(cactual_ps.prefix.arg_types):
|
| 1166 |
+
param_spec_target = cactual_ps.copy_modified(
|
| 1167 |
+
prefix=Parameters(
|
| 1168 |
+
arg_types=cactual_ps.prefix.arg_types[prefix_len:],
|
| 1169 |
+
arg_kinds=cactual_ps.prefix.arg_kinds[prefix_len:],
|
| 1170 |
+
arg_names=cactual_ps.prefix.arg_names[prefix_len:],
|
| 1171 |
+
imprecise_arg_kinds=cactual_ps.prefix.imprecise_arg_kinds,
|
| 1172 |
+
)
|
| 1173 |
+
)
|
| 1174 |
+
if param_spec_target is not None:
|
| 1175 |
+
res.append(Constraint(param_spec, self.direction, param_spec_target))
|
| 1176 |
+
if extra_tvars:
|
| 1177 |
+
for c in res:
|
| 1178 |
+
c.extra_tvars += cactual.variables
|
| 1179 |
+
return res
|
| 1180 |
+
elif isinstance(self.actual, AnyType):
|
| 1181 |
+
param_spec = template.param_spec()
|
| 1182 |
+
any_type = AnyType(TypeOfAny.from_another_any, source_any=self.actual)
|
| 1183 |
+
if param_spec is None:
|
| 1184 |
+
# FIX what if generic
|
| 1185 |
+
res = self.infer_against_any(template.arg_types, self.actual)
|
| 1186 |
+
else:
|
| 1187 |
+
res = [
|
| 1188 |
+
Constraint(
|
| 1189 |
+
param_spec,
|
| 1190 |
+
SUBTYPE_OF,
|
| 1191 |
+
Parameters([any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None]),
|
| 1192 |
+
)
|
| 1193 |
+
]
|
| 1194 |
+
res.extend(infer_constraints(template.ret_type, any_type, self.direction))
|
| 1195 |
+
return res
|
| 1196 |
+
elif isinstance(self.actual, Overloaded):
|
| 1197 |
+
return self.infer_against_overloaded(self.actual, template)
|
| 1198 |
+
elif isinstance(self.actual, TypeType):
|
| 1199 |
+
return infer_constraints(template.ret_type, self.actual.item, self.direction)
|
| 1200 |
+
elif isinstance(self.actual, Instance):
|
| 1201 |
+
# Instances with __call__ method defined are considered structural
|
| 1202 |
+
# subtypes of Callable with a compatible signature.
|
| 1203 |
+
call = mypy.subtypes.find_member(
|
| 1204 |
+
"__call__", self.actual, self.actual, is_operator=True
|
| 1205 |
+
)
|
| 1206 |
+
if call:
|
| 1207 |
+
return infer_constraints(template, call, self.direction)
|
| 1208 |
+
else:
|
| 1209 |
+
return []
|
| 1210 |
+
else:
|
| 1211 |
+
return []
|
| 1212 |
+
|
| 1213 |
+
def infer_against_overloaded(
|
| 1214 |
+
self, overloaded: Overloaded, template: CallableType
|
| 1215 |
+
) -> list[Constraint]:
|
| 1216 |
+
# Create constraints by matching an overloaded type against a template.
|
| 1217 |
+
# This is tricky to do in general. We cheat by only matching against
|
| 1218 |
+
# the first overload item that is callable compatible. This
|
| 1219 |
+
# seems to work somewhat well, but we should really use a more
|
| 1220 |
+
# reliable technique.
|
| 1221 |
+
item = find_matching_overload_item(overloaded, template)
|
| 1222 |
+
return infer_constraints(template, item, self.direction)
|
| 1223 |
+
|
| 1224 |
+
def visit_tuple_type(self, template: TupleType) -> list[Constraint]:
|
| 1225 |
+
actual = self.actual
|
| 1226 |
+
unpack_index = find_unpack_in_list(template.items)
|
| 1227 |
+
is_varlength_tuple = (
|
| 1228 |
+
isinstance(actual, Instance) and actual.type.fullname == "builtins.tuple"
|
| 1229 |
+
)
|
| 1230 |
+
|
| 1231 |
+
if isinstance(actual, TupleType) or is_varlength_tuple:
|
| 1232 |
+
res: list[Constraint] = []
|
| 1233 |
+
if unpack_index is not None:
|
| 1234 |
+
if is_varlength_tuple:
|
| 1235 |
+
# Variadic tuple can be only a supertype of a tuple type, but even if
|
| 1236 |
+
# direction is opposite, inferring something may give better error messages.
|
| 1237 |
+
unpack_type = template.items[unpack_index]
|
| 1238 |
+
assert isinstance(unpack_type, UnpackType)
|
| 1239 |
+
unpacked_type = get_proper_type(unpack_type.type)
|
| 1240 |
+
if isinstance(unpacked_type, TypeVarTupleType):
|
| 1241 |
+
res = [
|
| 1242 |
+
Constraint(type_var=unpacked_type, op=self.direction, target=actual)
|
| 1243 |
+
]
|
| 1244 |
+
else:
|
| 1245 |
+
assert (
|
| 1246 |
+
isinstance(unpacked_type, Instance)
|
| 1247 |
+
and unpacked_type.type.fullname == "builtins.tuple"
|
| 1248 |
+
)
|
| 1249 |
+
res = infer_constraints(unpacked_type, actual, self.direction)
|
| 1250 |
+
assert isinstance(actual, Instance) # ensured by is_varlength_tuple == True
|
| 1251 |
+
for i, ti in enumerate(template.items):
|
| 1252 |
+
if i == unpack_index:
|
| 1253 |
+
# This one we just handled above.
|
| 1254 |
+
continue
|
| 1255 |
+
# For Tuple[T, *Ts, S] <: tuple[X, ...] infer also T <: X and S <: X.
|
| 1256 |
+
res.extend(infer_constraints(ti, actual.args[0], self.direction))
|
| 1257 |
+
return res
|
| 1258 |
+
else:
|
| 1259 |
+
assert isinstance(actual, TupleType)
|
| 1260 |
+
unpack_constraints = build_constraints_for_simple_unpack(
|
| 1261 |
+
template.items, actual.items, self.direction
|
| 1262 |
+
)
|
| 1263 |
+
actual_items: tuple[Type, ...] = ()
|
| 1264 |
+
template_items: tuple[Type, ...] = ()
|
| 1265 |
+
res.extend(unpack_constraints)
|
| 1266 |
+
elif isinstance(actual, TupleType):
|
| 1267 |
+
a_unpack_index = find_unpack_in_list(actual.items)
|
| 1268 |
+
if a_unpack_index is not None:
|
| 1269 |
+
# The case where template tuple doesn't have an unpack, but actual tuple
|
| 1270 |
+
# has an unpack. We can infer something if actual unpack is a variadic tuple.
|
| 1271 |
+
# Tuple[T, S, U] <: tuple[X, *tuple[Y, ...], Z] => T <: X, S <: Y, U <: Z.
|
| 1272 |
+
a_unpack = actual.items[a_unpack_index]
|
| 1273 |
+
assert isinstance(a_unpack, UnpackType)
|
| 1274 |
+
a_unpacked = get_proper_type(a_unpack.type)
|
| 1275 |
+
if len(actual.items) + 1 <= len(template.items):
|
| 1276 |
+
a_prefix_len = a_unpack_index
|
| 1277 |
+
a_suffix_len = len(actual.items) - a_unpack_index - 1
|
| 1278 |
+
t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(
|
| 1279 |
+
tuple(template.items), a_prefix_len, a_suffix_len
|
| 1280 |
+
)
|
| 1281 |
+
actual_items = tuple(actual.items[:a_prefix_len])
|
| 1282 |
+
if a_suffix_len:
|
| 1283 |
+
actual_items += tuple(actual.items[-a_suffix_len:])
|
| 1284 |
+
template_items = t_prefix + t_suffix
|
| 1285 |
+
if isinstance(a_unpacked, Instance):
|
| 1286 |
+
assert a_unpacked.type.fullname == "builtins.tuple"
|
| 1287 |
+
for tm in t_middle:
|
| 1288 |
+
res.extend(
|
| 1289 |
+
infer_constraints(tm, a_unpacked.args[0], self.direction)
|
| 1290 |
+
)
|
| 1291 |
+
else:
|
| 1292 |
+
actual_items = ()
|
| 1293 |
+
template_items = ()
|
| 1294 |
+
else:
|
| 1295 |
+
actual_items = tuple(actual.items)
|
| 1296 |
+
template_items = tuple(template.items)
|
| 1297 |
+
else:
|
| 1298 |
+
return res
|
| 1299 |
+
|
| 1300 |
+
# Cases above will return if actual wasn't a TupleType.
|
| 1301 |
+
assert isinstance(actual, TupleType)
|
| 1302 |
+
if len(actual_items) == len(template_items):
|
| 1303 |
+
if (
|
| 1304 |
+
actual.partial_fallback.type.is_named_tuple
|
| 1305 |
+
and template.partial_fallback.type.is_named_tuple
|
| 1306 |
+
):
|
| 1307 |
+
# For named tuples using just the fallbacks usually gives better results.
|
| 1308 |
+
return res + infer_constraints(
|
| 1309 |
+
template.partial_fallback, actual.partial_fallback, self.direction
|
| 1310 |
+
)
|
| 1311 |
+
for i in range(len(template_items)):
|
| 1312 |
+
res.extend(
|
| 1313 |
+
infer_constraints(template_items[i], actual_items[i], self.direction)
|
| 1314 |
+
)
|
| 1315 |
+
res.extend(
|
| 1316 |
+
infer_constraints(
|
| 1317 |
+
template.partial_fallback, actual.partial_fallback, self.direction
|
| 1318 |
+
)
|
| 1319 |
+
)
|
| 1320 |
+
return res
|
| 1321 |
+
elif isinstance(actual, AnyType):
|
| 1322 |
+
return self.infer_against_any(template.items, actual)
|
| 1323 |
+
else:
|
| 1324 |
+
return []
|
| 1325 |
+
|
| 1326 |
+
def visit_typeddict_type(self, template: TypedDictType) -> list[Constraint]:
|
| 1327 |
+
actual = self.actual
|
| 1328 |
+
if isinstance(actual, TypedDictType):
|
| 1329 |
+
res: list[Constraint] = []
|
| 1330 |
+
# NOTE: Non-matching keys are ignored. Compatibility is checked
|
| 1331 |
+
# elsewhere so this shouldn't be unsafe.
|
| 1332 |
+
for item_name, template_item_type, actual_item_type in template.zip(actual):
|
| 1333 |
+
res.extend(infer_constraints(template_item_type, actual_item_type, self.direction))
|
| 1334 |
+
return res
|
| 1335 |
+
elif isinstance(actual, AnyType):
|
| 1336 |
+
return self.infer_against_any(template.items.values(), actual)
|
| 1337 |
+
else:
|
| 1338 |
+
return []
|
| 1339 |
+
|
| 1340 |
+
def visit_union_type(self, template: UnionType) -> list[Constraint]:
|
| 1341 |
+
assert False, (
|
| 1342 |
+
"Unexpected UnionType in ConstraintBuilderVisitor"
|
| 1343 |
+
" (should have been handled in infer_constraints)"
|
| 1344 |
+
)
|
| 1345 |
+
|
| 1346 |
+
def visit_type_alias_type(self, template: TypeAliasType) -> list[Constraint]:
|
| 1347 |
+
assert False, f"This should be never called, got {template}"
|
| 1348 |
+
|
| 1349 |
+
def infer_against_any(self, types: Iterable[Type], any_type: AnyType) -> list[Constraint]:
|
| 1350 |
+
res: list[Constraint] = []
|
| 1351 |
+
# Some items may be things like `*Tuple[*Ts, T]` for example from callable types with
|
| 1352 |
+
# suffix after *arg, so flatten them.
|
| 1353 |
+
for t in flatten_nested_tuples(types):
|
| 1354 |
+
if isinstance(t, UnpackType):
|
| 1355 |
+
if isinstance(t.type, TypeVarTupleType):
|
| 1356 |
+
res.append(Constraint(t.type, self.direction, any_type))
|
| 1357 |
+
else:
|
| 1358 |
+
unpacked = get_proper_type(t.type)
|
| 1359 |
+
assert isinstance(unpacked, Instance)
|
| 1360 |
+
res.extend(infer_constraints(unpacked, any_type, self.direction))
|
| 1361 |
+
else:
|
| 1362 |
+
# Note that we ignore variance and simply always use the
|
| 1363 |
+
# original direction. This is because for Any targets direction is
|
| 1364 |
+
# irrelevant in most cases, see e.g. is_same_constraint().
|
| 1365 |
+
res.extend(infer_constraints(t, any_type, self.direction))
|
| 1366 |
+
return res
|
| 1367 |
+
|
| 1368 |
+
def visit_overloaded(self, template: Overloaded) -> list[Constraint]:
|
| 1369 |
+
if isinstance(self.actual, CallableType):
|
| 1370 |
+
items = find_matching_overload_items(template, self.actual)
|
| 1371 |
+
else:
|
| 1372 |
+
items = template.items
|
| 1373 |
+
res: list[Constraint] = []
|
| 1374 |
+
for t in items:
|
| 1375 |
+
res.extend(infer_constraints(t, self.actual, self.direction))
|
| 1376 |
+
return res
|
| 1377 |
+
|
| 1378 |
+
def visit_type_type(self, template: TypeType) -> list[Constraint]:
|
| 1379 |
+
if isinstance(self.actual, CallableType):
|
| 1380 |
+
return infer_constraints(template.item, self.actual.ret_type, self.direction)
|
| 1381 |
+
elif isinstance(self.actual, Overloaded):
|
| 1382 |
+
return infer_constraints(template.item, self.actual.items[0].ret_type, self.direction)
|
| 1383 |
+
elif isinstance(self.actual, TypeType):
|
| 1384 |
+
return infer_constraints(template.item, self.actual.item, self.direction)
|
| 1385 |
+
elif isinstance(self.actual, AnyType):
|
| 1386 |
+
return infer_constraints(template.item, self.actual, self.direction)
|
| 1387 |
+
else:
|
| 1388 |
+
return []
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
+
def neg_op(op: int) -> int:
|
| 1392 |
+
"""Map SubtypeOf to SupertypeOf and vice versa."""
|
| 1393 |
+
|
| 1394 |
+
if op == SUBTYPE_OF:
|
| 1395 |
+
return SUPERTYPE_OF
|
| 1396 |
+
elif op == SUPERTYPE_OF:
|
| 1397 |
+
return SUBTYPE_OF
|
| 1398 |
+
else:
|
| 1399 |
+
raise ValueError(f"Invalid operator {op}")
|
| 1400 |
+
|
| 1401 |
+
|
| 1402 |
+
def find_matching_overload_item(overloaded: Overloaded, template: CallableType) -> CallableType:
|
| 1403 |
+
"""Disambiguate overload item against a template."""
|
| 1404 |
+
items = overloaded.items
|
| 1405 |
+
for item in items:
|
| 1406 |
+
# Return type may be indeterminate in the template, so ignore it when performing a
|
| 1407 |
+
# subtype check.
|
| 1408 |
+
if mypy.subtypes.is_callable_compatible(
|
| 1409 |
+
item,
|
| 1410 |
+
template,
|
| 1411 |
+
is_compat=mypy.subtypes.is_subtype,
|
| 1412 |
+
is_proper_subtype=False,
|
| 1413 |
+
ignore_return=True,
|
| 1414 |
+
):
|
| 1415 |
+
return item
|
| 1416 |
+
# Fall back to the first item if we can't find a match. This is totally arbitrary --
|
| 1417 |
+
# maybe we should just bail out at this point.
|
| 1418 |
+
return items[0]
|
| 1419 |
+
|
| 1420 |
+
|
| 1421 |
+
def find_matching_overload_items(
|
| 1422 |
+
overloaded: Overloaded, template: CallableType
|
| 1423 |
+
) -> list[CallableType]:
|
| 1424 |
+
"""Like find_matching_overload_item, but return all matches, not just the first."""
|
| 1425 |
+
items = overloaded.items
|
| 1426 |
+
res = []
|
| 1427 |
+
for item in items:
|
| 1428 |
+
# Return type may be indeterminate in the template, so ignore it when performing a
|
| 1429 |
+
# subtype check.
|
| 1430 |
+
if mypy.subtypes.is_callable_compatible(
|
| 1431 |
+
item,
|
| 1432 |
+
template,
|
| 1433 |
+
is_compat=mypy.subtypes.is_subtype,
|
| 1434 |
+
is_proper_subtype=False,
|
| 1435 |
+
ignore_return=True,
|
| 1436 |
+
):
|
| 1437 |
+
res.append(item)
|
| 1438 |
+
if not res:
|
| 1439 |
+
# Falling back to all items if we can't find a match is pretty arbitrary, but
|
| 1440 |
+
# it maintains backward compatibility.
|
| 1441 |
+
res = items.copy()
|
| 1442 |
+
return res
|
| 1443 |
+
|
| 1444 |
+
|
| 1445 |
+
def get_tuple_fallback_from_unpack(unpack: UnpackType) -> TypeInfo:
|
| 1446 |
+
"""Get builtins.tuple type from available types to construct homogeneous tuples."""
|
| 1447 |
+
tp = get_proper_type(unpack.type)
|
| 1448 |
+
if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple":
|
| 1449 |
+
return tp.type
|
| 1450 |
+
if isinstance(tp, TypeVarTupleType):
|
| 1451 |
+
return tp.tuple_fallback.type
|
| 1452 |
+
if isinstance(tp, TupleType):
|
| 1453 |
+
for base in tp.partial_fallback.type.mro:
|
| 1454 |
+
if base.fullname == "builtins.tuple":
|
| 1455 |
+
return base
|
| 1456 |
+
assert False, "Invalid unpack type"
|
| 1457 |
+
|
| 1458 |
+
|
| 1459 |
+
def repack_callable_args(callable: CallableType, tuple_type: TypeInfo) -> list[Type]:
|
| 1460 |
+
"""Present callable with star unpack in a normalized form.
|
| 1461 |
+
|
| 1462 |
+
Since positional arguments cannot follow star argument, they are packed in a suffix,
|
| 1463 |
+
while prefix is represented as individual positional args. We want to put all in a single
|
| 1464 |
+
list with unpack in the middle, and prefix/suffix on the sides (as they would appear
|
| 1465 |
+
in e.g. a TupleType).
|
| 1466 |
+
"""
|
| 1467 |
+
if ARG_STAR not in callable.arg_kinds:
|
| 1468 |
+
return callable.arg_types
|
| 1469 |
+
star_index = callable.arg_kinds.index(ARG_STAR)
|
| 1470 |
+
arg_types = callable.arg_types[:star_index]
|
| 1471 |
+
star_type = callable.arg_types[star_index]
|
| 1472 |
+
suffix_types = []
|
| 1473 |
+
if not isinstance(star_type, UnpackType):
|
| 1474 |
+
# Re-normalize *args: X -> *args: *tuple[X, ...]
|
| 1475 |
+
star_type = UnpackType(Instance(tuple_type, [star_type]))
|
| 1476 |
+
else:
|
| 1477 |
+
tp = get_proper_type(star_type.type)
|
| 1478 |
+
if isinstance(tp, TupleType):
|
| 1479 |
+
assert isinstance(tp.items[0], UnpackType)
|
| 1480 |
+
star_type = tp.items[0]
|
| 1481 |
+
suffix_types = tp.items[1:]
|
| 1482 |
+
return arg_types + [star_type] + suffix_types
|
| 1483 |
+
|
| 1484 |
+
|
| 1485 |
+
def build_constraints_for_simple_unpack(
|
| 1486 |
+
template_args: list[Type], actual_args: list[Type], direction: int
|
| 1487 |
+
) -> list[Constraint]:
|
| 1488 |
+
"""Infer constraints between two lists of types with variadic items.
|
| 1489 |
+
|
| 1490 |
+
This function is only supposed to be called when a variadic item is present in templates.
|
| 1491 |
+
If there is no variadic item the actuals, we simply use split_with_prefix_and_suffix()
|
| 1492 |
+
and infer prefix <: prefix, suffix <: suffix, variadic <: middle. If there is a variadic
|
| 1493 |
+
item in the actuals we need to be more careful, only common prefix/suffix can generate
|
| 1494 |
+
constraints, also we can only infer constraints for variadic template item, if template
|
| 1495 |
+
prefix/suffix are shorter that actual ones, otherwise there may be partial overlap
|
| 1496 |
+
between variadic items, for example if template prefix is longer:
|
| 1497 |
+
|
| 1498 |
+
templates: T1, T2, Ts, Ts, Ts, ...
|
| 1499 |
+
actuals: A1, As, As, As, ...
|
| 1500 |
+
|
| 1501 |
+
Note: this function can only be called for builtin variadic constructors: Tuple and Callable.
|
| 1502 |
+
For instances, you should first find correct type argument mapping.
|
| 1503 |
+
"""
|
| 1504 |
+
template_unpack = find_unpack_in_list(template_args)
|
| 1505 |
+
assert template_unpack is not None
|
| 1506 |
+
template_prefix = template_unpack
|
| 1507 |
+
template_suffix = len(template_args) - template_prefix - 1
|
| 1508 |
+
|
| 1509 |
+
t_unpack = None
|
| 1510 |
+
res = []
|
| 1511 |
+
|
| 1512 |
+
actual_unpack = find_unpack_in_list(actual_args)
|
| 1513 |
+
if actual_unpack is None:
|
| 1514 |
+
t_unpack = template_args[template_unpack]
|
| 1515 |
+
if template_prefix + template_suffix > len(actual_args):
|
| 1516 |
+
# These can't be subtypes of each-other, return fast.
|
| 1517 |
+
assert isinstance(t_unpack, UnpackType)
|
| 1518 |
+
if isinstance(t_unpack.type, TypeVarTupleType):
|
| 1519 |
+
# Set TypeVarTuple to empty to improve error messages.
|
| 1520 |
+
return [
|
| 1521 |
+
Constraint(
|
| 1522 |
+
t_unpack.type, direction, TupleType([], t_unpack.type.tuple_fallback)
|
| 1523 |
+
)
|
| 1524 |
+
]
|
| 1525 |
+
else:
|
| 1526 |
+
return []
|
| 1527 |
+
common_prefix = template_prefix
|
| 1528 |
+
common_suffix = template_suffix
|
| 1529 |
+
else:
|
| 1530 |
+
actual_prefix = actual_unpack
|
| 1531 |
+
actual_suffix = len(actual_args) - actual_prefix - 1
|
| 1532 |
+
common_prefix = min(template_prefix, actual_prefix)
|
| 1533 |
+
common_suffix = min(template_suffix, actual_suffix)
|
| 1534 |
+
if actual_prefix >= template_prefix and actual_suffix >= template_suffix:
|
| 1535 |
+
# This is the only case where we can guarantee there will be no partial overlap
|
| 1536 |
+
# (note however partial overlap is OK for variadic tuples, it is handled below).
|
| 1537 |
+
t_unpack = template_args[template_unpack]
|
| 1538 |
+
|
| 1539 |
+
# Handle constraints from prefixes/suffixes first.
|
| 1540 |
+
start, middle, end = split_with_prefix_and_suffix(
|
| 1541 |
+
tuple(actual_args), common_prefix, common_suffix
|
| 1542 |
+
)
|
| 1543 |
+
for t, a in zip(template_args[:common_prefix], start):
|
| 1544 |
+
res.extend(infer_constraints(t, a, direction))
|
| 1545 |
+
if common_suffix:
|
| 1546 |
+
for t, a in zip(template_args[-common_suffix:], end):
|
| 1547 |
+
res.extend(infer_constraints(t, a, direction))
|
| 1548 |
+
|
| 1549 |
+
if t_unpack is not None:
|
| 1550 |
+
# Add constraint(s) for variadic item when possible.
|
| 1551 |
+
assert isinstance(t_unpack, UnpackType)
|
| 1552 |
+
tp = get_proper_type(t_unpack.type)
|
| 1553 |
+
if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple":
|
| 1554 |
+
# Homogeneous case *tuple[T, ...] <: [X, Y, Z, ...].
|
| 1555 |
+
for a in middle:
|
| 1556 |
+
# TODO: should we use union instead of join here?
|
| 1557 |
+
if not isinstance(a, UnpackType):
|
| 1558 |
+
res.extend(infer_constraints(tp.args[0], a, direction))
|
| 1559 |
+
else:
|
| 1560 |
+
a_tp = get_proper_type(a.type)
|
| 1561 |
+
# This is the case *tuple[T, ...] <: *tuple[A, ...].
|
| 1562 |
+
if isinstance(a_tp, Instance) and a_tp.type.fullname == "builtins.tuple":
|
| 1563 |
+
res.extend(infer_constraints(tp.args[0], a_tp.args[0], direction))
|
| 1564 |
+
elif isinstance(tp, TypeVarTupleType):
|
| 1565 |
+
res.append(Constraint(tp, direction, TupleType(list(middle), tp.tuple_fallback)))
|
| 1566 |
+
elif actual_unpack is not None:
|
| 1567 |
+
# A special case for a variadic tuple unpack, we simply infer T <: X from
|
| 1568 |
+
# Tuple[..., *tuple[T, ...], ...] <: Tuple[..., *tuple[X, ...], ...].
|
| 1569 |
+
actual_unpack_type = actual_args[actual_unpack]
|
| 1570 |
+
assert isinstance(actual_unpack_type, UnpackType)
|
| 1571 |
+
a_unpacked = get_proper_type(actual_unpack_type.type)
|
| 1572 |
+
if isinstance(a_unpacked, Instance) and a_unpacked.type.fullname == "builtins.tuple":
|
| 1573 |
+
t_unpack = template_args[template_unpack]
|
| 1574 |
+
assert isinstance(t_unpack, UnpackType)
|
| 1575 |
+
tp = get_proper_type(t_unpack.type)
|
| 1576 |
+
if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple":
|
| 1577 |
+
res.extend(infer_constraints(tp.args[0], a_unpacked.args[0], direction))
|
| 1578 |
+
return res
|
| 1579 |
+
|
| 1580 |
+
|
| 1581 |
+
def infer_directed_arg_constraints(left: Type, right: Type, direction: int) -> list[Constraint]:
|
| 1582 |
+
"""Infer constraints between two arguments using direction between original callables."""
|
| 1583 |
+
if isinstance(left, (ParamSpecType, UnpackType)) or isinstance(
|
| 1584 |
+
right, (ParamSpecType, UnpackType)
|
| 1585 |
+
):
|
| 1586 |
+
# This avoids bogus constraints like T <: P.args
|
| 1587 |
+
# TODO: can we infer something useful for *T vs P?
|
| 1588 |
+
return []
|
| 1589 |
+
if direction == SUBTYPE_OF:
|
| 1590 |
+
# We invert direction to account for argument contravariance.
|
| 1591 |
+
return infer_constraints(left, right, neg_op(direction))
|
| 1592 |
+
else:
|
| 1593 |
+
return infer_constraints(right, left, neg_op(direction))
|
| 1594 |
+
|
| 1595 |
+
|
| 1596 |
+
def infer_callable_arguments_constraints(
|
| 1597 |
+
template: NormalizedCallableType | Parameters,
|
| 1598 |
+
actual: NormalizedCallableType | Parameters,
|
| 1599 |
+
direction: int,
|
| 1600 |
+
) -> list[Constraint]:
|
| 1601 |
+
"""Infer constraints between argument types of two callables.
|
| 1602 |
+
|
| 1603 |
+
This function essentially extracts four steps from are_parameters_compatible() in
|
| 1604 |
+
subtypes.py that involve subtype checks between argument types. We keep the argument
|
| 1605 |
+
matching logic, but ignore various strictness flags present there, and checks that
|
| 1606 |
+
do not involve subtyping. Then in place of every subtype check we put an infer_constraints()
|
| 1607 |
+
call for the same types.
|
| 1608 |
+
"""
|
| 1609 |
+
res = []
|
| 1610 |
+
if direction == SUBTYPE_OF:
|
| 1611 |
+
left, right = template, actual
|
| 1612 |
+
else:
|
| 1613 |
+
left, right = actual, template
|
| 1614 |
+
left_star = left.var_arg()
|
| 1615 |
+
left_star2 = left.kw_arg()
|
| 1616 |
+
right_star = right.var_arg()
|
| 1617 |
+
right_star2 = right.kw_arg()
|
| 1618 |
+
|
| 1619 |
+
# Numbering of steps below matches the one in are_parameters_compatible() for convenience.
|
| 1620 |
+
# Phase 1a: compare star vs star arguments.
|
| 1621 |
+
if left_star is not None and right_star is not None:
|
| 1622 |
+
res.extend(infer_directed_arg_constraints(left_star.typ, right_star.typ, direction))
|
| 1623 |
+
if left_star2 is not None and right_star2 is not None:
|
| 1624 |
+
res.extend(infer_directed_arg_constraints(left_star2.typ, right_star2.typ, direction))
|
| 1625 |
+
|
| 1626 |
+
# Phase 1b: compare left args with corresponding non-star right arguments.
|
| 1627 |
+
for right_arg in right.formal_arguments():
|
| 1628 |
+
left_arg = mypy.typeops.callable_corresponding_argument(left, right_arg)
|
| 1629 |
+
if left_arg is None:
|
| 1630 |
+
continue
|
| 1631 |
+
res.extend(infer_directed_arg_constraints(left_arg.typ, right_arg.typ, direction))
|
| 1632 |
+
|
| 1633 |
+
# Phase 1c: compare left args with right *args.
|
| 1634 |
+
if right_star is not None:
|
| 1635 |
+
right_by_position = right.try_synthesizing_arg_from_vararg(None)
|
| 1636 |
+
assert right_by_position is not None
|
| 1637 |
+
i = right_star.pos
|
| 1638 |
+
assert i is not None
|
| 1639 |
+
while i < len(left.arg_kinds) and left.arg_kinds[i].is_positional():
|
| 1640 |
+
left_by_position = left.argument_by_position(i)
|
| 1641 |
+
assert left_by_position is not None
|
| 1642 |
+
res.extend(
|
| 1643 |
+
infer_directed_arg_constraints(
|
| 1644 |
+
left_by_position.typ, right_by_position.typ, direction
|
| 1645 |
+
)
|
| 1646 |
+
)
|
| 1647 |
+
i += 1
|
| 1648 |
+
|
| 1649 |
+
# Phase 1d: compare left args with right **kwargs.
|
| 1650 |
+
if right_star2 is not None:
|
| 1651 |
+
right_names = {name for name in right.arg_names if name is not None}
|
| 1652 |
+
left_only_names = set()
|
| 1653 |
+
for name, kind in zip(left.arg_names, left.arg_kinds):
|
| 1654 |
+
if name is None or kind.is_star() or name in right_names:
|
| 1655 |
+
continue
|
| 1656 |
+
left_only_names.add(name)
|
| 1657 |
+
|
| 1658 |
+
right_by_name = right.try_synthesizing_arg_from_kwarg(None)
|
| 1659 |
+
assert right_by_name is not None
|
| 1660 |
+
for name in left_only_names:
|
| 1661 |
+
left_by_name = left.argument_by_name(name)
|
| 1662 |
+
assert left_by_name is not None
|
| 1663 |
+
res.extend(
|
| 1664 |
+
infer_directed_arg_constraints(left_by_name.typ, right_by_name.typ, direction)
|
| 1665 |
+
)
|
| 1666 |
+
return res
|
| 1667 |
+
|
| 1668 |
+
|
| 1669 |
+
def filter_imprecise_kinds(cs: list[Constraint]) -> list[Constraint]:
|
| 1670 |
+
"""For each ParamSpec remove all imprecise constraints, if at least one precise available."""
|
| 1671 |
+
have_precise = set()
|
| 1672 |
+
for c in cs:
|
| 1673 |
+
if not isinstance(c.origin_type_var, ParamSpecType):
|
| 1674 |
+
continue
|
| 1675 |
+
if (
|
| 1676 |
+
isinstance(c.target, ParamSpecType)
|
| 1677 |
+
or isinstance(c.target, Parameters)
|
| 1678 |
+
and not c.target.imprecise_arg_kinds
|
| 1679 |
+
):
|
| 1680 |
+
have_precise.add(c.type_var)
|
| 1681 |
+
new_cs = []
|
| 1682 |
+
for c in cs:
|
| 1683 |
+
if not isinstance(c.origin_type_var, ParamSpecType) or c.type_var not in have_precise:
|
| 1684 |
+
new_cs.append(c)
|
| 1685 |
+
if not isinstance(c.target, Parameters) or not c.target.imprecise_arg_kinds:
|
| 1686 |
+
new_cs.append(c)
|
| 1687 |
+
return new_cs
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/copytype.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, cast
|
| 4 |
+
|
| 5 |
+
from mypy.types import (
|
| 6 |
+
AnyType,
|
| 7 |
+
CallableType,
|
| 8 |
+
DeletedType,
|
| 9 |
+
ErasedType,
|
| 10 |
+
Instance,
|
| 11 |
+
LiteralType,
|
| 12 |
+
NoneType,
|
| 13 |
+
Overloaded,
|
| 14 |
+
Parameters,
|
| 15 |
+
ParamSpecType,
|
| 16 |
+
PartialType,
|
| 17 |
+
ProperType,
|
| 18 |
+
TupleType,
|
| 19 |
+
TypeAliasType,
|
| 20 |
+
TypedDictType,
|
| 21 |
+
TypeType,
|
| 22 |
+
TypeVarTupleType,
|
| 23 |
+
TypeVarType,
|
| 24 |
+
UnboundType,
|
| 25 |
+
UninhabitedType,
|
| 26 |
+
UnionType,
|
| 27 |
+
UnpackType,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# type_visitor needs to be imported after types
|
| 31 |
+
from mypy.type_visitor import TypeVisitor # ruff: isort: skip
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def copy_type(t: ProperType) -> ProperType:
|
| 35 |
+
"""Create a shallow copy of a type.
|
| 36 |
+
|
| 37 |
+
This can be used to mutate the copy with truthiness information.
|
| 38 |
+
|
| 39 |
+
Classes compiled with mypyc don't support copy.copy(), so we need
|
| 40 |
+
a custom implementation.
|
| 41 |
+
"""
|
| 42 |
+
return t.accept(TypeShallowCopier())
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TypeShallowCopier(TypeVisitor[ProperType]):
|
| 46 |
+
def visit_unbound_type(self, t: UnboundType) -> ProperType:
|
| 47 |
+
return t
|
| 48 |
+
|
| 49 |
+
def visit_any(self, t: AnyType) -> ProperType:
|
| 50 |
+
return self.copy_common(t, AnyType(t.type_of_any, t.source_any, t.missing_import_name))
|
| 51 |
+
|
| 52 |
+
def visit_none_type(self, t: NoneType) -> ProperType:
|
| 53 |
+
return self.copy_common(t, NoneType())
|
| 54 |
+
|
| 55 |
+
def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:
|
| 56 |
+
dup = UninhabitedType()
|
| 57 |
+
dup.ambiguous = t.ambiguous
|
| 58 |
+
return self.copy_common(t, dup)
|
| 59 |
+
|
| 60 |
+
def visit_erased_type(self, t: ErasedType) -> ProperType:
|
| 61 |
+
return self.copy_common(t, ErasedType())
|
| 62 |
+
|
| 63 |
+
def visit_deleted_type(self, t: DeletedType) -> ProperType:
|
| 64 |
+
return self.copy_common(t, DeletedType(t.source))
|
| 65 |
+
|
| 66 |
+
def visit_instance(self, t: Instance) -> ProperType:
|
| 67 |
+
dup = Instance(t.type, t.args, last_known_value=t.last_known_value)
|
| 68 |
+
return self.copy_common(t, dup)
|
| 69 |
+
|
| 70 |
+
def visit_type_var(self, t: TypeVarType) -> ProperType:
|
| 71 |
+
return self.copy_common(t, t.copy_modified())
|
| 72 |
+
|
| 73 |
+
def visit_param_spec(self, t: ParamSpecType) -> ProperType:
|
| 74 |
+
dup = ParamSpecType(
|
| 75 |
+
t.name, t.fullname, t.id, t.flavor, t.upper_bound, t.default, prefix=t.prefix
|
| 76 |
+
)
|
| 77 |
+
return self.copy_common(t, dup)
|
| 78 |
+
|
| 79 |
+
def visit_parameters(self, t: Parameters) -> ProperType:
|
| 80 |
+
dup = Parameters(
|
| 81 |
+
t.arg_types,
|
| 82 |
+
t.arg_kinds,
|
| 83 |
+
t.arg_names,
|
| 84 |
+
variables=t.variables,
|
| 85 |
+
is_ellipsis_args=t.is_ellipsis_args,
|
| 86 |
+
)
|
| 87 |
+
return self.copy_common(t, dup)
|
| 88 |
+
|
| 89 |
+
def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:
|
| 90 |
+
dup = TypeVarTupleType(
|
| 91 |
+
t.name, t.fullname, t.id, t.upper_bound, t.tuple_fallback, t.default
|
| 92 |
+
)
|
| 93 |
+
return self.copy_common(t, dup)
|
| 94 |
+
|
| 95 |
+
def visit_unpack_type(self, t: UnpackType) -> ProperType:
|
| 96 |
+
dup = UnpackType(t.type)
|
| 97 |
+
return self.copy_common(t, dup)
|
| 98 |
+
|
| 99 |
+
def visit_partial_type(self, t: PartialType) -> ProperType:
|
| 100 |
+
return self.copy_common(t, PartialType(t.type, t.var, t.value_type))
|
| 101 |
+
|
| 102 |
+
def visit_callable_type(self, t: CallableType) -> ProperType:
|
| 103 |
+
return self.copy_common(t, t.copy_modified())
|
| 104 |
+
|
| 105 |
+
def visit_tuple_type(self, t: TupleType) -> ProperType:
|
| 106 |
+
return self.copy_common(t, TupleType(t.items, t.partial_fallback, implicit=t.implicit))
|
| 107 |
+
|
| 108 |
+
def visit_typeddict_type(self, t: TypedDictType) -> ProperType:
|
| 109 |
+
return self.copy_common(
|
| 110 |
+
t, TypedDictType(t.items, t.required_keys, t.readonly_keys, t.fallback)
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
def visit_literal_type(self, t: LiteralType) -> ProperType:
|
| 114 |
+
return self.copy_common(t, LiteralType(value=t.value, fallback=t.fallback))
|
| 115 |
+
|
| 116 |
+
def visit_union_type(self, t: UnionType) -> ProperType:
|
| 117 |
+
return self.copy_common(t, UnionType(t.items))
|
| 118 |
+
|
| 119 |
+
def visit_overloaded(self, t: Overloaded) -> ProperType:
|
| 120 |
+
return self.copy_common(t, Overloaded(items=t.items))
|
| 121 |
+
|
| 122 |
+
def visit_type_type(self, t: TypeType) -> ProperType:
|
| 123 |
+
# Use cast since the type annotations in TypeType are imprecise.
|
| 124 |
+
return self.copy_common(t, TypeType(cast(Any, t.item), is_type_form=t.is_type_form))
|
| 125 |
+
|
| 126 |
+
def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:
|
| 127 |
+
assert False, "only ProperTypes supported"
|
| 128 |
+
|
| 129 |
+
def copy_common(self, t: ProperType, t2: ProperType) -> ProperType:
|
| 130 |
+
t2.line = t.line
|
| 131 |
+
t2.column = t.column
|
| 132 |
+
t2.can_be_false = t.can_be_false
|
| 133 |
+
t2.can_be_true = t.can_be_true
|
| 134 |
+
return t2
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/defaults.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from typing import Final
|
| 5 |
+
|
| 6 |
+
# Earliest fully supported Python 3.x version. Used as the default Python
|
| 7 |
+
# version in tests. Mypy wheels should be built starting with this version,
|
| 8 |
+
# and CI tests should be run on this version (and later versions).
|
| 9 |
+
PYTHON3_VERSION: Final = (3, 10)
|
| 10 |
+
|
| 11 |
+
# Earliest Python 3.x version supported via --python-version 3.x. To run
|
| 12 |
+
# mypy, at least version PYTHON3_VERSION is needed.
|
| 13 |
+
PYTHON3_VERSION_MIN: Final = (3, 9) # Keep in sync with typeshed's python support
|
| 14 |
+
|
| 15 |
+
CACHE_DIR: Final = ".mypy_cache"
|
| 16 |
+
|
| 17 |
+
CONFIG_NAMES: Final = ["mypy.ini", ".mypy.ini"]
|
| 18 |
+
SHARED_CONFIG_NAMES: Final = ["pyproject.toml", "setup.cfg"]
|
| 19 |
+
|
| 20 |
+
USER_CONFIG_FILES: list[str] = ["~/.config/mypy/config", "~/.mypy.ini"]
|
| 21 |
+
if os.environ.get("XDG_CONFIG_HOME"):
|
| 22 |
+
USER_CONFIG_FILES.insert(0, os.path.join(os.environ["XDG_CONFIG_HOME"], "mypy/config"))
|
| 23 |
+
USER_CONFIG_FILES = [os.path.expanduser(f) for f in USER_CONFIG_FILES]
|
| 24 |
+
|
| 25 |
+
# This must include all reporters defined in mypy.report. This is defined here
|
| 26 |
+
# to make reporter names available without importing mypy.report -- this speeds
|
| 27 |
+
# up startup.
|
| 28 |
+
REPORTER_NAMES: Final = [
|
| 29 |
+
"linecount",
|
| 30 |
+
"any-exprs",
|
| 31 |
+
"linecoverage",
|
| 32 |
+
"memory-xml",
|
| 33 |
+
"cobertura-xml",
|
| 34 |
+
"xml",
|
| 35 |
+
"xslt-html",
|
| 36 |
+
"xslt-txt",
|
| 37 |
+
"html",
|
| 38 |
+
"txt",
|
| 39 |
+
"lineprecision",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
# Threshold after which we sometimes filter out most errors to avoid very
|
| 43 |
+
# verbose output. The default is to show all errors.
|
| 44 |
+
MANY_ERRORS_THRESHOLD: Final = -1
|
| 45 |
+
|
| 46 |
+
RECURSION_LIMIT: Final = 2**14
|
| 47 |
+
|
| 48 |
+
WORKER_START_INTERVAL: Final = 0.01
|
| 49 |
+
WORKER_START_TIMEOUT: Final = 3
|
| 50 |
+
WORKER_CONNECTION_TIMEOUT: Final = 10
|
| 51 |
+
WORKER_DONE_TIMEOUT: Final = 600
|
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
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/pkgs/https/conda.anaconda.org/conda-forge/win-64/mypy-1.20.2-py314h5a2d7ad_0/Lib/site-packages/mypy/dmypy_os.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
if sys.platform == "win32":
|
| 8 |
+
import ctypes
|
| 9 |
+
import subprocess
|
| 10 |
+
from ctypes.wintypes import DWORD, HANDLE
|
| 11 |
+
|
| 12 |
+
PROCESS_QUERY_LIMITED_INFORMATION = ctypes.c_ulong(0x1000)
|
| 13 |
+
|
| 14 |
+
kernel32 = ctypes.windll.kernel32
|
| 15 |
+
OpenProcess: Callable[[DWORD, int, int], HANDLE] = kernel32.OpenProcess
|
| 16 |
+
GetExitCodeProcess: Callable[[HANDLE, Any], int] = kernel32.GetExitCodeProcess
|
| 17 |
+
else:
|
| 18 |
+
import os
|
| 19 |
+
import signal
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def alive(pid: int) -> bool:
|
| 23 |
+
"""Is the process alive?"""
|
| 24 |
+
if sys.platform == "win32":
|
| 25 |
+
# why can't anything be easy...
|
| 26 |
+
status = DWORD()
|
| 27 |
+
handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
|
| 28 |
+
GetExitCodeProcess(handle, ctypes.byref(status))
|
| 29 |
+
return status.value == 259 # STILL_ACTIVE
|
| 30 |
+
else:
|
| 31 |
+
try:
|
| 32 |
+
os.kill(pid, 0)
|
| 33 |
+
except OSError:
|
| 34 |
+
return False
|
| 35 |
+
return True
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def kill(pid: int) -> None:
|
| 39 |
+
"""Kill the process."""
|
| 40 |
+
if sys.platform == "win32":
|
| 41 |
+
subprocess.check_output(f"taskkill /pid {pid} /f /t")
|
| 42 |
+
else:
|
| 43 |
+
os.kill(pid, signal.SIGKILL)
|