codekingpro commited on
Commit
203c2b3
·
verified ·
1 Parent(s): d0e89a8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER +1 -0
  2. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/METADATA +56 -0
  3. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/RECORD +0 -0
  4. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/REQUESTED +0 -0
  5. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/WHEEL +5 -0
  6. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/direct_url.json +1 -0
  7. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/entry_points.txt +6 -0
  8. micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/top_level.txt +3 -0
  9. micromamba_root/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd +0 -0
  10. micromamba_root/Lib/site-packages/mypy/__init__.py +1 -0
  11. micromamba_root/Lib/site-packages/mypy/__main__.py +50 -0
  12. micromamba_root/Lib/site-packages/mypy/error_formatter.py +39 -0
  13. micromamba_root/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd +0 -0
  14. micromamba_root/Lib/site-packages/mypy/evalexpr.py +211 -0
  15. micromamba_root/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd +0 -0
  16. micromamba_root/Lib/site-packages/mypy/expandtype.py +662 -0
  17. micromamba_root/Lib/site-packages/mypy/exportjson.py +612 -0
  18. micromamba_root/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd +0 -0
  19. micromamba_root/Lib/site-packages/mypy/exprtotype.py +289 -0
  20. micromamba_root/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd +0 -0
  21. micromamba_root/Lib/site-packages/mypy/fastparse.py +2256 -0
  22. micromamba_root/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd +0 -0
  23. micromamba_root/Lib/site-packages/mypy/find_sources.py +257 -0
  24. micromamba_root/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd +0 -0
  25. micromamba_root/Lib/site-packages/mypy/fixup.py +444 -0
  26. micromamba_root/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd +0 -0
  27. micromamba_root/Lib/site-packages/mypy/freetree.py +23 -0
  28. micromamba_root/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd +0 -0
  29. micromamba_root/Lib/site-packages/mypy/fscache.py +307 -0
  30. micromamba_root/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd +0 -0
  31. micromamba_root/Lib/site-packages/mypy/fswatcher.py +106 -0
  32. micromamba_root/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd +0 -0
  33. micromamba_root/Lib/site-packages/mypy/gclogger.py +48 -0
  34. micromamba_root/Lib/site-packages/mypy/git.cp314-win_amd64.pyd +0 -0
  35. micromamba_root/Lib/site-packages/mypy/git.py +34 -0
  36. micromamba_root/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd +0 -0
  37. micromamba_root/Lib/site-packages/mypy/graph_utils.py +161 -0
  38. micromamba_root/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd +0 -0
  39. micromamba_root/Lib/site-packages/mypy/indirection.py +170 -0
  40. micromamba_root/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd +0 -0
  41. micromamba_root/Lib/site-packages/mypy/infer.py +76 -0
  42. micromamba_root/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd +0 -0
  43. micromamba_root/Lib/site-packages/mypy/inspections.py +626 -0
  44. micromamba_root/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd +0 -0
  45. micromamba_root/Lib/site-packages/mypy/ipc.py +457 -0
  46. micromamba_root/Lib/site-packages/mypy/join.cp314-win_amd64.pyd +0 -0
  47. micromamba_root/Lib/site-packages/mypy/join.py +916 -0
  48. micromamba_root/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd +0 -0
  49. micromamba_root/Lib/site-packages/mypy/literals.py +327 -0
  50. micromamba_root/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd +0 -0
micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ conda
micromamba_root/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/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/Lib/site-packages/mypy-1.20.2.dist-info/REQUESTED ADDED
File without changes
micromamba_root/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/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/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/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/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This page intentionally left blank
micromamba_root/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/Lib/site-packages/mypy/error_formatter.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Defines the different custom formats in which mypy can output."""
2
+
3
+ import json
4
+ from abc import ABC, abstractmethod
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from mypy.errors import MypyError
9
+
10
+
11
+ class ErrorFormatter(ABC):
12
+ """Base class to define how errors are formatted before being printed."""
13
+
14
+ @abstractmethod
15
+ def report_error(self, error: "MypyError") -> str:
16
+ raise NotImplementedError
17
+
18
+
19
+ class JSONFormatter(ErrorFormatter):
20
+ """Formatter for basic JSON output format."""
21
+
22
+ def report_error(self, error: "MypyError") -> str:
23
+ """Prints out the errors as simple, static JSON lines."""
24
+ return json.dumps(
25
+ {
26
+ "file": error.file_path,
27
+ "line": error.line,
28
+ "column": error.column,
29
+ "end_line": error.end_line,
30
+ "end_column": error.end_column,
31
+ "message": error.message,
32
+ "hint": None if len(error.hints) == 0 else "\n".join(error.hints),
33
+ "code": error.errorcode,
34
+ "severity": error.severity,
35
+ }
36
+ )
37
+
38
+
39
+ OUTPUT_CHOICES = {"json": JSONFormatter()}
micromamba_root/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/evalexpr.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Evaluate an expression.
4
+
5
+ Used by stubtest; in a separate file because things break if we don't
6
+ put it in a mypyc-compiled file.
7
+
8
+ """
9
+
10
+ import ast
11
+ from typing import Final
12
+
13
+ import mypy.nodes
14
+ from mypy.visitor import ExpressionVisitor
15
+
16
+ UNKNOWN = object()
17
+
18
+
19
+ class _NodeEvaluator(ExpressionVisitor[object]):
20
+ def visit_int_expr(self, o: mypy.nodes.IntExpr) -> int:
21
+ return o.value
22
+
23
+ def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str:
24
+ return o.value
25
+
26
+ def visit_bytes_expr(self, o: mypy.nodes.BytesExpr) -> object:
27
+ # The value of a BytesExpr is a string created from the repr()
28
+ # of the bytes object. Get the original bytes back.
29
+ try:
30
+ return ast.literal_eval(f"b'{o.value}'")
31
+ except SyntaxError:
32
+ return ast.literal_eval(f'b"{o.value}"')
33
+
34
+ def visit_float_expr(self, o: mypy.nodes.FloatExpr) -> float:
35
+ return o.value
36
+
37
+ def visit_complex_expr(self, o: mypy.nodes.ComplexExpr) -> object:
38
+ return o.value
39
+
40
+ def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr) -> object:
41
+ return Ellipsis
42
+
43
+ def visit_star_expr(self, o: mypy.nodes.StarExpr) -> object:
44
+ return UNKNOWN
45
+
46
+ def visit_name_expr(self, o: mypy.nodes.NameExpr) -> object:
47
+ if o.name == "True":
48
+ return True
49
+ elif o.name == "False":
50
+ return False
51
+ elif o.name == "None":
52
+ return None
53
+ # TODO: Handle more names by figuring out a way to hook into the
54
+ # symbol table.
55
+ return UNKNOWN
56
+
57
+ def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> object:
58
+ return UNKNOWN
59
+
60
+ def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> object:
61
+ return UNKNOWN
62
+
63
+ def visit_yield_expr(self, o: mypy.nodes.YieldExpr) -> object:
64
+ return UNKNOWN
65
+
66
+ def visit_call_expr(self, o: mypy.nodes.CallExpr) -> object:
67
+ return UNKNOWN
68
+
69
+ def visit_op_expr(self, o: mypy.nodes.OpExpr) -> object:
70
+ return UNKNOWN
71
+
72
+ def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr) -> object:
73
+ return UNKNOWN
74
+
75
+ def visit_cast_expr(self, o: mypy.nodes.CastExpr) -> object:
76
+ return o.expr.accept(self)
77
+
78
+ def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr) -> object:
79
+ return UNKNOWN
80
+
81
+ def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr) -> object:
82
+ return o.expr.accept(self)
83
+
84
+ def visit_reveal_expr(self, o: mypy.nodes.RevealExpr) -> object:
85
+ return UNKNOWN
86
+
87
+ def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> object:
88
+ return UNKNOWN
89
+
90
+ def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> object:
91
+ operand = o.expr.accept(self)
92
+ if operand is UNKNOWN:
93
+ return UNKNOWN
94
+ if o.op == "-":
95
+ if isinstance(operand, (int, float, complex)):
96
+ return -operand
97
+ elif o.op == "+":
98
+ if isinstance(operand, (int, float, complex)):
99
+ return +operand
100
+ elif o.op == "~":
101
+ if isinstance(operand, int):
102
+ return ~operand
103
+ elif o.op == "not":
104
+ if isinstance(operand, (bool, int, float, str, bytes)):
105
+ return not operand
106
+ return UNKNOWN
107
+
108
+ def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> object:
109
+ return o.value.accept(self)
110
+
111
+ def visit_list_expr(self, o: mypy.nodes.ListExpr) -> object:
112
+ items = [item.accept(self) for item in o.items]
113
+ if all(item is not UNKNOWN for item in items):
114
+ return items
115
+ return UNKNOWN
116
+
117
+ def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> object:
118
+ items = [
119
+ (UNKNOWN if key is None else key.accept(self), value.accept(self))
120
+ for key, value in o.items
121
+ ]
122
+ if all(key is not UNKNOWN and value is not None for key, value in items):
123
+ return dict(items)
124
+ return UNKNOWN
125
+
126
+ def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> object:
127
+ items = [item.accept(self) for item in o.items]
128
+ if all(item is not UNKNOWN for item in items):
129
+ return tuple(items)
130
+ return UNKNOWN
131
+
132
+ def visit_set_expr(self, o: mypy.nodes.SetExpr) -> object:
133
+ items = [item.accept(self) for item in o.items]
134
+ if all(item is not UNKNOWN for item in items):
135
+ return set(items)
136
+ return UNKNOWN
137
+
138
+ def visit_index_expr(self, o: mypy.nodes.IndexExpr) -> object:
139
+ return UNKNOWN
140
+
141
+ def visit_type_application(self, o: mypy.nodes.TypeApplication) -> object:
142
+ return UNKNOWN
143
+
144
+ def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr) -> object:
145
+ return UNKNOWN
146
+
147
+ def visit_list_comprehension(self, o: mypy.nodes.ListComprehension) -> object:
148
+ return UNKNOWN
149
+
150
+ def visit_set_comprehension(self, o: mypy.nodes.SetComprehension) -> object:
151
+ return UNKNOWN
152
+
153
+ def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension) -> object:
154
+ return UNKNOWN
155
+
156
+ def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr) -> object:
157
+ return UNKNOWN
158
+
159
+ def visit_slice_expr(self, o: mypy.nodes.SliceExpr) -> object:
160
+ return UNKNOWN
161
+
162
+ def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr) -> object:
163
+ return UNKNOWN
164
+
165
+ def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr) -> object:
166
+ return UNKNOWN
167
+
168
+ def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr) -> object:
169
+ return UNKNOWN
170
+
171
+ def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr) -> object:
172
+ return UNKNOWN
173
+
174
+ def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr) -> object:
175
+ return UNKNOWN
176
+
177
+ def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr) -> object:
178
+ return UNKNOWN
179
+
180
+ def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr) -> object:
181
+ return UNKNOWN
182
+
183
+ def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr) -> object:
184
+ return UNKNOWN
185
+
186
+ def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr) -> object:
187
+ return UNKNOWN
188
+
189
+ def visit__promote_expr(self, o: mypy.nodes.PromoteExpr) -> object:
190
+ return UNKNOWN
191
+
192
+ def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> object:
193
+ return UNKNOWN
194
+
195
+ def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr) -> object:
196
+ return UNKNOWN
197
+
198
+ def visit_temp_node(self, o: mypy.nodes.TempNode) -> object:
199
+ return UNKNOWN
200
+
201
+
202
+ _evaluator: Final = _NodeEvaluator()
203
+
204
+
205
+ def evaluate_expression(expr: mypy.nodes.Expression) -> object:
206
+ """Evaluate an expression at runtime.
207
+
208
+ Return the result of the expression, or UNKNOWN if the expression cannot be
209
+ evaluated.
210
+ """
211
+ return expr.accept(_evaluator)
micromamba_root/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/expandtype.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable, Mapping
4
+ from typing import Final, TypeVar, cast, overload
5
+
6
+ from mypy.nodes import ARG_STAR, ArgKind, FakeInfo, Var
7
+ from mypy.state import state
8
+ from mypy.types import (
9
+ ANY_STRATEGY,
10
+ AnyType,
11
+ BoolTypeQuery,
12
+ CallableType,
13
+ DeletedType,
14
+ ErasedType,
15
+ FunctionLike,
16
+ Instance,
17
+ LiteralType,
18
+ NoneType,
19
+ Overloaded,
20
+ Parameters,
21
+ ParamSpecFlavor,
22
+ ParamSpecType,
23
+ PartialType,
24
+ ProperType,
25
+ TrivialSyntheticTypeTranslator,
26
+ TupleType,
27
+ Type,
28
+ TypeAliasType,
29
+ TypedDictType,
30
+ TypeOfAny,
31
+ TypeType,
32
+ TypeVarId,
33
+ TypeVarLikeType,
34
+ TypeVarTupleType,
35
+ TypeVarType,
36
+ UnboundType,
37
+ UninhabitedType,
38
+ UnionType,
39
+ UnpackType,
40
+ flatten_nested_unions,
41
+ get_proper_type,
42
+ split_with_prefix_and_suffix,
43
+ )
44
+ from mypy.typevartuples import split_with_instance
45
+
46
+ # Solving the import cycle:
47
+ import mypy.type_visitor # ruff: isort: skip
48
+
49
+ # WARNING: these functions should never (directly or indirectly) depend on
50
+ # is_subtype(), meet_types(), join_types() etc.
51
+ # TODO: add a static dependency test for this.
52
+
53
+
54
+ @overload
55
+ def expand_type(typ: CallableType, env: Mapping[TypeVarId, Type]) -> CallableType: ...
56
+
57
+
58
+ @overload
59
+ def expand_type(typ: ProperType, env: Mapping[TypeVarId, Type]) -> ProperType: ...
60
+
61
+
62
+ @overload
63
+ def expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: ...
64
+
65
+
66
+ def expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type:
67
+ """Substitute any type variable references in a type given by a type
68
+ environment.
69
+ """
70
+ return typ.accept(ExpandTypeVisitor(env))
71
+
72
+
73
+ @overload
74
+ def expand_type_by_instance(typ: CallableType, instance: Instance) -> CallableType: ...
75
+
76
+
77
+ @overload
78
+ def expand_type_by_instance(typ: ProperType, instance: Instance) -> ProperType: ...
79
+
80
+
81
+ @overload
82
+ def expand_type_by_instance(typ: Type, instance: Instance) -> Type: ...
83
+
84
+
85
+ def expand_type_by_instance(typ: Type, instance: Instance) -> Type:
86
+ """Substitute type variables in type using values from an Instance.
87
+ Type variables are considered to be bound by the class declaration."""
88
+ if not instance.args and not instance.type.has_type_var_tuple_type:
89
+ return typ
90
+ else:
91
+ variables: dict[TypeVarId, Type] = {}
92
+ if instance.type.has_type_var_tuple_type:
93
+ assert instance.type.type_var_tuple_prefix is not None
94
+ assert instance.type.type_var_tuple_suffix is not None
95
+
96
+ args_prefix, args_middle, args_suffix = split_with_instance(instance)
97
+ tvars_prefix, tvars_middle, tvars_suffix = split_with_prefix_and_suffix(
98
+ tuple(instance.type.defn.type_vars),
99
+ instance.type.type_var_tuple_prefix,
100
+ instance.type.type_var_tuple_suffix,
101
+ )
102
+ tvar = tvars_middle[0]
103
+ assert isinstance(tvar, TypeVarTupleType)
104
+ variables = {tvar.id: TupleType(list(args_middle), tvar.tuple_fallback)}
105
+ instance_args = args_prefix + args_suffix
106
+ tvars = tvars_prefix + tvars_suffix
107
+ else:
108
+ tvars = tuple(instance.type.defn.type_vars)
109
+ instance_args = instance.args
110
+
111
+ for binder, arg in zip(tvars, instance_args):
112
+ assert isinstance(binder, TypeVarLikeType)
113
+ variables[binder.id] = arg
114
+
115
+ return expand_type(typ, variables)
116
+
117
+
118
+ F = TypeVar("F", bound=FunctionLike)
119
+
120
+
121
+ def freshen_function_type_vars(callee: F) -> F:
122
+ """Substitute fresh type variables for generic function type variables."""
123
+ if isinstance(callee, CallableType):
124
+ if not callee.is_generic():
125
+ return callee
126
+ tvs = []
127
+ tvmap: dict[TypeVarId, Type] = {}
128
+ for v in callee.variables:
129
+ tv = v.new_unification_variable(v)
130
+ tvs.append(tv)
131
+ tvmap[v.id] = tv
132
+ fresh = expand_type(callee, tvmap).copy_modified(variables=tvs)
133
+ return cast(F, fresh)
134
+ else:
135
+ assert isinstance(callee, Overloaded)
136
+ fresh_overload = Overloaded([freshen_function_type_vars(item) for item in callee.items])
137
+ return cast(F, fresh_overload)
138
+
139
+
140
+ class HasGenericCallable(BoolTypeQuery):
141
+ def __init__(self) -> None:
142
+ super().__init__(ANY_STRATEGY)
143
+
144
+ def visit_callable_type(self, t: CallableType) -> bool:
145
+ return t.is_generic() or super().visit_callable_type(t)
146
+
147
+
148
+ # Share a singleton since this is performance sensitive
149
+ has_generic_callable: Final = HasGenericCallable()
150
+
151
+
152
+ T = TypeVar("T", bound=Type)
153
+
154
+
155
+ def freshen_all_functions_type_vars(t: T) -> T:
156
+ result: Type
157
+ has_generic_callable.reset()
158
+ if not t.accept(has_generic_callable):
159
+ return t # Fast path to avoid expensive freshening
160
+ else:
161
+ result = t.accept(FreshenCallableVisitor())
162
+ assert isinstance(result, type(t))
163
+ return result
164
+
165
+
166
+ class FreshenCallableVisitor(mypy.type_visitor.TypeTranslator):
167
+ def visit_callable_type(self, t: CallableType) -> Type:
168
+ result = super().visit_callable_type(t)
169
+ assert isinstance(result, ProperType) and isinstance(result, CallableType)
170
+ return freshen_function_type_vars(result)
171
+
172
+ def visit_type_alias_type(self, t: TypeAliasType) -> Type:
173
+ # Same as for ExpandTypeVisitor
174
+ return t.copy_modified(args=[arg.accept(self) for arg in t.args])
175
+
176
+
177
+ class ExpandTypeVisitor(TrivialSyntheticTypeTranslator):
178
+ """Visitor that substitutes type variables with values."""
179
+
180
+ variables: Mapping[TypeVarId, Type] # TypeVar id -> TypeVar value
181
+
182
+ def __init__(self, variables: Mapping[TypeVarId, Type]) -> None:
183
+ super().__init__()
184
+ self.variables = variables
185
+ self.recursive_tvar_guard: dict[TypeVarId, Type | None] | None = None
186
+
187
+ def visit_unbound_type(self, t: UnboundType) -> Type:
188
+ return t
189
+
190
+ def visit_any(self, t: AnyType) -> Type:
191
+ return t
192
+
193
+ def visit_none_type(self, t: NoneType) -> Type:
194
+ return t
195
+
196
+ def visit_uninhabited_type(self, t: UninhabitedType) -> Type:
197
+ return t
198
+
199
+ def visit_deleted_type(self, t: DeletedType) -> Type:
200
+ return t
201
+
202
+ def visit_erased_type(self, t: ErasedType) -> Type:
203
+ # This may happen during type inference if some function argument
204
+ # type is a generic callable, and its erased form will appear in inferred
205
+ # constraints, then solver may check subtyping between them, which will trigger
206
+ # unify_generic_callables(), this is why we can get here. Another example is
207
+ # when inferring type of lambda in generic context, the lambda body contains
208
+ # a generic method in generic class.
209
+ return t
210
+
211
+ def visit_instance(self, t: Instance) -> Type:
212
+ if len(t.args) == 0:
213
+ return t
214
+
215
+ args = self.expand_type_tuple_with_unpack(t.args)
216
+
217
+ if isinstance(t.type, FakeInfo):
218
+ # The type checker expands function definitions and bodies
219
+ # if they depend on constrained type variables but the body
220
+ # might contain a tuple type comment (e.g., # type: (int, float)),
221
+ # in which case 't.type' is not yet available.
222
+ #
223
+ # See: https://github.com/python/mypy/issues/16649
224
+ return t.copy_modified(args=args)
225
+
226
+ if t.type.fullname == "builtins.tuple":
227
+ # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...]
228
+ arg = args[0]
229
+ if isinstance(arg, UnpackType):
230
+ unpacked = get_proper_type(arg.type)
231
+ if isinstance(unpacked, Instance):
232
+ # TODO: this and similar asserts below may be unsafe because get_proper_type()
233
+ # may be called during semantic analysis before all invalid types are removed.
234
+ assert unpacked.type.fullname == "builtins.tuple"
235
+ args = list(unpacked.args)
236
+ return t.copy_modified(args=args)
237
+
238
+ def visit_type_var(self, t: TypeVarType) -> Type:
239
+ # Normally upper bounds can't contain other type variables, the only exception is
240
+ # special type variable Self`0 <: C[T, S], where C is the class where Self is used.
241
+ if t.id.is_self():
242
+ t = t.copy_modified(upper_bound=t.upper_bound.accept(self))
243
+ repl = self.variables.get(t.id, t)
244
+ if isinstance(repl, ProperType) and isinstance(repl, Instance):
245
+ # TODO: do we really need to do this?
246
+ # If I try to remove this special-casing ~40 tests fail on reveal_type().
247
+ return repl.copy_modified(last_known_value=None)
248
+ if isinstance(repl, TypeVarType) and repl.has_default():
249
+ if self.recursive_tvar_guard is None:
250
+ self.recursive_tvar_guard = {}
251
+ if (tvar_id := repl.id) in self.recursive_tvar_guard:
252
+ return self.recursive_tvar_guard[tvar_id] or repl
253
+ self.recursive_tvar_guard[tvar_id] = None
254
+ repl.default = repl.default.accept(self)
255
+ expanded = repl.accept(self) # Note: `expanded is repl` may be true.
256
+ repl = repl if isinstance(expanded, TypeVarType) else expanded
257
+ self.recursive_tvar_guard[tvar_id] = repl
258
+ return repl
259
+
260
+ def visit_param_spec(self, t: ParamSpecType) -> Type:
261
+ # Set prefix to something empty, so we don't duplicate it below.
262
+ repl = self.variables.get(t.id, t.copy_modified(prefix=Parameters([], [], [])))
263
+ if isinstance(repl, ParamSpecType):
264
+ return repl.copy_modified(
265
+ flavor=t.flavor,
266
+ prefix=t.prefix.copy_modified(
267
+ arg_types=self.expand_types(t.prefix.arg_types) + repl.prefix.arg_types,
268
+ arg_kinds=t.prefix.arg_kinds + repl.prefix.arg_kinds,
269
+ arg_names=t.prefix.arg_names + repl.prefix.arg_names,
270
+ ),
271
+ )
272
+ elif isinstance(repl, Parameters):
273
+ assert isinstance(t.upper_bound, ProperType) and isinstance(t.upper_bound, Instance)
274
+ if t.flavor == ParamSpecFlavor.BARE:
275
+ return Parameters(
276
+ self.expand_types(t.prefix.arg_types) + repl.arg_types,
277
+ t.prefix.arg_kinds + repl.arg_kinds,
278
+ t.prefix.arg_names + repl.arg_names,
279
+ variables=[*t.prefix.variables, *repl.variables],
280
+ imprecise_arg_kinds=repl.imprecise_arg_kinds,
281
+ )
282
+ elif t.flavor == ParamSpecFlavor.ARGS:
283
+ assert all(k.is_positional() for k in t.prefix.arg_kinds)
284
+ return self._possible_callable_varargs(
285
+ repl, list(t.prefix.arg_types), t.upper_bound
286
+ )
287
+ else:
288
+ assert t.flavor == ParamSpecFlavor.KWARGS
289
+ return self._possible_callable_kwargs(repl, t.upper_bound)
290
+ else:
291
+ # We could encode Any as trivial parameters etc., but it would be too verbose.
292
+ # TODO: assert this is a trivial type, like Any, Never, or object.
293
+ return repl
294
+
295
+ @classmethod
296
+ def _possible_callable_varargs(
297
+ cls, repl: Parameters, required_prefix: list[Type], tuple_type: Instance
298
+ ) -> ProperType:
299
+ """Given a callable, extract all parameters that can be passed as `*args`.
300
+
301
+ This builds a union of all (possibly variadic) tuples representing all possible
302
+ argument sequences that can be passed positionally. Each such tuple starts with
303
+ all required (pos-only without a default) arguments, followed by some prefix
304
+ of other arguments that can be passed positionally.
305
+ """
306
+ required_posargs = required_prefix
307
+ if repl.variables:
308
+ # We will tear the callable apart, do not leak type variables
309
+ return tuple_type
310
+ optional_posargs: list[Type] = []
311
+ for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types):
312
+ if kind == ArgKind.ARG_POS and name is None:
313
+ if optional_posargs:
314
+ # May happen following Unpack expansion without kinds correction
315
+ required_posargs += optional_posargs
316
+ optional_posargs = []
317
+ required_posargs.append(type)
318
+ elif kind.is_positional():
319
+ optional_posargs.append(type)
320
+ elif kind == ArgKind.ARG_STAR:
321
+ if isinstance(type, UnpackType):
322
+ optional_posargs.append(type)
323
+ else:
324
+ optional_posargs.append(UnpackType(Instance(tuple_type.type, [type])))
325
+ break
326
+ return UnionType.make_union(
327
+ [
328
+ TupleType(required_posargs + optional_posargs[:i], fallback=tuple_type)
329
+ for i in range(len(optional_posargs) + 1)
330
+ ]
331
+ )
332
+
333
+ @classmethod
334
+ def _possible_callable_kwargs(cls, repl: Parameters, dict_type: Instance) -> ProperType:
335
+ """Given a callable, extract all parameters that can be passed as `**kwargs`.
336
+
337
+ If the function only accepts **kwargs, this will be a `dict[str, KwargsValueType]`.
338
+ Otherwise, this will be a `TypedDict` containing all explicit args and ignoring
339
+ `**kwargs` (until PEP 728 `extra_items` is supported). TypedDict entries will
340
+ be required iff the corresponding argument is kw-only and has no default.
341
+ """
342
+ if repl.variables:
343
+ # We will tear the callable apart, do not leak type variables
344
+ return dict_type
345
+ kwargs = {}
346
+ required_names = set()
347
+ extra_items: Type = UninhabitedType()
348
+ for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types):
349
+ if kind == ArgKind.ARG_NAMED and name is not None:
350
+ kwargs[name] = type
351
+ required_names.add(name)
352
+ elif kind == ArgKind.ARG_STAR2:
353
+ # Unpack[TypedDict] is normalized early, it isn't stored as Unpack
354
+ extra_items = type
355
+ elif not kind.is_star() and name is not None:
356
+ kwargs[name] = type
357
+ if not kwargs:
358
+ return Instance(dict_type.type, [dict_type.args[0], extra_items])
359
+ # TODO: when PEP 728 is implemented, pass extra_items below.
360
+ return TypedDictType(kwargs, required_names, set(), fallback=dict_type)
361
+
362
+ def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:
363
+ # Sometimes solver may need to expand a type variable with (a copy of) itself
364
+ # (usually together with other TypeVars, but it is hard to filter out TypeVarTuples).
365
+ repl = self.variables.get(t.id, t)
366
+ if isinstance(repl, TypeVarTupleType):
367
+ return repl
368
+ elif isinstance(repl, ProperType) and isinstance(repl, (AnyType, UninhabitedType)):
369
+ # Some failed inference scenarios will try to set all type variables to Never.
370
+ # Instead of being picky and require all the callers to wrap them,
371
+ # do this here instead.
372
+ # Note: most cases when this happens are handled in expand unpack below, but
373
+ # in rare cases (e.g. ParamSpec containing Unpack star args) it may be skipped.
374
+ return t.tuple_fallback.copy_modified(args=[repl])
375
+ raise NotImplementedError
376
+
377
+ def visit_unpack_type(self, t: UnpackType) -> Type:
378
+ # It is impossible to reasonably implement visit_unpack_type, because
379
+ # unpacking inherently expands to something more like a list of types.
380
+ #
381
+ # Relevant sections that can call unpack should call expand_unpack()
382
+ # instead.
383
+ # However, if the item is a variadic tuple, we can simply carry it over.
384
+ # In particular, if we expand A[*tuple[T, ...]] with substitutions {T: str},
385
+ # it is hard to assert this without getting proper type. Another important
386
+ # example is non-normalized types when called from semanal.py.
387
+ return UnpackType(t.type.accept(self))
388
+
389
+ def expand_unpack(self, t: UnpackType) -> list[Type]:
390
+ assert isinstance(t.type, TypeVarTupleType)
391
+ repl = get_proper_type(self.variables.get(t.type.id, t.type))
392
+ if isinstance(repl, UnpackType):
393
+ repl = get_proper_type(repl.type)
394
+ if isinstance(repl, TupleType):
395
+ return repl.items
396
+ elif (
397
+ isinstance(repl, Instance)
398
+ and repl.type.fullname == "builtins.tuple"
399
+ or isinstance(repl, TypeVarTupleType)
400
+ ):
401
+ return [UnpackType(typ=repl)]
402
+ elif isinstance(repl, (AnyType, UninhabitedType)):
403
+ # Replace *Ts = Any with *Ts = *tuple[Any, ...] and same for Never.
404
+ # These types may appear here as a result of user error or failed inference.
405
+ return [UnpackType(t.type.tuple_fallback.copy_modified(args=[repl]))]
406
+ else:
407
+ raise RuntimeError(f"Invalid type replacement to expand: {repl}")
408
+
409
+ def visit_parameters(self, t: Parameters) -> Type:
410
+ return t.copy_modified(arg_types=self.expand_types(t.arg_types))
411
+
412
+ def interpolate_args_for_unpack(self, t: CallableType, var_arg: UnpackType) -> list[Type]:
413
+ star_index = t.arg_kinds.index(ARG_STAR)
414
+ prefix = self.expand_types(t.arg_types[:star_index])
415
+ suffix = self.expand_types(t.arg_types[star_index + 1 :])
416
+
417
+ var_arg_type = get_proper_type(var_arg.type)
418
+ new_unpack: Type
419
+ if isinstance(var_arg_type, TupleType):
420
+ # We have something like Unpack[Tuple[Unpack[Ts], X1, X2]]
421
+ expanded_tuple = var_arg_type.accept(self)
422
+ assert isinstance(expanded_tuple, ProperType) and isinstance(expanded_tuple, TupleType)
423
+ expanded_items = expanded_tuple.items
424
+ fallback = var_arg_type.partial_fallback
425
+ new_unpack = UnpackType(TupleType(expanded_items, fallback))
426
+ elif isinstance(var_arg_type, TypeVarTupleType):
427
+ # We have plain Unpack[Ts]
428
+ fallback = var_arg_type.tuple_fallback
429
+ expanded_items = self.expand_unpack(var_arg)
430
+ new_unpack = UnpackType(TupleType(expanded_items, fallback))
431
+ # Since get_proper_type() may be called in semanal.py before callable
432
+ # normalization happens, we need to also handle non-normal cases here.
433
+ elif isinstance(var_arg_type, Instance):
434
+ # we have something like Unpack[Tuple[Any, ...]]
435
+ new_unpack = UnpackType(var_arg.type.accept(self))
436
+ else:
437
+ # We have invalid type in Unpack. This can happen when expanding aliases
438
+ # to Callable[[*Invalid], Ret]
439
+ new_unpack = AnyType(TypeOfAny.from_error, line=var_arg.line, column=var_arg.column)
440
+ return prefix + [new_unpack] + suffix
441
+
442
+ def visit_callable_type(self, t: CallableType) -> CallableType:
443
+ param_spec = t.param_spec()
444
+ if param_spec is not None:
445
+ repl = self.variables.get(param_spec.id)
446
+ # If a ParamSpec in a callable type is substituted with a
447
+ # callable type, we can't use normal substitution logic,
448
+ # since ParamSpec is actually split into two components
449
+ # *P.args and **P.kwargs in the original type. Instead, we
450
+ # must expand both of them with all the argument types,
451
+ # kinds and names in the replacement. The return type in
452
+ # the replacement is ignored.
453
+ if isinstance(repl, Parameters):
454
+ # We need to expand both the types in the prefix and the ParamSpec itself
455
+ expanded = t.copy_modified(
456
+ arg_types=self.expand_types(t.arg_types[:-2]) + repl.arg_types,
457
+ arg_kinds=t.arg_kinds[:-2] + repl.arg_kinds,
458
+ arg_names=t.arg_names[:-2] + repl.arg_names,
459
+ ret_type=t.ret_type.accept(self),
460
+ type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None),
461
+ type_is=(t.type_is.accept(self) if t.type_is is not None else None),
462
+ imprecise_arg_kinds=(t.imprecise_arg_kinds or repl.imprecise_arg_kinds),
463
+ variables=[*repl.variables, *t.variables],
464
+ )
465
+ var_arg = expanded.var_arg()
466
+ if var_arg is not None and isinstance(var_arg.typ, UnpackType):
467
+ # Sometimes we get new unpacks after expanding ParamSpec.
468
+ expanded.normalize_trivial_unpack()
469
+ return expanded
470
+ elif isinstance(repl, ParamSpecType):
471
+ # We're substituting one ParamSpec for another; this can mean that the prefix
472
+ # changes, e.g. substitute Concatenate[int, P] in place of Q.
473
+ prefix = repl.prefix
474
+ clean_repl = repl.copy_modified(prefix=Parameters([], [], []))
475
+ return t.copy_modified(
476
+ arg_types=self.expand_types(t.arg_types[:-2])
477
+ + prefix.arg_types
478
+ + [
479
+ clean_repl.with_flavor(ParamSpecFlavor.ARGS),
480
+ clean_repl.with_flavor(ParamSpecFlavor.KWARGS),
481
+ ],
482
+ arg_kinds=t.arg_kinds[:-2] + prefix.arg_kinds + t.arg_kinds[-2:],
483
+ arg_names=t.arg_names[:-2] + prefix.arg_names + t.arg_names[-2:],
484
+ ret_type=t.ret_type.accept(self),
485
+ from_concatenate=t.from_concatenate or bool(repl.prefix.arg_types),
486
+ imprecise_arg_kinds=(t.imprecise_arg_kinds or prefix.imprecise_arg_kinds),
487
+ )
488
+
489
+ var_arg = t.var_arg()
490
+ needs_normalization = False
491
+ if var_arg is not None and isinstance(var_arg.typ, UnpackType):
492
+ needs_normalization = True
493
+ arg_types = self.interpolate_args_for_unpack(t, var_arg.typ)
494
+ else:
495
+ arg_types = self.expand_types(t.arg_types)
496
+ expanded = t.copy_modified(
497
+ arg_types=arg_types,
498
+ ret_type=t.ret_type.accept(self),
499
+ type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None),
500
+ type_is=(t.type_is.accept(self) if t.type_is is not None else None),
501
+ )
502
+ if needs_normalization:
503
+ return expanded.with_normalized_var_args()
504
+ return expanded
505
+
506
+ def visit_overloaded(self, t: Overloaded) -> Type:
507
+ items: list[CallableType] = []
508
+ for item in t.items:
509
+ new_item = item.accept(self)
510
+ assert isinstance(new_item, ProperType)
511
+ assert isinstance(new_item, CallableType)
512
+ items.append(new_item)
513
+ return Overloaded(items)
514
+
515
+ def expand_type_list_with_unpack(self, typs: list[Type]) -> list[Type]:
516
+ """Expands a list of types that has an unpack."""
517
+ items: list[Type] = []
518
+ for item in typs:
519
+ if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType):
520
+ items.extend(self.expand_unpack(item))
521
+ else:
522
+ items.append(item.accept(self))
523
+ return items
524
+
525
+ def expand_type_tuple_with_unpack(self, typs: tuple[Type, ...]) -> list[Type]:
526
+ """Expands a tuple of types that has an unpack."""
527
+ # Micro-optimization: Specialized variant of expand_type_list_with_unpack
528
+ items: list[Type] = []
529
+ for item in typs:
530
+ if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType):
531
+ items.extend(self.expand_unpack(item))
532
+ else:
533
+ items.append(item.accept(self))
534
+ return items
535
+
536
+ def visit_tuple_type(self, t: TupleType) -> Type:
537
+ items = self.expand_type_list_with_unpack(t.items)
538
+ if len(items) == 1:
539
+ # Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...]
540
+ item = items[0]
541
+ if isinstance(item, UnpackType):
542
+ unpacked = get_proper_type(item.type)
543
+ if isinstance(unpacked, Instance):
544
+ # expand_type() may be called during semantic analysis, before invalid unpacks are fixed.
545
+ if unpacked.type.fullname != "builtins.tuple":
546
+ return t.partial_fallback.accept(self)
547
+ if t.partial_fallback.type.fullname != "builtins.tuple":
548
+ # If it is a subtype (like named tuple) we need to preserve it,
549
+ # this essentially mimics the logic in tuple_fallback().
550
+ return t.partial_fallback.accept(self)
551
+ return unpacked
552
+ fallback = t.partial_fallback.accept(self)
553
+ assert isinstance(fallback, ProperType) and isinstance(fallback, Instance)
554
+ return t.copy_modified(items=items, fallback=fallback)
555
+
556
+ def visit_typeddict_type(self, t: TypedDictType) -> Type:
557
+ if cached := self.get_cached(t):
558
+ return cached
559
+ fallback = t.fallback.accept(self)
560
+ assert isinstance(fallback, ProperType) and isinstance(fallback, Instance)
561
+ result = t.copy_modified(item_types=self.expand_types(t.items.values()), fallback=fallback)
562
+ self.set_cached(t, result)
563
+ return result
564
+
565
+ def visit_literal_type(self, t: LiteralType) -> Type:
566
+ # TODO: Verify this implementation is correct
567
+ return t
568
+
569
+ def visit_union_type(self, t: UnionType) -> Type:
570
+ # Use cache to avoid O(n**2) or worse expansion of types during translation
571
+ # (only for large unions, since caching adds overhead)
572
+ use_cache = len(t.items) > 3
573
+ if use_cache and (cached := self.get_cached(t)):
574
+ return cached
575
+
576
+ expanded = self.expand_types(t.items)
577
+ # After substituting for type variables in t.items, some resulting types
578
+ # might be subtypes of others, however calling make_simplified_union()
579
+ # can cause recursion, so we just remove strict duplicates.
580
+ simplified = UnionType.make_union(
581
+ remove_trivial(flatten_nested_unions(expanded)), t.line, t.column
582
+ )
583
+ # This call to get_proper_type() is unfortunate but is required to preserve
584
+ # the invariant that ProperType will stay ProperType after applying expand_type(),
585
+ # otherwise a single item union of a type alias will break it. Note this should not
586
+ # cause infinite recursion since pathological aliases like A = Union[A, B] are
587
+ # banned at the semantic analysis level.
588
+ result = get_proper_type(simplified)
589
+
590
+ if use_cache:
591
+ self.set_cached(t, result)
592
+ return result
593
+
594
+ def visit_partial_type(self, t: PartialType) -> Type:
595
+ return t
596
+
597
+ def visit_type_type(self, t: TypeType) -> Type:
598
+ # TODO: Verify that the new item type is valid (instance or
599
+ # union of instances or Any). Sadly we can't report errors
600
+ # here yet.
601
+ item = t.item.accept(self)
602
+ return TypeType.make_normalized(item, is_type_form=t.is_type_form)
603
+
604
+ def visit_type_alias_type(self, t: TypeAliasType) -> Type:
605
+ # Target of the type alias cannot contain type variables (not bound by the type
606
+ # alias itself), so we just expand the arguments.
607
+ if len(t.args) == 0:
608
+ return t
609
+ args = self.expand_type_list_with_unpack(t.args)
610
+ # TODO: normalize if target is Tuple, and args are [*tuple[X, ...]]?
611
+ return t.copy_modified(args=args)
612
+
613
+ def expand_types(self, types: Iterable[Type]) -> list[Type]:
614
+ a: list[Type] = []
615
+ for t in types:
616
+ a.append(t.accept(self))
617
+ return a
618
+
619
+
620
+ @overload
621
+ def expand_self_type(var: Var, typ: ProperType, replacement: ProperType) -> ProperType: ...
622
+
623
+
624
+ @overload
625
+ def expand_self_type(var: Var, typ: Type, replacement: Type) -> Type: ...
626
+
627
+
628
+ def expand_self_type(var: Var, typ: Type, replacement: Type) -> Type:
629
+ """Expand appearances of Self type in a variable type."""
630
+ if var.info.self_type is not None and not var.is_property:
631
+ return expand_type(typ, {var.info.self_type.id: replacement})
632
+ return typ
633
+
634
+
635
+ def remove_trivial(types: Iterable[Type]) -> list[Type]:
636
+ """Make trivial simplifications on a list of types without calling is_subtype().
637
+
638
+ This makes following simplifications:
639
+ * Remove bottom types (taking into account strict optional setting)
640
+ * Remove everything else if there is an `object`
641
+ * Remove strict duplicate types
642
+ """
643
+ removed_none = False
644
+ new_types = []
645
+ all_types = set()
646
+ for t in types:
647
+ p_t = get_proper_type(t)
648
+ if isinstance(p_t, UninhabitedType):
649
+ continue
650
+ if isinstance(p_t, NoneType) and not state.strict_optional:
651
+ removed_none = True
652
+ continue
653
+ if isinstance(p_t, Instance) and p_t.type.fullname == "builtins.object":
654
+ return [p_t]
655
+ if p_t not in all_types:
656
+ new_types.append(t)
657
+ all_types.add(p_t)
658
+ if new_types:
659
+ return new_types
660
+ if removed_none:
661
+ return [NoneType()]
662
+ return [UninhabitedType()]
micromamba_root/Lib/site-packages/mypy/exportjson.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tool to convert binary mypy cache files (.ff) to JSON (.ff.json).
2
+
3
+ Usage:
4
+ python -m mypy.exportjson .mypy_cache/.../my_module.data.ff
5
+
6
+ The idea is to make caches introspectable once we've switched to a binary
7
+ cache format and removed support for the older JSON cache format.
8
+
9
+ This is primarily to support existing use cases that need to inspect
10
+ cache files, and to support debugging mypy caching issues. This means that
11
+ this doesn't necessarily need to be kept 1:1 up to date with changes in the
12
+ binary cache format (to simplify maintenance -- we don't want this to slow
13
+ down mypy development).
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import sys
19
+ from typing import Any, TypeAlias as _TypeAlias
20
+
21
+ from librt.internal import ReadBuffer, cache_version
22
+
23
+ from mypy.cache import CACHE_VERSION, CacheMeta
24
+ from mypy.nodes import (
25
+ FUNCBASE_FLAGS,
26
+ FUNCDEF_FLAGS,
27
+ VAR_FLAGS,
28
+ ClassDef,
29
+ DataclassTransformSpec,
30
+ Decorator,
31
+ FuncDef,
32
+ MypyFile,
33
+ OverloadedFuncDef,
34
+ OverloadPart,
35
+ ParamSpecExpr,
36
+ SymbolNode,
37
+ SymbolTable,
38
+ SymbolTableNode,
39
+ TypeAlias,
40
+ TypeInfo,
41
+ TypeVarExpr,
42
+ TypeVarTupleExpr,
43
+ Var,
44
+ get_flags,
45
+ node_kinds,
46
+ )
47
+ from mypy.types import (
48
+ NOT_READY,
49
+ AnyType,
50
+ CallableType,
51
+ ExtraAttrs,
52
+ Instance,
53
+ LiteralType,
54
+ NoneType,
55
+ Overloaded,
56
+ Parameters,
57
+ ParamSpecType,
58
+ TupleType,
59
+ Type,
60
+ TypeAliasType,
61
+ TypedDictType,
62
+ TypeType,
63
+ TypeVarTupleType,
64
+ TypeVarType,
65
+ UnboundType,
66
+ UninhabitedType,
67
+ UnionType,
68
+ UnpackType,
69
+ get_proper_type,
70
+ )
71
+
72
+ Json: _TypeAlias = dict[str, Any] | str
73
+
74
+
75
+ class Config:
76
+ def __init__(self, *, implicit_names: bool = True) -> None:
77
+ self.implicit_names = implicit_names
78
+
79
+
80
+ def convert_binary_cache_to_json(data: bytes, *, implicit_names: bool = True) -> Json:
81
+ tree = MypyFile.read(ReadBuffer(data))
82
+ return convert_mypy_file_to_json(tree, Config(implicit_names=implicit_names))
83
+
84
+
85
+ def convert_mypy_file_to_json(self: MypyFile, cfg: Config) -> Json:
86
+ return {
87
+ ".class": "MypyFile",
88
+ "_fullname": self._fullname,
89
+ "names": convert_symbol_table(self.names, cfg),
90
+ "is_stub": self.is_stub,
91
+ "path": self.path,
92
+ "is_partial_stub_package": self.is_partial_stub_package,
93
+ "future_import_flags": sorted(self.future_import_flags),
94
+ }
95
+
96
+
97
+ def convert_symbol_table(self: SymbolTable, cfg: Config) -> Json:
98
+ data: dict[str, Any] = {".class": "SymbolTable"}
99
+ for key, value in self.items():
100
+ # Skip __builtins__: it's a reference to the builtins
101
+ # module that gets added to every module by
102
+ # SemanticAnalyzerPass2.visit_file(), but it shouldn't be
103
+ # accessed by users of the module.
104
+ if key == "__builtins__" or value.no_serialize:
105
+ continue
106
+ if not cfg.implicit_names and key in {
107
+ "__spec__",
108
+ "__package__",
109
+ "__file__",
110
+ "__doc__",
111
+ "__annotations__",
112
+ "__name__",
113
+ }:
114
+ continue
115
+ data[key] = convert_symbol_table_node(value, cfg)
116
+ return data
117
+
118
+
119
+ def convert_symbol_table_node(self: SymbolTableNode, cfg: Config) -> Json:
120
+ data: dict[str, Any] = {".class": "SymbolTableNode", "kind": node_kinds[self.kind]}
121
+ if self.module_hidden:
122
+ data["module_hidden"] = True
123
+ if not self.module_public:
124
+ data["module_public"] = False
125
+ if self.implicit:
126
+ data["implicit"] = True
127
+ if self.plugin_generated:
128
+ data["plugin_generated"] = True
129
+ if self.cross_ref:
130
+ data["cross_ref"] = self.cross_ref
131
+ elif self.node is not None:
132
+ data["node"] = convert_symbol_node(self.node, cfg)
133
+ return data
134
+
135
+
136
+ def convert_symbol_node(self: SymbolNode, cfg: Config) -> Json:
137
+ if isinstance(self, FuncDef):
138
+ return convert_func_def(self)
139
+ elif isinstance(self, OverloadedFuncDef):
140
+ return convert_overloaded_func_def(self)
141
+ elif isinstance(self, Decorator):
142
+ return convert_decorator(self)
143
+ elif isinstance(self, Var):
144
+ return convert_var(self)
145
+ elif isinstance(self, TypeInfo):
146
+ return convert_type_info(self, cfg)
147
+ elif isinstance(self, TypeAlias):
148
+ return convert_type_alias(self)
149
+ elif isinstance(self, TypeVarExpr):
150
+ return convert_type_var_expr(self)
151
+ elif isinstance(self, ParamSpecExpr):
152
+ return convert_param_spec_expr(self)
153
+ elif isinstance(self, TypeVarTupleExpr):
154
+ return convert_type_var_tuple_expr(self)
155
+ return {"ERROR": f"{type(self)!r} unrecognized"}
156
+
157
+
158
+ def convert_func_def(self: FuncDef) -> Json:
159
+ return {
160
+ ".class": "FuncDef",
161
+ "name": self._name,
162
+ "fullname": self._fullname,
163
+ "arg_names": self.arg_names,
164
+ "arg_kinds": [int(x.value) for x in self.arg_kinds],
165
+ "type": None if self.type is None else convert_type(self.type),
166
+ "flags": get_flags(self, FUNCDEF_FLAGS),
167
+ "abstract_status": self.abstract_status,
168
+ # TODO: Do we need expanded, original_def?
169
+ "dataclass_transform_spec": (
170
+ None
171
+ if self.dataclass_transform_spec is None
172
+ else convert_dataclass_transform_spec(self.dataclass_transform_spec)
173
+ ),
174
+ "deprecated": self.deprecated,
175
+ "original_first_arg": self.original_first_arg,
176
+ }
177
+
178
+
179
+ def convert_dataclass_transform_spec(self: DataclassTransformSpec) -> Json:
180
+ return {
181
+ "eq_default": self.eq_default,
182
+ "order_default": self.order_default,
183
+ "kw_only_default": self.kw_only_default,
184
+ "frozen_default": self.frozen_default,
185
+ "field_specifiers": list(self.field_specifiers),
186
+ }
187
+
188
+
189
+ def convert_overloaded_func_def(self: OverloadedFuncDef) -> Json:
190
+ return {
191
+ ".class": "OverloadedFuncDef",
192
+ "items": [convert_overload_part(i) for i in self.items],
193
+ "type": None if self.type is None else convert_type(self.type),
194
+ "fullname": self._fullname,
195
+ "impl": None if self.impl is None else convert_overload_part(self.impl),
196
+ "flags": get_flags(self, FUNCBASE_FLAGS),
197
+ "deprecated": self.deprecated,
198
+ "setter_index": self.setter_index,
199
+ }
200
+
201
+
202
+ def convert_overload_part(self: OverloadPart) -> Json:
203
+ if isinstance(self, FuncDef):
204
+ return convert_func_def(self)
205
+ else:
206
+ return convert_decorator(self)
207
+
208
+
209
+ def convert_decorator(self: Decorator) -> Json:
210
+ return {
211
+ ".class": "Decorator",
212
+ "func": convert_func_def(self.func),
213
+ "var": convert_var(self.var),
214
+ "is_overload": self.is_overload,
215
+ }
216
+
217
+
218
+ def convert_var(self: Var) -> Json:
219
+ data: dict[str, Any] = {
220
+ ".class": "Var",
221
+ "name": self._name,
222
+ "fullname": self._fullname,
223
+ "type": None if self.type is None else convert_type(self.type),
224
+ "setter_type": None if self.setter_type is None else convert_type(self.setter_type),
225
+ "flags": get_flags(self, VAR_FLAGS),
226
+ }
227
+ if self.final_value is not None:
228
+ data["final_value"] = self.final_value
229
+ return data
230
+
231
+
232
+ def convert_type_info(self: TypeInfo, cfg: Config) -> Json:
233
+ data = {
234
+ ".class": "TypeInfo",
235
+ "module_name": self.module_name,
236
+ "fullname": self.fullname,
237
+ "names": convert_symbol_table(self.names, cfg),
238
+ "defn": convert_class_def(self.defn),
239
+ "abstract_attributes": self.abstract_attributes,
240
+ "type_vars": self.type_vars,
241
+ "has_param_spec_type": self.has_param_spec_type,
242
+ "bases": [convert_type(b) for b in self.bases],
243
+ "mro": self._mro_refs,
244
+ "_promote": [convert_type(p) for p in self._promote],
245
+ "alt_promote": None if self.alt_promote is None else convert_type(self.alt_promote),
246
+ "declared_metaclass": (
247
+ None if self.declared_metaclass is None else convert_type(self.declared_metaclass)
248
+ ),
249
+ "metaclass_type": (
250
+ None if self.metaclass_type is None else convert_type(self.metaclass_type)
251
+ ),
252
+ "tuple_type": None if self.tuple_type is None else convert_type(self.tuple_type),
253
+ "typeddict_type": (
254
+ None if self.typeddict_type is None else convert_typeddict_type(self.typeddict_type)
255
+ ),
256
+ "flags": get_flags(self, TypeInfo.FLAGS),
257
+ "metadata": self.metadata,
258
+ "slots": sorted(self.slots) if self.slots is not None else None,
259
+ "deletable_attributes": self.deletable_attributes,
260
+ "self_type": convert_type(self.self_type) if self.self_type is not None else None,
261
+ "dataclass_transform_spec": (
262
+ convert_dataclass_transform_spec(self.dataclass_transform_spec)
263
+ if self.dataclass_transform_spec is not None
264
+ else None
265
+ ),
266
+ "deprecated": self.deprecated,
267
+ }
268
+ return data
269
+
270
+
271
+ def convert_class_def(self: ClassDef) -> Json:
272
+ return {
273
+ ".class": "ClassDef",
274
+ "name": self.name,
275
+ "fullname": self.fullname,
276
+ "type_vars": [convert_type(v) for v in self.type_vars],
277
+ }
278
+
279
+
280
+ def convert_type_alias(self: TypeAlias) -> Json:
281
+ data: Json = {
282
+ ".class": "TypeAlias",
283
+ "fullname": self._fullname,
284
+ "module": self.module,
285
+ "target": convert_type(self.target),
286
+ "alias_tvars": [convert_type(v) for v in self.alias_tvars],
287
+ "no_args": self.no_args,
288
+ "normalized": self.normalized,
289
+ "python_3_12_type_alias": self.python_3_12_type_alias,
290
+ }
291
+ return data
292
+
293
+
294
+ def convert_type_var_expr(self: TypeVarExpr) -> Json:
295
+ return {
296
+ ".class": "TypeVarExpr",
297
+ "name": self._name,
298
+ "fullname": self._fullname,
299
+ "values": [convert_type(t) for t in self.values],
300
+ "upper_bound": convert_type(self.upper_bound),
301
+ "default": convert_type(self.default),
302
+ "variance": self.variance,
303
+ }
304
+
305
+
306
+ def convert_param_spec_expr(self: ParamSpecExpr) -> Json:
307
+ return {
308
+ ".class": "ParamSpecExpr",
309
+ "name": self._name,
310
+ "fullname": self._fullname,
311
+ "upper_bound": convert_type(self.upper_bound),
312
+ "default": convert_type(self.default),
313
+ "variance": self.variance,
314
+ }
315
+
316
+
317
+ def convert_type_var_tuple_expr(self: TypeVarTupleExpr) -> Json:
318
+ return {
319
+ ".class": "TypeVarTupleExpr",
320
+ "name": self._name,
321
+ "fullname": self._fullname,
322
+ "upper_bound": convert_type(self.upper_bound),
323
+ "tuple_fallback": convert_type(self.tuple_fallback),
324
+ "default": convert_type(self.default),
325
+ "variance": self.variance,
326
+ }
327
+
328
+
329
+ def convert_type(typ: Type) -> Json:
330
+ if type(typ) is TypeAliasType:
331
+ return convert_type_alias_type(typ)
332
+ typ = get_proper_type(typ)
333
+ if isinstance(typ, Instance):
334
+ return convert_instance(typ)
335
+ elif isinstance(typ, AnyType):
336
+ return convert_any_type(typ)
337
+ elif isinstance(typ, NoneType):
338
+ return convert_none_type(typ)
339
+ elif isinstance(typ, UnionType):
340
+ return convert_union_type(typ)
341
+ elif isinstance(typ, TupleType):
342
+ return convert_tuple_type(typ)
343
+ elif isinstance(typ, CallableType):
344
+ return convert_callable_type(typ)
345
+ elif isinstance(typ, Overloaded):
346
+ return convert_overloaded(typ)
347
+ elif isinstance(typ, LiteralType):
348
+ return convert_literal_type(typ)
349
+ elif isinstance(typ, TypeVarType):
350
+ return convert_type_var_type(typ)
351
+ elif isinstance(typ, TypeType):
352
+ return convert_type_type(typ)
353
+ elif isinstance(typ, UninhabitedType):
354
+ return convert_uninhabited_type(typ)
355
+ elif isinstance(typ, UnpackType):
356
+ return convert_unpack_type(typ)
357
+ elif isinstance(typ, ParamSpecType):
358
+ return convert_param_spec_type(typ)
359
+ elif isinstance(typ, TypeVarTupleType):
360
+ return convert_type_var_tuple_type(typ)
361
+ elif isinstance(typ, Parameters):
362
+ return convert_parameters(typ)
363
+ elif isinstance(typ, TypedDictType):
364
+ return convert_typeddict_type(typ)
365
+ elif isinstance(typ, UnboundType):
366
+ return convert_unbound_type(typ)
367
+ return {"ERROR": f"{type(typ)!r} unrecognized"}
368
+
369
+
370
+ def convert_instance(self: Instance) -> Json:
371
+ ready = self.type is not NOT_READY
372
+ if not self.args and not self.last_known_value and not self.extra_attrs:
373
+ if ready:
374
+ return self.type.fullname
375
+ elif self.type_ref:
376
+ return self.type_ref
377
+
378
+ data: dict[str, Any] = {
379
+ ".class": "Instance",
380
+ "type_ref": self.type.fullname if ready else self.type_ref,
381
+ "args": [convert_type(arg) for arg in self.args],
382
+ }
383
+ if self.last_known_value is not None:
384
+ data["last_known_value"] = convert_type(self.last_known_value)
385
+ data["extra_attrs"] = convert_extra_attrs(self.extra_attrs) if self.extra_attrs else None
386
+ return data
387
+
388
+
389
+ def convert_extra_attrs(self: ExtraAttrs) -> Json:
390
+ return {
391
+ ".class": "ExtraAttrs",
392
+ "attrs": {k: convert_type(v) for k, v in self.attrs.items()},
393
+ "immutable": sorted(self.immutable),
394
+ "mod_name": self.mod_name,
395
+ }
396
+
397
+
398
+ def convert_type_alias_type(self: TypeAliasType) -> Json:
399
+ data: Json = {
400
+ ".class": "TypeAliasType",
401
+ "type_ref": self.type_ref,
402
+ "args": [convert_type(arg) for arg in self.args],
403
+ }
404
+ return data
405
+
406
+
407
+ def convert_any_type(self: AnyType) -> Json:
408
+ return {
409
+ ".class": "AnyType",
410
+ "type_of_any": self.type_of_any,
411
+ "source_any": convert_type(self.source_any) if self.source_any is not None else None,
412
+ "missing_import_name": self.missing_import_name,
413
+ }
414
+
415
+
416
+ def convert_none_type(self: NoneType) -> Json:
417
+ return {".class": "NoneType"}
418
+
419
+
420
+ def convert_union_type(self: UnionType) -> Json:
421
+ return {
422
+ ".class": "UnionType",
423
+ "items": [convert_type(t) for t in self.items],
424
+ "uses_pep604_syntax": self.uses_pep604_syntax,
425
+ }
426
+
427
+
428
+ def convert_tuple_type(self: TupleType) -> Json:
429
+ return {
430
+ ".class": "TupleType",
431
+ "items": [convert_type(t) for t in self.items],
432
+ "partial_fallback": convert_type(self.partial_fallback),
433
+ "implicit": self.implicit,
434
+ }
435
+
436
+
437
+ def convert_literal_type(self: LiteralType) -> Json:
438
+ return {".class": "LiteralType", "value": self.value, "fallback": convert_type(self.fallback)}
439
+
440
+
441
+ def convert_type_var_type(self: TypeVarType) -> Json:
442
+ assert not self.id.is_meta_var()
443
+ return {
444
+ ".class": "TypeVarType",
445
+ "name": self.name,
446
+ "fullname": self.fullname,
447
+ "id": self.id.raw_id,
448
+ "namespace": self.id.namespace,
449
+ "values": [convert_type(v) for v in self.values],
450
+ "upper_bound": convert_type(self.upper_bound),
451
+ "default": convert_type(self.default),
452
+ "variance": self.variance,
453
+ }
454
+
455
+
456
+ def convert_callable_type(self: CallableType) -> Json:
457
+ return {
458
+ ".class": "CallableType",
459
+ "arg_types": [convert_type(t) for t in self.arg_types],
460
+ "arg_kinds": [int(x.value) for x in self.arg_kinds],
461
+ "arg_names": self.arg_names,
462
+ "ret_type": convert_type(self.ret_type),
463
+ "fallback": convert_type(self.fallback),
464
+ "name": self.name,
465
+ # We don't serialize the definition (only used for error messages).
466
+ "variables": [convert_type(v) for v in self.variables],
467
+ "is_ellipsis_args": self.is_ellipsis_args,
468
+ "implicit": self.implicit,
469
+ "is_bound": self.is_bound,
470
+ "type_guard": convert_type(self.type_guard) if self.type_guard is not None else None,
471
+ "type_is": convert_type(self.type_is) if self.type_is is not None else None,
472
+ "from_concatenate": self.from_concatenate,
473
+ "imprecise_arg_kinds": self.imprecise_arg_kinds,
474
+ "unpack_kwargs": self.unpack_kwargs,
475
+ }
476
+
477
+
478
+ def convert_overloaded(self: Overloaded) -> Json:
479
+ return {".class": "Overloaded", "items": [convert_type(t) for t in self.items]}
480
+
481
+
482
+ def convert_type_type(self: TypeType) -> Json:
483
+ return {".class": "TypeType", "item": convert_type(self.item)}
484
+
485
+
486
+ def convert_uninhabited_type(self: UninhabitedType) -> Json:
487
+ return {".class": "UninhabitedType"}
488
+
489
+
490
+ def convert_unpack_type(self: UnpackType) -> Json:
491
+ return {".class": "UnpackType", "type": convert_type(self.type)}
492
+
493
+
494
+ def convert_param_spec_type(self: ParamSpecType) -> Json:
495
+ assert not self.id.is_meta_var()
496
+ return {
497
+ ".class": "ParamSpecType",
498
+ "name": self.name,
499
+ "fullname": self.fullname,
500
+ "id": self.id.raw_id,
501
+ "namespace": self.id.namespace,
502
+ "flavor": self.flavor,
503
+ "upper_bound": convert_type(self.upper_bound),
504
+ "default": convert_type(self.default),
505
+ "prefix": convert_type(self.prefix),
506
+ }
507
+
508
+
509
+ def convert_type_var_tuple_type(self: TypeVarTupleType) -> Json:
510
+ assert not self.id.is_meta_var()
511
+ return {
512
+ ".class": "TypeVarTupleType",
513
+ "name": self.name,
514
+ "fullname": self.fullname,
515
+ "id": self.id.raw_id,
516
+ "namespace": self.id.namespace,
517
+ "upper_bound": convert_type(self.upper_bound),
518
+ "tuple_fallback": convert_type(self.tuple_fallback),
519
+ "default": convert_type(self.default),
520
+ "min_len": self.min_len,
521
+ }
522
+
523
+
524
+ def convert_parameters(self: Parameters) -> Json:
525
+ return {
526
+ ".class": "Parameters",
527
+ "arg_types": [convert_type(t) for t in self.arg_types],
528
+ "arg_kinds": [int(x.value) for x in self.arg_kinds],
529
+ "arg_names": self.arg_names,
530
+ "variables": [convert_type(tv) for tv in self.variables],
531
+ "imprecise_arg_kinds": self.imprecise_arg_kinds,
532
+ }
533
+
534
+
535
+ def convert_typeddict_type(self: TypedDictType) -> Json:
536
+ return {
537
+ ".class": "TypedDictType",
538
+ "items": [[n, convert_type(t)] for (n, t) in self.items.items()],
539
+ "required_keys": sorted(self.required_keys),
540
+ "readonly_keys": sorted(self.readonly_keys),
541
+ "fallback": convert_type(self.fallback),
542
+ }
543
+
544
+
545
+ def convert_unbound_type(self: UnboundType) -> Json:
546
+ return {
547
+ ".class": "UnboundType",
548
+ "name": self.name,
549
+ "args": [convert_type(a) for a in self.args],
550
+ "expr": self.original_str_expr,
551
+ "expr_fallback": self.original_str_fallback,
552
+ }
553
+
554
+
555
+ def convert_binary_cache_meta_to_json(data: bytes, data_file: str) -> Json:
556
+ assert (
557
+ data[0] == cache_version() and data[1] == CACHE_VERSION
558
+ ), "Cache file created by an incompatible mypy version"
559
+ meta = CacheMeta.read(ReadBuffer(data[2:]), data_file)
560
+ assert meta is not None, f"Error reading meta cache file associated with {data_file}"
561
+ return {
562
+ "id": meta.id,
563
+ "path": meta.path,
564
+ "mtime": meta.mtime,
565
+ "size": meta.size,
566
+ "hash": meta.hash,
567
+ "data_mtime": meta.data_mtime,
568
+ "dependencies": meta.dependencies,
569
+ "suppressed": meta.suppressed,
570
+ "options": meta.options,
571
+ "dep_prios": meta.dep_prios,
572
+ "dep_lines": meta.dep_lines,
573
+ "dep_hashes": [dep.hex() for dep in meta.dep_hashes],
574
+ "interface_hash": meta.interface_hash.hex(),
575
+ "version_id": meta.version_id,
576
+ "ignore_all": meta.ignore_all,
577
+ "plugin_data": meta.plugin_data,
578
+ }
579
+
580
+
581
+ def main() -> None:
582
+ parser = argparse.ArgumentParser(
583
+ description="Convert binary cache files to JSON. "
584
+ "Create files in the same directory with extra .json extension."
585
+ )
586
+ parser.add_argument(
587
+ "path", nargs="+", help="mypy cache data file to convert (.data.ff extension)"
588
+ )
589
+ args = parser.parse_args()
590
+ fnams: list[str] = args.path
591
+ for fnam in fnams:
592
+ if fnam.endswith(".data.ff"):
593
+ is_data = True
594
+ elif fnam.endswith(".meta.ff"):
595
+ is_data = False
596
+ else:
597
+ sys.exit(f"error: Expected .data.ff or .meta.ff extension, but got {fnam}")
598
+ with open(fnam, "rb") as f:
599
+ data = f.read()
600
+ if is_data:
601
+ json_data = convert_binary_cache_to_json(data)
602
+ else:
603
+ data_file = fnam.removesuffix(".meta.ff") + ".data.ff"
604
+ json_data = convert_binary_cache_meta_to_json(data, data_file)
605
+ new_fnam = fnam + ".json"
606
+ with open(new_fnam, "w") as f:
607
+ json.dump(json_data, f)
608
+ print(f"{fnam} -> {new_fnam}")
609
+
610
+
611
+ if __name__ == "__main__":
612
+ main()
micromamba_root/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/exprtotype.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Translate an Expression to a Type value."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+
7
+ from mypy.fastparse import parse_type_string
8
+ from mypy.nodes import (
9
+ MISSING_FALLBACK,
10
+ BytesExpr,
11
+ CallExpr,
12
+ ComplexExpr,
13
+ Context,
14
+ DictExpr,
15
+ EllipsisExpr,
16
+ Expression,
17
+ FloatExpr,
18
+ IndexExpr,
19
+ IntExpr,
20
+ ListExpr,
21
+ MemberExpr,
22
+ NameExpr,
23
+ OpExpr,
24
+ RefExpr,
25
+ StarExpr,
26
+ StrExpr,
27
+ SymbolTableNode,
28
+ TupleExpr,
29
+ UnaryExpr,
30
+ get_member_expr_fullname,
31
+ )
32
+ from mypy.options import Options
33
+ from mypy.types import (
34
+ ANNOTATED_TYPE_NAMES,
35
+ AnyType,
36
+ CallableArgument,
37
+ EllipsisType,
38
+ Instance,
39
+ ProperType,
40
+ RawExpressionType,
41
+ Type,
42
+ TypedDictType,
43
+ TypeList,
44
+ TypeOfAny,
45
+ UnboundType,
46
+ UnionType,
47
+ UnpackType,
48
+ )
49
+
50
+
51
+ class TypeTranslationError(Exception):
52
+ """Exception raised when an expression is not valid as a type."""
53
+
54
+
55
+ def _extract_argument_name(expr: Expression) -> str | None:
56
+ if isinstance(expr, NameExpr) and expr.name == "None":
57
+ return None
58
+ elif isinstance(expr, StrExpr):
59
+ return expr.value
60
+ else:
61
+ raise TypeTranslationError()
62
+
63
+
64
+ def expr_to_unanalyzed_type(
65
+ expr: Expression,
66
+ options: Options,
67
+ allow_new_syntax: bool = False,
68
+ _parent: Expression | None = None,
69
+ allow_unpack: bool = False,
70
+ lookup_qualified: Callable[[str, Context], SymbolTableNode | None] | None = None,
71
+ ) -> ProperType:
72
+ """Translate an expression to the corresponding type.
73
+
74
+ The result is not semantically analyzed. It can be UnboundType or TypeList.
75
+ Raise TypeTranslationError if the expression cannot represent a type.
76
+
77
+ If lookup_qualified is not provided, the expression is expected to be semantically
78
+ analyzed.
79
+
80
+ If allow_new_syntax is True, allow all type syntax independent of the target
81
+ Python version (used in stubs).
82
+
83
+ # TODO: a lot of code here is duplicated in fastparse.py, refactor this.
84
+ """
85
+ # The `parent` parameter is used in recursive calls to provide context for
86
+ # understanding whether an CallableArgument is ok.
87
+ name: str | None = None
88
+ if isinstance(expr, NameExpr):
89
+ name = expr.name
90
+ if name == "True":
91
+ return RawExpressionType(True, "builtins.bool", line=expr.line, column=expr.column)
92
+ elif name == "False":
93
+ return RawExpressionType(False, "builtins.bool", line=expr.line, column=expr.column)
94
+ else:
95
+ return UnboundType(name, line=expr.line, column=expr.column)
96
+ elif isinstance(expr, MemberExpr):
97
+ fullname = get_member_expr_fullname(expr)
98
+ if fullname:
99
+ return UnboundType(fullname, line=expr.line, column=expr.column)
100
+ else:
101
+ raise TypeTranslationError()
102
+ elif isinstance(expr, IndexExpr):
103
+ base = expr_to_unanalyzed_type(
104
+ expr.base, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified
105
+ )
106
+ if isinstance(base, UnboundType):
107
+ if base.args:
108
+ raise TypeTranslationError()
109
+ if isinstance(expr.index, TupleExpr):
110
+ args = expr.index.items
111
+ else:
112
+ args = [expr.index]
113
+
114
+ if isinstance(expr.base, RefExpr):
115
+ # Check if the type is Annotated[...]. For this we need the fullname,
116
+ # which must be looked up if the expression hasn't been semantically analyzed.
117
+ base_fullname = None
118
+ if lookup_qualified is not None:
119
+ sym = lookup_qualified(base.name, expr)
120
+ if sym and sym.node:
121
+ base_fullname = sym.node.fullname
122
+ else:
123
+ base_fullname = expr.base.fullname
124
+
125
+ if base_fullname is not None and base_fullname in ANNOTATED_TYPE_NAMES:
126
+ # TODO: this is not the optimal solution as we are basically getting rid
127
+ # of the Annotation definition and only returning the type information,
128
+ # losing all the annotations.
129
+ return expr_to_unanalyzed_type(
130
+ args[0], options, allow_new_syntax, expr, lookup_qualified=lookup_qualified
131
+ )
132
+ base.args = tuple(
133
+ expr_to_unanalyzed_type(
134
+ arg,
135
+ options,
136
+ allow_new_syntax,
137
+ expr,
138
+ allow_unpack=True,
139
+ lookup_qualified=lookup_qualified,
140
+ )
141
+ for arg in args
142
+ )
143
+ if not base.args:
144
+ base.empty_tuple_index = True
145
+ return base
146
+ else:
147
+ raise TypeTranslationError()
148
+ elif (
149
+ isinstance(expr, OpExpr)
150
+ and expr.op == "|"
151
+ and ((options.python_version >= (3, 10)) or allow_new_syntax)
152
+ ):
153
+ return UnionType(
154
+ [
155
+ expr_to_unanalyzed_type(
156
+ expr.left, options, allow_new_syntax, lookup_qualified=lookup_qualified
157
+ ),
158
+ expr_to_unanalyzed_type(
159
+ expr.right, options, allow_new_syntax, lookup_qualified=lookup_qualified
160
+ ),
161
+ ],
162
+ uses_pep604_syntax=True,
163
+ )
164
+ elif isinstance(expr, CallExpr) and isinstance(_parent, ListExpr):
165
+ c = expr.callee
166
+ names = []
167
+ # Go through the dotted member expr chain to get the full arg
168
+ # constructor name to look up
169
+ while True:
170
+ if isinstance(c, NameExpr):
171
+ names.append(c.name)
172
+ break
173
+ elif isinstance(c, MemberExpr):
174
+ names.append(c.name)
175
+ c = c.expr
176
+ else:
177
+ raise TypeTranslationError()
178
+ arg_const = ".".join(reversed(names))
179
+
180
+ # Go through the constructor args to get its name and type.
181
+ name = None
182
+ default_type = AnyType(TypeOfAny.unannotated)
183
+ typ: Type = default_type
184
+ for i, arg in enumerate(expr.args):
185
+ if expr.arg_names[i] is not None:
186
+ if expr.arg_names[i] == "name":
187
+ if name is not None:
188
+ # Two names
189
+ raise TypeTranslationError()
190
+ name = _extract_argument_name(arg)
191
+ continue
192
+ elif expr.arg_names[i] == "type":
193
+ if typ is not default_type:
194
+ # Two types
195
+ raise TypeTranslationError()
196
+ typ = expr_to_unanalyzed_type(
197
+ arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified
198
+ )
199
+ continue
200
+ else:
201
+ raise TypeTranslationError()
202
+ elif i == 0:
203
+ typ = expr_to_unanalyzed_type(
204
+ arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified
205
+ )
206
+ elif i == 1:
207
+ name = _extract_argument_name(arg)
208
+ else:
209
+ raise TypeTranslationError()
210
+ return CallableArgument(typ, name, arg_const, expr.line, expr.column)
211
+ elif isinstance(expr, ListExpr):
212
+ return TypeList(
213
+ [
214
+ expr_to_unanalyzed_type(
215
+ t,
216
+ options,
217
+ allow_new_syntax,
218
+ expr,
219
+ allow_unpack=True,
220
+ lookup_qualified=lookup_qualified,
221
+ )
222
+ for t in expr.items
223
+ ],
224
+ line=expr.line,
225
+ column=expr.column,
226
+ )
227
+ elif isinstance(expr, StrExpr):
228
+ return parse_type_string(expr.value, "builtins.str", expr.line, expr.column)
229
+ elif isinstance(expr, BytesExpr):
230
+ return parse_type_string(expr.value, "builtins.bytes", expr.line, expr.column)
231
+ elif isinstance(expr, UnaryExpr):
232
+ typ = expr_to_unanalyzed_type(
233
+ expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified
234
+ )
235
+ if isinstance(typ, RawExpressionType):
236
+ if isinstance(typ.literal_value, int):
237
+ if expr.op == "-":
238
+ typ.literal_value *= -1
239
+ return typ
240
+ elif expr.op == "+":
241
+ return typ
242
+ raise TypeTranslationError()
243
+ elif isinstance(expr, IntExpr):
244
+ return RawExpressionType(expr.value, "builtins.int", line=expr.line, column=expr.column)
245
+ elif isinstance(expr, FloatExpr):
246
+ # Floats are not valid parameters for RawExpressionType , so we just
247
+ # pass in 'None' for now. We'll report the appropriate error at a later stage.
248
+ return RawExpressionType(None, "builtins.float", line=expr.line, column=expr.column)
249
+ elif isinstance(expr, ComplexExpr):
250
+ # Same thing as above with complex numbers.
251
+ return RawExpressionType(None, "builtins.complex", line=expr.line, column=expr.column)
252
+ elif isinstance(expr, EllipsisExpr):
253
+ return EllipsisType(expr.line)
254
+ elif allow_unpack and isinstance(expr, StarExpr):
255
+ return UnpackType(
256
+ expr_to_unanalyzed_type(
257
+ expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified
258
+ ),
259
+ from_star_syntax=True,
260
+ )
261
+ elif isinstance(expr, DictExpr):
262
+ if not expr.items:
263
+ raise TypeTranslationError()
264
+ items: dict[str, Type] = {}
265
+ extra_items_from = []
266
+ for item_name, value in expr.items:
267
+ if not isinstance(item_name, StrExpr):
268
+ if item_name is None:
269
+ extra_items_from.append(
270
+ expr_to_unanalyzed_type(
271
+ value,
272
+ options,
273
+ allow_new_syntax,
274
+ expr,
275
+ lookup_qualified=lookup_qualified,
276
+ )
277
+ )
278
+ continue
279
+ raise TypeTranslationError()
280
+ items[item_name.value] = expr_to_unanalyzed_type(
281
+ value, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified
282
+ )
283
+ result = TypedDictType(
284
+ items, set(), set(), Instance(MISSING_FALLBACK, ()), expr.line, expr.column
285
+ )
286
+ result.extra_items_from = extra_items_from
287
+ return result
288
+ else:
289
+ raise TypeTranslationError()
micromamba_root/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/fastparse.py ADDED
@@ -0,0 +1,2256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import sys
5
+ import warnings
6
+ from collections.abc import Callable, Sequence
7
+ from typing import Any, Final, Literal, TypeVar, cast, overload
8
+
9
+ from mypy import defaults, errorcodes as codes, message_registry
10
+ from mypy.errors import Errors
11
+ from mypy.message_registry import ErrorMessage
12
+ from mypy.nodes import (
13
+ ARG_NAMED,
14
+ ARG_NAMED_OPT,
15
+ ARG_OPT,
16
+ ARG_POS,
17
+ ARG_STAR,
18
+ ARG_STAR2,
19
+ MISSING_FALLBACK,
20
+ PARAM_SPEC_KIND,
21
+ TYPE_VAR_KIND,
22
+ TYPE_VAR_TUPLE_KIND,
23
+ ArgKind,
24
+ Argument,
25
+ AssertStmt,
26
+ AssignmentExpr,
27
+ AssignmentStmt,
28
+ AwaitExpr,
29
+ Block,
30
+ BreakStmt,
31
+ BytesExpr,
32
+ CallExpr,
33
+ ClassDef,
34
+ ComparisonExpr,
35
+ ComplexExpr,
36
+ ConditionalExpr,
37
+ ContinueStmt,
38
+ Decorator,
39
+ DelStmt,
40
+ DictExpr,
41
+ DictionaryComprehension,
42
+ EllipsisExpr,
43
+ Expression,
44
+ ExpressionStmt,
45
+ FloatExpr,
46
+ ForStmt,
47
+ FuncDef,
48
+ GeneratorExpr,
49
+ GlobalDecl,
50
+ IfStmt,
51
+ Import,
52
+ ImportAll,
53
+ ImportBase,
54
+ ImportFrom,
55
+ IndexExpr,
56
+ IntExpr,
57
+ LambdaExpr,
58
+ ListComprehension,
59
+ ListExpr,
60
+ MatchStmt,
61
+ MemberExpr,
62
+ MypyFile,
63
+ NameExpr,
64
+ Node,
65
+ NonlocalDecl,
66
+ OperatorAssignmentStmt,
67
+ OpExpr,
68
+ OverloadedFuncDef,
69
+ OverloadPart,
70
+ PassStmt,
71
+ RaiseStmt,
72
+ RefExpr,
73
+ ReturnStmt,
74
+ SetComprehension,
75
+ SetExpr,
76
+ SliceExpr,
77
+ StarExpr,
78
+ Statement,
79
+ StrExpr,
80
+ SuperExpr,
81
+ TemplateStrExpr,
82
+ TempNode,
83
+ TryStmt,
84
+ TupleExpr,
85
+ TypeAliasStmt,
86
+ TypeParam,
87
+ UnaryExpr,
88
+ Var,
89
+ WhileStmt,
90
+ WithStmt,
91
+ YieldExpr,
92
+ YieldFromExpr,
93
+ check_param_names,
94
+ )
95
+ from mypy.options import Options
96
+ from mypy.patterns import (
97
+ AsPattern,
98
+ ClassPattern,
99
+ MappingPattern,
100
+ OrPattern,
101
+ SequencePattern,
102
+ SingletonPattern,
103
+ StarredPattern,
104
+ ValuePattern,
105
+ )
106
+ from mypy.reachability import infer_reachability_of_if_statement, mark_block_unreachable
107
+ from mypy.sharedparse import argument_elide_name, special_function_elide_names
108
+ from mypy.traverser import TraverserVisitor
109
+ from mypy.types import (
110
+ AnyType,
111
+ CallableArgument,
112
+ CallableType,
113
+ EllipsisType,
114
+ Instance,
115
+ ProperType,
116
+ RawExpressionType,
117
+ TupleType,
118
+ Type,
119
+ TypedDictType,
120
+ TypeList,
121
+ TypeOfAny,
122
+ UnboundType,
123
+ UnionType,
124
+ UnpackType,
125
+ )
126
+ from mypy.util import bytes_to_human_readable_repr, unnamed_function
127
+
128
+ # pull this into a final variable to make mypyc be quiet about the
129
+ # the default argument warning
130
+ PY_MINOR_VERSION: Final = sys.version_info[1]
131
+
132
+ import ast as ast3
133
+ from ast import AST, Attribute, Call, FunctionType, Name, Starred, UAdd, UnaryOp, USub
134
+
135
+
136
+ def ast3_parse(
137
+ source: str | bytes, filename: str, mode: str, feature_version: int = PY_MINOR_VERSION
138
+ ) -> AST:
139
+ # Ignore warnings that look like:
140
+ # <type_comment>:1: SyntaxWarning: invalid escape sequence '\.'
141
+ # because `source` could be anything, including literals like r'(re\.match)'
142
+ with warnings.catch_warnings():
143
+ warnings.simplefilter("ignore", SyntaxWarning)
144
+ return ast3.parse(
145
+ source,
146
+ filename,
147
+ mode,
148
+ type_comments=True, # This works the magic
149
+ feature_version=feature_version,
150
+ )
151
+
152
+
153
+ AstNode = ast3.expr | ast3.stmt | ast3.pattern | ast3.ExceptHandler
154
+
155
+ if sys.version_info >= (3, 11):
156
+ TryStar = ast3.TryStar
157
+ else:
158
+ TryStar = Any
159
+
160
+ if sys.version_info >= (3, 12):
161
+ ast_TypeAlias = ast3.TypeAlias
162
+ ast_ParamSpec = ast3.ParamSpec
163
+ ast_TypeVar = ast3.TypeVar
164
+ ast_TypeVarTuple = ast3.TypeVarTuple
165
+ else:
166
+ ast_TypeAlias = Any
167
+ ast_ParamSpec = Any
168
+ ast_TypeVar = Any
169
+ ast_TypeVarTuple = Any
170
+
171
+ if sys.version_info >= (3, 14):
172
+ ast_TemplateStr = ast3.TemplateStr
173
+ ast_Interpolation = ast3.Interpolation
174
+ else:
175
+ ast_TemplateStr = Any
176
+ ast_Interpolation = Any
177
+
178
+ N = TypeVar("N", bound=Node)
179
+
180
+ # There is no way to create reasonable fallbacks at this stage,
181
+ # they must be patched later.
182
+ _dummy_fallback: Final = Instance(MISSING_FALLBACK, [], -1)
183
+
184
+ TYPE_IGNORE_PATTERN: Final = re.compile(r"[^#]*#\s*type:\s*ignore\s*(.*)")
185
+
186
+
187
+ def parse(
188
+ source: str | bytes,
189
+ fnam: str,
190
+ module: str | None,
191
+ errors: Errors,
192
+ options: Options | None = None,
193
+ ) -> MypyFile:
194
+ """Parse a source file, without doing any semantic analysis.
195
+
196
+ Return the parse tree. If errors is not provided, raise ParseError
197
+ on failure. Otherwise, use the errors object to report parse errors.
198
+ """
199
+ ignore_errors = (options is not None and options.ignore_errors) or (
200
+ fnam in errors.ignored_files
201
+ )
202
+ # If errors are ignored, we can drop many function bodies to speed up type checking.
203
+ strip_function_bodies = ignore_errors and (options is None or not options.preserve_asts)
204
+
205
+ if options is None:
206
+ options = Options()
207
+ errors.set_file(fnam, module, options=options)
208
+ is_stub_file = fnam.endswith(".pyi")
209
+ if is_stub_file:
210
+ feature_version = defaults.PYTHON3_VERSION[1]
211
+ if options.python_version[0] == 3 and options.python_version[1] > feature_version:
212
+ feature_version = options.python_version[1]
213
+ else:
214
+ assert options.python_version[0] >= 3
215
+ feature_version = options.python_version[1]
216
+ try:
217
+ # Disable
218
+ # - deprecation warnings for 'invalid escape sequence' (Python 3.11 and below)
219
+ # - syntax warnings for 'invalid escape sequence' (3.12+) and 'return in finally' (3.14+)
220
+ with warnings.catch_warnings():
221
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
222
+ warnings.filterwarnings("ignore", category=SyntaxWarning)
223
+ ast = ast3_parse(source, fnam, "exec", feature_version=feature_version)
224
+
225
+ tree = ASTConverter(
226
+ options=options,
227
+ is_stub=is_stub_file,
228
+ errors=errors,
229
+ strip_function_bodies=strip_function_bodies,
230
+ path=fnam,
231
+ ).visit(ast)
232
+
233
+ except RecursionError as e:
234
+ # For very complex expressions it is possible to hit recursion limit
235
+ # before reaching a leaf node.
236
+ # Should reject at top level instead at bottom, since bottom would already
237
+ # be at the threshold of the recursion limit, and may fail again later.
238
+ # E.G. x1+x2+x3+...+xn -> BinOp(left=BinOp(left=BinOp(left=...
239
+ try:
240
+ # But to prove that is the cause of this particular recursion error,
241
+ # try to walk the tree using builtin visitor
242
+ ast3.NodeVisitor().visit(ast)
243
+ except RecursionError:
244
+ errors.report(
245
+ -1, -1, "Source expression too complex to parse", blocker=False, code=codes.MISC
246
+ )
247
+
248
+ tree = MypyFile([], [], False, {})
249
+
250
+ else:
251
+ # re-raise original recursion error if it *can* be unparsed,
252
+ # maybe this is some other issue that shouldn't be silenced/misdirected
253
+ raise e
254
+
255
+ except SyntaxError as e:
256
+ message = e.msg
257
+ if feature_version > sys.version_info.minor and message.startswith("invalid syntax"):
258
+ python_version_str = f"{options.python_version[0]}.{options.python_version[1]}"
259
+ message += f"; you likely need to run mypy using Python {python_version_str} or newer"
260
+ errors.report(
261
+ e.lineno if e.lineno is not None else -1,
262
+ e.offset,
263
+ re.sub(
264
+ r"^(\s*\w)", lambda m: m.group(1).upper(), message
265
+ ), # Standardizing error message
266
+ blocker=True,
267
+ code=codes.SYNTAX,
268
+ )
269
+ tree = MypyFile([], [], False, {})
270
+
271
+ assert isinstance(tree, MypyFile)
272
+ return tree
273
+
274
+
275
+ def parse_type_ignore_tag(tag: str | None) -> list[str] | None:
276
+ """Parse optional "[code, ...]" tag after "# type: ignore".
277
+
278
+ Return:
279
+ * [] if no tag was found (ignore all errors)
280
+ * list of ignored error codes if a tag was found
281
+ * None if the tag was invalid.
282
+ """
283
+ if not tag or tag.strip() == "" or tag.strip().startswith("#"):
284
+ # No tag -- ignore all errors.
285
+ return []
286
+ m = re.match(r"\s*\[([^]#]*)\]\s*(#.*)?$", tag)
287
+ if m is None:
288
+ # Invalid "# type: ignore" comment.
289
+ return None
290
+ return [stripped_code for code in m.group(1).split(",") if (stripped_code := code.strip())]
291
+
292
+
293
+ def parse_type_comment(
294
+ type_comment: str, line: int, column: int, errors: Errors | None
295
+ ) -> tuple[list[str] | None, ProperType | None]:
296
+ """Parse type portion of a type comment (+ optional type ignore).
297
+
298
+ Return (ignore info, parsed type).
299
+ """
300
+ try:
301
+ typ = ast3_parse(type_comment, "<type_comment>", "eval")
302
+ except SyntaxError:
303
+ if errors is not None:
304
+ stripped_type = type_comment.split("#", 2)[0].strip()
305
+ err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type)
306
+ errors.report(line, column, err_msg.value, blocker=True, code=err_msg.code)
307
+ return None, None
308
+ else:
309
+ raise
310
+ else:
311
+ extra_ignore = TYPE_IGNORE_PATTERN.match(type_comment)
312
+ if extra_ignore:
313
+ tag: str | None = extra_ignore.group(1)
314
+ ignored: list[str] | None = parse_type_ignore_tag(tag)
315
+ if ignored is None:
316
+ if errors is not None:
317
+ errors.report(
318
+ line, column, message_registry.INVALID_TYPE_IGNORE.value, code=codes.SYNTAX
319
+ )
320
+ else:
321
+ raise SyntaxError
322
+ else:
323
+ ignored = None
324
+ assert isinstance(typ, ast3.Expression)
325
+ converted = TypeConverter(
326
+ errors, line=line, override_column=column, is_evaluated=False
327
+ ).visit(typ.body)
328
+ return ignored, converted
329
+
330
+
331
+ def parse_type_string(
332
+ expr_string: str, expr_fallback_name: str, line: int, column: int
333
+ ) -> ProperType:
334
+ """Parses a type that was originally present inside of an explicit string.
335
+
336
+ For example, suppose we have the type `Foo["blah"]`. We should parse the
337
+ string expression "blah" using this function.
338
+ """
339
+ try:
340
+ _, node = parse_type_comment(f"({expr_string})", line=line, column=column, errors=None)
341
+ if isinstance(node, (UnboundType, UnionType)) and node.original_str_expr is None:
342
+ node.original_str_expr = expr_string
343
+ node.original_str_fallback = expr_fallback_name
344
+ return node
345
+ else:
346
+ return RawExpressionType(expr_string, expr_fallback_name, line, column)
347
+ except (SyntaxError, ValueError):
348
+ # Note: the parser will raise a `ValueError` instead of a SyntaxError if
349
+ # the string happens to contain things like \x00.
350
+ return RawExpressionType(expr_string, expr_fallback_name, line, column)
351
+
352
+
353
+ def is_no_type_check_decorator(expr: ast3.expr) -> bool:
354
+ if isinstance(expr, Name):
355
+ return expr.id == "no_type_check"
356
+ elif isinstance(expr, Attribute):
357
+ if isinstance(expr.value, Name):
358
+ return expr.value.id == "typing" and expr.attr == "no_type_check"
359
+ return False
360
+
361
+
362
+ def find_disallowed_expression_in_annotation_scope(expr: ast3.expr | None) -> ast3.expr | None:
363
+ if expr is None:
364
+ return None
365
+ for node in ast3.walk(expr):
366
+ if isinstance(node, (ast3.Yield, ast3.YieldFrom, ast3.NamedExpr, ast3.Await)):
367
+ return node
368
+ return None
369
+
370
+
371
+ class ASTConverter:
372
+ def __init__(
373
+ self,
374
+ options: Options,
375
+ is_stub: bool,
376
+ errors: Errors,
377
+ *,
378
+ strip_function_bodies: bool,
379
+ path: str,
380
+ ) -> None:
381
+ # 'C' for class, 'D' for function signature, 'F' for function, 'L' for lambda
382
+ self.class_and_function_stack: list[Literal["C", "D", "F", "L"]] = []
383
+ self.imports: list[ImportBase] = []
384
+
385
+ self.options = options
386
+ self.is_stub = is_stub
387
+ self.errors = errors
388
+ self.strip_function_bodies = strip_function_bodies
389
+ self.path = path
390
+
391
+ self.type_ignores: dict[int, list[str]] = {}
392
+ self.uses_template_strings = False
393
+
394
+ # Cache of visit_X methods keyed by type of visited object
395
+ self.visitor_cache: dict[type, Callable[[AST | None], Any]] = {}
396
+
397
+ def note(self, msg: str, line: int, column: int) -> None:
398
+ self.errors.report(line, column, msg, severity="note", code=codes.SYNTAX)
399
+
400
+ def fail(self, msg: ErrorMessage, line: int, column: int, blocker: bool) -> None:
401
+ if blocker or not self.options.ignore_errors:
402
+ # Make sure self.errors reflects any type ignores that we have parsed
403
+ self.errors.set_file_ignored_lines(
404
+ self.path, self.type_ignores, self.options.ignore_errors
405
+ )
406
+ self.errors.report(line, column, msg.value, blocker=blocker, code=msg.code)
407
+
408
+ def fail_merge_overload(self, node: IfStmt) -> None:
409
+ self.fail(
410
+ message_registry.FAILED_TO_MERGE_OVERLOADS,
411
+ line=node.line,
412
+ column=node.column,
413
+ blocker=False,
414
+ )
415
+
416
+ def visit(self, node: AST | None) -> Any:
417
+ if node is None:
418
+ return None
419
+ typeobj = type(node)
420
+ visitor = self.visitor_cache.get(typeobj)
421
+ if visitor is None:
422
+ method = "visit_" + node.__class__.__name__
423
+ visitor = getattr(self, method)
424
+ self.visitor_cache[typeobj] = visitor
425
+
426
+ return visitor(node)
427
+
428
+ def set_line(self, node: N, n: AstNode) -> N:
429
+ node.line = n.lineno
430
+ node.column = n.col_offset
431
+ node.end_line = n.end_lineno
432
+ node.end_column = n.end_col_offset
433
+
434
+ return node
435
+
436
+ def translate_opt_expr_list(self, l: Sequence[AST | None]) -> list[Expression | None]:
437
+ res: list[Expression | None] = []
438
+ for e in l:
439
+ exp = self.visit(e)
440
+ res.append(exp)
441
+ return res
442
+
443
+ def translate_expr_list(self, l: Sequence[AST]) -> list[Expression]:
444
+ return cast(list[Expression], self.translate_opt_expr_list(l))
445
+
446
+ def get_lineno(self, node: ast3.expr | ast3.stmt) -> int:
447
+ if (
448
+ isinstance(node, (ast3.AsyncFunctionDef, ast3.ClassDef, ast3.FunctionDef))
449
+ and node.decorator_list
450
+ ):
451
+ return node.decorator_list[0].lineno
452
+ return node.lineno
453
+
454
+ def translate_stmt_list(
455
+ self,
456
+ stmts: Sequence[ast3.stmt],
457
+ *,
458
+ ismodule: bool = False,
459
+ can_strip: bool = False,
460
+ is_coroutine: bool = False,
461
+ ) -> list[Statement]:
462
+ # A "# type: ignore" comment before the first statement of a module
463
+ # ignores the whole module:
464
+ if (
465
+ ismodule
466
+ and stmts
467
+ and self.type_ignores
468
+ and (first := min(self.type_ignores)) < self.get_lineno(stmts[0])
469
+ ):
470
+ ignores = self.type_ignores.pop(first)
471
+ if ignores:
472
+ joined_ignores = ", ".join(ignores)
473
+ self.fail(
474
+ message_registry.TYPE_IGNORE_WITH_ERRCODE_ON_MODULE.format(joined_ignores),
475
+ line=first,
476
+ column=0,
477
+ blocker=False,
478
+ )
479
+ block = Block(self.fix_function_overloads(self.translate_stmt_list(stmts)))
480
+ self.set_block_lines(block, stmts)
481
+ mark_block_unreachable(block)
482
+ return [block]
483
+
484
+ stack = self.class_and_function_stack
485
+ # Fast case for stripping function bodies
486
+ if (
487
+ can_strip
488
+ and self.strip_function_bodies
489
+ and len(stack) == 1
490
+ and stack[0] == "F"
491
+ and not is_coroutine
492
+ ):
493
+ return []
494
+
495
+ res: list[Statement] = []
496
+ for stmt in stmts:
497
+ node = self.visit(stmt)
498
+ res.append(node)
499
+
500
+ # Slow case for stripping function bodies
501
+ if can_strip and self.strip_function_bodies:
502
+ if stack[-2:] == ["C", "F"]:
503
+ if is_possible_trivial_body(res):
504
+ can_strip = False
505
+ else:
506
+ # We only strip method bodies if they don't assign to an attribute, as
507
+ # this may define an attribute which has an externally visible effect.
508
+ visitor = FindAttributeAssign()
509
+ for s in res:
510
+ s.accept(visitor)
511
+ if visitor.found:
512
+ can_strip = False
513
+ break
514
+
515
+ if can_strip and stack[-1] == "F" and is_coroutine:
516
+ # Yields inside an async function affect the return type and should not
517
+ # be stripped.
518
+ yield_visitor = FindYield()
519
+ for s in res:
520
+ s.accept(yield_visitor)
521
+ if yield_visitor.found:
522
+ can_strip = False
523
+ break
524
+
525
+ if can_strip:
526
+ return []
527
+ return res
528
+
529
+ def translate_type_comment(
530
+ self, n: ast3.stmt | ast3.arg, type_comment: str | None
531
+ ) -> ProperType | None:
532
+ if type_comment is None:
533
+ return None
534
+ else:
535
+ lineno = n.lineno
536
+ extra_ignore, typ = parse_type_comment(type_comment, lineno, n.col_offset, self.errors)
537
+ if extra_ignore is not None:
538
+ self.type_ignores[lineno] = extra_ignore
539
+ return typ
540
+
541
+ op_map: Final[dict[type[AST], str]] = {
542
+ ast3.Add: "+",
543
+ ast3.Sub: "-",
544
+ ast3.Mult: "*",
545
+ ast3.MatMult: "@",
546
+ ast3.Div: "/",
547
+ ast3.Mod: "%",
548
+ ast3.Pow: "**",
549
+ ast3.LShift: "<<",
550
+ ast3.RShift: ">>",
551
+ ast3.BitOr: "|",
552
+ ast3.BitXor: "^",
553
+ ast3.BitAnd: "&",
554
+ ast3.FloorDiv: "//",
555
+ }
556
+
557
+ def from_operator(self, op: ast3.operator) -> str:
558
+ op_name = ASTConverter.op_map.get(type(op))
559
+ if op_name is None:
560
+ raise RuntimeError("Unknown operator " + str(type(op)))
561
+ else:
562
+ return op_name
563
+
564
+ comp_op_map: Final[dict[type[AST], str]] = {
565
+ ast3.Gt: ">",
566
+ ast3.Lt: "<",
567
+ ast3.Eq: "==",
568
+ ast3.GtE: ">=",
569
+ ast3.LtE: "<=",
570
+ ast3.NotEq: "!=",
571
+ ast3.Is: "is",
572
+ ast3.IsNot: "is not",
573
+ ast3.In: "in",
574
+ ast3.NotIn: "not in", # codespell:ignore notin
575
+ }
576
+
577
+ def from_comp_operator(self, op: ast3.cmpop) -> str:
578
+ op_name = ASTConverter.comp_op_map.get(type(op))
579
+ if op_name is None:
580
+ raise RuntimeError("Unknown comparison operator " + str(type(op)))
581
+ else:
582
+ return op_name
583
+
584
+ def set_block_lines(self, b: Block, stmts: Sequence[ast3.stmt]) -> None:
585
+ first, last = stmts[0], stmts[-1]
586
+ b.line = first.lineno
587
+ b.column = first.col_offset
588
+ b.end_line = last.end_lineno
589
+ b.end_column = last.end_col_offset
590
+ if not b.body:
591
+ return
592
+ new_first = b.body[0]
593
+ if isinstance(new_first, (Decorator, OverloadedFuncDef)):
594
+ # Decorated function lines are different between Python versions.
595
+ # copy the normalization we do for them to block first lines.
596
+ b.line = new_first.line
597
+ b.column = new_first.column
598
+
599
+ def as_block(self, stmts: list[ast3.stmt]) -> Block | None:
600
+ b = None
601
+ if stmts:
602
+ b = Block(self.fix_function_overloads(self.translate_stmt_list(stmts)))
603
+ self.set_block_lines(b, stmts)
604
+ return b
605
+
606
+ def as_required_block(
607
+ self, stmts: list[ast3.stmt], *, can_strip: bool = False, is_coroutine: bool = False
608
+ ) -> Block:
609
+ assert stmts # must be non-empty
610
+ b = Block(
611
+ self.fix_function_overloads(
612
+ self.translate_stmt_list(stmts, can_strip=can_strip, is_coroutine=is_coroutine)
613
+ )
614
+ )
615
+ self.set_block_lines(b, stmts)
616
+ return b
617
+
618
+ def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]:
619
+ ret: list[Statement] = []
620
+ current_overload: list[OverloadPart] = []
621
+ current_overload_name: str | None = None
622
+ last_unconditional_func_def: str | None = None
623
+ last_if_stmt: IfStmt | None = None
624
+ last_if_overload: Decorator | FuncDef | OverloadedFuncDef | None = None
625
+ last_if_stmt_overload_name: str | None = None
626
+ last_if_unknown_truth_value: IfStmt | None = None
627
+ skipped_if_stmts: list[IfStmt] = []
628
+ for stmt in stmts:
629
+ if_overload_name: str | None = None
630
+ if_block_with_overload: Block | None = None
631
+ if_unknown_truth_value: IfStmt | None = None
632
+ if isinstance(stmt, IfStmt):
633
+ # Check IfStmt block to determine if function overloads can be merged
634
+ if_overload_name = self._check_ifstmt_for_overloads(stmt, current_overload_name)
635
+ if if_overload_name is not None:
636
+ if_block_with_overload, if_unknown_truth_value = (
637
+ self._get_executable_if_block_with_overloads(stmt)
638
+ )
639
+
640
+ if (
641
+ current_overload_name is not None
642
+ and isinstance(stmt, (Decorator, FuncDef))
643
+ and stmt.name == current_overload_name
644
+ ):
645
+ if last_if_stmt is not None:
646
+ skipped_if_stmts.append(last_if_stmt)
647
+ if last_if_overload is not None:
648
+ # Last stmt was an IfStmt with same overload name
649
+ # Add overloads to current_overload
650
+ if isinstance(last_if_overload, OverloadedFuncDef):
651
+ current_overload.extend(last_if_overload.items)
652
+ else:
653
+ current_overload.append(last_if_overload)
654
+ last_if_stmt, last_if_overload = None, None
655
+ if last_if_unknown_truth_value:
656
+ self.fail_merge_overload(last_if_unknown_truth_value)
657
+ last_if_unknown_truth_value = None
658
+ current_overload.append(stmt)
659
+ if isinstance(stmt, FuncDef):
660
+ # This is, strictly speaking, wrong: there might be a decorated
661
+ # implementation. However, it only affects the error message we show:
662
+ # ideally it's "already defined", but "implementation must come last"
663
+ # is also reasonable.
664
+ # TODO: can we get rid of this completely and just always emit
665
+ # "implementation must come last" instead?
666
+ last_unconditional_func_def = stmt.name
667
+ elif (
668
+ current_overload_name is not None
669
+ and isinstance(stmt, IfStmt)
670
+ and if_overload_name == current_overload_name
671
+ and last_unconditional_func_def != current_overload_name
672
+ ):
673
+ # IfStmt only contains stmts relevant to current_overload.
674
+ # Check if stmts are reachable and add them to current_overload,
675
+ # otherwise skip IfStmt to allow subsequent overload
676
+ # or function definitions.
677
+ skipped_if_stmts.append(stmt)
678
+ if if_block_with_overload is None:
679
+ if if_unknown_truth_value is not None:
680
+ self.fail_merge_overload(if_unknown_truth_value)
681
+ continue
682
+ if last_if_overload is not None:
683
+ # Last stmt was an IfStmt with same overload name
684
+ # Add overloads to current_overload
685
+ if isinstance(last_if_overload, OverloadedFuncDef):
686
+ current_overload.extend(last_if_overload.items)
687
+ else:
688
+ current_overload.append(last_if_overload)
689
+ last_if_stmt, last_if_overload = None, None
690
+ if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef):
691
+ skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1]))
692
+ current_overload.extend(if_block_with_overload.body[-1].items)
693
+ else:
694
+ current_overload.append(
695
+ cast(Decorator | FuncDef, if_block_with_overload.body[0])
696
+ )
697
+ else:
698
+ if last_if_stmt is not None:
699
+ ret.append(last_if_stmt)
700
+ last_if_stmt_overload_name = current_overload_name
701
+ last_if_stmt, last_if_overload = None, None
702
+ last_if_unknown_truth_value = None
703
+
704
+ if current_overload and current_overload_name == last_if_stmt_overload_name:
705
+ # Remove last stmt (IfStmt) from ret if the overload names matched
706
+ # Only happens if no executable block had been found in IfStmt
707
+ popped = ret.pop()
708
+ assert isinstance(popped, IfStmt)
709
+ skipped_if_stmts.append(popped)
710
+ if current_overload and skipped_if_stmts:
711
+ # Add bare IfStmt (without overloads) to ret
712
+ # Required for mypy to be able to still check conditions
713
+ for if_stmt in skipped_if_stmts:
714
+ self._strip_contents_from_if_stmt(if_stmt)
715
+ ret.append(if_stmt)
716
+ skipped_if_stmts = []
717
+ if len(current_overload) == 1:
718
+ ret.append(current_overload[0])
719
+ elif len(current_overload) > 1:
720
+ ret.append(OverloadedFuncDef(current_overload))
721
+
722
+ # If we have multiple decorated functions named "_" next to each, we want to treat
723
+ # them as a series of regular FuncDefs instead of one OverloadedFuncDef because
724
+ # most of mypy/mypyc assumes that all the functions in an OverloadedFuncDef are
725
+ # related, but multiple underscore functions next to each other aren't necessarily
726
+ # related
727
+ last_unconditional_func_def = None
728
+ if isinstance(stmt, Decorator) and not unnamed_function(stmt.name):
729
+ current_overload = [stmt]
730
+ current_overload_name = stmt.name
731
+ elif isinstance(stmt, IfStmt) and if_overload_name is not None:
732
+ current_overload = []
733
+ current_overload_name = if_overload_name
734
+ last_if_stmt = stmt
735
+ last_if_stmt_overload_name = None
736
+ if if_block_with_overload is not None:
737
+ skipped_if_stmts.extend(
738
+ cast(list[IfStmt], if_block_with_overload.body[:-1])
739
+ )
740
+ last_if_overload = cast(
741
+ Decorator | FuncDef | OverloadedFuncDef,
742
+ if_block_with_overload.body[-1],
743
+ )
744
+ last_if_unknown_truth_value = if_unknown_truth_value
745
+ else:
746
+ current_overload = []
747
+ current_overload_name = None
748
+ ret.append(stmt)
749
+
750
+ if current_overload and skipped_if_stmts:
751
+ # Add bare IfStmt (without overloads) to ret
752
+ # Required for mypy to be able to still check conditions
753
+ for if_stmt in skipped_if_stmts:
754
+ self._strip_contents_from_if_stmt(if_stmt)
755
+ ret.append(if_stmt)
756
+ if len(current_overload) == 1:
757
+ ret.append(current_overload[0])
758
+ elif len(current_overload) > 1:
759
+ ret.append(OverloadedFuncDef(current_overload))
760
+ elif last_if_overload is not None:
761
+ ret.append(last_if_overload)
762
+ elif last_if_stmt is not None:
763
+ ret.append(last_if_stmt)
764
+ return ret
765
+
766
+ def _check_ifstmt_for_overloads(
767
+ self, stmt: IfStmt, current_overload_name: str | None = None
768
+ ) -> str | None:
769
+ """Check if IfStmt contains only overloads with the same name.
770
+ Return overload_name if found, None otherwise.
771
+ """
772
+ # Check that block only contains a single Decorator, FuncDef, or OverloadedFuncDef.
773
+ # Multiple overloads have already been merged as OverloadedFuncDef.
774
+ if not (
775
+ len(stmt.body[0].body) == 1
776
+ and (
777
+ isinstance(stmt.body[0].body[0], (Decorator, OverloadedFuncDef))
778
+ or current_overload_name is not None
779
+ and isinstance(stmt.body[0].body[0], FuncDef)
780
+ )
781
+ or len(stmt.body[0].body) > 1
782
+ and isinstance(stmt.body[0].body[-1], OverloadedFuncDef)
783
+ and all(self._is_stripped_if_stmt(if_stmt) for if_stmt in stmt.body[0].body[:-1])
784
+ ):
785
+ return None
786
+
787
+ overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name
788
+ if stmt.else_body is None:
789
+ return overload_name
790
+
791
+ if len(stmt.else_body.body) == 1:
792
+ # For elif: else_body contains an IfStmt itself -> do a recursive check.
793
+ if (
794
+ isinstance(stmt.else_body.body[0], (Decorator, FuncDef, OverloadedFuncDef))
795
+ and stmt.else_body.body[0].name == overload_name
796
+ ):
797
+ return overload_name
798
+ if (
799
+ isinstance(stmt.else_body.body[0], IfStmt)
800
+ and self._check_ifstmt_for_overloads(stmt.else_body.body[0], current_overload_name)
801
+ == overload_name
802
+ ):
803
+ return overload_name
804
+
805
+ return None
806
+
807
+ def _get_executable_if_block_with_overloads(
808
+ self, stmt: IfStmt
809
+ ) -> tuple[Block | None, IfStmt | None]:
810
+ """Return block from IfStmt that will get executed.
811
+
812
+ Return
813
+ 0 -> A block if sure that alternative blocks are unreachable.
814
+ 1 -> An IfStmt if the reachability of it can't be inferred,
815
+ i.e. the truth value is unknown.
816
+ """
817
+ infer_reachability_of_if_statement(stmt, self.options)
818
+ if stmt.else_body is None and stmt.body[0].is_unreachable is True:
819
+ # always False condition with no else
820
+ return None, None
821
+ if (
822
+ stmt.else_body is None
823
+ or stmt.body[0].is_unreachable is False
824
+ and stmt.else_body.is_unreachable is False
825
+ ):
826
+ # The truth value is unknown, thus not conclusive
827
+ return None, stmt
828
+ if stmt.else_body.is_unreachable is True:
829
+ # else_body will be set unreachable if condition is always True
830
+ return stmt.body[0], None
831
+ if stmt.body[0].is_unreachable is True:
832
+ # body will be set unreachable if condition is always False
833
+ # else_body can contain an IfStmt itself (for elif) -> do a recursive check
834
+ if isinstance(stmt.else_body.body[0], IfStmt):
835
+ return self._get_executable_if_block_with_overloads(stmt.else_body.body[0])
836
+ return stmt.else_body, None
837
+ return None, stmt
838
+
839
+ def _strip_contents_from_if_stmt(self, stmt: IfStmt) -> None:
840
+ """Remove contents from IfStmt.
841
+
842
+ Needed to still be able to check the conditions after the contents
843
+ have been merged with the surrounding function overloads.
844
+ """
845
+ if len(stmt.body) == 1:
846
+ stmt.body[0].body = []
847
+ if stmt.else_body and len(stmt.else_body.body) == 1:
848
+ if isinstance(stmt.else_body.body[0], IfStmt):
849
+ self._strip_contents_from_if_stmt(stmt.else_body.body[0])
850
+ else:
851
+ stmt.else_body.body = []
852
+
853
+ def _is_stripped_if_stmt(self, stmt: Statement) -> bool:
854
+ """Check stmt to make sure it is a stripped IfStmt.
855
+
856
+ See also: _strip_contents_from_if_stmt
857
+ """
858
+ if not isinstance(stmt, IfStmt):
859
+ return False
860
+
861
+ if not (len(stmt.body) == 1 and len(stmt.body[0].body) == 0):
862
+ # Body not empty
863
+ return False
864
+
865
+ if not stmt.else_body or len(stmt.else_body.body) == 0:
866
+ # No or empty else_body
867
+ return True
868
+
869
+ # For elif, IfStmt are stored recursively in else_body
870
+ return self._is_stripped_if_stmt(stmt.else_body.body[0])
871
+
872
+ def translate_module_id(self, id: str) -> str:
873
+ """Return the actual, internal module id for a source text id."""
874
+ if id == self.options.custom_typing_module:
875
+ return "typing"
876
+ return id
877
+
878
+ def visit_Module(self, mod: ast3.Module) -> MypyFile:
879
+ self.type_ignores = {}
880
+ self.uses_template_strings = False
881
+ for ti in mod.type_ignores:
882
+ parsed = parse_type_ignore_tag(ti.tag)
883
+ if parsed is not None:
884
+ self.type_ignores[ti.lineno] = parsed
885
+ else:
886
+ self.fail(message_registry.INVALID_TYPE_IGNORE, ti.lineno, -1, blocker=False)
887
+
888
+ body = self.fix_function_overloads(self.translate_stmt_list(mod.body, ismodule=True))
889
+
890
+ ret = MypyFile(body, self.imports, False, ignored_lines=self.type_ignores)
891
+ ret.is_stub = self.is_stub
892
+ ret.path = self.path
893
+ ret.uses_template_strings = self.uses_template_strings
894
+ return ret
895
+
896
+ # --- stmt ---
897
+ # FunctionDef(identifier name, arguments args,
898
+ # stmt* body, expr* decorator_list, expr? returns, string? type_comment)
899
+ # arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults,
900
+ # arg? kwarg, expr* defaults)
901
+ def visit_FunctionDef(self, n: ast3.FunctionDef) -> FuncDef | Decorator:
902
+ return self.do_func_def(n)
903
+
904
+ # AsyncFunctionDef(identifier name, arguments args,
905
+ # stmt* body, expr* decorator_list, expr? returns, string? type_comment)
906
+ def visit_AsyncFunctionDef(self, n: ast3.AsyncFunctionDef) -> FuncDef | Decorator:
907
+ return self.do_func_def(n, is_coroutine=True)
908
+
909
+ def do_func_def(
910
+ self, n: ast3.FunctionDef | ast3.AsyncFunctionDef, is_coroutine: bool = False
911
+ ) -> FuncDef | Decorator:
912
+ """Helper shared between visit_FunctionDef and visit_AsyncFunctionDef."""
913
+ self.class_and_function_stack.append("D")
914
+ no_type_check = bool(
915
+ n.decorator_list and any(is_no_type_check_decorator(d) for d in n.decorator_list)
916
+ )
917
+
918
+ lineno = n.lineno
919
+ args = self.transform_args(n.args, lineno, no_type_check=no_type_check)
920
+ if self.options.pos_only_special_methods and special_function_elide_names(n.name):
921
+ for arg in args:
922
+ arg.pos_only = True
923
+
924
+ arg_kinds = [arg.kind for arg in args]
925
+ arg_names = [None if arg.pos_only else arg.variable.name for arg in args]
926
+ # Type parameters, if using new syntax for generics (PEP 695)
927
+ explicit_type_params: list[TypeParam] | None = None
928
+
929
+ arg_types: list[Type | None] = []
930
+ if no_type_check:
931
+ arg_types = [None] * len(args)
932
+ return_type = None
933
+ elif n.type_comment is not None:
934
+ try:
935
+ func_type_ast = ast3_parse(n.type_comment, "<func_type>", "func_type")
936
+ assert isinstance(func_type_ast, FunctionType)
937
+ # for ellipsis arg
938
+ if (
939
+ len(func_type_ast.argtypes) == 1
940
+ and isinstance(func_type_ast.argtypes[0], ast3.Constant)
941
+ and func_type_ast.argtypes[0].value is Ellipsis
942
+ ):
943
+ if n.returns:
944
+ # PEP 484 disallows both type annotations and type comments
945
+ self.fail(
946
+ message_registry.DUPLICATE_TYPE_SIGNATURES,
947
+ lineno,
948
+ n.col_offset,
949
+ blocker=False,
950
+ )
951
+ arg_types = [
952
+ (
953
+ a.type_annotation
954
+ if a.type_annotation is not None
955
+ else AnyType(TypeOfAny.unannotated)
956
+ )
957
+ for a in args
958
+ ]
959
+ else:
960
+ # PEP 484 disallows both type annotations and type comments
961
+ if n.returns or any(a.type_annotation is not None for a in args):
962
+ self.fail(
963
+ message_registry.DUPLICATE_TYPE_SIGNATURES,
964
+ lineno,
965
+ n.col_offset,
966
+ blocker=False,
967
+ )
968
+ translated_args: list[Type] = TypeConverter(
969
+ self.errors, line=lineno, override_column=n.col_offset
970
+ ).translate_expr_list(func_type_ast.argtypes)
971
+ # Use a cast to work around `list` invariance
972
+ arg_types = cast(list[Type | None], translated_args)
973
+ return_type = TypeConverter(self.errors, line=lineno).visit(func_type_ast.returns)
974
+
975
+ # add implicit self type
976
+ in_method_scope = self.class_and_function_stack[-2:] == ["C", "D"]
977
+ if in_method_scope and len(arg_types) < len(args):
978
+ arg_types.insert(0, AnyType(TypeOfAny.special_form))
979
+ except SyntaxError:
980
+ stripped_type = n.type_comment.split("#", 2)[0].strip()
981
+ err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type)
982
+ self.fail(err_msg, lineno, n.col_offset, blocker=False)
983
+ if n.type_comment and n.type_comment[0] not in ["(", "#"]:
984
+ self.note(
985
+ "Suggestion: wrap argument types in parentheses", lineno, n.col_offset
986
+ )
987
+ arg_types = [AnyType(TypeOfAny.from_error)] * len(args)
988
+ return_type = AnyType(TypeOfAny.from_error)
989
+ else:
990
+ if sys.version_info >= (3, 12) and n.type_params:
991
+ explicit_type_params = self.translate_type_params(n.type_params)
992
+
993
+ arg_types = [a.type_annotation for a in args]
994
+ return_type = TypeConverter(
995
+ self.errors, line=n.returns.lineno if n.returns else lineno
996
+ ).visit(n.returns)
997
+
998
+ for arg, arg_type in zip(args, arg_types):
999
+ self.set_type_optional(arg_type, arg.initializer)
1000
+
1001
+ func_type = None
1002
+ if any(arg_types) or return_type:
1003
+ if len(arg_types) != 1 and any(isinstance(t, EllipsisType) for t in arg_types):
1004
+ self.fail(
1005
+ message_registry.ELLIPSIS_WITH_OTHER_TYPEPARAMS,
1006
+ lineno,
1007
+ n.col_offset,
1008
+ blocker=False,
1009
+ )
1010
+ elif len(arg_types) > len(arg_kinds):
1011
+ self.fail(
1012
+ message_registry.TYPE_SIGNATURE_TOO_MANY_PARAMS,
1013
+ lineno,
1014
+ n.col_offset,
1015
+ blocker=False,
1016
+ )
1017
+ elif len(arg_types) < len(arg_kinds):
1018
+ self.fail(
1019
+ message_registry.TYPE_SIGNATURE_TOO_FEW_PARAMS,
1020
+ lineno,
1021
+ n.col_offset,
1022
+ blocker=False,
1023
+ )
1024
+ else:
1025
+ func_type = CallableType(
1026
+ [a if a is not None else AnyType(TypeOfAny.unannotated) for a in arg_types],
1027
+ arg_kinds,
1028
+ arg_names,
1029
+ return_type if return_type is not None else AnyType(TypeOfAny.unannotated),
1030
+ _dummy_fallback,
1031
+ )
1032
+
1033
+ # End position is always the same.
1034
+ end_line = n.end_lineno
1035
+ end_column = n.end_col_offset
1036
+
1037
+ self.class_and_function_stack.pop()
1038
+ self.class_and_function_stack.append("F")
1039
+ body = self.as_required_block(n.body, can_strip=True, is_coroutine=is_coroutine)
1040
+ func_def = FuncDef(n.name, args, body, func_type, explicit_type_params)
1041
+ if isinstance(func_def.type, CallableType):
1042
+ # semanal.py does some in-place modifications we want to avoid
1043
+ func_def.unanalyzed_type = func_def.type.copy_modified()
1044
+ if is_coroutine:
1045
+ func_def.is_coroutine = True
1046
+ if func_type is not None:
1047
+ func_type.definition = func_def
1048
+ func_type.set_line(lineno)
1049
+
1050
+ if n.decorator_list:
1051
+ var = Var(func_def.name)
1052
+ var.is_ready = False
1053
+ var.set_line(lineno)
1054
+
1055
+ func_def.is_decorated = True
1056
+ self.set_line(func_def, n)
1057
+
1058
+ deco = Decorator(func_def, self.translate_expr_list(n.decorator_list), var)
1059
+ first = n.decorator_list[0]
1060
+ deco.set_line(first.lineno, first.col_offset, end_line, end_column)
1061
+ retval: FuncDef | Decorator = deco
1062
+ else:
1063
+ self.set_line(func_def, n)
1064
+ retval = func_def
1065
+ if self.options.include_docstrings:
1066
+ func_def.docstring = ast3.get_docstring(n, clean=False)
1067
+ self.class_and_function_stack.pop()
1068
+ return retval
1069
+
1070
+ def set_type_optional(self, type: Type | None, initializer: Expression | None) -> None:
1071
+ if not self.options.implicit_optional:
1072
+ return
1073
+ # Indicate that type should be wrapped in an Optional if arg is initialized to None.
1074
+ optional = isinstance(initializer, NameExpr) and initializer.name == "None"
1075
+ if isinstance(type, UnboundType):
1076
+ type.optional = optional
1077
+
1078
+ def transform_args(
1079
+ self, args: ast3.arguments, line: int, no_type_check: bool = False
1080
+ ) -> list[Argument]:
1081
+ new_args = []
1082
+ names: list[ast3.arg] = []
1083
+ posonlyargs = args.posonlyargs
1084
+ args_args = posonlyargs + args.args
1085
+ args_defaults = args.defaults
1086
+ num_no_defaults = len(args_args) - len(args_defaults)
1087
+ # positional arguments without defaults
1088
+ for i, a in enumerate(args_args[:num_no_defaults]):
1089
+ pos_only = i < len(posonlyargs)
1090
+ new_args.append(self.make_argument(a, None, ARG_POS, no_type_check, pos_only))
1091
+ names.append(a)
1092
+
1093
+ # positional arguments with defaults
1094
+ for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)):
1095
+ pos_only = num_no_defaults + i < len(posonlyargs)
1096
+ new_args.append(self.make_argument(a, d, ARG_OPT, no_type_check, pos_only))
1097
+ names.append(a)
1098
+
1099
+ # *arg
1100
+ if args.vararg is not None:
1101
+ new_args.append(self.make_argument(args.vararg, None, ARG_STAR, no_type_check))
1102
+ names.append(args.vararg)
1103
+
1104
+ # keyword-only arguments with defaults
1105
+ for a, kd in zip(args.kwonlyargs, args.kw_defaults):
1106
+ new_args.append(
1107
+ self.make_argument(
1108
+ a, kd, ARG_NAMED if kd is None else ARG_NAMED_OPT, no_type_check
1109
+ )
1110
+ )
1111
+ names.append(a)
1112
+
1113
+ # **kwarg
1114
+ if args.kwarg is not None:
1115
+ new_args.append(self.make_argument(args.kwarg, None, ARG_STAR2, no_type_check))
1116
+ names.append(args.kwarg)
1117
+
1118
+ check_param_names([arg.variable.name for arg in new_args], names, self.fail_arg)
1119
+
1120
+ return new_args
1121
+
1122
+ def make_argument(
1123
+ self,
1124
+ arg: ast3.arg,
1125
+ default: ast3.expr | None,
1126
+ kind: ArgKind,
1127
+ no_type_check: bool,
1128
+ pos_only: bool = False,
1129
+ ) -> Argument:
1130
+ if no_type_check:
1131
+ arg_type = None
1132
+ else:
1133
+ annotation = arg.annotation
1134
+ type_comment = arg.type_comment
1135
+ if annotation is not None and type_comment is not None:
1136
+ self.fail(
1137
+ message_registry.DUPLICATE_TYPE_SIGNATURES,
1138
+ arg.lineno,
1139
+ arg.col_offset,
1140
+ blocker=False,
1141
+ )
1142
+ arg_type = None
1143
+ if annotation is not None:
1144
+ arg_type = TypeConverter(self.errors, line=arg.lineno).visit(annotation)
1145
+ else:
1146
+ arg_type = self.translate_type_comment(arg, type_comment)
1147
+ if argument_elide_name(arg.arg):
1148
+ pos_only = True
1149
+
1150
+ var = Var(arg.arg, arg_type)
1151
+ var.is_inferred = False
1152
+ var.is_argument = True
1153
+ argument = Argument(var, arg_type, self.visit(default), kind, pos_only)
1154
+ argument.set_line(arg.lineno, arg.col_offset, arg.end_lineno, arg.end_col_offset)
1155
+ return argument
1156
+
1157
+ def fail_arg(self, msg: str, arg: ast3.arg) -> None:
1158
+ self.fail(ErrorMessage(msg), arg.lineno, arg.col_offset, blocker=True)
1159
+
1160
+ # ClassDef(identifier name,
1161
+ # expr* bases,
1162
+ # keyword* keywords,
1163
+ # stmt* body,
1164
+ # expr* decorator_list)
1165
+ def visit_ClassDef(self, n: ast3.ClassDef) -> ClassDef:
1166
+ self.class_and_function_stack.append("C")
1167
+ keywords = [(kw.arg, self.visit(kw.value)) for kw in n.keywords if kw.arg]
1168
+
1169
+ # Type parameters, if using new syntax for generics (PEP 695)
1170
+ explicit_type_params: list[TypeParam] | None = None
1171
+
1172
+ if sys.version_info >= (3, 12) and n.type_params:
1173
+ explicit_type_params = self.translate_type_params(n.type_params)
1174
+
1175
+ cdef = ClassDef(
1176
+ n.name,
1177
+ self.as_required_block(n.body),
1178
+ None,
1179
+ self.translate_expr_list(n.bases),
1180
+ metaclass=dict(keywords).get("metaclass"),
1181
+ keywords=keywords,
1182
+ type_args=explicit_type_params,
1183
+ )
1184
+ cdef.decorators = self.translate_expr_list(n.decorator_list)
1185
+ self.set_line(cdef, n)
1186
+
1187
+ if self.options.include_docstrings:
1188
+ cdef.docstring = ast3.get_docstring(n, clean=False)
1189
+ cdef.column = n.col_offset
1190
+ cdef.end_line = n.end_lineno
1191
+ cdef.end_column = n.end_col_offset
1192
+ self.class_and_function_stack.pop()
1193
+ return cdef
1194
+
1195
+ def validate_type_param(self, type_param: ast_TypeVar) -> None:
1196
+ incorrect_expr = find_disallowed_expression_in_annotation_scope(type_param.bound)
1197
+ if incorrect_expr is None:
1198
+ return
1199
+ if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)):
1200
+ self.fail(
1201
+ message_registry.TYPE_VAR_YIELD_EXPRESSION_IN_BOUND,
1202
+ type_param.lineno,
1203
+ type_param.col_offset,
1204
+ blocker=True,
1205
+ )
1206
+ if isinstance(incorrect_expr, ast3.NamedExpr):
1207
+ self.fail(
1208
+ message_registry.TYPE_VAR_NAMED_EXPRESSION_IN_BOUND,
1209
+ type_param.lineno,
1210
+ type_param.col_offset,
1211
+ blocker=True,
1212
+ )
1213
+ if isinstance(incorrect_expr, ast3.Await):
1214
+ self.fail(
1215
+ message_registry.TYPE_VAR_AWAIT_EXPRESSION_IN_BOUND,
1216
+ type_param.lineno,
1217
+ type_param.col_offset,
1218
+ blocker=True,
1219
+ )
1220
+
1221
+ def translate_type_params(self, type_params: list[Any]) -> list[TypeParam]:
1222
+ explicit_type_params = []
1223
+ for p in type_params:
1224
+ bound: Type | None = None
1225
+ values: list[Type] = []
1226
+ default: Type | None = None
1227
+ if sys.version_info >= (3, 13):
1228
+ default = TypeConverter(self.errors, line=p.lineno).visit(p.default_value)
1229
+ if isinstance(p, ast_ParamSpec): # type: ignore[misc]
1230
+ explicit_type_params.append(TypeParam(p.name, PARAM_SPEC_KIND, None, [], default))
1231
+ elif isinstance(p, ast_TypeVarTuple): # type: ignore[misc]
1232
+ explicit_type_params.append(
1233
+ TypeParam(p.name, TYPE_VAR_TUPLE_KIND, None, [], default)
1234
+ )
1235
+ else:
1236
+ if isinstance(p.bound, ast3.Tuple):
1237
+ if len(p.bound.elts) < 2:
1238
+ self.fail(
1239
+ message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES,
1240
+ p.lineno,
1241
+ p.col_offset,
1242
+ blocker=False,
1243
+ )
1244
+ else:
1245
+ conv = TypeConverter(self.errors, line=p.lineno)
1246
+ values = [conv.visit(t) for t in p.bound.elts]
1247
+ elif p.bound is not None:
1248
+ self.validate_type_param(p)
1249
+ bound = TypeConverter(self.errors, line=p.lineno).visit(p.bound)
1250
+ explicit_type_params.append(
1251
+ TypeParam(p.name, TYPE_VAR_KIND, bound, values, default)
1252
+ )
1253
+ return explicit_type_params
1254
+
1255
+ # Return(expr? value)
1256
+ def visit_Return(self, n: ast3.Return) -> ReturnStmt:
1257
+ node = ReturnStmt(self.visit(n.value))
1258
+ return self.set_line(node, n)
1259
+
1260
+ # Delete(expr* targets)
1261
+ def visit_Delete(self, n: ast3.Delete) -> DelStmt:
1262
+ if len(n.targets) > 1:
1263
+ tup = TupleExpr(self.translate_expr_list(n.targets))
1264
+ tup.set_line(n.lineno)
1265
+ node = DelStmt(tup)
1266
+ else:
1267
+ node = DelStmt(self.visit(n.targets[0]))
1268
+ return self.set_line(node, n)
1269
+
1270
+ # Assign(expr* targets, expr? value, string? type_comment, expr? annotation)
1271
+ def visit_Assign(self, n: ast3.Assign) -> AssignmentStmt:
1272
+ lvalues = self.translate_expr_list(n.targets)
1273
+ rvalue = self.visit(n.value)
1274
+ typ = self.translate_type_comment(n, n.type_comment)
1275
+ s = AssignmentStmt(lvalues, rvalue, type=typ, new_syntax=False)
1276
+ return self.set_line(s, n)
1277
+
1278
+ # AnnAssign(expr target, expr annotation, expr? value, int simple)
1279
+ def visit_AnnAssign(self, n: ast3.AnnAssign) -> AssignmentStmt:
1280
+ line = n.lineno
1281
+ if n.value is None: # always allow 'x: int'
1282
+ rvalue: Expression = TempNode(AnyType(TypeOfAny.special_form), no_rhs=True)
1283
+ self.set_line(rvalue, n)
1284
+ else:
1285
+ rvalue = self.visit(n.value)
1286
+ typ = TypeConverter(self.errors, line=line).visit(n.annotation)
1287
+ assert typ is not None
1288
+ typ.column = n.annotation.col_offset
1289
+ s = AssignmentStmt([self.visit(n.target)], rvalue, type=typ, new_syntax=True)
1290
+ return self.set_line(s, n)
1291
+
1292
+ # AugAssign(expr target, operator op, expr value)
1293
+ def visit_AugAssign(self, n: ast3.AugAssign) -> OperatorAssignmentStmt:
1294
+ s = OperatorAssignmentStmt(
1295
+ self.from_operator(n.op), self.visit(n.target), self.visit(n.value)
1296
+ )
1297
+ return self.set_line(s, n)
1298
+
1299
+ # For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
1300
+ def visit_For(self, n: ast3.For) -> ForStmt:
1301
+ target_type = self.translate_type_comment(n, n.type_comment)
1302
+ node = ForStmt(
1303
+ self.visit(n.target),
1304
+ self.visit(n.iter),
1305
+ self.as_required_block(n.body),
1306
+ self.as_block(n.orelse),
1307
+ target_type,
1308
+ )
1309
+ return self.set_line(node, n)
1310
+
1311
+ # AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
1312
+ def visit_AsyncFor(self, n: ast3.AsyncFor) -> ForStmt:
1313
+ target_type = self.translate_type_comment(n, n.type_comment)
1314
+ node = ForStmt(
1315
+ self.visit(n.target),
1316
+ self.visit(n.iter),
1317
+ self.as_required_block(n.body),
1318
+ self.as_block(n.orelse),
1319
+ target_type,
1320
+ )
1321
+ node.is_async = True
1322
+ return self.set_line(node, n)
1323
+
1324
+ # While(expr test, stmt* body, stmt* orelse)
1325
+ def visit_While(self, n: ast3.While) -> WhileStmt:
1326
+ node = WhileStmt(
1327
+ self.visit(n.test), self.as_required_block(n.body), self.as_block(n.orelse)
1328
+ )
1329
+ return self.set_line(node, n)
1330
+
1331
+ # If(expr test, stmt* body, stmt* orelse)
1332
+ def visit_If(self, n: ast3.If) -> IfStmt:
1333
+ node = IfStmt(
1334
+ [self.visit(n.test)], [self.as_required_block(n.body)], self.as_block(n.orelse)
1335
+ )
1336
+ return self.set_line(node, n)
1337
+
1338
+ # With(withitem* items, stmt* body, string? type_comment)
1339
+ def visit_With(self, n: ast3.With) -> WithStmt:
1340
+ target_type = self.translate_type_comment(n, n.type_comment)
1341
+ node = WithStmt(
1342
+ [self.visit(i.context_expr) for i in n.items],
1343
+ [self.visit(i.optional_vars) for i in n.items],
1344
+ self.as_required_block(n.body),
1345
+ target_type,
1346
+ )
1347
+ return self.set_line(node, n)
1348
+
1349
+ # AsyncWith(withitem* items, stmt* body, string? type_comment)
1350
+ def visit_AsyncWith(self, n: ast3.AsyncWith) -> WithStmt:
1351
+ target_type = self.translate_type_comment(n, n.type_comment)
1352
+ s = WithStmt(
1353
+ [self.visit(i.context_expr) for i in n.items],
1354
+ [self.visit(i.optional_vars) for i in n.items],
1355
+ self.as_required_block(n.body),
1356
+ target_type,
1357
+ )
1358
+ s.is_async = True
1359
+ return self.set_line(s, n)
1360
+
1361
+ # Raise(expr? exc, expr? cause)
1362
+ def visit_Raise(self, n: ast3.Raise) -> RaiseStmt:
1363
+ node = RaiseStmt(self.visit(n.exc), self.visit(n.cause))
1364
+ return self.set_line(node, n)
1365
+
1366
+ # Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
1367
+ def visit_Try(self, n: ast3.Try) -> TryStmt:
1368
+ vs = [
1369
+ self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers
1370
+ ]
1371
+ types = [self.visit(h.type) for h in n.handlers]
1372
+ handlers = [self.as_required_block(h.body) for h in n.handlers]
1373
+
1374
+ node = TryStmt(
1375
+ self.as_required_block(n.body),
1376
+ vs,
1377
+ types,
1378
+ handlers,
1379
+ self.as_block(n.orelse),
1380
+ self.as_block(n.finalbody),
1381
+ )
1382
+ return self.set_line(node, n)
1383
+
1384
+ def visit_TryStar(self, n: TryStar) -> TryStmt:
1385
+ vs = [
1386
+ self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers
1387
+ ]
1388
+ types = [self.visit(h.type) for h in n.handlers]
1389
+ handlers = [self.as_required_block(h.body) for h in n.handlers]
1390
+
1391
+ node = TryStmt(
1392
+ self.as_required_block(n.body),
1393
+ vs,
1394
+ types,
1395
+ handlers,
1396
+ self.as_block(n.orelse),
1397
+ self.as_block(n.finalbody),
1398
+ )
1399
+ node.is_star = True
1400
+ return self.set_line(node, n)
1401
+
1402
+ # Assert(expr test, expr? msg)
1403
+ def visit_Assert(self, n: ast3.Assert) -> AssertStmt:
1404
+ node = AssertStmt(self.visit(n.test), self.visit(n.msg))
1405
+ return self.set_line(node, n)
1406
+
1407
+ # Import(alias* names)
1408
+ def visit_Import(self, n: ast3.Import) -> Import:
1409
+ names: list[tuple[str, str | None]] = []
1410
+ for alias in n.names:
1411
+ name = self.translate_module_id(alias.name)
1412
+ asname = alias.asname
1413
+ if asname is None and name != alias.name:
1414
+ # if the module name has been translated (and it's not already
1415
+ # an explicit import-as), make it an implicit import-as the
1416
+ # original name
1417
+ asname = alias.name
1418
+ names.append((name, asname))
1419
+ i = Import(names)
1420
+ self.imports.append(i)
1421
+ return self.set_line(i, n)
1422
+
1423
+ # ImportFrom(identifier? module, alias* names, int? level)
1424
+ def visit_ImportFrom(self, n: ast3.ImportFrom) -> ImportBase:
1425
+ assert n.level is not None
1426
+ if len(n.names) == 1 and n.names[0].name == "*":
1427
+ mod = n.module if n.module is not None else ""
1428
+ i: ImportBase = ImportAll(mod, n.level)
1429
+ else:
1430
+ i = ImportFrom(
1431
+ self.translate_module_id(n.module) if n.module is not None else "",
1432
+ n.level,
1433
+ [(a.name, a.asname) for a in n.names],
1434
+ )
1435
+ self.imports.append(i)
1436
+ return self.set_line(i, n)
1437
+
1438
+ # Global(identifier* names)
1439
+ def visit_Global(self, n: ast3.Global) -> GlobalDecl:
1440
+ g = GlobalDecl(n.names)
1441
+ return self.set_line(g, n)
1442
+
1443
+ # Nonlocal(identifier* names)
1444
+ def visit_Nonlocal(self, n: ast3.Nonlocal) -> NonlocalDecl:
1445
+ d = NonlocalDecl(n.names)
1446
+ return self.set_line(d, n)
1447
+
1448
+ # Expr(expr value)
1449
+ def visit_Expr(self, n: ast3.Expr) -> ExpressionStmt:
1450
+ value = self.visit(n.value)
1451
+ node = ExpressionStmt(value)
1452
+ return self.set_line(node, n)
1453
+
1454
+ # Pass
1455
+ def visit_Pass(self, n: ast3.Pass) -> PassStmt:
1456
+ s = PassStmt()
1457
+ return self.set_line(s, n)
1458
+
1459
+ # Break
1460
+ def visit_Break(self, n: ast3.Break) -> BreakStmt:
1461
+ s = BreakStmt()
1462
+ return self.set_line(s, n)
1463
+
1464
+ # Continue
1465
+ def visit_Continue(self, n: ast3.Continue) -> ContinueStmt:
1466
+ s = ContinueStmt()
1467
+ return self.set_line(s, n)
1468
+
1469
+ # --- expr ---
1470
+
1471
+ def visit_NamedExpr(self, n: ast3.NamedExpr) -> AssignmentExpr:
1472
+ s = AssignmentExpr(self.visit(n.target), self.visit(n.value))
1473
+ return self.set_line(s, n)
1474
+
1475
+ # BoolOp(boolop op, expr* values)
1476
+ def visit_BoolOp(self, n: ast3.BoolOp) -> OpExpr:
1477
+ # mypy translates (1 and 2 and 3) as (1 and (2 and 3))
1478
+ assert len(n.values) >= 2
1479
+ op_node = n.op
1480
+ if isinstance(op_node, ast3.And):
1481
+ op = "and"
1482
+ elif isinstance(op_node, ast3.Or):
1483
+ op = "or"
1484
+ else:
1485
+ raise RuntimeError("unknown BoolOp " + str(type(n)))
1486
+
1487
+ # potentially inefficient!
1488
+ return self.group(op, self.translate_expr_list(n.values), n)
1489
+
1490
+ def group(self, op: str, vals: list[Expression], n: ast3.expr) -> OpExpr:
1491
+ if len(vals) == 2:
1492
+ e = OpExpr(op, vals[0], vals[1])
1493
+ else:
1494
+ e = OpExpr(op, vals[0], self.group(op, vals[1:], n))
1495
+ return self.set_line(e, n)
1496
+
1497
+ # BinOp(expr left, operator op, expr right)
1498
+ def visit_BinOp(self, n: ast3.BinOp) -> OpExpr:
1499
+ op = self.from_operator(n.op)
1500
+
1501
+ if op is None:
1502
+ raise RuntimeError("cannot translate BinOp " + str(type(n.op)))
1503
+
1504
+ e = OpExpr(op, self.visit(n.left), self.visit(n.right))
1505
+ return self.set_line(e, n)
1506
+
1507
+ # UnaryOp(unaryop op, expr operand)
1508
+ def visit_UnaryOp(self, n: ast3.UnaryOp) -> UnaryExpr:
1509
+ op = None
1510
+ if isinstance(n.op, ast3.Invert):
1511
+ op = "~"
1512
+ elif isinstance(n.op, ast3.Not):
1513
+ op = "not"
1514
+ elif isinstance(n.op, ast3.UAdd):
1515
+ op = "+"
1516
+ elif isinstance(n.op, ast3.USub):
1517
+ op = "-"
1518
+
1519
+ if op is None:
1520
+ raise RuntimeError("cannot translate UnaryOp " + str(type(n.op)))
1521
+
1522
+ e = UnaryExpr(op, self.visit(n.operand))
1523
+ return self.set_line(e, n)
1524
+
1525
+ # Lambda(arguments args, expr body)
1526
+ def visit_Lambda(self, n: ast3.Lambda) -> LambdaExpr:
1527
+ body = ast3.Return(n.body)
1528
+ body.lineno = n.body.lineno
1529
+ body.col_offset = n.body.col_offset
1530
+
1531
+ self.class_and_function_stack.append("L")
1532
+ e = LambdaExpr(self.transform_args(n.args, n.lineno), self.as_required_block([body]))
1533
+ self.class_and_function_stack.pop()
1534
+ e.set_line(n.lineno, n.col_offset) # Overrides set_line -- can't use self.set_line
1535
+ return e
1536
+
1537
+ # IfExp(expr test, expr body, expr orelse)
1538
+ def visit_IfExp(self, n: ast3.IfExp) -> ConditionalExpr:
1539
+ e = ConditionalExpr(self.visit(n.test), self.visit(n.body), self.visit(n.orelse))
1540
+ return self.set_line(e, n)
1541
+
1542
+ # Dict(expr* keys, expr* values)
1543
+ def visit_Dict(self, n: ast3.Dict) -> DictExpr:
1544
+ e = DictExpr(
1545
+ list(zip(self.translate_opt_expr_list(n.keys), self.translate_expr_list(n.values)))
1546
+ )
1547
+ return self.set_line(e, n)
1548
+
1549
+ # Set(expr* elts)
1550
+ def visit_Set(self, n: ast3.Set) -> SetExpr:
1551
+ e = SetExpr(self.translate_expr_list(n.elts))
1552
+ return self.set_line(e, n)
1553
+
1554
+ # ListComp(expr elt, comprehension* generators)
1555
+ def visit_ListComp(self, n: ast3.ListComp) -> ListComprehension:
1556
+ e = ListComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n)))
1557
+ return self.set_line(e, n)
1558
+
1559
+ # SetComp(expr elt, comprehension* generators)
1560
+ def visit_SetComp(self, n: ast3.SetComp) -> SetComprehension:
1561
+ e = SetComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n)))
1562
+ return self.set_line(e, n)
1563
+
1564
+ # DictComp(expr key, expr value, comprehension* generators)
1565
+ def visit_DictComp(self, n: ast3.DictComp) -> DictionaryComprehension:
1566
+ targets = [self.visit(c.target) for c in n.generators]
1567
+ iters = [self.visit(c.iter) for c in n.generators]
1568
+ ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators]
1569
+ is_async = [bool(c.is_async) for c in n.generators]
1570
+ e = DictionaryComprehension(
1571
+ self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async
1572
+ )
1573
+ return self.set_line(e, n)
1574
+
1575
+ # GeneratorExp(expr elt, comprehension* generators)
1576
+ def visit_GeneratorExp(self, n: ast3.GeneratorExp) -> GeneratorExpr:
1577
+ targets = [self.visit(c.target) for c in n.generators]
1578
+ iters = [self.visit(c.iter) for c in n.generators]
1579
+ ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators]
1580
+ is_async = [bool(c.is_async) for c in n.generators]
1581
+ e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async)
1582
+ return self.set_line(e, n)
1583
+
1584
+ # Await(expr value)
1585
+ def visit_Await(self, n: ast3.Await) -> AwaitExpr:
1586
+ v = self.visit(n.value)
1587
+ e = AwaitExpr(v)
1588
+ return self.set_line(e, n)
1589
+
1590
+ # Yield(expr? value)
1591
+ def visit_Yield(self, n: ast3.Yield) -> YieldExpr:
1592
+ e = YieldExpr(self.visit(n.value))
1593
+ return self.set_line(e, n)
1594
+
1595
+ # YieldFrom(expr value)
1596
+ def visit_YieldFrom(self, n: ast3.YieldFrom) -> YieldFromExpr:
1597
+ e = YieldFromExpr(self.visit(n.value))
1598
+ return self.set_line(e, n)
1599
+
1600
+ # Compare(expr left, cmpop* ops, expr* comparators)
1601
+ def visit_Compare(self, n: ast3.Compare) -> ComparisonExpr:
1602
+ operators = [self.from_comp_operator(o) for o in n.ops]
1603
+ operands = self.translate_expr_list([n.left] + n.comparators)
1604
+ e = ComparisonExpr(operators, operands)
1605
+ return self.set_line(e, n)
1606
+
1607
+ # Call(expr func, expr* args, keyword* keywords)
1608
+ # keyword = (identifier? arg, expr value)
1609
+ def visit_Call(self, n: Call) -> CallExpr:
1610
+ args = n.args
1611
+ keywords = n.keywords
1612
+ keyword_names = [k.arg for k in keywords]
1613
+ arg_types = self.translate_expr_list(
1614
+ [a.value if isinstance(a, Starred) else a for a in args] + [k.value for k in keywords]
1615
+ )
1616
+ arg_kinds = [ARG_STAR if type(a) is Starred else ARG_POS for a in args] + [
1617
+ ARG_STAR2 if arg is None else ARG_NAMED for arg in keyword_names
1618
+ ]
1619
+ e = CallExpr(
1620
+ self.visit(n.func),
1621
+ arg_types,
1622
+ arg_kinds,
1623
+ cast("list[str | None]", [None] * len(args)) + keyword_names,
1624
+ )
1625
+ return self.set_line(e, n)
1626
+
1627
+ # Constant(object value)
1628
+ def visit_Constant(self, n: ast3.Constant) -> Any:
1629
+ val = n.value
1630
+ e: Any = None
1631
+ if val is None:
1632
+ e = NameExpr("None")
1633
+ elif isinstance(val, str):
1634
+ e = StrExpr(val)
1635
+ elif isinstance(val, bytes):
1636
+ e = BytesExpr(bytes_to_human_readable_repr(val))
1637
+ elif isinstance(val, bool): # Must check before int!
1638
+ e = NameExpr(str(val))
1639
+ elif isinstance(val, int):
1640
+ e = IntExpr(val)
1641
+ elif isinstance(val, float):
1642
+ e = FloatExpr(val)
1643
+ elif isinstance(val, complex):
1644
+ e = ComplexExpr(val)
1645
+ elif val is Ellipsis:
1646
+ e = EllipsisExpr()
1647
+ else:
1648
+ raise RuntimeError("Constant not implemented for " + str(type(val)))
1649
+ return self.set_line(e, n)
1650
+
1651
+ # JoinedStr(expr* values)
1652
+ def visit_JoinedStr(self, n: ast3.JoinedStr) -> Expression:
1653
+ # Each of n.values is a str or FormattedValue; we just concatenate
1654
+ # them all using ''.join.
1655
+ empty_string = StrExpr("")
1656
+ empty_string.set_line(n.lineno, n.col_offset)
1657
+ strs_to_join = ListExpr(self.translate_expr_list(n.values))
1658
+ strs_to_join.set_line(empty_string)
1659
+ # Don't make unnecessary join call if there is only one str to join
1660
+ if len(strs_to_join.items) == 1:
1661
+ return self.set_line(strs_to_join.items[0], n)
1662
+ elif len(strs_to_join.items) > 1:
1663
+ last = strs_to_join.items[-1]
1664
+ if isinstance(last, StrExpr) and last.value == "":
1665
+ # 3.12 can add an empty literal at the end. Delete it for consistency
1666
+ # between Python versions.
1667
+ del strs_to_join.items[-1:]
1668
+ join_method = MemberExpr(empty_string, "join")
1669
+ join_method.set_line(empty_string)
1670
+ result_expression = CallExpr(join_method, [strs_to_join], [ARG_POS], [None])
1671
+ return self.set_line(result_expression, n)
1672
+
1673
+ # FormattedValue(expr value)
1674
+ def visit_FormattedValue(self, n: ast3.FormattedValue) -> Expression:
1675
+ # A FormattedValue is a component of a JoinedStr, or it can exist
1676
+ # on its own. We translate them to individual '{}'.format(value)
1677
+ # calls. Format specifier and conversion information is passed along
1678
+ # to allow mypyc to support f-strings with format specifiers and conversions.
1679
+ val_exp = self.visit(n.value)
1680
+ val_exp.set_line(n.lineno, n.col_offset)
1681
+ conv_str = "" if n.conversion < 0 else "!" + chr(n.conversion)
1682
+ format_string = StrExpr("{" + conv_str + ":{}}")
1683
+ format_spec_exp = self.visit(n.format_spec) if n.format_spec is not None else StrExpr("")
1684
+ format_string.set_line(n.lineno, n.col_offset)
1685
+ format_method = MemberExpr(format_string, "format")
1686
+ format_method.set_line(format_string)
1687
+ result_expression = CallExpr(
1688
+ format_method, [val_exp, format_spec_exp], [ARG_POS, ARG_POS], [None, None]
1689
+ )
1690
+ return self.set_line(result_expression, n)
1691
+
1692
+ # TemplateStr(expr* values)
1693
+ def visit_TemplateStr(self, n: ast_TemplateStr) -> TemplateStrExpr:
1694
+ self.uses_template_strings = True
1695
+ items: list[Expression | tuple[Expression, str, str | None, Expression | None]] = []
1696
+ for value in n.values:
1697
+ if isinstance(value, ast_Interpolation): # type: ignore[misc]
1698
+ val_expr = self.visit(value.value)
1699
+ val_expr.set_line(value.lineno, value.col_offset)
1700
+ conversion = None if value.conversion < 0 else chr(value.conversion)
1701
+ format_spec = (
1702
+ self.visit(value.format_spec) if value.format_spec is not None else None
1703
+ )
1704
+ items.append((val_expr, value.str, conversion, format_spec))
1705
+ else:
1706
+ items.append(self.visit(value))
1707
+ e = TemplateStrExpr(items)
1708
+ return self.set_line(e, n)
1709
+
1710
+ # Attribute(expr value, identifier attr, expr_context ctx)
1711
+ def visit_Attribute(self, n: Attribute) -> MemberExpr | SuperExpr:
1712
+ value = n.value
1713
+ member_expr = MemberExpr(self.visit(value), n.attr)
1714
+ obj = member_expr.expr
1715
+ if (
1716
+ isinstance(obj, CallExpr)
1717
+ and isinstance(obj.callee, NameExpr)
1718
+ and obj.callee.name == "super"
1719
+ ):
1720
+ e: MemberExpr | SuperExpr = SuperExpr(member_expr.name, obj)
1721
+ else:
1722
+ e = member_expr
1723
+ return self.set_line(e, n)
1724
+
1725
+ # Subscript(expr value, slice slice, expr_context ctx)
1726
+ def visit_Subscript(self, n: ast3.Subscript) -> IndexExpr:
1727
+ e = IndexExpr(self.visit(n.value), self.visit(n.slice))
1728
+ return self.set_line(e, n)
1729
+
1730
+ # Starred(expr value, expr_context ctx)
1731
+ def visit_Starred(self, n: Starred) -> StarExpr:
1732
+ e = StarExpr(self.visit(n.value))
1733
+ return self.set_line(e, n)
1734
+
1735
+ # Name(identifier id, expr_context ctx)
1736
+ def visit_Name(self, n: Name) -> NameExpr:
1737
+ e = NameExpr(n.id)
1738
+ return self.set_line(e, n)
1739
+
1740
+ # List(expr* elts, expr_context ctx)
1741
+ def visit_List(self, n: ast3.List) -> ListExpr | TupleExpr:
1742
+ expr_list: list[Expression] = [self.visit(e) for e in n.elts]
1743
+ if isinstance(n.ctx, ast3.Store):
1744
+ # [x, y] = z and (x, y) = z means exactly the same thing
1745
+ e: ListExpr | TupleExpr = TupleExpr(expr_list)
1746
+ else:
1747
+ e = ListExpr(expr_list)
1748
+ return self.set_line(e, n)
1749
+
1750
+ # Tuple(expr* elts, expr_context ctx)
1751
+ def visit_Tuple(self, n: ast3.Tuple) -> TupleExpr:
1752
+ e = TupleExpr(self.translate_expr_list(n.elts))
1753
+ return self.set_line(e, n)
1754
+
1755
+ # Slice(expr? lower, expr? upper, expr? step)
1756
+ def visit_Slice(self, n: ast3.Slice) -> SliceExpr:
1757
+ e = SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step))
1758
+ return self.set_line(e, n)
1759
+
1760
+ # Match(expr subject, match_case* cases) # python 3.10 and later
1761
+ def visit_Match(self, n: ast3.Match) -> MatchStmt:
1762
+ node = MatchStmt(
1763
+ self.visit(n.subject),
1764
+ [self.visit(c.pattern) for c in n.cases],
1765
+ [self.visit(c.guard) for c in n.cases],
1766
+ [self.as_required_block(c.body) for c in n.cases],
1767
+ )
1768
+ return self.set_line(node, n)
1769
+
1770
+ def visit_MatchValue(self, n: ast3.MatchValue) -> ValuePattern:
1771
+ node = ValuePattern(self.visit(n.value))
1772
+ return self.set_line(node, n)
1773
+
1774
+ def visit_MatchSingleton(self, n: ast3.MatchSingleton) -> SingletonPattern:
1775
+ node = SingletonPattern(n.value)
1776
+ return self.set_line(node, n)
1777
+
1778
+ def visit_MatchSequence(self, n: ast3.MatchSequence) -> SequencePattern:
1779
+ patterns = [self.visit(p) for p in n.patterns]
1780
+ stars = [p for p in patterns if isinstance(p, StarredPattern)]
1781
+ assert len(stars) < 2
1782
+
1783
+ node = SequencePattern(patterns)
1784
+ return self.set_line(node, n)
1785
+
1786
+ def visit_MatchStar(self, n: ast3.MatchStar) -> StarredPattern:
1787
+ if n.name is None:
1788
+ node = StarredPattern(None)
1789
+ else:
1790
+ name = self.set_line(NameExpr(n.name), n)
1791
+ node = StarredPattern(name)
1792
+
1793
+ return self.set_line(node, n)
1794
+
1795
+ def visit_MatchMapping(self, n: ast3.MatchMapping) -> MappingPattern:
1796
+ keys = [self.visit(k) for k in n.keys]
1797
+ values = [self.visit(v) for v in n.patterns]
1798
+
1799
+ if n.rest is None:
1800
+ rest = None
1801
+ else:
1802
+ rest = self.set_line(NameExpr(n.rest), n)
1803
+
1804
+ node = MappingPattern(keys, values, rest)
1805
+ return self.set_line(node, n)
1806
+
1807
+ def visit_MatchClass(self, n: ast3.MatchClass) -> ClassPattern:
1808
+ class_ref = self.visit(n.cls)
1809
+ assert isinstance(class_ref, RefExpr)
1810
+ positionals = [self.visit(p) for p in n.patterns]
1811
+ keyword_keys = n.kwd_attrs
1812
+ keyword_values = [self.visit(p) for p in n.kwd_patterns]
1813
+
1814
+ node = ClassPattern(class_ref, positionals, keyword_keys, keyword_values)
1815
+ return self.set_line(node, n)
1816
+
1817
+ # MatchAs(expr pattern, identifier name)
1818
+ def visit_MatchAs(self, n: ast3.MatchAs) -> AsPattern:
1819
+ if n.name is None:
1820
+ name = None
1821
+ else:
1822
+ name = NameExpr(n.name)
1823
+ name = self.set_line(name, n)
1824
+ node = AsPattern(self.visit(n.pattern), name)
1825
+ return self.set_line(node, n)
1826
+
1827
+ # MatchOr(expr* pattern)
1828
+ def visit_MatchOr(self, n: ast3.MatchOr) -> OrPattern:
1829
+ node = OrPattern([self.visit(pattern) for pattern in n.patterns])
1830
+ return self.set_line(node, n)
1831
+
1832
+ def validate_type_alias(self, n: ast_TypeAlias) -> None:
1833
+ incorrect_expr = find_disallowed_expression_in_annotation_scope(n.value)
1834
+ if incorrect_expr is None:
1835
+ return
1836
+ if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)):
1837
+ self.fail(
1838
+ message_registry.TYPE_ALIAS_WITH_YIELD_EXPRESSION,
1839
+ n.lineno,
1840
+ n.col_offset,
1841
+ blocker=True,
1842
+ )
1843
+ if isinstance(incorrect_expr, ast3.NamedExpr):
1844
+ self.fail(
1845
+ message_registry.TYPE_ALIAS_WITH_NAMED_EXPRESSION,
1846
+ n.lineno,
1847
+ n.col_offset,
1848
+ blocker=True,
1849
+ )
1850
+ if isinstance(incorrect_expr, ast3.Await):
1851
+ self.fail(
1852
+ message_registry.TYPE_ALIAS_WITH_AWAIT_EXPRESSION,
1853
+ n.lineno,
1854
+ n.col_offset,
1855
+ blocker=True,
1856
+ )
1857
+
1858
+ # TypeAlias(identifier name, type_param* type_params, expr value)
1859
+ def visit_TypeAlias(self, n: ast_TypeAlias) -> TypeAliasStmt | AssignmentStmt:
1860
+ node: TypeAliasStmt | AssignmentStmt
1861
+ type_params = self.translate_type_params(n.type_params)
1862
+ self.validate_type_alias(n)
1863
+ value = self.visit(n.value)
1864
+ # Since the value is evaluated lazily, wrap the value inside a lambda.
1865
+ # This helps mypyc.
1866
+ ret = ReturnStmt(value)
1867
+ self.set_line(ret, n.value)
1868
+ value_func = LambdaExpr(body=Block([ret]))
1869
+ self.set_line(value_func, n.value)
1870
+ node = TypeAliasStmt(self.visit_Name(n.name), type_params, value_func)
1871
+ return self.set_line(node, n)
1872
+
1873
+
1874
+ class TypeConverter:
1875
+ def __init__(
1876
+ self,
1877
+ errors: Errors | None,
1878
+ line: int = -1,
1879
+ override_column: int = -1,
1880
+ is_evaluated: bool = True,
1881
+ ) -> None:
1882
+ self.errors = errors
1883
+ self.line = line
1884
+ self.override_column = override_column
1885
+ self.node_stack: list[AST] = []
1886
+ self.is_evaluated = is_evaluated
1887
+
1888
+ def convert_column(self, column: int) -> int:
1889
+ """Apply column override if defined; otherwise return column.
1890
+
1891
+ Column numbers are sometimes incorrect in the AST and the column
1892
+ override can be used to work around that.
1893
+ """
1894
+ if self.override_column < 0:
1895
+ return column
1896
+ else:
1897
+ return self.override_column
1898
+
1899
+ def invalid_type(self, node: AST, note: str | None = None) -> RawExpressionType:
1900
+ """Constructs a type representing some expression that normally forms an invalid type.
1901
+ For example, if we see a type hint that says "3 + 4", we would transform that
1902
+ expression into a RawExpressionType.
1903
+
1904
+ The semantic analysis layer will report an "Invalid type" error when it
1905
+ encounters this type, along with the given note if one is provided.
1906
+
1907
+ See RawExpressionType's docstring for more details on how it's used.
1908
+ """
1909
+ return RawExpressionType(
1910
+ None, "typing.Any", line=self.line, column=getattr(node, "col_offset", -1), note=note
1911
+ )
1912
+
1913
+ @overload
1914
+ def visit(self, node: ast3.expr) -> ProperType: ...
1915
+
1916
+ @overload
1917
+ def visit(self, node: AST | None) -> ProperType | None: ...
1918
+
1919
+ def visit(self, node: AST | None) -> ProperType | None:
1920
+ """Modified visit -- keep track of the stack of nodes"""
1921
+ if node is None:
1922
+ return None
1923
+ self.node_stack.append(node)
1924
+ try:
1925
+ method = "visit_" + node.__class__.__name__
1926
+ visitor = getattr(self, method, None)
1927
+ if visitor is not None:
1928
+ typ = visitor(node)
1929
+ assert isinstance(typ, ProperType)
1930
+ return typ
1931
+ else:
1932
+ return self.invalid_type(node)
1933
+ finally:
1934
+ self.node_stack.pop()
1935
+
1936
+ def parent(self) -> AST | None:
1937
+ """Return the AST node above the one we are processing"""
1938
+ if len(self.node_stack) < 2:
1939
+ return None
1940
+ return self.node_stack[-2]
1941
+
1942
+ def fail(self, msg: ErrorMessage, line: int, column: int) -> None:
1943
+ if self.errors:
1944
+ self.errors.report(line, column, msg.value, blocker=True, code=msg.code)
1945
+
1946
+ def note(self, msg: str, line: int, column: int) -> None:
1947
+ if self.errors:
1948
+ self.errors.report(line, column, msg, severity="note", code=codes.SYNTAX)
1949
+
1950
+ def translate_expr_list(self, l: Sequence[ast3.expr]) -> list[Type]:
1951
+ return [self.visit(e) for e in l]
1952
+
1953
+ def visit_Call(self, e: Call) -> Type:
1954
+ # Parse the arg constructor
1955
+ f = e.func
1956
+ constructor = stringify_name(f)
1957
+
1958
+ if not isinstance(self.parent(), ast3.List):
1959
+ note = None
1960
+ if constructor:
1961
+ note = "Suggestion: use {0}[...] instead of {0}(...)".format(constructor)
1962
+ return self.invalid_type(e, note=note)
1963
+ if not constructor:
1964
+ self.fail(message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED, e.lineno, e.col_offset)
1965
+
1966
+ name: str | None = None
1967
+ default_type = AnyType(TypeOfAny.special_form)
1968
+ typ: Type = default_type
1969
+ for i, arg in enumerate(e.args):
1970
+ if i == 0:
1971
+ converted = self.visit(arg)
1972
+ assert converted is not None
1973
+ typ = converted
1974
+ elif i == 1:
1975
+ name = self._extract_argument_name(arg)
1976
+ else:
1977
+ self.fail(message_registry.ARG_CONSTRUCTOR_TOO_MANY_ARGS, f.lineno, f.col_offset)
1978
+ for k in e.keywords:
1979
+ value = k.value
1980
+ if k.arg == "name":
1981
+ if name is not None:
1982
+ self.fail(
1983
+ message_registry.MULTIPLE_VALUES_FOR_NAME_KWARG.format(constructor),
1984
+ f.lineno,
1985
+ f.col_offset,
1986
+ )
1987
+ name = self._extract_argument_name(value)
1988
+ elif k.arg == "type":
1989
+ if typ is not default_type:
1990
+ self.fail(
1991
+ message_registry.MULTIPLE_VALUES_FOR_TYPE_KWARG.format(constructor),
1992
+ f.lineno,
1993
+ f.col_offset,
1994
+ )
1995
+ converted = self.visit(value)
1996
+ assert converted is not None
1997
+ typ = converted
1998
+ else:
1999
+ self.fail(
2000
+ message_registry.ARG_CONSTRUCTOR_UNEXPECTED_ARG.format(k.arg),
2001
+ value.lineno,
2002
+ value.col_offset,
2003
+ )
2004
+ return CallableArgument(typ, name, constructor, e.lineno, e.col_offset)
2005
+
2006
+ def translate_argument_list(self, l: Sequence[ast3.expr]) -> TypeList:
2007
+ return TypeList([self.visit(e) for e in l], line=self.line)
2008
+
2009
+ def _extract_argument_name(self, n: ast3.expr) -> str | None:
2010
+ if isinstance(n, ast3.Constant) and isinstance(n.value, str):
2011
+ return n.value.strip()
2012
+ elif isinstance(n, ast3.Constant) and n.value is None:
2013
+ return None
2014
+ self.fail(
2015
+ message_registry.ARG_NAME_EXPECTED_STRING_LITERAL.format(type(n).__name__),
2016
+ self.line,
2017
+ 0,
2018
+ )
2019
+ return None
2020
+
2021
+ def visit_Name(self, n: Name) -> Type:
2022
+ return UnboundType(n.id, line=self.line, column=self.convert_column(n.col_offset))
2023
+
2024
+ def visit_BinOp(self, n: ast3.BinOp) -> Type:
2025
+ if not isinstance(n.op, ast3.BitOr):
2026
+ return self.invalid_type(n)
2027
+
2028
+ left = self.visit(n.left)
2029
+ right = self.visit(n.right)
2030
+ return UnionType(
2031
+ [left, right],
2032
+ line=self.line,
2033
+ column=self.convert_column(n.col_offset),
2034
+ is_evaluated=self.is_evaluated,
2035
+ uses_pep604_syntax=True,
2036
+ )
2037
+
2038
+ def visit_Constant(self, n: ast3.Constant) -> Type:
2039
+ val = n.value
2040
+ if val is None:
2041
+ # None is a type.
2042
+ return UnboundType("None", line=self.line)
2043
+ if isinstance(val, str):
2044
+ # Parse forward reference.
2045
+ return parse_type_string(val, "builtins.str", self.line, n.col_offset)
2046
+ if val is Ellipsis:
2047
+ # '...' is valid in some types.
2048
+ return EllipsisType(line=self.line)
2049
+ if isinstance(val, bool):
2050
+ # Special case for True/False.
2051
+ return RawExpressionType(val, "builtins.bool", line=self.line)
2052
+ if isinstance(val, (int, float, complex)):
2053
+ return self.numeric_type(val, n)
2054
+ if isinstance(val, bytes):
2055
+ contents = bytes_to_human_readable_repr(val)
2056
+ return RawExpressionType(contents, "builtins.bytes", self.line, column=n.col_offset)
2057
+ # Everything else is invalid.
2058
+
2059
+ # UnaryOp(op, operand)
2060
+ def visit_UnaryOp(self, n: UnaryOp) -> Type:
2061
+ # We support specifically Literal[-4], Literal[+4], and nothing else.
2062
+ # For example, Literal[~6] or Literal[not False] is not supported.
2063
+ typ = self.visit(n.operand)
2064
+ if (
2065
+ isinstance(typ, RawExpressionType)
2066
+ # Use type() because we do not want to allow bools.
2067
+ and type(typ.literal_value) is int
2068
+ ):
2069
+ if isinstance(n.op, USub):
2070
+ typ.literal_value *= -1
2071
+ return typ
2072
+ if isinstance(n.op, UAdd):
2073
+ return typ
2074
+ return self.invalid_type(n)
2075
+
2076
+ def numeric_type(self, value: object, n: AST) -> Type:
2077
+ # The node's field has the type complex, but complex isn't *really*
2078
+ # a parent of int and float, and this causes isinstance below
2079
+ # to think that the complex branch is always picked. Avoid
2080
+ # this by throwing away the type.
2081
+ if isinstance(value, int):
2082
+ numeric_value: int | None = value
2083
+ type_name = "builtins.int"
2084
+ else:
2085
+ # Other kinds of numbers (floats, complex) are not valid parameters for
2086
+ # RawExpressionType so we just pass in 'None' for now. We'll report the
2087
+ # appropriate error at a later stage.
2088
+ numeric_value = None
2089
+ type_name = f"builtins.{type(value).__name__}"
2090
+ return RawExpressionType(
2091
+ numeric_value, type_name, line=self.line, column=getattr(n, "col_offset", -1)
2092
+ )
2093
+
2094
+ def visit_Slice(self, n: ast3.Slice) -> Type:
2095
+ return self.invalid_type(n, note="did you mean to use ',' instead of ':' ?")
2096
+
2097
+ # Subscript(expr value, expr slice, expr_context ctx)
2098
+ def visit_Subscript(self, n: ast3.Subscript) -> Type:
2099
+ empty_tuple_index = False
2100
+ if isinstance(n.slice, ast3.Tuple):
2101
+ params = self.translate_expr_list(n.slice.elts)
2102
+ if len(n.slice.elts) == 0:
2103
+ empty_tuple_index = True
2104
+ else:
2105
+ params = [self.visit(n.slice)]
2106
+
2107
+ value = self.visit(n.value)
2108
+ if isinstance(value, UnboundType) and not value.args:
2109
+ result = UnboundType(
2110
+ value.name,
2111
+ params,
2112
+ line=self.line,
2113
+ column=value.column,
2114
+ empty_tuple_index=empty_tuple_index,
2115
+ )
2116
+ result.end_column = n.end_col_offset
2117
+ result.end_line = n.end_lineno
2118
+ return result
2119
+ else:
2120
+ return self.invalid_type(n)
2121
+
2122
+ def visit_Tuple(self, n: ast3.Tuple) -> Type:
2123
+ return TupleType(
2124
+ self.translate_expr_list(n.elts),
2125
+ _dummy_fallback,
2126
+ implicit=True,
2127
+ line=self.line,
2128
+ column=self.convert_column(n.col_offset),
2129
+ )
2130
+
2131
+ def visit_Dict(self, n: ast3.Dict) -> Type:
2132
+ if not n.keys:
2133
+ return self.invalid_type(n)
2134
+ items: dict[str, Type] = {}
2135
+ extra_items_from = []
2136
+ for item_name, value in zip(n.keys, n.values):
2137
+ if not isinstance(item_name, ast3.Constant) or not isinstance(item_name.value, str):
2138
+ if item_name is None:
2139
+ extra_items_from.append(self.visit(value))
2140
+ continue
2141
+ return self.invalid_type(n)
2142
+ items[item_name.value] = self.visit(value)
2143
+ result = TypedDictType(items, set(), set(), _dummy_fallback, n.lineno, n.col_offset)
2144
+ result.extra_items_from = extra_items_from
2145
+ return result
2146
+
2147
+ # Attribute(expr value, identifier attr, expr_context ctx)
2148
+ def visit_Attribute(self, n: Attribute) -> Type:
2149
+ before_dot = self.visit(n.value)
2150
+
2151
+ if isinstance(before_dot, UnboundType) and not before_dot.args:
2152
+ return UnboundType(f"{before_dot.name}.{n.attr}", line=self.line, column=n.col_offset)
2153
+ else:
2154
+ return self.invalid_type(n)
2155
+
2156
+ # Used for Callable[[X *Ys, Z], R] etc.
2157
+ def visit_Starred(self, n: ast3.Starred) -> Type:
2158
+ return UnpackType(self.visit(n.value), from_star_syntax=True)
2159
+
2160
+ # List(expr* elts, expr_context ctx)
2161
+ def visit_List(self, n: ast3.List) -> Type:
2162
+ assert isinstance(n.ctx, ast3.Load)
2163
+ result = self.translate_argument_list(n.elts)
2164
+ return result
2165
+
2166
+
2167
+ def stringify_name(n: AST) -> str | None:
2168
+ if isinstance(n, Name):
2169
+ return n.id
2170
+ elif isinstance(n, Attribute):
2171
+ sv = stringify_name(n.value)
2172
+ if sv is not None:
2173
+ return f"{sv}.{n.attr}"
2174
+ return None # Can't do it.
2175
+
2176
+
2177
+ class FindAttributeAssign(TraverserVisitor):
2178
+ """Check if an AST contains attribute assignments (e.g. self.x = 0)."""
2179
+
2180
+ def __init__(self) -> None:
2181
+ self.lvalue = False
2182
+ self.found = False
2183
+
2184
+ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
2185
+ self.lvalue = True
2186
+ for lv in s.lvalues:
2187
+ lv.accept(self)
2188
+ self.lvalue = False
2189
+
2190
+ def visit_with_stmt(self, s: WithStmt) -> None:
2191
+ self.lvalue = True
2192
+ for lv in s.target:
2193
+ if lv is not None:
2194
+ lv.accept(self)
2195
+ self.lvalue = False
2196
+ s.body.accept(self)
2197
+
2198
+ def visit_for_stmt(self, s: ForStmt) -> None:
2199
+ self.lvalue = True
2200
+ s.index.accept(self)
2201
+ self.lvalue = False
2202
+ s.body.accept(self)
2203
+ if s.else_body:
2204
+ s.else_body.accept(self)
2205
+
2206
+ def visit_expression_stmt(self, s: ExpressionStmt) -> None:
2207
+ # No need to look inside these
2208
+ pass
2209
+
2210
+ def visit_call_expr(self, e: CallExpr) -> None:
2211
+ # No need to look inside these
2212
+ pass
2213
+
2214
+ def visit_index_expr(self, e: IndexExpr) -> None:
2215
+ # No need to look inside these
2216
+ pass
2217
+
2218
+ def visit_member_expr(self, e: MemberExpr) -> None:
2219
+ if self.lvalue and isinstance(e.expr, NameExpr):
2220
+ self.found = True
2221
+
2222
+
2223
+ class FindYield(TraverserVisitor):
2224
+ """Check if an AST contains yields or yield froms.""" # codespell:ignore froms
2225
+
2226
+ def __init__(self) -> None:
2227
+ self.found = False
2228
+
2229
+ def visit_yield_expr(self, e: YieldExpr) -> None:
2230
+ self.found = True
2231
+
2232
+ def visit_yield_from_expr(self, e: YieldFromExpr) -> None:
2233
+ self.found = True
2234
+
2235
+
2236
+ def is_possible_trivial_body(s: list[Statement]) -> bool:
2237
+ """Could the statements form a "trivial" function body, such as 'pass'?
2238
+
2239
+ This mimics mypy.semanal.is_trivial_body, but this runs before
2240
+ semantic analysis so some checks must be conservative.
2241
+ """
2242
+ l = len(s)
2243
+ if l == 0:
2244
+ return False
2245
+ i = 0
2246
+ if isinstance(s[0], ExpressionStmt) and isinstance(s[0].expr, StrExpr):
2247
+ # Skip docstring
2248
+ i += 1
2249
+ if i == l:
2250
+ return True
2251
+ if l > i + 1:
2252
+ return False
2253
+ stmt = s[i]
2254
+ return isinstance(stmt, (PassStmt, RaiseStmt)) or (
2255
+ isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)
2256
+ )
micromamba_root/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/find_sources.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routines for finding the sources that mypy will check"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import os
7
+ from collections.abc import Sequence
8
+ from typing import Final
9
+
10
+ from mypy.fscache import FileSystemCache
11
+ from mypy.modulefinder import (
12
+ PYTHON_EXTENSIONS,
13
+ BuildSource,
14
+ matches_exclude,
15
+ matches_gitignore,
16
+ mypy_path,
17
+ )
18
+ from mypy.options import Options
19
+
20
+ PY_EXTENSIONS: Final = tuple(PYTHON_EXTENSIONS)
21
+
22
+
23
+ class InvalidSourceList(Exception):
24
+ """Exception indicating a problem in the list of sources given to mypy."""
25
+
26
+
27
+ def create_source_list(
28
+ paths: Sequence[str],
29
+ options: Options,
30
+ fscache: FileSystemCache | None = None,
31
+ allow_empty_dir: bool = False,
32
+ ) -> list[BuildSource]:
33
+ """From a list of source files/directories, makes a list of BuildSources.
34
+
35
+ Raises InvalidSourceList on errors.
36
+ """
37
+ fscache = fscache or FileSystemCache()
38
+ finder = SourceFinder(fscache, options)
39
+
40
+ sources = []
41
+ for path in paths:
42
+ path = os.path.normpath(path)
43
+ if path.endswith(PY_EXTENSIONS):
44
+ # Can raise InvalidSourceList if a directory doesn't have a valid module name.
45
+ name, base_dir = finder.crawl_up(path)
46
+ sources.append(BuildSource(path, name, None, base_dir))
47
+ elif fscache.isdir(path):
48
+ sub_sources = finder.find_sources_in_dir(path)
49
+ if not sub_sources and not allow_empty_dir:
50
+ raise InvalidSourceList(f"There are no .py[i] files in directory '{path}'")
51
+ sources.extend(sub_sources)
52
+ else:
53
+ mod = os.path.basename(path) if options.scripts_are_modules else None
54
+ sources.append(BuildSource(path, mod, None))
55
+ return sources
56
+
57
+
58
+ def keyfunc(name: str) -> tuple[bool, int, str]:
59
+ """Determines sort order for directory listing.
60
+
61
+ The desirable properties are:
62
+ 1) foo < foo.pyi < foo.py
63
+ 2) __init__.py[i] < foo
64
+ """
65
+ base, suffix = os.path.splitext(name)
66
+ for i, ext in enumerate(PY_EXTENSIONS):
67
+ if suffix == ext:
68
+ return (base != "__init__", i, base)
69
+ return (base != "__init__", -1, name)
70
+
71
+
72
+ def normalise_package_base(root: str) -> str:
73
+ if not root:
74
+ root = os.curdir
75
+ root = os.path.abspath(root)
76
+ if root.endswith(os.sep):
77
+ root = root[:-1]
78
+ return root
79
+
80
+
81
+ def get_explicit_package_bases(options: Options) -> list[str] | None:
82
+ """Returns explicit package bases to use if the option is enabled, or None if disabled.
83
+
84
+ We currently use MYPYPATH and the current directory as the package bases. In the future,
85
+ when --namespace-packages is the default could also use the values passed with the
86
+ --package-root flag, see #9632.
87
+
88
+ Values returned are normalised so we can use simple string comparisons in
89
+ SourceFinder.is_explicit_package_base
90
+ """
91
+ if not options.explicit_package_bases:
92
+ return None
93
+ roots = mypy_path() + options.mypy_path + [os.getcwd()]
94
+ return [normalise_package_base(root) for root in roots]
95
+
96
+
97
+ class SourceFinder:
98
+ def __init__(self, fscache: FileSystemCache, options: Options) -> None:
99
+ self.fscache = fscache
100
+ self.explicit_package_bases = get_explicit_package_bases(options)
101
+ self.namespace_packages = options.namespace_packages
102
+ self.exclude = options.exclude
103
+ self.exclude_gitignore = options.exclude_gitignore
104
+ self.verbosity = options.verbosity
105
+
106
+ def is_explicit_package_base(self, path: str) -> bool:
107
+ assert self.explicit_package_bases
108
+ return normalise_package_base(path) in self.explicit_package_bases
109
+
110
+ def find_sources_in_dir(self, path: str) -> list[BuildSource]:
111
+ sources = []
112
+
113
+ seen: set[str] = set()
114
+ names = sorted(self.fscache.listdir(path), key=keyfunc)
115
+ for name in names:
116
+ # Skip certain names altogether
117
+ if name in ("__pycache__", "site-packages", "node_modules") or name.startswith("."):
118
+ continue
119
+ subpath = os.path.join(path, name)
120
+
121
+ if matches_exclude(subpath, self.exclude, self.fscache, self.verbosity >= 2):
122
+ continue
123
+ if self.exclude_gitignore and matches_gitignore(
124
+ subpath, self.fscache, self.verbosity >= 2
125
+ ):
126
+ continue
127
+
128
+ if self.fscache.isdir(subpath):
129
+ sub_sources = self.find_sources_in_dir(subpath)
130
+ if sub_sources:
131
+ seen.add(name)
132
+ sources.extend(sub_sources)
133
+ else:
134
+ stem, suffix = os.path.splitext(name)
135
+ if stem not in seen and suffix in PY_EXTENSIONS:
136
+ seen.add(stem)
137
+ module, base_dir = self.crawl_up(subpath)
138
+ sources.append(BuildSource(subpath, module, None, base_dir))
139
+
140
+ return sources
141
+
142
+ def crawl_up(self, path: str) -> tuple[str, str]:
143
+ """Given a .py[i] filename, return module and base directory.
144
+
145
+ For example, given "xxx/yyy/foo/bar.py", we might return something like:
146
+ ("foo.bar", "xxx/yyy")
147
+
148
+ If namespace packages is off, we crawl upwards until we find a directory without
149
+ an __init__.py
150
+
151
+ If namespace packages is on, we crawl upwards until the nearest explicit base directory.
152
+ Failing that, we return one past the highest directory containing an __init__.py
153
+
154
+ We won't crawl past directories with invalid package names.
155
+ The base directory returned is an absolute path.
156
+ """
157
+ path = os.path.abspath(path)
158
+ parent, filename = os.path.split(path)
159
+
160
+ module_name = strip_py(filename) or filename
161
+
162
+ parent_module, base_dir = self.crawl_up_dir(parent)
163
+ if module_name == "__init__":
164
+ return parent_module, base_dir
165
+
166
+ # Note that module_name might not actually be a valid identifier, but that's okay
167
+ # Ignoring this possibility sidesteps some search path confusion
168
+ module = module_join(parent_module, module_name)
169
+ return module, base_dir
170
+
171
+ def crawl_up_dir(self, dir: str) -> tuple[str, str]:
172
+ return self._crawl_up_helper(dir) or ("", dir)
173
+
174
+ @functools.lru_cache # noqa: B019
175
+ def _crawl_up_helper(self, dir: str) -> tuple[str, str] | None:
176
+ """Given a directory, maybe returns module and base directory.
177
+
178
+ We return a non-None value if we were able to find something clearly intended as a base
179
+ directory (as adjudicated by being an explicit base directory or by containing a package
180
+ with __init__.py).
181
+
182
+ This distinction is necessary for namespace packages, so that we know when to treat
183
+ ourselves as a subpackage.
184
+ """
185
+ # stop crawling if we're an explicit base directory
186
+ if self.explicit_package_bases is not None and self.is_explicit_package_base(dir):
187
+ return "", dir
188
+
189
+ parent, name = os.path.split(dir)
190
+ name = name.removesuffix("-stubs") # PEP-561 stub-only directory
191
+
192
+ # recurse if there's an __init__.py
193
+ init_file = self.get_init_file(dir)
194
+ if init_file is not None:
195
+ if not name.isidentifier():
196
+ # in most cases the directory name is invalid, we'll just stop crawling upwards
197
+ # but if there's an __init__.py in the directory, something is messed up
198
+ raise InvalidSourceList(
199
+ f"{name} contains {os.path.basename(init_file)} "
200
+ "but is not a valid Python package name"
201
+ )
202
+ # we're definitely a package, so we always return a non-None value
203
+ mod_prefix, base_dir = self.crawl_up_dir(parent)
204
+ return module_join(mod_prefix, name), base_dir
205
+
206
+ # stop crawling if we're out of path components or our name is an invalid identifier
207
+ if not name or not parent or not name.isidentifier():
208
+ return None
209
+
210
+ # stop crawling if namespace packages is off (since we don't have an __init__.py)
211
+ if not self.namespace_packages:
212
+ return None
213
+
214
+ # at this point: namespace packages is on, we don't have an __init__.py and we're not an
215
+ # explicit base directory
216
+ result = self._crawl_up_helper(parent)
217
+ if result is None:
218
+ # we're not an explicit base directory and we don't have an __init__.py
219
+ # and none of our parents are either, so return
220
+ return None
221
+ # one of our parents was an explicit base directory or had an __init__.py, so we're
222
+ # definitely a subpackage! chain our name to the module.
223
+ mod_prefix, base_dir = result
224
+ return module_join(mod_prefix, name), base_dir
225
+
226
+ def get_init_file(self, dir: str) -> str | None:
227
+ """Check whether a directory contains a file named __init__.py[i].
228
+
229
+ If so, return the file's name (with dir prefixed). If not, return None.
230
+
231
+ This prefers .pyi over .py (because of the ordering of PY_EXTENSIONS).
232
+ """
233
+ for ext in PY_EXTENSIONS:
234
+ f = os.path.join(dir, "__init__" + ext)
235
+ if self.fscache.isfile(f):
236
+ return f
237
+ if ext == ".py" and self.fscache.init_under_package_root(f):
238
+ return f
239
+ return None
240
+
241
+
242
+ def module_join(parent: str, child: str) -> str:
243
+ """Join module ids, accounting for a possibly empty parent."""
244
+ if parent:
245
+ return parent + "." + child
246
+ return child
247
+
248
+
249
+ def strip_py(arg: str) -> str | None:
250
+ """Strip a trailing .py or .pyi suffix.
251
+
252
+ Return None if no such suffix is found.
253
+ """
254
+ for ext in PY_EXTENSIONS:
255
+ if arg.endswith(ext):
256
+ return arg[: -len(ext)]
257
+ return None
micromamba_root/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/fixup.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix up various things after deserialization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Final
6
+
7
+ from mypy.lookup import lookup_fully_qualified
8
+ from mypy.nodes import (
9
+ Block,
10
+ ClassDef,
11
+ Decorator,
12
+ FuncDef,
13
+ MypyFile,
14
+ OverloadedFuncDef,
15
+ ParamSpecExpr,
16
+ SymbolTable,
17
+ TypeAlias,
18
+ TypeInfo,
19
+ TypeVarExpr,
20
+ TypeVarTupleExpr,
21
+ Var,
22
+ )
23
+ from mypy.types import (
24
+ NOT_READY,
25
+ AnyType,
26
+ CallableType,
27
+ Instance,
28
+ LiteralType,
29
+ Overloaded,
30
+ Parameters,
31
+ ParamSpecType,
32
+ ProperType,
33
+ TupleType,
34
+ TypeAliasType,
35
+ TypedDictType,
36
+ TypeOfAny,
37
+ TypeType,
38
+ TypeVarTupleType,
39
+ TypeVarType,
40
+ TypeVisitor,
41
+ UnboundType,
42
+ UnionType,
43
+ UnpackType,
44
+ )
45
+ from mypy.visitor import NodeVisitor
46
+
47
+
48
+ # N.B: we do a allow_missing fixup when fixing up a fine-grained
49
+ # incremental cache load (since there may be cross-refs into deleted
50
+ # modules)
51
+ def fixup_module(tree: MypyFile, modules: dict[str, MypyFile], allow_missing: bool) -> None:
52
+ node_fixer = NodeFixer(modules, allow_missing)
53
+ node_fixer.visit_symbol_table(tree.names, tree.fullname)
54
+
55
+
56
+ # TODO: Fix up .info when deserializing, i.e. much earlier.
57
+ class NodeFixer(NodeVisitor[None]):
58
+ current_info: TypeInfo | None = None
59
+
60
+ def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:
61
+ self.modules = modules
62
+ self.allow_missing = allow_missing
63
+ self.type_fixer = TypeFixer(self.modules, allow_missing)
64
+
65
+ # NOTE: This method isn't (yet) part of the NodeVisitor API.
66
+ def visit_type_info(self, info: TypeInfo) -> None:
67
+ save_info = self.current_info
68
+ try:
69
+ self.current_info = info
70
+ if info.defn:
71
+ info.defn.accept(self)
72
+ if info.names:
73
+ self.visit_symbol_table(info.names, info.fullname)
74
+ if info.bases:
75
+ for base in info.bases:
76
+ base.accept(self.type_fixer)
77
+ if info._promote:
78
+ for p in info._promote:
79
+ p.accept(self.type_fixer)
80
+ if info.tuple_type:
81
+ info.tuple_type.accept(self.type_fixer)
82
+ info.update_tuple_type(info.tuple_type)
83
+ if info.special_alias:
84
+ info.special_alias.alias_tvars = list(info.defn.type_vars)
85
+ for i, t in enumerate(info.defn.type_vars):
86
+ if isinstance(t, TypeVarTupleType):
87
+ info.special_alias.tvar_tuple_index = i
88
+ if info.typeddict_type:
89
+ info.typeddict_type.accept(self.type_fixer)
90
+ info.update_typeddict_type(info.typeddict_type)
91
+ if info.special_alias:
92
+ info.special_alias.alias_tvars = list(info.defn.type_vars)
93
+ for i, t in enumerate(info.defn.type_vars):
94
+ if isinstance(t, TypeVarTupleType):
95
+ info.special_alias.tvar_tuple_index = i
96
+ if info.declared_metaclass:
97
+ info.declared_metaclass.accept(self.type_fixer)
98
+ if info.metaclass_type:
99
+ info.metaclass_type.accept(self.type_fixer)
100
+ if info.self_type:
101
+ info.self_type.accept(self.type_fixer)
102
+ if info.alt_promote:
103
+ info.alt_promote.accept(self.type_fixer)
104
+ instance = Instance(info, [])
105
+ # Hack: We may also need to add a backwards promotion (from int to native int),
106
+ # since it might not be serialized.
107
+ if instance not in info.alt_promote.type._promote:
108
+ info.alt_promote.type._promote.append(instance)
109
+ if info._mro_refs:
110
+ info.mro = [
111
+ lookup_fully_qualified_typeinfo(
112
+ self.modules, name, allow_missing=self.allow_missing
113
+ )
114
+ for name in info._mro_refs
115
+ ]
116
+ info._mro_refs = None
117
+ finally:
118
+ self.current_info = save_info
119
+
120
+ # NOTE: This method *definitely* isn't part of the NodeVisitor API.
121
+ def visit_symbol_table(self, symtab: SymbolTable, table_fullname: str) -> None:
122
+ # Copy the items because we may mutate symtab.
123
+ for key in list(symtab):
124
+ value = symtab[key]
125
+ cross_ref = value.cross_ref
126
+ if cross_ref is not None: # Fix up cross-reference.
127
+ value.cross_ref = None
128
+ if cross_ref in self.modules:
129
+ value.node = self.modules[cross_ref]
130
+ else:
131
+ stnode = lookup_fully_qualified(
132
+ cross_ref, self.modules, raise_on_missing=not self.allow_missing
133
+ )
134
+ if stnode is not None:
135
+ if stnode is value:
136
+ # The node seems to refer to itself, which can mean that
137
+ # the target is a deleted submodule of the current module,
138
+ # and thus lookup falls back to the symbol table of the parent
139
+ # package. Here's how this may happen:
140
+ #
141
+ # pkg/__init__.py:
142
+ # from pkg import sub
143
+ #
144
+ # Now if pkg.sub is deleted, the pkg.sub symbol table entry
145
+ # appears to refer to itself. Replace the entry with a
146
+ # placeholder to avoid a crash. We can't delete the entry,
147
+ # as it would stop dependency propagation.
148
+ value.node = Var(key + "@deleted")
149
+ else:
150
+ assert stnode.node is not None, (table_fullname + "." + key, cross_ref)
151
+ value.node = stnode.node
152
+ elif not self.allow_missing:
153
+ assert False, f"Could not find cross-ref {cross_ref}"
154
+ else:
155
+ # We have a missing crossref in allow missing mode, need to put something
156
+ value.node = missing_info(self.modules)
157
+ else:
158
+ if isinstance(value.node, TypeInfo):
159
+ # TypeInfo has no accept(). TODO: Add it?
160
+ self.visit_type_info(value.node)
161
+ elif value.node is not None:
162
+ value.node.accept(self)
163
+ else:
164
+ assert False, f"Unexpected empty node {key!r}: {value}"
165
+
166
+ def visit_func_def(self, func: FuncDef) -> None:
167
+ if self.current_info is not None:
168
+ func.info = self.current_info
169
+ if func.type is not None:
170
+ func.type.accept(self.type_fixer)
171
+ if isinstance(func.type, CallableType):
172
+ func.type.definition = func
173
+
174
+ def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:
175
+ if self.current_info is not None:
176
+ o.info = self.current_info
177
+ if o.type:
178
+ o.type.accept(self.type_fixer)
179
+ for item in o.items:
180
+ item.accept(self)
181
+ if o.impl:
182
+ o.impl.accept(self)
183
+ if isinstance(o.type, Overloaded):
184
+ # For error messages we link the original definition for each item.
185
+ for typ, item in zip(o.type.items, o.items):
186
+ typ.definition = item
187
+
188
+ def visit_decorator(self, d: Decorator) -> None:
189
+ if self.current_info is not None:
190
+ d.var.info = self.current_info
191
+ if d.func:
192
+ d.func.accept(self)
193
+ if d.var:
194
+ d.var.accept(self)
195
+ for node in d.decorators:
196
+ node.accept(self)
197
+ typ = d.var.type
198
+ if isinstance(typ, ProperType) and isinstance(typ, CallableType):
199
+ typ.definition = d.func
200
+
201
+ def visit_class_def(self, c: ClassDef) -> None:
202
+ for v in c.type_vars:
203
+ v.accept(self.type_fixer)
204
+
205
+ def visit_type_var_expr(self, tv: TypeVarExpr) -> None:
206
+ for value in tv.values:
207
+ value.accept(self.type_fixer)
208
+ tv.upper_bound.accept(self.type_fixer)
209
+ tv.default.accept(self.type_fixer)
210
+
211
+ def visit_paramspec_expr(self, p: ParamSpecExpr) -> None:
212
+ p.upper_bound.accept(self.type_fixer)
213
+ p.default.accept(self.type_fixer)
214
+
215
+ def visit_type_var_tuple_expr(self, tv: TypeVarTupleExpr) -> None:
216
+ tv.upper_bound.accept(self.type_fixer)
217
+ tv.tuple_fallback.accept(self.type_fixer)
218
+ tv.default.accept(self.type_fixer)
219
+
220
+ def visit_var(self, v: Var) -> None:
221
+ if self.current_info is not None:
222
+ v.info = self.current_info
223
+ if v.type is not None:
224
+ v.type.accept(self.type_fixer)
225
+ if v.setter_type is not None:
226
+ v.setter_type.accept(self.type_fixer)
227
+
228
+ def visit_type_alias(self, a: TypeAlias) -> None:
229
+ a.target.accept(self.type_fixer)
230
+ for v in a.alias_tvars:
231
+ v.accept(self.type_fixer)
232
+
233
+
234
+ class TypeFixer(TypeVisitor[None]):
235
+ def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:
236
+ self.modules = modules
237
+ self.allow_missing = allow_missing
238
+
239
+ def visit_instance(self, inst: Instance) -> None:
240
+ # TODO: Combine Instances that are exactly the same?
241
+ type_ref = inst.type_ref
242
+ if type_ref is None:
243
+ return # We've already been here.
244
+ inst.type_ref = None
245
+ inst.type = lookup_fully_qualified_typeinfo(
246
+ self.modules, type_ref, allow_missing=self.allow_missing
247
+ )
248
+ # TODO: Is this needed or redundant?
249
+ # Also fix up the bases, just in case.
250
+ for base in inst.type.bases:
251
+ if base.type is NOT_READY:
252
+ base.accept(self)
253
+ for a in inst.args:
254
+ a.accept(self)
255
+ if inst.last_known_value is not None:
256
+ inst.last_known_value.accept(self)
257
+ if inst.extra_attrs:
258
+ for v in inst.extra_attrs.attrs.values():
259
+ v.accept(self)
260
+
261
+ def visit_type_alias_type(self, t: TypeAliasType) -> None:
262
+ type_ref = t.type_ref
263
+ if type_ref is None:
264
+ return # We've already been here.
265
+ t.type_ref = None
266
+ t.alias = lookup_fully_qualified_alias(
267
+ self.modules, type_ref, allow_missing=self.allow_missing
268
+ )
269
+ for a in t.args:
270
+ a.accept(self)
271
+
272
+ def visit_any(self, o: Any) -> None:
273
+ pass # Nothing to descend into.
274
+
275
+ def visit_callable_type(self, ct: CallableType) -> None:
276
+ if ct.fallback:
277
+ ct.fallback.accept(self)
278
+ for argt in ct.arg_types:
279
+ # argt may be None, e.g. for __self in NamedTuple constructors.
280
+ if argt is not None:
281
+ argt.accept(self)
282
+ if ct.ret_type is not None:
283
+ ct.ret_type.accept(self)
284
+ for v in ct.variables:
285
+ v.accept(self)
286
+ if ct.type_guard is not None:
287
+ ct.type_guard.accept(self)
288
+ if ct.type_is is not None:
289
+ ct.type_is.accept(self)
290
+
291
+ def visit_overloaded(self, t: Overloaded) -> None:
292
+ for ct in t.items:
293
+ ct.accept(self)
294
+
295
+ def visit_erased_type(self, o: Any) -> None:
296
+ # This type should exist only temporarily during type inference
297
+ raise RuntimeError("Shouldn't get here", o)
298
+
299
+ def visit_deleted_type(self, o: Any) -> None:
300
+ pass # Nothing to descend into.
301
+
302
+ def visit_none_type(self, o: Any) -> None:
303
+ pass # Nothing to descend into.
304
+
305
+ def visit_uninhabited_type(self, o: Any) -> None:
306
+ pass # Nothing to descend into.
307
+
308
+ def visit_partial_type(self, o: Any) -> None:
309
+ raise RuntimeError("Shouldn't get here", o)
310
+
311
+ def visit_tuple_type(self, tt: TupleType) -> None:
312
+ if tt.items:
313
+ for it in tt.items:
314
+ it.accept(self)
315
+ if tt.partial_fallback is not None:
316
+ tt.partial_fallback.accept(self)
317
+
318
+ def visit_typeddict_type(self, tdt: TypedDictType) -> None:
319
+ if tdt.items:
320
+ for it in tdt.items.values():
321
+ it.accept(self)
322
+ if tdt.fallback is not None:
323
+ if tdt.fallback.type_ref is not None:
324
+ if (
325
+ lookup_fully_qualified(
326
+ tdt.fallback.type_ref,
327
+ self.modules,
328
+ raise_on_missing=not self.allow_missing,
329
+ )
330
+ is None
331
+ ):
332
+ # We reject fake TypeInfos for TypedDict fallbacks because
333
+ # the latter are used in type checking and must be valid.
334
+ tdt.fallback.type_ref = "typing._TypedDict"
335
+ tdt.fallback.accept(self)
336
+
337
+ def visit_literal_type(self, lt: LiteralType) -> None:
338
+ lt.fallback.accept(self)
339
+
340
+ def visit_type_var(self, tvt: TypeVarType) -> None:
341
+ if tvt.values:
342
+ for vt in tvt.values:
343
+ vt.accept(self)
344
+ tvt.upper_bound.accept(self)
345
+ tvt.default.accept(self)
346
+
347
+ def visit_param_spec(self, p: ParamSpecType) -> None:
348
+ p.upper_bound.accept(self)
349
+ p.default.accept(self)
350
+ p.prefix.accept(self)
351
+
352
+ def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:
353
+ t.tuple_fallback.accept(self)
354
+ t.upper_bound.accept(self)
355
+ t.default.accept(self)
356
+
357
+ def visit_unpack_type(self, u: UnpackType) -> None:
358
+ u.type.accept(self)
359
+
360
+ def visit_parameters(self, p: Parameters) -> None:
361
+ for argt in p.arg_types:
362
+ if argt is not None:
363
+ argt.accept(self)
364
+ for var in p.variables:
365
+ var.accept(self)
366
+
367
+ def visit_unbound_type(self, o: UnboundType) -> None:
368
+ for a in o.args:
369
+ a.accept(self)
370
+
371
+ def visit_union_type(self, ut: UnionType) -> None:
372
+ if ut.items:
373
+ for it in ut.items:
374
+ it.accept(self)
375
+
376
+ def visit_type_type(self, t: TypeType) -> None:
377
+ t.item.accept(self)
378
+
379
+
380
+ def lookup_fully_qualified_typeinfo(
381
+ modules: dict[str, MypyFile], name: str, *, allow_missing: bool
382
+ ) -> TypeInfo:
383
+ stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)
384
+ node = stnode.node if stnode else None
385
+ if isinstance(node, TypeInfo):
386
+ return node
387
+ else:
388
+ # Looks like a missing TypeInfo during an initial daemon load, put something there
389
+ assert (
390
+ allow_missing
391
+ ), "Should never get here in normal mode, got {}:{} instead of TypeInfo".format(
392
+ type(node).__name__, node.fullname if node else ""
393
+ )
394
+ return missing_info(modules)
395
+
396
+
397
+ def lookup_fully_qualified_alias(
398
+ modules: dict[str, MypyFile], name: str, *, allow_missing: bool
399
+ ) -> TypeAlias:
400
+ stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)
401
+ node = stnode.node if stnode else None
402
+ if isinstance(node, TypeAlias):
403
+ return node
404
+ elif isinstance(node, TypeInfo):
405
+ if node.special_alias:
406
+ # Already fixed up.
407
+ return node.special_alias
408
+ if node.tuple_type:
409
+ alias = TypeAlias.from_tuple_type(node)
410
+ elif node.typeddict_type:
411
+ alias = TypeAlias.from_typeddict_type(node)
412
+ else:
413
+ assert allow_missing
414
+ return missing_alias()
415
+ node.special_alias = alias
416
+ return alias
417
+ else:
418
+ # Looks like a missing TypeAlias during an initial daemon load, put something there
419
+ assert (
420
+ allow_missing
421
+ ), "Should never get here in normal mode, got {}:{} instead of TypeAlias".format(
422
+ type(node).__name__, node.fullname if node else ""
423
+ )
424
+ return missing_alias()
425
+
426
+
427
+ _SUGGESTION: Final = "<missing {}: *should* have gone away during fine-grained update>"
428
+
429
+
430
+ def missing_info(modules: dict[str, MypyFile]) -> TypeInfo:
431
+ suggestion = _SUGGESTION.format("info")
432
+ dummy_def = ClassDef(suggestion, Block([]))
433
+ dummy_def.fullname = suggestion
434
+
435
+ info = TypeInfo(SymbolTable(), dummy_def, "<missing>")
436
+ obj_type = lookup_fully_qualified_typeinfo(modules, "builtins.object", allow_missing=False)
437
+ info.bases = [Instance(obj_type, [])]
438
+ info.mro = [info, obj_type]
439
+ return info
440
+
441
+
442
+ def missing_alias() -> TypeAlias:
443
+ suggestion = _SUGGESTION.format("alias")
444
+ return TypeAlias(AnyType(TypeOfAny.special_form), suggestion, "<missing>", line=-1, column=-1)
micromamba_root/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/freetree.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generic node traverser visitor"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from mypy.nodes import Block, MypyFile
6
+ from mypy.traverser import TraverserVisitor
7
+
8
+
9
+ class TreeFreer(TraverserVisitor):
10
+ def visit_block(self, block: Block) -> None:
11
+ super().visit_block(block)
12
+ block.body.clear()
13
+
14
+
15
+ def free_tree(tree: MypyFile) -> None:
16
+ """Free all the ASTs associated with a module.
17
+
18
+ This needs to be done recursively, since symbol tables contain
19
+ references to definitions, so those won't be freed but we want their
20
+ contents to be.
21
+ """
22
+ tree.accept(TreeFreer())
23
+ tree.defs.clear()
micromamba_root/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/fscache.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interface for accessing the file system with automatic caching.
2
+
3
+ The idea is to cache the results of any file system state reads during
4
+ a single transaction. This has two main benefits:
5
+
6
+ * This avoids redundant syscalls, as we won't perform the same OS
7
+ operations multiple times.
8
+
9
+ * This makes it easier to reason about concurrent FS updates, as different
10
+ operations targeting the same paths can't report different state during
11
+ a transaction.
12
+
13
+ Note that this only deals with reading state, not writing.
14
+
15
+ Properties maintained by the API:
16
+
17
+ * The contents of the file are always from the same or later time compared
18
+ to the reported mtime of the file, even if mtime is queried after reading
19
+ a file.
20
+
21
+ * Repeating an operation produces the same result as the first one during
22
+ a transaction.
23
+
24
+ * Call flush() to start a new transaction (flush the caches).
25
+
26
+ The API is a bit limited. It's easy to add new cached operations, however.
27
+ You should perform all file system reads through the API to actually take
28
+ advantage of the benefits.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import os
34
+ import stat
35
+
36
+ from mypy_extensions import mypyc_attr
37
+
38
+ from mypy.util import hash_digest
39
+
40
+
41
+ @mypyc_attr(allow_interpreted_subclasses=True) # for tests
42
+ class FileSystemCache:
43
+ def __init__(self) -> None:
44
+ # The package root is not flushed with the caches.
45
+ # It is set by set_package_root() below.
46
+ self.package_root: list[str] = []
47
+ self.flush()
48
+
49
+ def set_package_root(self, package_root: list[str]) -> None:
50
+ self.package_root = package_root
51
+
52
+ def flush(self) -> None:
53
+ """Start another transaction and empty all caches."""
54
+ self.stat_or_none_cache: dict[str, os.stat_result | None] = {}
55
+
56
+ self.listdir_cache: dict[str, list[str]] = {}
57
+ self.listdir_error_cache: dict[str, OSError] = {}
58
+ self.isfile_case_cache: dict[str, bool] = {}
59
+ self.exists_case_cache: dict[str, bool] = {}
60
+ self.read_cache: dict[str, bytes] = {}
61
+ self.read_error_cache: dict[str, Exception] = {}
62
+ self.hash_cache: dict[str, str] = {}
63
+ self.fake_package_cache: set[str] = set()
64
+
65
+ def stat_or_none(self, path: str) -> os.stat_result | None:
66
+ if path in self.stat_or_none_cache:
67
+ return self.stat_or_none_cache[path]
68
+
69
+ st = None
70
+ try:
71
+ st = os.stat(path)
72
+ except OSError:
73
+ if self.init_under_package_root(path):
74
+ try:
75
+ st = self._fake_init(path)
76
+ except OSError:
77
+ pass
78
+
79
+ self.stat_or_none_cache[path] = st
80
+ return st
81
+
82
+ def init_under_package_root(self, path: str) -> bool:
83
+ """Is this path an __init__.py under a package root?
84
+
85
+ This is used to detect packages that don't contain __init__.py
86
+ files, which is needed to support Bazel. The function should
87
+ only be called for non-existing files.
88
+
89
+ It will return True if it refers to a __init__.py file that
90
+ Bazel would create, so that at runtime Python would think the
91
+ directory containing it is a package. For this to work you
92
+ must pass one or more package roots using the --package-root
93
+ flag.
94
+
95
+ As an exceptional case, any directory that is a package root
96
+ itself will not be considered to contain a __init__.py file.
97
+ This is different from the rules Bazel itself applies, but is
98
+ necessary for mypy to properly distinguish packages from other
99
+ directories.
100
+
101
+ See https://docs.bazel.build/versions/master/be/python.html,
102
+ where this behavior is described under legacy_create_init.
103
+ """
104
+ if not self.package_root:
105
+ return False
106
+ dirname, basename = os.path.split(path)
107
+ if basename != "__init__.py":
108
+ return False
109
+ if not os.path.basename(dirname).isidentifier():
110
+ # Can't put an __init__.py in a place that's not an identifier
111
+ return False
112
+
113
+ st = self.stat_or_none(dirname)
114
+ if st is None:
115
+ return False
116
+ else:
117
+ if not stat.S_ISDIR(st.st_mode):
118
+ return False
119
+ ok = False
120
+
121
+ # skip if on a different drive
122
+ current_drive, _ = os.path.splitdrive(os.getcwd())
123
+ drive, _ = os.path.splitdrive(path)
124
+ if drive != current_drive:
125
+ return False
126
+ if os.path.isabs(path):
127
+ path = os.path.relpath(path)
128
+ path = os.path.normpath(path)
129
+ for root in self.package_root:
130
+ if path.startswith(root):
131
+ if path == root + basename:
132
+ # A package root itself is never a package.
133
+ ok = False
134
+ break
135
+ else:
136
+ ok = True
137
+ return ok
138
+
139
+ def _fake_init(self, path: str) -> os.stat_result:
140
+ """Prime the cache with a fake __init__.py file.
141
+
142
+ This makes code that looks for path believe an empty file by
143
+ that name exists. Should only be called after
144
+ init_under_package_root() returns True.
145
+ """
146
+ dirname, basename = os.path.split(path)
147
+ assert basename == "__init__.py", path
148
+ assert not os.path.exists(path), path # Not cached!
149
+ dirname = os.path.normpath(dirname)
150
+ st = os.stat(dirname) # May raise OSError
151
+ # Get stat result as a list so we can modify it.
152
+ seq: list[float] = list(st)
153
+ seq[stat.ST_MODE] = stat.S_IFREG | 0o444
154
+ seq[stat.ST_INO] = 1
155
+ seq[stat.ST_NLINK] = 1
156
+ seq[stat.ST_SIZE] = 0
157
+ st = os.stat_result(seq)
158
+ # Make listdir() and read() also pretend this file exists.
159
+ self.fake_package_cache.add(dirname)
160
+ return st
161
+
162
+ def listdir(self, path: str) -> list[str]:
163
+ path = os.path.normpath(path)
164
+ if path in self.listdir_cache:
165
+ res = self.listdir_cache[path]
166
+ # Check the fake cache.
167
+ if path in self.fake_package_cache and "__init__.py" not in res:
168
+ res.append("__init__.py") # Updates the result as well as the cache
169
+ return res
170
+ if path in self.listdir_error_cache:
171
+ raise copy_os_error(self.listdir_error_cache[path])
172
+ try:
173
+ results = os.listdir(path)
174
+ except OSError as err:
175
+ # Like above, take a copy to reduce memory use.
176
+ self.listdir_error_cache[path] = copy_os_error(err)
177
+ raise err
178
+ self.listdir_cache[path] = results
179
+ # Check the fake cache.
180
+ if path in self.fake_package_cache and "__init__.py" not in results:
181
+ results.append("__init__.py")
182
+ return results
183
+
184
+ def isfile(self, path: str) -> bool:
185
+ st = self.stat_or_none(path)
186
+ if st is None:
187
+ return False
188
+ return stat.S_ISREG(st.st_mode)
189
+
190
+ def isfile_case(self, path: str, prefix: str) -> bool:
191
+ """Return whether path exists and is a file.
192
+
193
+ On case-insensitive filesystems (like Mac or Windows) this returns
194
+ False if the case of path's last component does not exactly match
195
+ the case found in the filesystem.
196
+
197
+ We check also the case of other path components up to prefix.
198
+ For example, if path is 'user-stubs/pack/mod.pyi' and prefix is 'user-stubs',
199
+ we check that the case of 'pack' and 'mod.py' matches exactly, 'user-stubs' will be
200
+ case insensitive on case insensitive filesystems.
201
+
202
+ The caller must ensure that prefix is a valid file system prefix of path.
203
+ """
204
+ if not self.isfile(path):
205
+ # Fast path
206
+ return False
207
+ if path in self.isfile_case_cache:
208
+ return self.isfile_case_cache[path]
209
+ head, tail = os.path.split(path)
210
+ if not tail:
211
+ self.isfile_case_cache[path] = False
212
+ return False
213
+ try:
214
+ names = self.listdir(head)
215
+ # This allows one to check file name case sensitively in
216
+ # case-insensitive filesystems.
217
+ res = tail in names
218
+ except OSError:
219
+ res = False
220
+ if res:
221
+ # Also recursively check the other path components in case sensitive way.
222
+ res = self.exists_case(head, prefix)
223
+ self.isfile_case_cache[path] = res
224
+ return res
225
+
226
+ def exists_case(self, path: str, prefix: str) -> bool:
227
+ """Return whether path exists - checking path components in case sensitive
228
+ fashion, up to prefix.
229
+ """
230
+ if path in self.exists_case_cache:
231
+ return self.exists_case_cache[path]
232
+ head, tail = os.path.split(path)
233
+ if not head.startswith(prefix) or not tail:
234
+ # Only perform the check for paths under prefix.
235
+ self.exists_case_cache[path] = True
236
+ return True
237
+ try:
238
+ names = self.listdir(head)
239
+ # This allows one to check file name case sensitively in
240
+ # case-insensitive filesystems.
241
+ res = tail in names
242
+ except OSError:
243
+ res = False
244
+ if res:
245
+ # Also recursively check other path components.
246
+ res = self.exists_case(head, prefix)
247
+ self.exists_case_cache[path] = res
248
+ return res
249
+
250
+ def isdir(self, path: str) -> bool:
251
+ st = self.stat_or_none(path)
252
+ if st is None:
253
+ return False
254
+ return stat.S_ISDIR(st.st_mode)
255
+
256
+ def exists(self, path: str) -> bool:
257
+ st = self.stat_or_none(path)
258
+ return st is not None
259
+
260
+ def read(self, path: str) -> bytes:
261
+ if path in self.read_cache:
262
+ return self.read_cache[path]
263
+ if path in self.read_error_cache:
264
+ raise self.read_error_cache[path]
265
+
266
+ # Need to stat first so that the contents of file are from no
267
+ # earlier instant than the mtime reported by self.stat().
268
+ self.stat_or_none(path)
269
+
270
+ dirname, basename = os.path.split(path)
271
+ dirname = os.path.normpath(dirname)
272
+ # Check the fake cache.
273
+ if basename == "__init__.py" and dirname in self.fake_package_cache:
274
+ data = b""
275
+ else:
276
+ try:
277
+ with open(path, "rb") as f:
278
+ data = f.read()
279
+ except OSError as err:
280
+ self.read_error_cache[path] = err
281
+ raise
282
+
283
+ self.read_cache[path] = data
284
+ self.hash_cache[path] = hash_digest(data)
285
+ return data
286
+
287
+ def hash_digest(self, path: str) -> str:
288
+ if path not in self.hash_cache:
289
+ self.read(path)
290
+ return self.hash_cache[path]
291
+
292
+ def samefile(self, f1: str, f2: str) -> bool:
293
+ s1 = self.stat_or_none(f1)
294
+ s2 = self.stat_or_none(f2)
295
+ if s1 is None or s2 is None:
296
+ return False
297
+ return os.path.samestat(s1, s2)
298
+
299
+
300
+ def copy_os_error(e: OSError) -> OSError:
301
+ new = OSError(*e.args)
302
+ new.errno = e.errno
303
+ new.strerror = e.strerror
304
+ new.filename = e.filename
305
+ if e.filename2:
306
+ new.filename2 = e.filename2
307
+ return new
micromamba_root/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/fswatcher.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Watch parts of the file system for changes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Iterable, Set as AbstractSet
7
+ from typing import NamedTuple
8
+
9
+ from mypy.fscache import FileSystemCache
10
+
11
+
12
+ class FileData(NamedTuple):
13
+ st_mtime: float
14
+ st_size: int
15
+ hash: str
16
+
17
+
18
+ class FileSystemWatcher:
19
+ """Watcher for file system changes among specific paths.
20
+
21
+ All file system access is performed using FileSystemCache. We
22
+ detect changed files by stat()ing them all and comparing hashes
23
+ of potentially changed files. If a file has both size and mtime
24
+ unmodified, the file is assumed to be unchanged.
25
+
26
+ An important goal of this class is to make it easier to eventually
27
+ use file system events to detect file changes.
28
+
29
+ Note: This class doesn't flush the file system cache. If you don't
30
+ manually flush it, changes won't be seen.
31
+ """
32
+
33
+ # TODO: Watching directories?
34
+ # TODO: Handle non-files
35
+
36
+ def __init__(self, fs: FileSystemCache) -> None:
37
+ self.fs = fs
38
+ self._paths: set[str] = set()
39
+ self._file_data: dict[str, FileData | None] = {}
40
+
41
+ def dump_file_data(self) -> dict[str, tuple[float, int, str]]:
42
+ return {k: v for k, v in self._file_data.items() if v is not None}
43
+
44
+ def set_file_data(self, path: str, data: FileData) -> None:
45
+ self._file_data[path] = data
46
+
47
+ def add_watched_paths(self, paths: Iterable[str]) -> None:
48
+ for path in paths:
49
+ if path not in self._paths:
50
+ # By storing None this path will get reported as changed by
51
+ # find_changed if it exists.
52
+ self._file_data[path] = None
53
+ self._paths |= set(paths)
54
+
55
+ def remove_watched_paths(self, paths: Iterable[str]) -> None:
56
+ for path in paths:
57
+ if path in self._file_data:
58
+ del self._file_data[path]
59
+ self._paths -= set(paths)
60
+
61
+ def _update(self, path: str, st: os.stat_result) -> None:
62
+ hash_digest = self.fs.hash_digest(path)
63
+ self._file_data[path] = FileData(st.st_mtime, st.st_size, hash_digest)
64
+
65
+ def _find_changed(self, paths: Iterable[str]) -> AbstractSet[str]:
66
+ changed = set()
67
+ for path in paths:
68
+ old = self._file_data[path]
69
+ st = self.fs.stat_or_none(path)
70
+ if st is None:
71
+ if old is not None:
72
+ # File was deleted.
73
+ changed.add(path)
74
+ self._file_data[path] = None
75
+ else:
76
+ if old is None:
77
+ # File is new.
78
+ changed.add(path)
79
+ self._update(path, st)
80
+ # Round mtimes down, to match the mtimes we write to meta files
81
+ elif st.st_size != old.st_size or int(st.st_mtime) != int(old.st_mtime):
82
+ # Only look for changes if size or mtime has changed as an
83
+ # optimization, since calculating hash is expensive.
84
+ new_hash = self.fs.hash_digest(path)
85
+ self._update(path, st)
86
+ if st.st_size != old.st_size or new_hash != old.hash:
87
+ # Changed file.
88
+ changed.add(path)
89
+ return changed
90
+
91
+ def find_changed(self) -> AbstractSet[str]:
92
+ """Return paths that have changes since the last call, in the watched set."""
93
+ return self._find_changed(self._paths)
94
+
95
+ def update_changed(self, remove: list[str], update: list[str]) -> AbstractSet[str]:
96
+ """Alternative to find_changed() given explicit changes.
97
+
98
+ This only calls self.fs.stat() on added or updated files, not
99
+ on all files. It believes all other files are unchanged!
100
+
101
+ Implies add_watched_paths() for add and update, and
102
+ remove_watched_paths() for remove.
103
+ """
104
+ self.remove_watched_paths(remove)
105
+ self.add_watched_paths(update)
106
+ return self._find_changed(update)
micromamba_root/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/gclogger.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import gc
4
+ import time
5
+ from collections.abc import Mapping
6
+
7
+
8
+ class GcLogger:
9
+ """Context manager to log GC stats and overall time."""
10
+
11
+ def __enter__(self) -> GcLogger:
12
+ self.gc_start_time: float | None = None
13
+ self.gc_time = 0.0
14
+ self.gc_calls = 0
15
+ self.gc_collected = 0
16
+ self.gc_uncollectable = 0
17
+ gc.callbacks.append(self.gc_callback)
18
+ self.start_time = time.time()
19
+ return self
20
+
21
+ def gc_callback(self, phase: str, info: Mapping[str, int]) -> None:
22
+ if phase == "start":
23
+ assert self.gc_start_time is None, "Start phase out of sequence"
24
+ self.gc_start_time = time.time()
25
+ elif phase == "stop":
26
+ assert self.gc_start_time is not None, "Stop phase out of sequence"
27
+ self.gc_calls += 1
28
+ self.gc_time += time.time() - self.gc_start_time
29
+ self.gc_start_time = None
30
+ self.gc_collected += info["collected"]
31
+ self.gc_uncollectable += info["uncollectable"]
32
+ else:
33
+ assert False, f"Unrecognized gc phase ({phase!r})"
34
+
35
+ def __exit__(self, *args: object) -> None:
36
+ while self.gc_callback in gc.callbacks:
37
+ gc.callbacks.remove(self.gc_callback)
38
+
39
+ def get_stats(self) -> Mapping[str, float]:
40
+ end_time = time.time()
41
+ result = {
42
+ "gc_time": self.gc_time,
43
+ "gc_calls": self.gc_calls,
44
+ "gc_collected": self.gc_collected,
45
+ "gc_uncollectable": self.gc_uncollectable,
46
+ "build_time": end_time - self.start_time,
47
+ }
48
+ return result
micromamba_root/Lib/site-packages/mypy/git.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/git.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Git utilities."""
2
+
3
+ # Used also from setup.py, so don't pull in anything additional here (like mypy or typing):
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import subprocess
8
+
9
+
10
+ def is_git_repo(dir: str) -> bool:
11
+ """Is the given directory version-controlled with git?"""
12
+ return os.path.exists(os.path.join(dir, ".git"))
13
+
14
+
15
+ def have_git() -> bool:
16
+ """Can we run the git executable?"""
17
+ try:
18
+ subprocess.check_output(["git", "--help"])
19
+ return True
20
+ except subprocess.CalledProcessError:
21
+ return False
22
+ except OSError:
23
+ return False
24
+
25
+
26
+ def git_revision(dir: str) -> bytes:
27
+ """Get the SHA-1 of the HEAD of a git repository."""
28
+ return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=dir).strip()
29
+
30
+
31
+ def is_dirty(dir: str) -> bool:
32
+ """Check whether a git repository has uncommitted changes."""
33
+ output = subprocess.check_output(["git", "status", "-uno", "--porcelain"], cwd=dir)
34
+ return output.strip() != b""
micromamba_root/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/graph_utils.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for manipulations with graphs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Set as AbstractSet
6
+ from typing import TypeVar
7
+
8
+ T = TypeVar("T")
9
+
10
+
11
+ def strongly_connected_components(
12
+ vertices: AbstractSet[T], edges: dict[T, list[T]]
13
+ ) -> Iterator[set[T]]:
14
+ """Compute Strongly Connected Components of a directed graph.
15
+
16
+ Args:
17
+ vertices: the labels for the vertices
18
+ edges: for each vertex, gives the target vertices of its outgoing edges
19
+
20
+ Returns:
21
+ An iterator yielding strongly connected components, each
22
+ represented as a set of vertices. Each input vertex will occur
23
+ exactly once; vertices not part of a SCC are returned as
24
+ singleton sets.
25
+
26
+ From https://code.activestate.com/recipes/578507/.
27
+ """
28
+ identified: set[T] = set()
29
+ stack: list[T] = []
30
+ index: dict[T, int] = {}
31
+ boundaries: list[int] = []
32
+
33
+ def dfs(v: T) -> Iterator[set[T]]:
34
+ index[v] = len(stack)
35
+ stack.append(v)
36
+ boundaries.append(index[v])
37
+
38
+ for w in edges[v]:
39
+ if w not in index:
40
+ yield from dfs(w)
41
+ elif w not in identified:
42
+ while index[w] < boundaries[-1]:
43
+ boundaries.pop()
44
+
45
+ if boundaries[-1] == index[v]:
46
+ boundaries.pop()
47
+ scc = set(stack[index[v] :])
48
+ del stack[index[v] :]
49
+ identified.update(scc)
50
+ yield scc
51
+
52
+ for v in vertices:
53
+ if v not in index:
54
+ yield from dfs(v)
55
+
56
+
57
+ def prepare_sccs(
58
+ sccs: list[set[T]], edges: dict[T, list[T]]
59
+ ) -> dict[AbstractSet[T], set[AbstractSet[T]]]:
60
+ """Use original edges to organize SCCs in a graph by dependencies between them."""
61
+ sccsmap = {}
62
+ for scc in sccs:
63
+ scc_frozen = frozenset(scc)
64
+ for v in scc:
65
+ sccsmap[v] = scc_frozen
66
+ data: dict[AbstractSet[T], set[AbstractSet[T]]] = {}
67
+ for scc in sccs:
68
+ deps: set[AbstractSet[T]] = set()
69
+ for v in scc:
70
+ deps.update(sccsmap[x] for x in edges[v])
71
+ data[frozenset(scc)] = deps
72
+ return data
73
+
74
+
75
+ class topsort(Iterator[set[T]]): # noqa: N801
76
+ """Topological sort using Kahn's algorithm.
77
+
78
+ Uses in-degree counters and a reverse adjacency list, so the total work
79
+ is O(V + E).
80
+
81
+ Implemented as a class rather than a generator for better mypyc
82
+ compilation.
83
+
84
+ Args:
85
+ data: A map from vertices to all vertices that it has an edge
86
+ connecting it to. NOTE: dependency sets in this data
87
+ structure are modified in place to remove self-dependencies.
88
+ Orphans are handled internally and are not added to `data`.
89
+
90
+ Returns:
91
+ An iterator yielding sets of vertices that have an equivalent
92
+ ordering.
93
+
94
+ Example:
95
+ Suppose the input has the following structure:
96
+
97
+ {A: {B, C}, B: {D}, C: {D}}
98
+
99
+ The algorithm treats orphan dependencies as if normalized to:
100
+
101
+ {A: {B, C}, B: {D}, C: {D}, D: {}}
102
+
103
+ It will yield the following values:
104
+
105
+ {D}
106
+ {B, C}
107
+ {A}
108
+ """
109
+
110
+ def __init__(self, data: dict[T, set[T]]) -> None:
111
+ # Single pass: remove self-deps, build reverse adjacency list,
112
+ # compute in-degree counts, detect orphans, and find initial ready set.
113
+ in_degree: dict[T, int] = {}
114
+ rev: dict[T, list[T]] = {}
115
+ ready: set[T] = set()
116
+ for item, deps in data.items():
117
+ deps.discard(item) # Ignore self dependencies.
118
+ deg = len(deps)
119
+ in_degree[item] = deg
120
+ if deg == 0:
121
+ ready.add(item)
122
+ if item not in rev:
123
+ rev[item] = []
124
+ for dep in deps:
125
+ if dep in rev:
126
+ rev[dep].append(item)
127
+ else:
128
+ rev[dep] = [item]
129
+ if dep not in data:
130
+ # Orphan: appears as dependency but has no entry in data.
131
+ in_degree[dep] = 0
132
+ ready.add(dep)
133
+
134
+ self.in_degree = in_degree
135
+ self.rev = rev
136
+ self.ready = ready
137
+ self.remaining = len(in_degree) - len(ready)
138
+
139
+ def __iter__(self) -> Iterator[set[T]]:
140
+ return self
141
+
142
+ def __next__(self) -> set[T]:
143
+ ready = self.ready
144
+ if not ready:
145
+ assert self.remaining == 0, (
146
+ f"A cyclic dependency exists amongst "
147
+ f"{[k for k, deg in self.in_degree.items() if deg > 0]!r}"
148
+ )
149
+ raise StopIteration
150
+ in_degree = self.in_degree
151
+ rev = self.rev
152
+ new_ready: set[T] = set()
153
+ for item in ready:
154
+ for dependent in rev[item]:
155
+ new_deg = in_degree[dependent] - 1
156
+ in_degree[dependent] = new_deg
157
+ if new_deg == 0:
158
+ new_ready.add(dependent)
159
+ self.remaining -= len(new_ready)
160
+ self.ready = new_ready
161
+ return ready
micromamba_root/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/indirection.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+
5
+ import mypy.types as types
6
+ from mypy.types import TypeVisitor
7
+
8
+
9
+ class TypeIndirectionVisitor(TypeVisitor[None]):
10
+ """Returns all module references within a particular type."""
11
+
12
+ def __init__(self) -> None:
13
+ # Module references are collected here
14
+ self.modules: set[str] = set()
15
+ # User to avoid infinite recursion with recursive types
16
+ self.seen_types: set[types.TypeAliasType | types.Instance] = set()
17
+
18
+ def find_modules(self, typs: Iterable[types.Type]) -> set[str]:
19
+ self.modules = set()
20
+ self.seen_types = set()
21
+ for typ in typs:
22
+ self._visit(typ)
23
+ return self.modules
24
+
25
+ def _visit(self, typ: types.Type) -> None:
26
+ # Note: instances are needed for `class str(Sequence[str]): ...`
27
+ if (
28
+ isinstance(typ, types.TypeAliasType)
29
+ or isinstance(typ, types.ProperType)
30
+ and isinstance(typ, types.Instance)
31
+ ):
32
+ # Avoid infinite recursion for recursive types.
33
+ if typ in self.seen_types:
34
+ return
35
+ self.seen_types.add(typ)
36
+ typ.accept(self)
37
+
38
+ def _visit_type_tuple(self, typs: tuple[types.Type, ...]) -> None:
39
+ # Micro-optimization: Specialized version of _visit for lists
40
+ for typ in typs:
41
+ if (
42
+ isinstance(typ, types.TypeAliasType)
43
+ or isinstance(typ, types.ProperType)
44
+ and isinstance(typ, types.Instance)
45
+ ):
46
+ # Avoid infinite recursion for recursive types.
47
+ if typ in self.seen_types:
48
+ continue
49
+ self.seen_types.add(typ)
50
+ typ.accept(self)
51
+
52
+ def _visit_type_list(self, typs: list[types.Type]) -> None:
53
+ # Micro-optimization: Specialized version of _visit for tuples
54
+ for typ in typs:
55
+ if (
56
+ isinstance(typ, types.TypeAliasType)
57
+ or isinstance(typ, types.ProperType)
58
+ and isinstance(typ, types.Instance)
59
+ ):
60
+ # Avoid infinite recursion for recursive types.
61
+ if typ in self.seen_types:
62
+ continue
63
+ self.seen_types.add(typ)
64
+ typ.accept(self)
65
+
66
+ def visit_unbound_type(self, t: types.UnboundType) -> None:
67
+ self._visit_type_tuple(t.args)
68
+
69
+ def visit_any(self, t: types.AnyType) -> None:
70
+ pass
71
+
72
+ def visit_none_type(self, t: types.NoneType) -> None:
73
+ pass
74
+
75
+ def visit_uninhabited_type(self, t: types.UninhabitedType) -> None:
76
+ pass
77
+
78
+ def visit_erased_type(self, t: types.ErasedType) -> None:
79
+ pass
80
+
81
+ def visit_deleted_type(self, t: types.DeletedType) -> None:
82
+ pass
83
+
84
+ def visit_type_var(self, t: types.TypeVarType) -> None:
85
+ self._visit_type_list(t.values)
86
+ self._visit(t.upper_bound)
87
+ self._visit(t.default)
88
+
89
+ def visit_param_spec(self, t: types.ParamSpecType) -> None:
90
+ self._visit(t.upper_bound)
91
+ self._visit(t.default)
92
+ self._visit(t.prefix)
93
+
94
+ def visit_type_var_tuple(self, t: types.TypeVarTupleType) -> None:
95
+ self._visit(t.upper_bound)
96
+ self._visit(t.default)
97
+
98
+ def visit_unpack_type(self, t: types.UnpackType) -> None:
99
+ t.type.accept(self)
100
+
101
+ def visit_parameters(self, t: types.Parameters) -> None:
102
+ self._visit_type_list(t.arg_types)
103
+
104
+ def visit_instance(self, t: types.Instance) -> None:
105
+ # Instance is named, record its definition and continue digging into
106
+ # components that constitute semantic meaning of this type: bases, metaclass,
107
+ # tuple type, and typeddict type.
108
+ # Note: we cannot simply record the MRO, in case an intermediate base contains
109
+ # a reference to type alias, this affects meaning of map_instance_to_supertype(),
110
+ # see e.g. testDoubleReexportGenericUpdated.
111
+ self._visit_type_tuple(t.args)
112
+ if t.type:
113
+ # Important optimization: instead of simply recording the definition and
114
+ # recursing into bases, record the MRO and only traverse generic bases.
115
+ for s in t.type.mro:
116
+ self.modules.add(s.module_name)
117
+ for base in s.bases:
118
+ if base.args:
119
+ self._visit_type_tuple(base.args)
120
+ if t.type.metaclass_type:
121
+ self._visit(t.type.metaclass_type)
122
+ if t.type.typeddict_type:
123
+ self._visit(t.type.typeddict_type)
124
+ if t.type.tuple_type:
125
+ self._visit(t.type.tuple_type)
126
+ if t.type.is_protocol:
127
+ # For protocols, member types constitute the semantic meaning of the type.
128
+ # TODO: this doesn't cover some edge cases, like setter types and exotic nodes.
129
+ for m in t.type.protocol_members:
130
+ node = t.type.names.get(m)
131
+ if node and node.type:
132
+ self._visit(node.type)
133
+
134
+ def visit_callable_type(self, t: types.CallableType) -> None:
135
+ self._visit_type_list(t.arg_types)
136
+ self._visit(t.ret_type)
137
+ self._visit_type_tuple(t.variables)
138
+
139
+ def visit_overloaded(self, t: types.Overloaded) -> None:
140
+ for item in t.items:
141
+ self._visit(item)
142
+ self._visit(t.fallback)
143
+
144
+ def visit_tuple_type(self, t: types.TupleType) -> None:
145
+ self._visit_type_list(t.items)
146
+ self._visit(t.partial_fallback)
147
+
148
+ def visit_typeddict_type(self, t: types.TypedDictType) -> None:
149
+ self._visit_type_list(list(t.items.values()))
150
+ self._visit(t.fallback)
151
+
152
+ def visit_literal_type(self, t: types.LiteralType) -> None:
153
+ self._visit(t.fallback)
154
+
155
+ def visit_union_type(self, t: types.UnionType) -> None:
156
+ self._visit_type_list(t.items)
157
+
158
+ def visit_partial_type(self, t: types.PartialType) -> None:
159
+ pass
160
+
161
+ def visit_type_type(self, t: types.TypeType) -> None:
162
+ self._visit(t.item)
163
+
164
+ def visit_type_alias_type(self, t: types.TypeAliasType) -> None:
165
+ # Type alias is named, record its definition and continue digging into
166
+ # components that constitute semantic meaning of this type: target and args.
167
+ if t.alias:
168
+ self.modules.add(t.alias.module)
169
+ self._visit(t.alias.target)
170
+ self._visit_type_list(t.args)
micromamba_root/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/infer.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for type argument inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import NamedTuple
7
+
8
+ from mypy.constraints import (
9
+ SUBTYPE_OF,
10
+ SUPERTYPE_OF,
11
+ infer_constraints,
12
+ infer_constraints_for_callable,
13
+ )
14
+ from mypy.nodes import ArgKind
15
+ from mypy.solve import solve_constraints
16
+ from mypy.types import CallableType, Instance, Type, TypeVarLikeType
17
+
18
+
19
+ class ArgumentInferContext(NamedTuple):
20
+ """Type argument inference context.
21
+
22
+ We need this because we pass around ``Mapping`` and ``Iterable`` types.
23
+ These types are only known by ``TypeChecker`` itself.
24
+ It is required for ``*`` and ``**`` argument inference.
25
+
26
+ https://github.com/python/mypy/issues/11144
27
+ """
28
+
29
+ mapping_type: Instance
30
+ iterable_type: Instance
31
+
32
+
33
+ def infer_function_type_arguments(
34
+ callee_type: CallableType,
35
+ arg_types: Sequence[Type | None],
36
+ arg_kinds: list[ArgKind],
37
+ arg_names: Sequence[str | None] | None,
38
+ formal_to_actual: list[list[int]],
39
+ context: ArgumentInferContext,
40
+ strict: bool = True,
41
+ allow_polymorphic: bool = False,
42
+ ) -> tuple[list[Type | None], list[TypeVarLikeType]]:
43
+ """Infer the type arguments of a generic function.
44
+
45
+ Return an array of lower bound types for the type variables -1 (at
46
+ index 0), -2 (at index 1), etc. A lower bound is None if a value
47
+ could not be inferred.
48
+
49
+ Arguments:
50
+ callee_type: the target generic function
51
+ arg_types: argument types at the call site (each optional; if None,
52
+ we are not considering this argument in the current pass)
53
+ arg_kinds: nodes.ARG_* values for arg_types
54
+ formal_to_actual: mapping from formal to actual variable indices
55
+ """
56
+ # Infer constraints.
57
+ constraints = infer_constraints_for_callable(
58
+ callee_type, arg_types, arg_kinds, arg_names, formal_to_actual, context
59
+ )
60
+
61
+ # Solve constraints.
62
+ type_vars = callee_type.variables
63
+ return solve_constraints(type_vars, constraints, strict, allow_polymorphic)
64
+
65
+
66
+ def infer_type_arguments(
67
+ type_vars: Sequence[TypeVarLikeType],
68
+ template: Type,
69
+ actual: Type,
70
+ is_supertype: bool = False,
71
+ skip_unsatisfied: bool = False,
72
+ ) -> list[Type | None]:
73
+ # Like infer_function_type_arguments, but only match a single type
74
+ # against a generic type.
75
+ constraints = infer_constraints(template, actual, SUPERTYPE_OF if is_supertype else SUBTYPE_OF)
76
+ return solve_constraints(type_vars, constraints, skip_unsatisfied=skip_unsatisfied)[0]
micromamba_root/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/inspections.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from collections import defaultdict
5
+ from collections.abc import Callable
6
+ from functools import cmp_to_key
7
+
8
+ from mypy.build import State
9
+ from mypy.messages import format_type
10
+ from mypy.modulefinder import PYTHON_EXTENSIONS
11
+ from mypy.nodes import (
12
+ LDEF,
13
+ Decorator,
14
+ Expression,
15
+ FuncBase,
16
+ MemberExpr,
17
+ MypyFile,
18
+ Node,
19
+ OverloadedFuncDef,
20
+ RefExpr,
21
+ SymbolNode,
22
+ TypeInfo,
23
+ Var,
24
+ )
25
+ from mypy.server.update import FineGrainedBuildManager
26
+ from mypy.traverser import ExtendedTraverserVisitor
27
+ from mypy.typeops import tuple_fallback
28
+ from mypy.types import (
29
+ FunctionLike,
30
+ Instance,
31
+ LiteralType,
32
+ ProperType,
33
+ TupleType,
34
+ TypedDictType,
35
+ TypeVarType,
36
+ UnionType,
37
+ get_proper_type,
38
+ )
39
+ from mypy.typevars import fill_typevars_with_any
40
+
41
+
42
+ def node_starts_after(o: Node, line: int, column: int) -> bool:
43
+ return o.line > line or o.line == line and o.column > column
44
+
45
+
46
+ def node_ends_before(o: Node, line: int, column: int) -> bool:
47
+ # Unfortunately, end positions for some statements are a mess,
48
+ # e.g. overloaded functions, so we return False when we don't know.
49
+ if o.end_line is not None and o.end_column is not None:
50
+ if o.end_line < line or o.end_line == line and o.end_column < column:
51
+ return True
52
+ return False
53
+
54
+
55
+ def expr_span(expr: Expression) -> str:
56
+ """Format expression span as in mypy error messages."""
57
+ return f"{expr.line}:{expr.column + 1}:{expr.end_line}:{expr.end_column}"
58
+
59
+
60
+ def get_instance_fallback(typ: ProperType) -> list[Instance]:
61
+ """Returns the Instance fallback for this type if one exists or None."""
62
+ if isinstance(typ, Instance):
63
+ return [typ]
64
+ elif isinstance(typ, TupleType):
65
+ return [tuple_fallback(typ)]
66
+ elif isinstance(typ, TypedDictType):
67
+ return [typ.fallback]
68
+ elif isinstance(typ, FunctionLike):
69
+ return [typ.fallback]
70
+ elif isinstance(typ, LiteralType):
71
+ return [typ.fallback]
72
+ elif isinstance(typ, TypeVarType):
73
+ if typ.values:
74
+ res = []
75
+ for t in typ.values:
76
+ res.extend(get_instance_fallback(get_proper_type(t)))
77
+ return res
78
+ return get_instance_fallback(get_proper_type(typ.upper_bound))
79
+ elif isinstance(typ, UnionType):
80
+ res = []
81
+ for t in typ.items:
82
+ res.extend(get_instance_fallback(get_proper_type(t)))
83
+ return res
84
+ return []
85
+
86
+
87
+ def find_node(name: str, info: TypeInfo) -> Var | FuncBase | None:
88
+ """Find the node defining member 'name' in given TypeInfo."""
89
+ # TODO: this code shares some logic with checkmember.py
90
+ method = info.get_method(name)
91
+ if method:
92
+ if isinstance(method, Decorator):
93
+ return method.var
94
+ if method.is_property:
95
+ assert isinstance(method, OverloadedFuncDef)
96
+ dec = method.items[0]
97
+ assert isinstance(dec, Decorator)
98
+ return dec.var
99
+ return method
100
+ else:
101
+ # don't have such method, maybe variable?
102
+ node = info.get(name)
103
+ v = node.node if node else None
104
+ if isinstance(v, Var):
105
+ return v
106
+ return None
107
+
108
+
109
+ def find_module_by_fullname(fullname: str, modules: dict[str, State]) -> State | None:
110
+ """Find module by a node fullname.
111
+
112
+ This logic mimics the one we use in fixup, so should be good enough.
113
+ """
114
+ head = fullname
115
+ # Special case: a module symbol is considered to be defined in itself, not in enclosing
116
+ # package, since this is what users want when clicking go to definition on a module.
117
+ if head in modules:
118
+ return modules[head]
119
+ while True:
120
+ if "." not in head:
121
+ return None
122
+ head, tail = head.rsplit(".", maxsplit=1)
123
+ mod = modules.get(head)
124
+ if mod is not None:
125
+ return mod
126
+
127
+
128
+ class SearchVisitor(ExtendedTraverserVisitor):
129
+ """Visitor looking for an expression whose span matches given one exactly."""
130
+
131
+ def __init__(self, line: int, column: int, end_line: int, end_column: int) -> None:
132
+ self.line = line
133
+ self.column = column
134
+ self.end_line = end_line
135
+ self.end_column = end_column
136
+ self.result: Expression | None = None
137
+
138
+ def visit(self, o: Node) -> bool:
139
+ if node_starts_after(o, self.line, self.column):
140
+ return False
141
+ if node_ends_before(o, self.end_line, self.end_column):
142
+ return False
143
+ if (
144
+ o.line == self.line
145
+ and o.end_line == self.end_line
146
+ and o.column == self.column
147
+ and o.end_column == self.end_column
148
+ ):
149
+ if isinstance(o, Expression):
150
+ self.result = o
151
+ return self.result is None
152
+
153
+
154
+ def find_by_location(
155
+ tree: MypyFile, line: int, column: int, end_line: int, end_column: int
156
+ ) -> Expression | None:
157
+ """Find an expression matching given span, or None if not found."""
158
+ if end_line < line:
159
+ raise ValueError('"end_line" must not be before "line"')
160
+ if end_line == line and end_column <= column:
161
+ raise ValueError('"end_column" must be after "column"')
162
+ visitor = SearchVisitor(line, column, end_line, end_column)
163
+ tree.accept(visitor)
164
+ return visitor.result
165
+
166
+
167
+ class SearchAllVisitor(ExtendedTraverserVisitor):
168
+ """Visitor looking for all expressions whose spans enclose given position."""
169
+
170
+ def __init__(self, line: int, column: int) -> None:
171
+ self.line = line
172
+ self.column = column
173
+ self.result: list[Expression] = []
174
+
175
+ def visit(self, o: Node) -> bool:
176
+ if node_starts_after(o, self.line, self.column):
177
+ return False
178
+ if node_ends_before(o, self.line, self.column):
179
+ return False
180
+ if isinstance(o, Expression):
181
+ self.result.append(o)
182
+ return True
183
+
184
+
185
+ def find_all_by_location(tree: MypyFile, line: int, column: int) -> list[Expression]:
186
+ """Find all expressions enclosing given position starting from innermost."""
187
+ visitor = SearchAllVisitor(line, column)
188
+ tree.accept(visitor)
189
+ return list(reversed(visitor.result))
190
+
191
+
192
+ class InspectionEngine:
193
+ """Engine for locating and statically inspecting expressions."""
194
+
195
+ def __init__(
196
+ self,
197
+ fg_manager: FineGrainedBuildManager,
198
+ *,
199
+ verbosity: int = 0,
200
+ limit: int = 0,
201
+ include_span: bool = False,
202
+ include_kind: bool = False,
203
+ include_object_attrs: bool = False,
204
+ union_attrs: bool = False,
205
+ force_reload: bool = False,
206
+ ) -> None:
207
+ self.fg_manager = fg_manager
208
+ self.verbosity = verbosity
209
+ self.limit = limit
210
+ self.include_span = include_span
211
+ self.include_kind = include_kind
212
+ self.include_object_attrs = include_object_attrs
213
+ self.union_attrs = union_attrs
214
+ self.force_reload = force_reload
215
+ # Module for which inspection was requested.
216
+ self.module: State | None = None
217
+
218
+ def reload_module(self, state: State) -> None:
219
+ """Reload given module while temporary exporting types."""
220
+ old = self.fg_manager.manager.options.export_types
221
+ self.fg_manager.manager.options.export_types = True
222
+ try:
223
+ self.fg_manager.flush_cache()
224
+ assert state.path is not None
225
+ self.fg_manager.update([(state.id, state.path)], [])
226
+ finally:
227
+ self.fg_manager.manager.options.export_types = old
228
+
229
+ def expr_type(self, expression: Expression) -> tuple[str, bool]:
230
+ """Format type for an expression using current options.
231
+
232
+ If type is known, second item returned is True. If type is not known, an error
233
+ message is returned instead, and second item returned is False.
234
+ """
235
+ expr_type = self.fg_manager.manager.all_types.get(expression)
236
+ if expr_type is None:
237
+ return self.missing_type(expression), False
238
+
239
+ type_str = format_type(
240
+ expr_type, self.fg_manager.manager.options, verbosity=self.verbosity
241
+ )
242
+ return self.add_prefixes(type_str, expression), True
243
+
244
+ def object_type(self) -> Instance:
245
+ builtins = self.fg_manager.graph["builtins"].tree
246
+ assert builtins is not None
247
+ object_node = builtins.names["object"].node
248
+ assert isinstance(object_node, TypeInfo)
249
+ return Instance(object_node, [])
250
+
251
+ def collect_attrs(self, instances: list[Instance]) -> dict[TypeInfo, list[str]]:
252
+ """Collect attributes from all union/typevar variants."""
253
+
254
+ def item_attrs(attr_dict: dict[TypeInfo, list[str]]) -> set[str]:
255
+ attrs = set()
256
+ for base in attr_dict:
257
+ attrs |= set(attr_dict[base])
258
+ return attrs
259
+
260
+ def cmp_types(x: TypeInfo, y: TypeInfo) -> int:
261
+ if x in y.mro:
262
+ return 1
263
+ if y in x.mro:
264
+ return -1
265
+ return 0
266
+
267
+ # First gather all attributes for every union variant.
268
+ assert instances
269
+ all_attrs = []
270
+ for instance in instances:
271
+ attrs = {}
272
+ mro = instance.type.mro
273
+ if not self.include_object_attrs:
274
+ mro = mro[:-1]
275
+ for base in mro:
276
+ attrs[base] = sorted(base.names)
277
+ all_attrs.append(attrs)
278
+
279
+ # Find attributes valid for all variants in a union or type variable.
280
+ intersection = item_attrs(all_attrs[0])
281
+ for item in all_attrs[1:]:
282
+ intersection &= item_attrs(item)
283
+
284
+ # Combine attributes from all variants into a single dict while
285
+ # also removing invalid attributes (unless using --union-attrs).
286
+ combined_attrs = defaultdict(list)
287
+ for item in all_attrs:
288
+ for base in item:
289
+ if base in combined_attrs:
290
+ continue
291
+ for name in item[base]:
292
+ if self.union_attrs or name in intersection:
293
+ combined_attrs[base].append(name)
294
+
295
+ # Sort bases by MRO, unrelated will appear in the order they appeared as union variants.
296
+ sorted_bases = sorted(combined_attrs.keys(), key=cmp_to_key(cmp_types))
297
+ result = {}
298
+ for base in sorted_bases:
299
+ if not combined_attrs[base]:
300
+ # Skip bases where everytihng was filtered out.
301
+ continue
302
+ result[base] = combined_attrs[base]
303
+ return result
304
+
305
+ def _fill_from_dict(
306
+ self, attrs_strs: list[str], attrs_dict: dict[TypeInfo, list[str]]
307
+ ) -> None:
308
+ for base in attrs_dict:
309
+ cls_name = base.name if self.verbosity < 1 else base.fullname
310
+ attrs = [f'"{attr}"' for attr in attrs_dict[base]]
311
+ attrs_strs.append(f'"{cls_name}": [{", ".join(attrs)}]')
312
+
313
+ def expr_attrs(self, expression: Expression) -> tuple[str, bool]:
314
+ """Format attributes that are valid for a given expression.
315
+
316
+ If expression type is not an Instance, try using fallback. Attributes are
317
+ returned as a JSON (ordered by MRO) that maps base class name to list of
318
+ attributes. Attributes may appear in multiple bases if overridden (we simply
319
+ follow usual mypy logic for creating new Vars etc).
320
+ """
321
+ expr_type = self.fg_manager.manager.all_types.get(expression)
322
+ if expr_type is None:
323
+ return self.missing_type(expression), False
324
+
325
+ expr_type = get_proper_type(expr_type)
326
+ instances = get_instance_fallback(expr_type)
327
+ if not instances:
328
+ # Everything is an object in Python.
329
+ instances = [self.object_type()]
330
+
331
+ attrs_dict = self.collect_attrs(instances)
332
+
333
+ # Special case: modules have names apart from those from ModuleType.
334
+ if isinstance(expression, RefExpr) and isinstance(expression.node, MypyFile):
335
+ node = expression.node
336
+ names = sorted(node.names)
337
+ if "__builtins__" in names:
338
+ # This is just to make tests stable. No one will really need this name.
339
+ names.remove("__builtins__")
340
+ mod_dict = {f'"<{node.fullname}>"': [f'"{name}"' for name in names]}
341
+ else:
342
+ mod_dict = {}
343
+
344
+ # Special case: for class callables, prepend with the class attributes.
345
+ # TODO: also handle cases when such callable appears in a union.
346
+ if isinstance(expr_type, FunctionLike) and expr_type.is_type_obj():
347
+ template = fill_typevars_with_any(expr_type.type_object())
348
+ class_dict = self.collect_attrs(get_instance_fallback(template))
349
+ else:
350
+ class_dict = {}
351
+
352
+ # We don't use JSON dump to be sure keys order is always preserved.
353
+ base_attrs = []
354
+ if mod_dict:
355
+ for mod in mod_dict:
356
+ base_attrs.append(f'{mod}: [{", ".join(mod_dict[mod])}]')
357
+ self._fill_from_dict(base_attrs, class_dict)
358
+ self._fill_from_dict(base_attrs, attrs_dict)
359
+ return self.add_prefixes(f'{{{", ".join(base_attrs)}}}', expression), True
360
+
361
+ def format_node(self, module: State, node: FuncBase | SymbolNode) -> str:
362
+ return f"{module.path}:{node.line}:{node.column + 1}:{node.name}"
363
+
364
+ def collect_nodes(self, expression: RefExpr) -> list[FuncBase | SymbolNode]:
365
+ """Collect nodes that can be referred to by an expression.
366
+
367
+ Note: it can be more than one for example in case of a union attribute.
368
+ """
369
+ node: FuncBase | SymbolNode | None = expression.node
370
+ nodes: list[FuncBase | SymbolNode]
371
+ if node is None:
372
+ # Tricky case: instance attribute
373
+ if isinstance(expression, MemberExpr) and expression.kind is None:
374
+ base_type = self.fg_manager.manager.all_types.get(expression.expr)
375
+ if base_type is None:
376
+ return []
377
+
378
+ # Now we use the base type to figure out where the attribute is defined.
379
+ base_type = get_proper_type(base_type)
380
+ instances = get_instance_fallback(base_type)
381
+ nodes = []
382
+ for instance in instances:
383
+ node = find_node(expression.name, instance.type)
384
+ if node:
385
+ nodes.append(node)
386
+ if not nodes:
387
+ # Try checking class namespace if attribute is on a class object.
388
+ if isinstance(base_type, FunctionLike) and base_type.is_type_obj():
389
+ instances = get_instance_fallback(
390
+ fill_typevars_with_any(base_type.type_object())
391
+ )
392
+ for instance in instances:
393
+ node = find_node(expression.name, instance.type)
394
+ if node:
395
+ nodes.append(node)
396
+ else:
397
+ # Still no luck, give up.
398
+ return []
399
+ else:
400
+ return []
401
+ else:
402
+ # Easy case: a module-level definition
403
+ nodes = [node]
404
+ return nodes
405
+
406
+ def modules_for_nodes(
407
+ self, nodes: list[FuncBase | SymbolNode], expression: RefExpr
408
+ ) -> tuple[dict[FuncBase | SymbolNode, State], bool]:
409
+ """Gather modules where given nodes where defined.
410
+
411
+ Also check if they need to be refreshed (cached nodes may have
412
+ lines/columns missing).
413
+ """
414
+ modules = {}
415
+ reload_needed = False
416
+ for node in nodes:
417
+ module = find_module_by_fullname(node.fullname, self.fg_manager.graph)
418
+ if not module:
419
+ if expression.kind == LDEF and self.module:
420
+ module = self.module
421
+ else:
422
+ continue
423
+ modules[node] = module
424
+ if not module.tree or module.tree.is_cache_skeleton or self.force_reload:
425
+ reload_needed |= not module.tree or module.tree.is_cache_skeleton
426
+ self.reload_module(module)
427
+ return modules, reload_needed
428
+
429
+ def expression_def(self, expression: Expression) -> tuple[str, bool]:
430
+ """Find and format definition location for an expression.
431
+
432
+ If it is not a RefExpr, it is effectively skipped by returning an
433
+ empty result.
434
+ """
435
+ if not isinstance(expression, RefExpr):
436
+ # If there are no suitable matches at all, we return error later.
437
+ return "", True
438
+
439
+ nodes = self.collect_nodes(expression)
440
+
441
+ if not nodes:
442
+ return self.missing_node(expression), False
443
+
444
+ modules, reload_needed = self.modules_for_nodes(nodes, expression)
445
+ if reload_needed:
446
+ # TODO: line/column are not stored in cache for vast majority of symbol nodes.
447
+ # Adding them will make thing faster, but will have visible memory impact.
448
+ nodes = self.collect_nodes(expression)
449
+ modules, reload_needed = self.modules_for_nodes(nodes, expression)
450
+ assert not reload_needed
451
+
452
+ result = []
453
+ for node in modules:
454
+ result.append(self.format_node(modules[node], node))
455
+
456
+ if not result:
457
+ return self.missing_node(expression), False
458
+
459
+ return self.add_prefixes(", ".join(result), expression), True
460
+
461
+ def missing_type(self, expression: Expression) -> str:
462
+ alt_suggestion = ""
463
+ if not self.force_reload:
464
+ alt_suggestion = " or try --force-reload"
465
+ return (
466
+ f'No known type available for "{type(expression).__name__}"'
467
+ f" (maybe unreachable{alt_suggestion})"
468
+ )
469
+
470
+ def missing_node(self, expression: Expression) -> str:
471
+ return (
472
+ f'Cannot find definition for "{type(expression).__name__}" at {expr_span(expression)}'
473
+ )
474
+
475
+ def add_prefixes(self, result: str, expression: Expression) -> str:
476
+ prefixes = []
477
+ if self.include_kind:
478
+ prefixes.append(f"{type(expression).__name__}")
479
+ if self.include_span:
480
+ prefixes.append(expr_span(expression))
481
+ if prefixes:
482
+ prefix = ":".join(prefixes) + " -> "
483
+ else:
484
+ prefix = ""
485
+ return prefix + result
486
+
487
+ def run_inspection_by_exact_location(
488
+ self,
489
+ tree: MypyFile,
490
+ line: int,
491
+ column: int,
492
+ end_line: int,
493
+ end_column: int,
494
+ method: Callable[[Expression], tuple[str, bool]],
495
+ ) -> dict[str, object]:
496
+ """Get type of an expression matching a span.
497
+
498
+ Type or error is returned as a standard daemon response dict.
499
+ """
500
+ try:
501
+ expression = find_by_location(tree, line, column - 1, end_line, end_column)
502
+ except ValueError as err:
503
+ return {"error": str(err)}
504
+
505
+ if expression is None:
506
+ span = f"{line}:{column}:{end_line}:{end_column}"
507
+ return {"out": f"Can't find expression at span {span}", "err": "", "status": 1}
508
+
509
+ inspection_str, success = method(expression)
510
+ return {"out": inspection_str, "err": "", "status": 0 if success else 1}
511
+
512
+ def run_inspection_by_position(
513
+ self,
514
+ tree: MypyFile,
515
+ line: int,
516
+ column: int,
517
+ method: Callable[[Expression], tuple[str, bool]],
518
+ ) -> dict[str, object]:
519
+ """Get types of all expressions enclosing a position.
520
+
521
+ Types and/or errors are returned as a standard daemon response dict.
522
+ """
523
+ expressions = find_all_by_location(tree, line, column - 1)
524
+ if not expressions:
525
+ position = f"{line}:{column}"
526
+ return {
527
+ "out": f"Can't find any expressions at position {position}",
528
+ "err": "",
529
+ "status": 1,
530
+ }
531
+
532
+ inspection_strs = []
533
+ status = 0
534
+ for expression in expressions:
535
+ inspection_str, success = method(expression)
536
+ if not success:
537
+ status = 1
538
+ if inspection_str:
539
+ inspection_strs.append(inspection_str)
540
+ if self.limit:
541
+ inspection_strs = inspection_strs[: self.limit]
542
+ return {"out": "\n".join(inspection_strs), "err": "", "status": status}
543
+
544
+ def find_module(self, file: str) -> tuple[State | None, dict[str, object]]:
545
+ """Find module by path, or return a suitable error message.
546
+
547
+ Note we don't use exceptions to simplify handling 1 vs 2 statuses.
548
+ """
549
+ if not any(file.endswith(ext) for ext in PYTHON_EXTENSIONS):
550
+ return None, {"error": "Source file is not a Python file"}
551
+
552
+ # We are using a bit slower but robust way to find a module by path,
553
+ # to be sure that namespace packages are handled properly.
554
+ abs_path = os.path.abspath(file)
555
+ state = next((s for s in self.fg_manager.graph.values() if s.abspath == abs_path), None)
556
+ self.module = state
557
+ return (
558
+ state,
559
+ {"out": f"Unknown module: {file}", "err": "", "status": 1} if state is None else {},
560
+ )
561
+
562
+ def run_inspection(
563
+ self, location: str, method: Callable[[Expression], tuple[str, bool]]
564
+ ) -> dict[str, object]:
565
+ """Top-level logic to inspect expression(s) at a location.
566
+
567
+ This can be reused by various simple inspections.
568
+ """
569
+ try:
570
+ file, pos = parse_location(location)
571
+ except ValueError as err:
572
+ return {"error": str(err)}
573
+
574
+ state, err_dict = self.find_module(file)
575
+ if state is None:
576
+ assert err_dict
577
+ return err_dict
578
+
579
+ # Force reloading to load from cache, account for any edits, etc.
580
+ if not state.tree or state.tree.is_cache_skeleton or self.force_reload:
581
+ self.reload_module(state)
582
+ assert state.tree is not None
583
+
584
+ if len(pos) == 4:
585
+ # Full span, return an exact match only.
586
+ line, column, end_line, end_column = pos
587
+ return self.run_inspection_by_exact_location(
588
+ state.tree, line, column, end_line, end_column, method
589
+ )
590
+ assert len(pos) == 2
591
+ # Inexact location, return all expressions.
592
+ line, column = pos
593
+ return self.run_inspection_by_position(state.tree, line, column, method)
594
+
595
+ def get_type(self, location: str) -> dict[str, object]:
596
+ """Get types of expression(s) at a location."""
597
+ return self.run_inspection(location, self.expr_type)
598
+
599
+ def get_attrs(self, location: str) -> dict[str, object]:
600
+ """Get attributes of expression(s) at a location."""
601
+ return self.run_inspection(location, self.expr_attrs)
602
+
603
+ def get_definition(self, location: str) -> dict[str, object]:
604
+ """Get symbol definitions of expression(s) at a location."""
605
+ result = self.run_inspection(location, self.expression_def)
606
+ if "out" in result and not result["out"]:
607
+ # None of the expressions found turns out to be a RefExpr.
608
+ _, location = location.split(":", maxsplit=1)
609
+ result["out"] = f"No name or member expressions at {location}"
610
+ result["status"] = 1
611
+ return result
612
+
613
+
614
+ def parse_location(location: str) -> tuple[str, list[int]]:
615
+ if location.count(":") < 2:
616
+ raise ValueError("Format should be file:line:column[:end_line:end_column]")
617
+ parts = location.rsplit(":", maxsplit=2)
618
+ start, *rest = parts
619
+ # Note: we must allow drive prefix like `C:` on Windows.
620
+ if start.count(":") < 2:
621
+ return start, [int(p) for p in rest]
622
+ parts = start.rsplit(":", maxsplit=2)
623
+ start, *start_rest = parts
624
+ if start.count(":") < 2:
625
+ return start, [int(p) for p in start_rest + rest]
626
+ raise ValueError("Format should be file:line:column[:end_line:end_column]")
micromamba_root/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/ipc.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-platform abstractions for inter-process communication
2
+
3
+ On Unix, this uses AF_UNIX sockets.
4
+ On Windows, this uses NamedPipes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import shutil
12
+ import struct
13
+ import sys
14
+ import tempfile
15
+ from abc import abstractmethod
16
+ from collections.abc import Callable
17
+ from select import select
18
+ from types import TracebackType
19
+ from typing import Final
20
+ from typing_extensions import Self
21
+
22
+ from librt.base64 import urlsafe_b64encode
23
+ from librt.internal import ReadBuffer, WriteBuffer
24
+
25
+ if sys.platform == "win32":
26
+ # This may be private, but it is needed for IPC on Windows, and is basically stable
27
+ import _winapi
28
+ import ctypes
29
+
30
+ _IPCHandle = int
31
+
32
+ kernel32 = ctypes.windll.kernel32
33
+ DisconnectNamedPipe: Callable[[_IPCHandle], int] = kernel32.DisconnectNamedPipe
34
+ FlushFileBuffers: Callable[[_IPCHandle], int] = kernel32.FlushFileBuffers
35
+ else:
36
+ import socket
37
+
38
+ _IPCHandle = socket.socket
39
+
40
+ # Size of the message packed as !L, i.e. 4 bytes in network order (big-endian).
41
+ HEADER_SIZE = 4
42
+
43
+
44
+ # TODO: we should make sure consistent exceptions are raised on different platforms.
45
+ # Currently we raise either IPCException or OSError for equivalent conditions.
46
+ class IPCException(Exception):
47
+ """Exception for IPC issues."""
48
+
49
+
50
+ class IPCBase:
51
+ """Base class for communication between the dmypy client and server.
52
+
53
+ This contains logic shared between the client and server, such as reading
54
+ and writing.
55
+ We want to be able to send multiple "messages" over a single connection and
56
+ to be able to separate the messages. We do this by prefixing each message
57
+ with its size in a fixed format.
58
+ """
59
+
60
+ connection: _IPCHandle
61
+
62
+ def __init__(self, name: str, timeout: float | None) -> None:
63
+ self.name = name
64
+ self.timeout = timeout
65
+ self.message_size: int | None = None
66
+ self.buffer = bytearray()
67
+
68
+ def frame_from_buffer(self) -> bytes | None:
69
+ """Return a full frame from the bytes we have in the buffer."""
70
+ size = len(self.buffer)
71
+ if size < HEADER_SIZE:
72
+ return None
73
+ if self.message_size is None:
74
+ self.message_size = struct.unpack("!L", self.buffer[:HEADER_SIZE])[0]
75
+ if size < self.message_size + HEADER_SIZE:
76
+ return None
77
+ # We have a full frame, avoid extra copy in case we get a large frame.
78
+ bdata = memoryview(self.buffer)[HEADER_SIZE : HEADER_SIZE + self.message_size]
79
+ self.buffer = self.buffer[HEADER_SIZE + self.message_size :]
80
+ self.message_size = None
81
+ return bytes(bdata)
82
+
83
+ def read(self, size: int = 100000) -> str:
84
+ return self.read_bytes(size).decode("utf-8")
85
+
86
+ def read_bytes(self, size: int = 100000) -> bytes:
87
+ """Read bytes from an IPC connection until we have a full frame."""
88
+ if sys.platform == "win32":
89
+ while True:
90
+ # Check if we already have a message in the buffer before
91
+ # receiving any more data from the socket.
92
+ bdata = self.frame_from_buffer()
93
+ if bdata is not None:
94
+ break
95
+
96
+ # Receive more data into the buffer.
97
+ ov, err = _winapi.ReadFile(self.connection, size, overlapped=True)
98
+ try:
99
+ if err == _winapi.ERROR_IO_PENDING:
100
+ timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE
101
+ res = _winapi.WaitForSingleObject(ov.event, timeout)
102
+ if res != _winapi.WAIT_OBJECT_0:
103
+ raise IPCException(f"Bad result from I/O wait: {res}")
104
+ except BaseException:
105
+ ov.cancel()
106
+ raise
107
+ _, err = ov.GetOverlappedResult(True)
108
+ more = ov.getbuffer()
109
+ if more:
110
+ self.buffer.extend(more)
111
+ bdata = self.frame_from_buffer()
112
+ if bdata is not None:
113
+ break
114
+ if err == 0:
115
+ # we are done!
116
+ break
117
+ elif err == _winapi.ERROR_MORE_DATA:
118
+ # read again
119
+ continue
120
+ elif err == _winapi.ERROR_OPERATION_ABORTED:
121
+ raise IPCException("ReadFile operation aborted.")
122
+ else:
123
+ while True:
124
+ # Check if we already have a message in the buffer before
125
+ # receiving any more data from the socket.
126
+ bdata = self.frame_from_buffer()
127
+ if bdata is not None:
128
+ break
129
+
130
+ # Receive more data into the buffer.
131
+ more = self.connection.recv(size)
132
+ if not more:
133
+ # Connection closed
134
+ break
135
+ self.buffer.extend(more)
136
+
137
+ if not bdata:
138
+ # Socket was empty, and we didn't get any frame.
139
+ # This should only happen if the socket was closed.
140
+ return b""
141
+ return bdata
142
+
143
+ def write(self, data: str) -> None:
144
+ self.write_bytes(data.encode("utf-8"))
145
+
146
+ def write_bytes(self, data: bytes) -> None:
147
+ """Write to an IPC connection."""
148
+
149
+ # Frame the data by adding fixed size header.
150
+ encoded_data = struct.pack("!L", len(data)) + data
151
+
152
+ if sys.platform == "win32":
153
+ try:
154
+ ov, err = _winapi.WriteFile(self.connection, encoded_data, overlapped=True)
155
+ try:
156
+ if err == _winapi.ERROR_IO_PENDING:
157
+ timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE
158
+ res = _winapi.WaitForSingleObject(ov.event, timeout)
159
+ if res != _winapi.WAIT_OBJECT_0:
160
+ raise IPCException(f"Bad result from I/O wait: {res}")
161
+ elif err != 0:
162
+ raise IPCException(f"Failed writing to pipe with error: {err}")
163
+ except BaseException:
164
+ ov.cancel()
165
+ raise
166
+ bytes_written, err = ov.GetOverlappedResult(True)
167
+ assert err == 0, err
168
+ assert bytes_written == len(encoded_data)
169
+ except OSError as e:
170
+ raise IPCException(f"Failed to write with error: {e.winerror}") from e
171
+ else:
172
+ self.connection.sendall(encoded_data)
173
+
174
+ def close(self) -> None:
175
+ if sys.platform == "win32":
176
+ if self.connection != _winapi.NULL:
177
+ _winapi.CloseHandle(self.connection)
178
+ else:
179
+ self.connection.close()
180
+
181
+
182
+ class IPCClient(IPCBase):
183
+ """The client side of an IPC connection."""
184
+
185
+ def __init__(self, name: str, timeout: float | None) -> None:
186
+ super().__init__(name, timeout)
187
+ if sys.platform == "win32":
188
+ timeout = int(self.timeout * 1000) if self.timeout else _winapi.NMPWAIT_WAIT_FOREVER
189
+ try:
190
+ _winapi.WaitNamedPipe(self.name, timeout)
191
+ except FileNotFoundError as e:
192
+ raise IPCException(f"The NamedPipe at {self.name} was not found.") from e
193
+ except OSError as e:
194
+ if e.winerror == _winapi.ERROR_SEM_TIMEOUT:
195
+ raise IPCException("Timed out waiting for connection.") from e
196
+ else:
197
+ raise
198
+ try:
199
+ self.connection = _winapi.CreateFile(
200
+ self.name,
201
+ _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
202
+ 0,
203
+ _winapi.NULL,
204
+ _winapi.OPEN_EXISTING,
205
+ _winapi.FILE_FLAG_OVERLAPPED,
206
+ _winapi.NULL,
207
+ )
208
+ except OSError as e:
209
+ if e.winerror == _winapi.ERROR_PIPE_BUSY:
210
+ raise IPCException("The connection is busy.") from e
211
+ else:
212
+ raise
213
+ _winapi.SetNamedPipeHandleState(
214
+ self.connection, _winapi.PIPE_READMODE_MESSAGE, None, None
215
+ )
216
+ else:
217
+ self.connection = socket.socket(socket.AF_UNIX)
218
+ self.connection.settimeout(timeout)
219
+ self.connection.connect(name)
220
+
221
+ def __enter__(self) -> IPCClient:
222
+ return self
223
+
224
+ def __exit__(
225
+ self,
226
+ exc_ty: type[BaseException] | None = None,
227
+ exc_val: BaseException | None = None,
228
+ exc_tb: TracebackType | None = None,
229
+ ) -> None:
230
+ self.close()
231
+
232
+
233
+ class IPCServer(IPCBase):
234
+ BUFFER_SIZE: Final = 2**16
235
+
236
+ def __init__(self, name: str, timeout: float | None = None) -> None:
237
+ if sys.platform == "win32":
238
+ name = r"\\.\pipe\{}-{}.pipe".format(name, urlsafe_b64encode(os.urandom(6)).decode())
239
+ else:
240
+ name = f"{name}.sock"
241
+ super().__init__(name, timeout)
242
+ if sys.platform == "win32":
243
+ self.connection = _winapi.CreateNamedPipe(
244
+ self.name,
245
+ _winapi.PIPE_ACCESS_DUPLEX
246
+ | _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
247
+ | _winapi.FILE_FLAG_OVERLAPPED,
248
+ _winapi.PIPE_READMODE_MESSAGE
249
+ | _winapi.PIPE_TYPE_MESSAGE
250
+ | _winapi.PIPE_WAIT
251
+ | 0x8, # PIPE_REJECT_REMOTE_CLIENTS
252
+ 1, # one instance
253
+ self.BUFFER_SIZE,
254
+ self.BUFFER_SIZE,
255
+ _winapi.NMPWAIT_WAIT_FOREVER,
256
+ 0, # Use default security descriptor
257
+ )
258
+ if self.connection == -1: # INVALID_HANDLE_VALUE
259
+ err = _winapi.GetLastError()
260
+ raise IPCException(f"Invalid handle to pipe: {err}")
261
+ else:
262
+ self.sock_directory = tempfile.mkdtemp()
263
+ sockfile = os.path.join(self.sock_directory, self.name)
264
+ self.sock = socket.socket(socket.AF_UNIX)
265
+ self.sock.bind(sockfile)
266
+ self.sock.listen(1)
267
+ if timeout is not None:
268
+ self.sock.settimeout(timeout)
269
+
270
+ def __enter__(self) -> IPCServer:
271
+ if sys.platform == "win32":
272
+ # NOTE: It is theoretically possible that this will hang forever if the
273
+ # client never connects, though this can be "solved" by killing the server
274
+ try:
275
+ ov = _winapi.ConnectNamedPipe(self.connection, overlapped=True)
276
+ except OSError as e:
277
+ # Don't raise if the client already exists, or the client already connected
278
+ if e.winerror not in (_winapi.ERROR_PIPE_CONNECTED, _winapi.ERROR_NO_DATA):
279
+ raise
280
+ else:
281
+ try:
282
+ timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE
283
+ res = _winapi.WaitForSingleObject(ov.event, timeout)
284
+ assert res == _winapi.WAIT_OBJECT_0
285
+ except BaseException:
286
+ ov.cancel()
287
+ _winapi.CloseHandle(self.connection)
288
+ raise
289
+ _, err = ov.GetOverlappedResult(True)
290
+ assert err == 0
291
+ else:
292
+ try:
293
+ self.connection, _ = self.sock.accept()
294
+ except TimeoutError as e:
295
+ raise IPCException("The socket timed out") from e
296
+ return self
297
+
298
+ def __exit__(
299
+ self,
300
+ exc_ty: type[BaseException] | None = None,
301
+ exc_val: BaseException | None = None,
302
+ exc_tb: TracebackType | None = None,
303
+ ) -> None:
304
+ if sys.platform == "win32":
305
+ try:
306
+ # Wait for the client to finish reading the last write before disconnecting
307
+ if not FlushFileBuffers(self.connection):
308
+ raise IPCException(
309
+ "Failed to flush NamedPipe buffer, maybe the client hung up?"
310
+ )
311
+ finally:
312
+ DisconnectNamedPipe(self.connection)
313
+ else:
314
+ self.close()
315
+
316
+ def cleanup(self) -> None:
317
+ if sys.platform == "win32":
318
+ self.close()
319
+ else:
320
+ shutil.rmtree(self.sock_directory)
321
+
322
+ @property
323
+ def connection_name(self) -> str:
324
+ if sys.platform == "win32":
325
+ return self.name
326
+ elif sys.platform == "gnu0":
327
+ # GNU/Hurd returns empty string from getsockname()
328
+ # for AF_UNIX sockets
329
+ return os.path.join(self.sock_directory, self.name)
330
+ else:
331
+ name = self.sock.getsockname()
332
+ assert isinstance(name, str)
333
+ return name
334
+
335
+
336
+ class BadStatus(Exception):
337
+ """Exception raised when there is something wrong with the status file.
338
+
339
+ For example:
340
+ - No status file found
341
+ - Status file malformed
342
+ - Process whose pid is in the status file does not exist
343
+ """
344
+
345
+
346
+ def read_status(status_file: str) -> dict[str, object]:
347
+ """Read status file.
348
+
349
+ Raise BadStatus if the status file doesn't exist or contains
350
+ invalid JSON or the JSON is not a dict.
351
+ """
352
+ if not os.path.isfile(status_file):
353
+ raise BadStatus("No status file found")
354
+ with open(status_file) as f:
355
+ try:
356
+ data = json.load(f)
357
+ except Exception as e:
358
+ raise BadStatus(f"Malformed status file: {str(e)}") from e
359
+ if not isinstance(data, dict):
360
+ raise BadStatus(f"Invalid status file (not a dict): {data}")
361
+ return data
362
+
363
+
364
+ def ready_to_read(conns: list[IPCClient], timeout: float | None = None) -> list[int]:
365
+ """Wait until some connections are readable.
366
+
367
+ Return index of each readable connection in the original list.
368
+ """
369
+ if sys.platform == "win32":
370
+ # Windows doesn't support select() on named pipes. Instead, start an overlapped
371
+ # ReadFile on each pipe (which internally creates an event via CreateEventW),
372
+ # then WaitForMultipleObjects on those events for efficient OS-level waiting.
373
+ # Any data consumed by the probe reads is stored into each connection's buffer
374
+ # so the subsequent read_bytes() call will find it via frame_from_buffer().
375
+ WAIT_FAILED = 0xFFFFFFFF
376
+ pending: list[tuple[int, _winapi.Overlapped]] = []
377
+ events: list[int] = []
378
+ ready: list[int] = []
379
+
380
+ for i, conn in enumerate(conns):
381
+ try:
382
+ ov, err = _winapi.ReadFile(conn.connection, 1, overlapped=True)
383
+ except OSError:
384
+ # Broken/closed pipe. Mimic Linux behavior here, caller will get
385
+ # the exception when trying to read from this socket.
386
+ ready.append(i)
387
+ continue
388
+ if err == _winapi.ERROR_IO_PENDING:
389
+ events.append(ov.event)
390
+ pending.append((i, ov))
391
+ else:
392
+ # Data was immediately available (err == 0 or ERROR_MORE_DATA)
393
+ _, err = ov.GetOverlappedResult(True)
394
+ data = ov.getbuffer()
395
+ if data:
396
+ conn.buffer.extend(data)
397
+ ready.append(i)
398
+
399
+ # Wait only if nothing is immediately ready and there are pending operations
400
+ if not ready and events:
401
+ timeout_ms = int(timeout * 1000) if timeout is not None else _winapi.INFINITE
402
+ res = _winapi.WaitForMultipleObjects(events, False, timeout_ms)
403
+ if res == WAIT_FAILED:
404
+ for _, ov in pending:
405
+ ov.cancel()
406
+ raise IPCException(f"Failed to wait for connections: {_winapi.GetLastError()}")
407
+
408
+ # Check which pending operations completed, cancel the rest
409
+ for i, ov in pending:
410
+ if _winapi.WaitForSingleObject(ov.event, 0) == _winapi.WAIT_OBJECT_0:
411
+ _, err = ov.GetOverlappedResult(True)
412
+ data = ov.getbuffer()
413
+ if data:
414
+ conns[i].buffer.extend(data)
415
+ ready.append(i)
416
+ else:
417
+ ov.cancel()
418
+
419
+ return ready
420
+
421
+ else:
422
+ connections = [conn.connection for conn in conns]
423
+ ready, _, _ = select(connections, [], [], timeout)
424
+ return [connections.index(r) for r in ready]
425
+
426
+
427
+ def send(connection: IPCBase, data: IPCMessage) -> None:
428
+ """Send data to a connection encoded and framed.
429
+
430
+ The data must be a non-abstract IPCMessage. We assume that a single send call is a
431
+ single frame to be sent.
432
+ """
433
+ buf = WriteBuffer()
434
+ data.write(buf)
435
+ connection.write_bytes(buf.getvalue())
436
+
437
+
438
+ def receive(connection: IPCBase) -> ReadBuffer:
439
+ """Receive single encoded IPCMessage frame from a connection.
440
+
441
+ Raise OSError if the data received is not valid.
442
+ """
443
+ bdata = connection.read_bytes()
444
+ if not bdata:
445
+ raise OSError("No data received")
446
+ return ReadBuffer(bdata)
447
+
448
+
449
+ class IPCMessage:
450
+ @classmethod
451
+ @abstractmethod
452
+ def read(cls, buf: ReadBuffer) -> Self:
453
+ raise NotImplementedError
454
+
455
+ @abstractmethod
456
+ def write(self, buf: WriteBuffer) -> None:
457
+ raise NotImplementedError
micromamba_root/Lib/site-packages/mypy/join.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/join.py ADDED
@@ -0,0 +1,916 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calculation of the least upper bound types (joins)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import overload
7
+
8
+ import mypy.typeops
9
+ from mypy.expandtype import expand_type
10
+ from mypy.maptype import map_instance_to_supertype
11
+ from mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT, VARIANCE_NOT_READY, TypeInfo
12
+ from mypy.state import state
13
+ from mypy.subtypes import (
14
+ SubtypeContext,
15
+ find_member,
16
+ is_equivalent,
17
+ is_proper_subtype,
18
+ is_protocol_implementation,
19
+ is_subtype,
20
+ )
21
+ from mypy.types import (
22
+ AnyType,
23
+ CallableType,
24
+ DeletedType,
25
+ ErasedType,
26
+ FunctionLike,
27
+ Instance,
28
+ LiteralType,
29
+ NoneType,
30
+ Overloaded,
31
+ Parameters,
32
+ ParamSpecType,
33
+ PartialType,
34
+ ProperType,
35
+ TupleType,
36
+ Type,
37
+ TypeAliasType,
38
+ TypedDictType,
39
+ TypeOfAny,
40
+ TypeType,
41
+ TypeVarId,
42
+ TypeVarLikeType,
43
+ TypeVarTupleType,
44
+ TypeVarType,
45
+ TypeVisitor,
46
+ UnboundType,
47
+ UninhabitedType,
48
+ UnionType,
49
+ UnpackType,
50
+ find_unpack_in_list,
51
+ get_proper_type,
52
+ get_proper_types,
53
+ split_with_prefix_and_suffix,
54
+ )
55
+
56
+
57
+ class InstanceJoiner:
58
+ def __init__(self) -> None:
59
+ self.seen_instances: list[tuple[Instance, Instance]] = []
60
+
61
+ def join_instances(self, t: Instance, s: Instance) -> ProperType:
62
+ if (t, s) in self.seen_instances or (s, t) in self.seen_instances:
63
+ return object_from_instance(t)
64
+
65
+ self.seen_instances.append((t, s))
66
+
67
+ # Calculate the join of two instance types
68
+ if t.type == s.type:
69
+ # Simplest case: join two types with the same base type (but
70
+ # potentially different arguments).
71
+
72
+ # Combine type arguments.
73
+ args: list[Type] = []
74
+ # N.B: We use zip instead of indexing because the lengths might have
75
+ # mismatches during daemon reprocessing.
76
+ if t.type.has_type_var_tuple_type:
77
+ # We handle joins of variadic instances by simply creating correct mapping
78
+ # for type arguments and compute the individual joins same as for regular
79
+ # instances. All the heavy lifting is done in the join of tuple types.
80
+ assert s.type.type_var_tuple_prefix is not None
81
+ assert s.type.type_var_tuple_suffix is not None
82
+ prefix = s.type.type_var_tuple_prefix
83
+ suffix = s.type.type_var_tuple_suffix
84
+ tvt = s.type.defn.type_vars[prefix]
85
+ assert isinstance(tvt, TypeVarTupleType)
86
+ fallback = tvt.tuple_fallback
87
+ s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix(s.args, prefix, suffix)
88
+ t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(t.args, prefix, suffix)
89
+ s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix
90
+ t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix
91
+ else:
92
+ t_args = t.args
93
+ s_args = s.args
94
+ for ta, sa, type_var in zip(t_args, s_args, t.type.defn.type_vars):
95
+ ta_proper = get_proper_type(ta)
96
+ sa_proper = get_proper_type(sa)
97
+ new_type: Type | None = None
98
+ if isinstance(ta_proper, AnyType):
99
+ new_type = AnyType(TypeOfAny.from_another_any, ta_proper)
100
+ elif isinstance(sa_proper, AnyType):
101
+ new_type = AnyType(TypeOfAny.from_another_any, sa_proper)
102
+ elif isinstance(type_var, TypeVarType):
103
+ if type_var.variance in (COVARIANT, VARIANCE_NOT_READY):
104
+ new_type = join_types(ta, sa, self)
105
+ if len(type_var.values) != 0 and new_type not in type_var.values:
106
+ self.seen_instances.pop()
107
+ return object_from_instance(t)
108
+ if not is_subtype(new_type, type_var.upper_bound):
109
+ self.seen_instances.pop()
110
+ return object_from_instance(t)
111
+ # TODO: contravariant case should use meet but pass seen instances as
112
+ # an argument to keep track of recursive checks.
113
+ elif type_var.variance in (INVARIANT, CONTRAVARIANT):
114
+ if isinstance(ta_proper, UninhabitedType) and ta_proper.ambiguous:
115
+ new_type = sa
116
+ elif isinstance(sa_proper, UninhabitedType) and sa_proper.ambiguous:
117
+ new_type = ta
118
+ elif not is_equivalent(ta, sa):
119
+ self.seen_instances.pop()
120
+ return object_from_instance(t)
121
+ else:
122
+ # If the types are different but equivalent, then an Any is involved
123
+ # so using a join in the contravariant case is also OK.
124
+ new_type = join_types(ta, sa, self)
125
+ elif isinstance(type_var, TypeVarTupleType):
126
+ new_type = get_proper_type(join_types(ta, sa, self))
127
+ # Put the joined arguments back into instance in the normal form:
128
+ # a) Tuple[X, Y, Z] -> [X, Y, Z]
129
+ # b) tuple[X, ...] -> [*tuple[X, ...]]
130
+ if isinstance(new_type, Instance):
131
+ assert new_type.type.fullname == "builtins.tuple"
132
+ new_type = UnpackType(new_type)
133
+ else:
134
+ assert isinstance(new_type, TupleType)
135
+ args.extend(new_type.items)
136
+ continue
137
+ else:
138
+ # ParamSpec type variables behave the same, independent of variance
139
+ if not is_equivalent(ta, sa):
140
+ return get_proper_type(type_var.upper_bound)
141
+ new_type = join_types(ta, sa, self)
142
+ assert new_type is not None
143
+ args.append(new_type)
144
+ result: ProperType = Instance(t.type, args)
145
+ elif t.type.bases and is_proper_subtype(
146
+ t, s, subtype_context=SubtypeContext(ignore_type_params=True)
147
+ ):
148
+ result = self.join_instances_via_supertype(t, s)
149
+ else:
150
+ # Now t is not a subtype of s, and t != s. Now s could be a subtype
151
+ # of t; alternatively, we need to find a common supertype. This works
152
+ # in of the both cases.
153
+ result = self.join_instances_via_supertype(s, t)
154
+
155
+ self.seen_instances.pop()
156
+ return result
157
+
158
+ def join_instances_via_supertype(self, t: Instance, s: Instance) -> ProperType:
159
+ # Give preference to joins via duck typing relationship, so that
160
+ # join(int, float) == float, for example.
161
+ for p in t.type._promote:
162
+ if is_subtype(p, s):
163
+ return join_types(p, s, self)
164
+ for p in s.type._promote:
165
+ if is_subtype(p, t):
166
+ return join_types(t, p, self)
167
+
168
+ # Compute the "best" supertype of t when joined with s.
169
+ # The definition of "best" may evolve; for now it is the one with
170
+ # the longest MRO. Ties are broken by using the earlier base.
171
+
172
+ # Go over both sets of bases in case there's an explicit Protocol base. This is important
173
+ # to ensure commutativity of join (although in cases where both classes have relevant
174
+ # Protocol bases this maybe might still not be commutative)
175
+ base_types: dict[TypeInfo, None] = {} # dict to deduplicate but preserve order
176
+ for base in t.type.bases:
177
+ base_types[base.type] = None
178
+ for base in s.type.bases:
179
+ if base.type.is_protocol and is_subtype(t, base):
180
+ base_types[base.type] = None
181
+
182
+ best: ProperType | None = None
183
+ for base_type in base_types:
184
+ mapped = map_instance_to_supertype(t, base_type)
185
+ res = self.join_instances(mapped, s)
186
+ if best is None or is_better(res, best):
187
+ best = res
188
+ assert best is not None
189
+ for promote in t.type._promote:
190
+ if isinstance(promote, Instance):
191
+ res = self.join_instances(promote, s)
192
+ if is_better(res, best):
193
+ best = res
194
+ return best
195
+
196
+
197
+ def trivial_join(s: Type, t: Type) -> Type:
198
+ """Return one of types (expanded) if it is a supertype of other, otherwise top type."""
199
+ if is_subtype(s, t):
200
+ return t
201
+ elif is_subtype(t, s):
202
+ return s
203
+ else:
204
+ return object_or_any_from_type(get_proper_type(t))
205
+
206
+
207
+ @overload
208
+ def join_types(
209
+ s: ProperType, t: ProperType, instance_joiner: InstanceJoiner | None = None
210
+ ) -> ProperType: ...
211
+
212
+
213
+ @overload
214
+ def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: ...
215
+
216
+
217
+ def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type:
218
+ """Return the least upper bound of s and t.
219
+
220
+ For example, the join of 'int' and 'object' is 'object'.
221
+ """
222
+ if mypy.typeops.is_recursive_pair(s, t):
223
+ # This case can trigger an infinite recursion, general support for this will be
224
+ # tricky so we use a trivial join (like for protocols).
225
+ return trivial_join(s, t)
226
+ s = get_proper_type(s)
227
+ t = get_proper_type(t)
228
+
229
+ if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):
230
+ # if types are restricted in different ways, use the more general versions
231
+ s = mypy.typeops.true_or_false(s)
232
+ t = mypy.typeops.true_or_false(t)
233
+
234
+ if isinstance(s, UnionType) and not isinstance(t, UnionType):
235
+ s, t = t, s
236
+
237
+ if isinstance(s, AnyType):
238
+ return s
239
+
240
+ if isinstance(s, ErasedType):
241
+ return t
242
+
243
+ if isinstance(s, NoneType) and not isinstance(t, NoneType):
244
+ s, t = t, s
245
+
246
+ if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):
247
+ s, t = t, s
248
+
249
+ # Meets/joins require callable type normalization.
250
+ s, t = normalize_callables(s, t)
251
+
252
+ # Use a visitor to handle non-trivial cases.
253
+ return t.accept(TypeJoinVisitor(s, instance_joiner))
254
+
255
+
256
+ class TypeJoinVisitor(TypeVisitor[ProperType]):
257
+ """Implementation of the least upper bound algorithm.
258
+
259
+ Attributes:
260
+ s: The other (left) type operand.
261
+ """
262
+
263
+ def __init__(self, s: ProperType, instance_joiner: InstanceJoiner | None = None) -> None:
264
+ self.s = s
265
+ self.instance_joiner = instance_joiner
266
+
267
+ def visit_unbound_type(self, t: UnboundType) -> ProperType:
268
+ return AnyType(TypeOfAny.special_form)
269
+
270
+ def visit_union_type(self, t: UnionType) -> ProperType:
271
+ if is_proper_subtype(self.s, t):
272
+ return t
273
+ else:
274
+ return mypy.typeops.make_simplified_union([self.s, t])
275
+
276
+ def visit_any(self, t: AnyType) -> ProperType:
277
+ return t
278
+
279
+ def visit_none_type(self, t: NoneType) -> ProperType:
280
+ if state.strict_optional:
281
+ if isinstance(self.s, (NoneType, UninhabitedType)):
282
+ return t
283
+ elif isinstance(self.s, (UnboundType, AnyType)):
284
+ return AnyType(TypeOfAny.special_form)
285
+ else:
286
+ return mypy.typeops.make_simplified_union([self.s, t])
287
+ else:
288
+ return self.s
289
+
290
+ def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:
291
+ return self.s
292
+
293
+ def visit_deleted_type(self, t: DeletedType) -> ProperType:
294
+ return self.s
295
+
296
+ def visit_erased_type(self, t: ErasedType) -> ProperType:
297
+ return self.s
298
+
299
+ def visit_type_var(self, t: TypeVarType) -> ProperType:
300
+ if isinstance(self.s, TypeVarType):
301
+ if self.s.id == t.id:
302
+ if self.s.upper_bound == t.upper_bound:
303
+ return self.s
304
+ return self.s.copy_modified(
305
+ upper_bound=join_types(self.s.upper_bound, t.upper_bound)
306
+ )
307
+ # Fix non-commutative joins
308
+ return get_proper_type(join_types(self.s.upper_bound, t.upper_bound))
309
+ else:
310
+ return self.default(self.s)
311
+
312
+ def visit_param_spec(self, t: ParamSpecType) -> ProperType:
313
+ if self.s == t:
314
+ return t
315
+ return self.default(self.s)
316
+
317
+ def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:
318
+ if self.s == t:
319
+ return t
320
+ if isinstance(self.s, Instance) and is_subtype(t.upper_bound, self.s):
321
+ # TODO: should we do this more generally and for all TypeVarLikeTypes?
322
+ return self.s
323
+ return self.default(self.s)
324
+
325
+ def visit_unpack_type(self, t: UnpackType) -> UnpackType:
326
+ raise NotImplementedError
327
+
328
+ def visit_parameters(self, t: Parameters) -> ProperType:
329
+ if isinstance(self.s, Parameters):
330
+ if not is_similar_params(t, self.s):
331
+ # TODO: it would be prudent to return [*object, **object] instead of Any.
332
+ return self.default(self.s)
333
+ from mypy.meet import meet_types
334
+
335
+ return t.copy_modified(
336
+ arg_types=[
337
+ meet_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types)
338
+ ],
339
+ arg_names=combine_arg_names(self.s, t),
340
+ )
341
+ else:
342
+ return self.default(self.s)
343
+
344
+ def visit_instance(self, t: Instance) -> ProperType:
345
+ if isinstance(self.s, Instance):
346
+ if self.instance_joiner is None:
347
+ self.instance_joiner = InstanceJoiner()
348
+ nominal = self.instance_joiner.join_instances(t, self.s)
349
+ structural: Instance | None = None
350
+ if t.type.is_protocol and is_protocol_implementation(self.s, t):
351
+ structural = t
352
+ elif self.s.type.is_protocol and is_protocol_implementation(t, self.s):
353
+ structural = self.s
354
+ # Structural join is preferred in the case where we have found both
355
+ # structural and nominal and they have same MRO length (see two comments
356
+ # in join_instances_via_supertype). Otherwise, just return the nominal join.
357
+ if not structural or is_better(nominal, structural):
358
+ return nominal
359
+ return structural
360
+ elif isinstance(self.s, FunctionLike):
361
+ if t.type.is_protocol:
362
+ call = unpack_callback_protocol(t)
363
+ if call:
364
+ return join_types(call, self.s)
365
+ return join_types(t, self.s.fallback)
366
+ elif isinstance(self.s, TypeType):
367
+ return join_types(t, self.s)
368
+ elif isinstance(self.s, TypedDictType):
369
+ return join_types(t, self.s)
370
+ elif isinstance(self.s, TupleType):
371
+ return join_types(t, self.s)
372
+ elif isinstance(self.s, LiteralType):
373
+ return join_types(t, self.s)
374
+ elif isinstance(self.s, TypeVarTupleType) and is_subtype(self.s.upper_bound, t):
375
+ return t
376
+ else:
377
+ return self.default(self.s)
378
+
379
+ def visit_callable_type(self, t: CallableType) -> ProperType:
380
+ if isinstance(self.s, CallableType):
381
+ if is_similar_callables(t, self.s):
382
+ if is_equivalent(t, self.s):
383
+ return combine_similar_callables(t, self.s)
384
+ result = join_similar_callables(t, self.s)
385
+ if any(
386
+ isinstance(tp, (NoneType, UninhabitedType))
387
+ for tp in get_proper_types(result.arg_types)
388
+ ):
389
+ # We don't want to return unusable Callable, attempt fallback instead.
390
+ return join_types(t.fallback, self.s)
391
+ # We set the from_type_type flag to suppress error when a collection of
392
+ # concrete class objects gets inferred as their common abstract superclass.
393
+ if not (
394
+ (t.is_type_obj() and t.type_object().is_abstract)
395
+ or (self.s.is_type_obj() and self.s.type_object().is_abstract)
396
+ ):
397
+ result.from_type_type = True
398
+ return result
399
+ else:
400
+ s2, t2 = self.s, t
401
+ if t2.is_var_arg:
402
+ s2, t2 = t2, s2
403
+ if is_subtype(s2, t2):
404
+ return t2.copy_modified()
405
+ elif is_subtype(t2, s2):
406
+ return s2.copy_modified()
407
+ return join_types(t.fallback, self.s)
408
+ elif isinstance(self.s, Overloaded):
409
+ # Switch the order of arguments to that we'll get to visit_overloaded.
410
+ return join_types(t, self.s)
411
+ elif isinstance(self.s, Instance) and self.s.type.is_protocol:
412
+ call = unpack_callback_protocol(self.s)
413
+ if call:
414
+ return join_types(t, call)
415
+ return join_types(t.fallback, self.s)
416
+
417
+ def visit_overloaded(self, t: Overloaded) -> ProperType:
418
+ # This is more complex than most other cases. Here are some
419
+ # examples that illustrate how this works.
420
+ #
421
+ # First let's define a concise notation:
422
+ # - Cn are callable types (for n in 1, 2, ...)
423
+ # - Ov(C1, C2, ...) is an overloaded type with items C1, C2, ...
424
+ # - Callable[[T, ...], S] is written as [T, ...] -> S.
425
+ #
426
+ # We want some basic properties to hold (assume Cn are all
427
+ # unrelated via Any-similarity):
428
+ #
429
+ # join(Ov(C1, C2), C1) == C1
430
+ # join(Ov(C1, C2), Ov(C1, C2)) == Ov(C1, C2)
431
+ # join(Ov(C1, C2), Ov(C1, C3)) == C1
432
+ # join(Ov(C2, C2), C3) == join of fallback types
433
+ #
434
+ # The presence of Any types makes things more interesting. The join is the
435
+ # most general type we can get with respect to Any:
436
+ #
437
+ # join(Ov([int] -> int, [str] -> str), [Any] -> str) == Any -> str
438
+ #
439
+ # We could use a simplification step that removes redundancies, but that's not
440
+ # implemented right now. Consider this example, where we get a redundancy:
441
+ #
442
+ # join(Ov([int, Any] -> Any, [str, Any] -> Any), [Any, int] -> Any) ==
443
+ # Ov([Any, int] -> Any, [Any, int] -> Any)
444
+ #
445
+ # TODO: Consider more cases of callable subtyping.
446
+ result: list[CallableType] = []
447
+ s = self.s
448
+ if isinstance(s, FunctionLike):
449
+ # The interesting case where both types are function types.
450
+ for t_item in t.items:
451
+ for s_item in s.items:
452
+ if is_similar_callables(t_item, s_item):
453
+ if is_equivalent(t_item, s_item):
454
+ result.append(combine_similar_callables(t_item, s_item))
455
+ elif is_subtype(t_item, s_item):
456
+ result.append(s_item)
457
+ if result:
458
+ # TODO: Simplify redundancies from the result.
459
+ if len(result) == 1:
460
+ return result[0]
461
+ else:
462
+ return Overloaded(result)
463
+ return join_types(t.fallback, s.fallback)
464
+ elif isinstance(s, Instance) and s.type.is_protocol:
465
+ call = unpack_callback_protocol(s)
466
+ if call:
467
+ return join_types(t, call)
468
+ return join_types(t.fallback, s)
469
+
470
+ def join_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None:
471
+ """Join two tuple types while handling variadic entries.
472
+
473
+ This is surprisingly tricky, and we don't handle some tricky corner cases.
474
+ Most of the trickiness comes from the variadic tuple items like *tuple[X, ...]
475
+ since they can have arbitrary partial overlaps (while *Ts can't be split).
476
+ """
477
+ s_unpack_index = find_unpack_in_list(s.items)
478
+ t_unpack_index = find_unpack_in_list(t.items)
479
+ if s_unpack_index is None and t_unpack_index is None:
480
+ if s.length() == t.length():
481
+ items: list[Type] = []
482
+ for i in range(t.length()):
483
+ items.append(join_types(t.items[i], s.items[i]))
484
+ return items
485
+ return None
486
+ if s_unpack_index is not None and t_unpack_index is not None:
487
+ # The most complex case: both tuples have an unpack item.
488
+ s_unpack = s.items[s_unpack_index]
489
+ assert isinstance(s_unpack, UnpackType)
490
+ s_unpacked = get_proper_type(s_unpack.type)
491
+ t_unpack = t.items[t_unpack_index]
492
+ assert isinstance(t_unpack, UnpackType)
493
+ t_unpacked = get_proper_type(t_unpack.type)
494
+ if s.length() == t.length() and s_unpack_index == t_unpack_index:
495
+ # We can handle a case where arity is perfectly aligned, e.g.
496
+ # join(Tuple[X1, *tuple[Y1, ...], Z1], Tuple[X2, *tuple[Y2, ...], Z2]).
497
+ # We can essentially perform the join elementwise.
498
+ prefix_len = t_unpack_index
499
+ suffix_len = t.length() - t_unpack_index - 1
500
+ items = []
501
+ for si, ti in zip(s.items[:prefix_len], t.items[:prefix_len]):
502
+ items.append(join_types(si, ti))
503
+ joined = join_types(s_unpacked, t_unpacked)
504
+ if isinstance(joined, TypeVarTupleType):
505
+ items.append(UnpackType(joined))
506
+ elif isinstance(joined, Instance) and joined.type.fullname == "builtins.tuple":
507
+ items.append(UnpackType(joined))
508
+ else:
509
+ if isinstance(t_unpacked, Instance):
510
+ assert t_unpacked.type.fullname == "builtins.tuple"
511
+ tuple_instance = t_unpacked
512
+ else:
513
+ assert isinstance(t_unpacked, TypeVarTupleType)
514
+ tuple_instance = t_unpacked.tuple_fallback
515
+ items.append(
516
+ UnpackType(
517
+ tuple_instance.copy_modified(
518
+ args=[object_from_instance(tuple_instance)]
519
+ )
520
+ )
521
+ )
522
+ if suffix_len:
523
+ for si, ti in zip(s.items[-suffix_len:], t.items[-suffix_len:]):
524
+ items.append(join_types(si, ti))
525
+ return items
526
+ if s.length() == 1 or t.length() == 1:
527
+ # Another case we can handle is when one of tuple is purely variadic
528
+ # (i.e. a non-normalized form of tuple[X, ...]), in this case the join
529
+ # will be again purely variadic.
530
+ if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)):
531
+ return None
532
+ assert s_unpacked.type.fullname == "builtins.tuple"
533
+ assert t_unpacked.type.fullname == "builtins.tuple"
534
+ mid_joined = join_types(s_unpacked.args[0], t_unpacked.args[0])
535
+ t_other = [a for i, a in enumerate(t.items) if i != t_unpack_index]
536
+ s_other = [a for i, a in enumerate(s.items) if i != s_unpack_index]
537
+ other_joined = join_type_list(s_other + t_other)
538
+ mid_joined = join_types(mid_joined, other_joined)
539
+ return [UnpackType(s_unpacked.copy_modified(args=[mid_joined]))]
540
+ # TODO: are there other case we can handle (e.g. both prefix/suffix are shorter)?
541
+ return None
542
+ if s_unpack_index is not None:
543
+ variadic = s
544
+ unpack_index = s_unpack_index
545
+ fixed = t
546
+ else:
547
+ assert t_unpack_index is not None
548
+ variadic = t
549
+ unpack_index = t_unpack_index
550
+ fixed = s
551
+ # Case where one tuple has variadic item and the other one doesn't. The join will
552
+ # be variadic, since fixed tuple is a subtype of variadic, but not vice versa.
553
+ unpack = variadic.items[unpack_index]
554
+ assert isinstance(unpack, UnpackType)
555
+ unpacked = get_proper_type(unpack.type)
556
+ if not isinstance(unpacked, Instance):
557
+ return None
558
+ if fixed.length() < variadic.length() - 1:
559
+ # There are no non-trivial types that are supertype of both.
560
+ return None
561
+ prefix_len = unpack_index
562
+ suffix_len = variadic.length() - prefix_len - 1
563
+ prefix, middle, suffix = split_with_prefix_and_suffix(
564
+ tuple(fixed.items), prefix_len, suffix_len
565
+ )
566
+ items = []
567
+ for fi, vi in zip(prefix, variadic.items[:prefix_len]):
568
+ items.append(join_types(fi, vi))
569
+ mid_joined = join_type_list(list(middle))
570
+ mid_joined = join_types(mid_joined, unpacked.args[0])
571
+ items.append(UnpackType(unpacked.copy_modified(args=[mid_joined])))
572
+ if suffix_len:
573
+ for fi, vi in zip(suffix, variadic.items[-suffix_len:]):
574
+ items.append(join_types(fi, vi))
575
+ return items
576
+
577
+ def visit_tuple_type(self, t: TupleType) -> ProperType:
578
+ # When given two fixed-length tuples:
579
+ # * If they have the same length, join their subtypes item-wise:
580
+ # Tuple[int, bool] + Tuple[bool, bool] becomes Tuple[int, bool]
581
+ # * If lengths do not match, return a variadic tuple:
582
+ # Tuple[bool, int] + Tuple[bool] becomes Tuple[int, ...]
583
+ #
584
+ # Otherwise, `t` is a fixed-length tuple but `self.s` is NOT:
585
+ # * Joining with a variadic tuple returns variadic tuple:
586
+ # Tuple[int, bool] + Tuple[bool, ...] becomes Tuple[int, ...]
587
+ # * Joining with any Sequence also returns a Sequence:
588
+ # Tuple[int, bool] + List[bool] becomes Sequence[int]
589
+ if isinstance(self.s, TupleType):
590
+ if self.instance_joiner is None:
591
+ self.instance_joiner = InstanceJoiner()
592
+ fallback = self.instance_joiner.join_instances(
593
+ mypy.typeops.tuple_fallback(self.s), mypy.typeops.tuple_fallback(t)
594
+ )
595
+ assert isinstance(fallback, Instance)
596
+ items = self.join_tuples(self.s, t)
597
+ if items is not None:
598
+ if len(items) == 1 and isinstance(item := items[0], UnpackType):
599
+ if isinstance(unpacked := get_proper_type(item.type), Instance):
600
+ # Avoid double-wrapping tuple[*tuple[X, ...]]
601
+ return unpacked
602
+ return TupleType(items, fallback)
603
+ else:
604
+ # TODO: should this be a default fallback behaviour like for meet?
605
+ if is_proper_subtype(self.s, t):
606
+ return t
607
+ if is_proper_subtype(t, self.s):
608
+ return self.s
609
+ return fallback
610
+ else:
611
+ return join_types(self.s, mypy.typeops.tuple_fallback(t))
612
+
613
+ def visit_typeddict_type(self, t: TypedDictType) -> ProperType:
614
+ if isinstance(self.s, TypedDictType):
615
+ items = {
616
+ item_name: s_item_type
617
+ for (item_name, s_item_type, t_item_type) in self.s.zip(t)
618
+ if (
619
+ is_equivalent(s_item_type, t_item_type)
620
+ and (item_name in t.required_keys) == (item_name in self.s.required_keys)
621
+ )
622
+ }
623
+ fallback = self.s.create_anonymous_fallback()
624
+ all_keys = set(items.keys())
625
+ # We need to filter by items.keys() since some required keys present in both t and
626
+ # self.s might be missing from the join if the types are incompatible.
627
+ required_keys = all_keys & t.required_keys & self.s.required_keys
628
+ # If one type has a key as readonly, we mark it as readonly for both:
629
+ readonly_keys = (t.readonly_keys | t.readonly_keys) & all_keys
630
+ return TypedDictType(items, required_keys, readonly_keys, fallback)
631
+ elif isinstance(self.s, Instance):
632
+ return join_types(self.s, t.fallback)
633
+ else:
634
+ return self.default(self.s)
635
+
636
+ def visit_literal_type(self, t: LiteralType) -> ProperType:
637
+ if isinstance(self.s, LiteralType):
638
+ if t == self.s:
639
+ return t
640
+ if self.s.fallback.type.is_enum and t.fallback.type.is_enum:
641
+ return mypy.typeops.make_simplified_union([self.s, t])
642
+ return join_types(self.s.fallback, t.fallback)
643
+ elif isinstance(self.s, Instance) and self.s.last_known_value == t:
644
+ return t
645
+ else:
646
+ return join_types(self.s, t.fallback)
647
+
648
+ def visit_partial_type(self, t: PartialType) -> ProperType:
649
+ # We only have partial information so we can't decide the join result. We should
650
+ # never get here.
651
+ assert False, "Internal error"
652
+
653
+ def visit_type_type(self, t: TypeType) -> ProperType:
654
+ if isinstance(self.s, TypeType):
655
+ return TypeType.make_normalized(
656
+ join_types(t.item, self.s.item),
657
+ line=t.line,
658
+ is_type_form=self.s.is_type_form or t.is_type_form,
659
+ )
660
+ elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type":
661
+ return self.s
662
+ else:
663
+ return self.default(self.s)
664
+
665
+ def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:
666
+ assert False, f"This should be never called, got {t}"
667
+
668
+ def default(self, typ: Type) -> ProperType:
669
+ typ = get_proper_type(typ)
670
+ if isinstance(typ, Instance):
671
+ return object_from_instance(typ)
672
+ elif isinstance(typ, TypeType):
673
+ return self.default(typ.item)
674
+ elif isinstance(typ, UnboundType):
675
+ return AnyType(TypeOfAny.special_form)
676
+ elif isinstance(typ, TupleType):
677
+ return self.default(mypy.typeops.tuple_fallback(typ))
678
+ elif isinstance(typ, TypedDictType):
679
+ return self.default(typ.fallback)
680
+ elif isinstance(typ, FunctionLike):
681
+ return self.default(typ.fallback)
682
+ elif isinstance(typ, TypeVarType):
683
+ return self.default(typ.upper_bound)
684
+ elif isinstance(typ, ParamSpecType):
685
+ return self.default(typ.upper_bound)
686
+ else:
687
+ return AnyType(TypeOfAny.special_form)
688
+
689
+
690
+ def is_better(t: Type, s: Type) -> bool:
691
+ # Given two possible results from join_instances_via_supertype(),
692
+ # indicate whether t is the better one.
693
+ t = get_proper_type(t)
694
+ s = get_proper_type(s)
695
+
696
+ if isinstance(t, Instance):
697
+ if not isinstance(s, Instance):
698
+ return True
699
+ if t.type.is_protocol != s.type.is_protocol:
700
+ if t.type.fullname != "builtins.object" and s.type.fullname != "builtins.object":
701
+ # mro of protocol is not really relevant
702
+ return not t.type.is_protocol
703
+ # Use len(mro) as a proxy for the better choice.
704
+ if len(t.type.mro) > len(s.type.mro):
705
+ return True
706
+ return False
707
+
708
+
709
+ def normalize_callables(s: ProperType, t: ProperType) -> tuple[ProperType, ProperType]:
710
+ if isinstance(s, (CallableType, Overloaded)):
711
+ s = s.with_unpacked_kwargs()
712
+ if isinstance(t, (CallableType, Overloaded)):
713
+ t = t.with_unpacked_kwargs()
714
+ return s, t
715
+
716
+
717
+ def is_similar_callables(t: CallableType, s: CallableType) -> bool:
718
+ """Return True if t and s have identical numbers of
719
+ arguments, default arguments and varargs.
720
+ """
721
+ return (
722
+ len(t.arg_types) == len(s.arg_types)
723
+ and t.min_args == s.min_args
724
+ and t.is_var_arg == s.is_var_arg
725
+ )
726
+
727
+
728
+ def is_similar_params(t: Parameters, s: Parameters) -> bool:
729
+ # This matches the logic in is_similar_callables() above.
730
+ return (
731
+ len(t.arg_types) == len(s.arg_types)
732
+ and t.min_args == s.min_args
733
+ and (t.var_arg() is not None) == (s.var_arg() is not None)
734
+ )
735
+
736
+
737
+ def update_callable_ids(c: CallableType, ids: list[TypeVarId]) -> CallableType:
738
+ tv_map = {}
739
+ tvs = []
740
+ for tv, new_id in zip(c.variables, ids):
741
+ new_tv = tv.copy_modified(id=new_id)
742
+ tvs.append(new_tv)
743
+ tv_map[tv.id] = new_tv
744
+ return expand_type(c, tv_map).copy_modified(variables=tvs)
745
+
746
+
747
+ def match_generic_callables(t: CallableType, s: CallableType) -> tuple[CallableType, CallableType]:
748
+ # The case where we combine/join/meet similar callables, situation where both are generic
749
+ # requires special care. A more principled solution may involve unify_generic_callable(),
750
+ # but it would have two problems:
751
+ # * This adds risk of infinite recursion: e.g. join -> unification -> solver -> join
752
+ # * Using unification is an incorrect thing for meets, as it "widens" the types
753
+ # Finally, this effectively falls back to an old behaviour before namespaces were added to
754
+ # type variables, and it worked relatively well.
755
+ max_len = max(len(t.variables), len(s.variables))
756
+ min_len = min(len(t.variables), len(s.variables))
757
+ if min_len == 0:
758
+ return t, s
759
+ new_ids = [TypeVarId.new(meta_level=0) for _ in range(max_len)]
760
+ # Note: this relies on variables being in order they appear in function definition.
761
+ return update_callable_ids(t, new_ids), update_callable_ids(s, new_ids)
762
+
763
+
764
+ def join_similar_callables(t: CallableType, s: CallableType) -> CallableType:
765
+ t, s = match_generic_callables(t, s)
766
+ arg_types: list[Type] = []
767
+ for i in range(len(t.arg_types)):
768
+ arg_types.append(safe_meet(t.arg_types[i], s.arg_types[i]))
769
+ # TODO in combine_similar_callables also applies here (names and kinds; user metaclasses)
770
+ # The fallback type can be either 'function', 'type', or some user-provided metaclass.
771
+ # The result should always use 'function' as a fallback if either operands are using it.
772
+ if t.fallback.type.fullname == "builtins.function":
773
+ fallback = t.fallback
774
+ else:
775
+ fallback = s.fallback
776
+ return t.copy_modified(
777
+ arg_types=arg_types,
778
+ arg_names=combine_arg_names(t, s),
779
+ ret_type=join_types(t.ret_type, s.ret_type),
780
+ fallback=fallback,
781
+ name=None,
782
+ )
783
+
784
+
785
+ def safe_join(t: Type, s: Type) -> Type:
786
+ # This is a temporary solution to prevent crashes in combine_similar_callables() etc.,
787
+ # until relevant TODOs on handling arg_kinds will be addressed there.
788
+ if not isinstance(t, UnpackType) and not isinstance(s, UnpackType):
789
+ return join_types(t, s)
790
+ if isinstance(t, UnpackType) and isinstance(s, UnpackType):
791
+ return UnpackType(join_types(t.type, s.type))
792
+ return object_or_any_from_type(get_proper_type(t))
793
+
794
+
795
+ def safe_meet(t: Type, s: Type) -> Type:
796
+ # Similar to above but for meet_types().
797
+ from mypy.meet import meet_types
798
+
799
+ if not isinstance(t, UnpackType) and not isinstance(s, UnpackType):
800
+ return meet_types(t, s)
801
+ if isinstance(t, UnpackType) and isinstance(s, UnpackType):
802
+ unpacked = get_proper_type(t.type)
803
+ if isinstance(unpacked, TypeVarTupleType):
804
+ fallback_type = unpacked.tuple_fallback.type
805
+ elif isinstance(unpacked, TupleType):
806
+ fallback_type = unpacked.partial_fallback.type
807
+ else:
808
+ assert isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple"
809
+ fallback_type = unpacked.type
810
+ res = meet_types(t.type, s.type)
811
+ if isinstance(res, UninhabitedType):
812
+ res = Instance(fallback_type, [res])
813
+ return UnpackType(res)
814
+ return UninhabitedType()
815
+
816
+
817
+ def combine_similar_callables(t: CallableType, s: CallableType) -> CallableType:
818
+ t, s = match_generic_callables(t, s)
819
+ arg_types: list[Type] = []
820
+ for i in range(len(t.arg_types)):
821
+ arg_types.append(safe_join(t.arg_types[i], s.arg_types[i]))
822
+ # TODO kinds and argument names
823
+ # TODO what should happen if one fallback is 'type' and the other is a user-provided metaclass?
824
+ # The fallback type can be either 'function', 'type', or some user-provided metaclass.
825
+ # The result should always use 'function' as a fallback if either operands are using it.
826
+ if t.fallback.type.fullname == "builtins.function":
827
+ fallback = t.fallback
828
+ else:
829
+ fallback = s.fallback
830
+ return t.copy_modified(
831
+ arg_types=arg_types,
832
+ arg_names=combine_arg_names(t, s),
833
+ ret_type=join_types(t.ret_type, s.ret_type),
834
+ fallback=fallback,
835
+ name=None,
836
+ )
837
+
838
+
839
+ def combine_arg_names(
840
+ t: CallableType | Parameters, s: CallableType | Parameters
841
+ ) -> list[str | None]:
842
+ """Produces a list of argument names compatible with both callables.
843
+
844
+ For example, suppose 't' and 's' have the following signatures:
845
+
846
+ - t: (a: int, b: str, X: str) -> None
847
+ - s: (a: int, b: str, Y: str) -> None
848
+
849
+ This function would return ["a", "b", None]. This information
850
+ is then used above to compute the join of t and s, which results
851
+ in a signature of (a: int, b: str, str) -> None.
852
+
853
+ Note that the third argument's name is omitted and 't' and 's'
854
+ are both valid subtypes of this inferred signature.
855
+
856
+ Precondition: is_similar_types(t, s) is true.
857
+ """
858
+ num_args = len(t.arg_types)
859
+ new_names = []
860
+ for i in range(num_args):
861
+ t_name = t.arg_names[i]
862
+ s_name = s.arg_names[i]
863
+ if t_name == s_name or t.arg_kinds[i].is_named() or s.arg_kinds[i].is_named():
864
+ new_names.append(t_name)
865
+ else:
866
+ new_names.append(None)
867
+ return new_names
868
+
869
+
870
+ def object_from_instance(instance: Instance) -> Instance:
871
+ """Construct the type 'builtins.object' from an instance type."""
872
+ # Use the fact that 'object' is always the last class in the mro.
873
+ res = Instance(instance.type.mro[-1], [])
874
+ return res
875
+
876
+
877
+ def object_or_any_from_type(typ: ProperType) -> ProperType:
878
+ # Similar to object_from_instance() but tries hard for all types.
879
+ # TODO: find a better way to get object, or make this more reliable.
880
+ if isinstance(typ, Instance):
881
+ return object_from_instance(typ)
882
+ elif isinstance(typ, (CallableType, TypedDictType, LiteralType)):
883
+ return object_from_instance(typ.fallback)
884
+ elif isinstance(typ, TupleType):
885
+ return object_from_instance(typ.partial_fallback)
886
+ elif isinstance(typ, TypeType):
887
+ return object_or_any_from_type(typ.item)
888
+ elif isinstance(typ, TypeVarLikeType) and isinstance(typ.upper_bound, ProperType):
889
+ return object_or_any_from_type(typ.upper_bound)
890
+ elif isinstance(typ, UnionType):
891
+ for item in typ.items:
892
+ if isinstance(item, ProperType):
893
+ candidate = object_or_any_from_type(item)
894
+ if isinstance(candidate, Instance):
895
+ return candidate
896
+ elif isinstance(typ, UnpackType):
897
+ object_or_any_from_type(get_proper_type(typ.type))
898
+ return AnyType(TypeOfAny.implementation_artifact)
899
+
900
+
901
+ def join_type_list(types: Sequence[Type]) -> Type:
902
+ if not types:
903
+ # This is a little arbitrary but reasonable. Any empty tuple should be compatible
904
+ # with all variable length tuples, and this makes it possible.
905
+ return UninhabitedType()
906
+ joined = types[0]
907
+ for t in types[1:]:
908
+ joined = join_types(joined, t)
909
+ return joined
910
+
911
+
912
+ def unpack_callback_protocol(t: Instance) -> ProperType | None:
913
+ assert t.type.is_protocol
914
+ if t.type.protocol_members == ["__call__"]:
915
+ return get_proper_type(find_member("__call__", t, t, is_operator=True))
916
+ return None
micromamba_root/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file
 
micromamba_root/Lib/site-packages/mypy/literals.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+ from typing import Any, Final, TypeAlias as _TypeAlias
5
+
6
+ from mypy.nodes import (
7
+ LITERAL_NO,
8
+ LITERAL_TYPE,
9
+ LITERAL_YES,
10
+ AssertTypeExpr,
11
+ AssignmentExpr,
12
+ AwaitExpr,
13
+ BytesExpr,
14
+ CallExpr,
15
+ CastExpr,
16
+ ComparisonExpr,
17
+ ComplexExpr,
18
+ ConditionalExpr,
19
+ DictExpr,
20
+ DictionaryComprehension,
21
+ EllipsisExpr,
22
+ EnumCallExpr,
23
+ Expression,
24
+ FloatExpr,
25
+ GeneratorExpr,
26
+ IndexExpr,
27
+ IntExpr,
28
+ LambdaExpr,
29
+ ListComprehension,
30
+ ListExpr,
31
+ MemberExpr,
32
+ NamedTupleExpr,
33
+ NameExpr,
34
+ NewTypeExpr,
35
+ OpExpr,
36
+ ParamSpecExpr,
37
+ PromoteExpr,
38
+ RevealExpr,
39
+ SetComprehension,
40
+ SetExpr,
41
+ SliceExpr,
42
+ StarExpr,
43
+ StrExpr,
44
+ SuperExpr,
45
+ TemplateStrExpr,
46
+ TempNode,
47
+ TupleExpr,
48
+ TypeAliasExpr,
49
+ TypeApplication,
50
+ TypedDictExpr,
51
+ TypeFormExpr,
52
+ TypeVarExpr,
53
+ TypeVarTupleExpr,
54
+ UnaryExpr,
55
+ Var,
56
+ YieldExpr,
57
+ YieldFromExpr,
58
+ )
59
+ from mypy.visitor import ExpressionVisitor
60
+
61
+ # [Note Literals and literal_hash]
62
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
63
+ #
64
+ # Mypy uses the term "literal" to refer to any expression built out of
65
+ # the following:
66
+ #
67
+ # * Plain literal expressions, like `1` (integer, float, string, etc.)
68
+ #
69
+ # * Compound literal expressions, like `(lit1, lit2)` (list, dict,
70
+ # set, or tuple)
71
+ #
72
+ # * Operator expressions, like `lit1 + lit2`
73
+ #
74
+ # * Variable references, like `x`
75
+ #
76
+ # * Member references, like `lit.m`
77
+ #
78
+ # * Index expressions, like `lit[0]`
79
+ #
80
+ # A typical "literal" looks like `x[(i,j+1)].m`.
81
+ #
82
+ # An expression that is a literal has a `literal_hash`, with the
83
+ # following properties.
84
+ #
85
+ # * `literal_hash` is a Key: a tuple containing basic data types and
86
+ # possibly other Keys. So it can be used as a key in a dictionary
87
+ # that will be compared by value (as opposed to the Node itself,
88
+ # which is compared by identity).
89
+ #
90
+ # * Two expressions have equal `literal_hash`es if and only if they
91
+ # are syntactically equal expressions. (NB: Actually, we also
92
+ # identify as equal expressions like `3` and `3.0`; is this a good
93
+ # idea?)
94
+ #
95
+ # * The elements of `literal_hash` that are tuples are exactly the
96
+ # subexpressions of the original expression (e.g. the base and index
97
+ # of an index expression, or the operands of an operator expression).
98
+
99
+
100
+ Key: _TypeAlias = tuple[Any, ...]
101
+
102
+
103
+ def literal_hash(e: Expression) -> Key | None:
104
+ """Generate a hashable, (mostly) opaque key for expressions supported by the binder.
105
+
106
+ These allow using expressions as dictionary keys based on structural/value
107
+ matching (instead of based on expression identity).
108
+
109
+ Return None if the expression type is not supported (it cannot be narrowed).
110
+
111
+ See the comment above for more information.
112
+
113
+ NOTE: This is not directly related to literal types.
114
+ """
115
+ return e.accept(_hasher)
116
+
117
+
118
+ def literal(e: Expression) -> int:
119
+ """Return the literal kind for an expression."""
120
+
121
+ if isinstance(e, ComparisonExpr):
122
+ return min(literal(o) for o in e.operands)
123
+
124
+ elif isinstance(e, OpExpr):
125
+ return min(literal(e.left), literal(e.right))
126
+
127
+ elif isinstance(e, (MemberExpr, UnaryExpr, StarExpr)):
128
+ return literal(e.expr)
129
+
130
+ elif isinstance(e, AssignmentExpr):
131
+ return literal(e.target)
132
+
133
+ elif isinstance(e, IndexExpr):
134
+ if literal(e.index) == LITERAL_YES:
135
+ return literal(e.base)
136
+ else:
137
+ return LITERAL_NO
138
+
139
+ elif isinstance(e, NameExpr):
140
+ if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None:
141
+ return LITERAL_YES
142
+ return LITERAL_TYPE
143
+
144
+ if isinstance(e, (IntExpr, FloatExpr, ComplexExpr, StrExpr, BytesExpr)):
145
+ return LITERAL_YES
146
+
147
+ if literal_hash(e):
148
+ return LITERAL_YES
149
+
150
+ return LITERAL_NO
151
+
152
+
153
+ def subkeys(key: Key) -> Iterable[Key]:
154
+ return [elt for elt in key if isinstance(elt, tuple)]
155
+
156
+
157
+ def extract_var_from_literal_hash(key: Key) -> Var | None:
158
+ """If key refers to a Var node, return it.
159
+
160
+ Return None otherwise.
161
+ """
162
+ if len(key) == 2 and key[0] == "Var" and isinstance(key[1], Var):
163
+ return key[1]
164
+ return None
165
+
166
+
167
+ class _Hasher(ExpressionVisitor[Key | None]):
168
+ def visit_int_expr(self, e: IntExpr) -> Key:
169
+ return ("Literal", e.value)
170
+
171
+ def visit_str_expr(self, e: StrExpr) -> Key:
172
+ return ("Literal", e.value)
173
+
174
+ def visit_bytes_expr(self, e: BytesExpr) -> Key:
175
+ return ("Literal", e.value)
176
+
177
+ def visit_float_expr(self, e: FloatExpr) -> Key:
178
+ return ("Literal", e.value)
179
+
180
+ def visit_complex_expr(self, e: ComplexExpr) -> Key:
181
+ return ("Literal", e.value)
182
+
183
+ def visit_star_expr(self, e: StarExpr) -> Key:
184
+ return ("Star", literal_hash(e.expr))
185
+
186
+ def visit_name_expr(self, e: NameExpr) -> Key:
187
+ if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None:
188
+ return ("Literal", e.node.final_value)
189
+ # N.B: We use the node itself as the key, and not the name,
190
+ # because using the name causes issues when there is shadowing
191
+ # (for example, in list comprehensions).
192
+ return ("Var", e.node)
193
+
194
+ def visit_member_expr(self, e: MemberExpr) -> Key:
195
+ return ("Member", literal_hash(e.expr), e.name)
196
+
197
+ def visit_op_expr(self, e: OpExpr) -> Key:
198
+ return ("Binary", e.op, literal_hash(e.left), literal_hash(e.right))
199
+
200
+ def visit_comparison_expr(self, e: ComparisonExpr) -> Key:
201
+ rest: tuple[str | Key | None, ...] = tuple(e.operators)
202
+ rest += tuple(literal_hash(o) for o in e.operands)
203
+ return ("Comparison",) + rest
204
+
205
+ def visit_unary_expr(self, e: UnaryExpr) -> Key:
206
+ return ("Unary", e.op, literal_hash(e.expr))
207
+
208
+ def seq_expr(self, e: ListExpr | TupleExpr | SetExpr, name: str) -> Key | None:
209
+ if all(literal(x) == LITERAL_YES for x in e.items):
210
+ rest: tuple[Key | None, ...] = tuple(literal_hash(x) for x in e.items)
211
+ return (name,) + rest
212
+ return None
213
+
214
+ def visit_list_expr(self, e: ListExpr) -> Key | None:
215
+ return self.seq_expr(e, "List")
216
+
217
+ def visit_dict_expr(self, e: DictExpr) -> Key | None:
218
+ if all(a and literal(a) == literal(b) == LITERAL_YES for a, b in e.items):
219
+ rest: tuple[Key | None, ...] = tuple(
220
+ (literal_hash(a) if a else None, literal_hash(b)) for a, b in e.items
221
+ )
222
+ return ("Dict",) + rest
223
+ return None
224
+
225
+ def visit_tuple_expr(self, e: TupleExpr) -> Key | None:
226
+ return self.seq_expr(e, "Tuple")
227
+
228
+ def visit_set_expr(self, e: SetExpr) -> Key | None:
229
+ return self.seq_expr(e, "Set")
230
+
231
+ def visit_index_expr(self, e: IndexExpr) -> Key | None:
232
+ if literal(e.index) == LITERAL_YES:
233
+ return ("Index", literal_hash(e.base), literal_hash(e.index))
234
+ return None
235
+
236
+ def visit_assignment_expr(self, e: AssignmentExpr) -> Key | None:
237
+ return literal_hash(e.target)
238
+
239
+ def visit_call_expr(self, e: CallExpr) -> None:
240
+ return None
241
+
242
+ def visit_slice_expr(self, e: SliceExpr) -> None:
243
+ return None
244
+
245
+ def visit_cast_expr(self, e: CastExpr) -> None:
246
+ return None
247
+
248
+ def visit_type_form_expr(self, e: TypeFormExpr) -> None:
249
+ return None
250
+
251
+ def visit_assert_type_expr(self, e: AssertTypeExpr) -> None:
252
+ return None
253
+
254
+ def visit_conditional_expr(self, e: ConditionalExpr) -> None:
255
+ return None
256
+
257
+ def visit_ellipsis(self, e: EllipsisExpr) -> None:
258
+ return None
259
+
260
+ def visit_yield_from_expr(self, e: YieldFromExpr) -> None:
261
+ return None
262
+
263
+ def visit_yield_expr(self, e: YieldExpr) -> None:
264
+ return None
265
+
266
+ def visit_reveal_expr(self, e: RevealExpr) -> None:
267
+ return None
268
+
269
+ def visit_super_expr(self, e: SuperExpr) -> None:
270
+ return None
271
+
272
+ def visit_type_application(self, e: TypeApplication) -> None:
273
+ return None
274
+
275
+ def visit_lambda_expr(self, e: LambdaExpr) -> None:
276
+ return None
277
+
278
+ def visit_list_comprehension(self, e: ListComprehension) -> None:
279
+ return None
280
+
281
+ def visit_set_comprehension(self, e: SetComprehension) -> None:
282
+ return None
283
+
284
+ def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None:
285
+ return None
286
+
287
+ def visit_generator_expr(self, e: GeneratorExpr) -> None:
288
+ return None
289
+
290
+ def visit_type_var_expr(self, e: TypeVarExpr) -> None:
291
+ return None
292
+
293
+ def visit_paramspec_expr(self, e: ParamSpecExpr) -> None:
294
+ return None
295
+
296
+ def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> None:
297
+ return None
298
+
299
+ def visit_type_alias_expr(self, e: TypeAliasExpr) -> None:
300
+ return None
301
+
302
+ def visit_namedtuple_expr(self, e: NamedTupleExpr) -> None:
303
+ return None
304
+
305
+ def visit_enum_call_expr(self, e: EnumCallExpr) -> None:
306
+ return None
307
+
308
+ def visit_typeddict_expr(self, e: TypedDictExpr) -> None:
309
+ return None
310
+
311
+ def visit_newtype_expr(self, e: NewTypeExpr) -> None:
312
+ return None
313
+
314
+ def visit__promote_expr(self, e: PromoteExpr) -> None:
315
+ return None
316
+
317
+ def visit_await_expr(self, e: AwaitExpr) -> None:
318
+ return None
319
+
320
+ def visit_template_str_expr(self, e: TemplateStrExpr) -> None:
321
+ return None
322
+
323
+ def visit_temp_node(self, e: TempNode) -> None:
324
+ return None
325
+
326
+
327
+ _hasher: Final = _Hasher()
micromamba_root/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd ADDED
Binary file (10.2 kB). View file