Debian Codegraph @

mypy/reachability.py

raw
1 """Utilities related to determining the reachability of code (in semantic analysis)."""
2
3 from __future__ import annotations
4
5 from typing import Final, TypeVar
6
7 from mypy.literals import literal
8 from mypy.nodes import (
9 LITERAL_YES,
10 AssertStmt,
11 Block,
12 CallExpr,
13 ComparisonExpr,
14 Expression,
15 FuncDef,
16 IfStmt,
17 Import,
18 ImportAll,
19 ImportFrom,
20 IndexExpr,
21 IntExpr,
22 MatchStmt,
23 MemberExpr,
24 NameExpr,
25 OpExpr,
26 SliceExpr,
27 StrExpr,
28 TupleExpr,
29 UnaryExpr,
30 )
31 from mypy.options import Options
32 from mypy.patterns import AsPattern, OrPattern, Pattern
33 from mypy.traverser import TraverserVisitor
34
35 # Inferred truth value of an expression.
36 ALWAYS_TRUE: Final = 1
37 MYPY_TRUE: Final = 2 # True in mypy, False at runtime
38 ALWAYS_FALSE: Final = 3
39 MYPY_FALSE: Final = 4 # False in mypy, True at runtime
40 TRUTH_VALUE_UNKNOWN: Final = 5
41
42 inverted_truth_mapping: Final = {
43 ALWAYS_TRUE: ALWAYS_FALSE,
44 ALWAYS_FALSE: ALWAYS_TRUE,
45 TRUTH_VALUE_UNKNOWN: TRUTH_VALUE_UNKNOWN,
46 MYPY_TRUE: MYPY_FALSE,
47 MYPY_FALSE: MYPY_TRUE,
48 }
49
50 reverse_op: Final = {"==": "==", "!=": "!=", "<": ">", ">": "<", "<=": ">=", ">=": "<="}
51
52
53 def infer_reachability_of_if_statement(s: IfStmt, options: Options) -> None:
54 for i in range(len(s.expr)):
55 result = infer_condition_value(s.expr[i], options)
56 if result in (ALWAYS_FALSE, MYPY_FALSE):
57 # The condition is considered always false, so we skip the if/elif body.
58 mark_block_unreachable(s.body[i])
59 elif result in (ALWAYS_TRUE, MYPY_TRUE):
60 # This condition is considered always true, so all of the remaining
61 # elif/else bodies should not be checked.
62 if result == MYPY_TRUE:
63 # This condition is false at runtime; this will affect
64 # import priorities.
65 mark_block_mypy_only(s.body[i])
66 for body in s.body[i + 1 :]:
67 mark_block_unreachable(body)
68
69 # Make sure else body always exists and is marked as
70 # unreachable so the type checker always knows that
71 # all control flow paths will flow through the if
72 # statement body.
73 if not s.else_body:
74 s.else_body = Block([])
75 mark_block_unreachable(s.else_body)
76 break
77
78
79 def infer_reachability_of_match_statement(s: MatchStmt, options: Options) -> None:
80 for i, guard in enumerate(s.guards):
81 pattern_value = infer_pattern_value(s.patterns[i])
82
83 if guard is not None:
84 guard_value = infer_condition_value(guard, options)
85 else:
86 guard_value = ALWAYS_TRUE
87
88 if pattern_value in (ALWAYS_FALSE, MYPY_FALSE) or guard_value in (
89 ALWAYS_FALSE,
90 MYPY_FALSE,
91 ):
92 # The case is considered always false, so we skip the case body.
93 mark_block_unreachable(s.bodies[i])
94 elif pattern_value in (ALWAYS_TRUE, MYPY_TRUE) and guard_value in (ALWAYS_TRUE, MYPY_TRUE):
95 for body in s.bodies[i + 1 :]:
96 mark_block_unreachable(body)
97
98 if guard_value == MYPY_TRUE:
99 # This condition is false at runtime; this will affect
100 # import priorities.
101 mark_block_mypy_only(s.bodies[i])
102
103
104 def assert_will_always_fail(s: AssertStmt, options: Options) -> bool:
105 return infer_condition_value(s.expr, options) in (ALWAYS_FALSE, MYPY_FALSE)
106
107
108 def infer_condition_value(expr: Expression, options: Options) -> int:
109 """Infer whether the given condition is always true/false.
110
111 Return ALWAYS_TRUE if always true, ALWAYS_FALSE if always false,
112 MYPY_TRUE if true under mypy and false at runtime, MYPY_FALSE if
113 false under mypy and true at runtime, else TRUTH_VALUE_UNKNOWN.
114 """
115 if isinstance(expr, UnaryExpr) and expr.op == "not":
116 positive = infer_condition_value(expr.expr, options)
117 return inverted_truth_mapping[positive]
118
119 pyversion = options.python_version
120 name = ""
121
122 result = TRUTH_VALUE_UNKNOWN
123 if isinstance(expr, NameExpr):
124 name = expr.name
125 elif isinstance(expr, MemberExpr):
126 name = expr.name
127 elif isinstance(expr, OpExpr):
128 if expr.op not in ("or", "and"):
129 return TRUTH_VALUE_UNKNOWN
130
131 left = infer_condition_value(expr.left, options)
132 right = infer_condition_value(expr.right, options)
133 results = {left, right}
134 if expr.op == "or":
135 if ALWAYS_TRUE in results:
136 return ALWAYS_TRUE
137 elif MYPY_TRUE in results:
138 return MYPY_TRUE
139 elif left == right == MYPY_FALSE:
140 return MYPY_FALSE
141 elif results <= {ALWAYS_FALSE, MYPY_FALSE}:
142 return ALWAYS_FALSE
143 elif expr.op == "and":
144 if ALWAYS_FALSE in results:
145 return ALWAYS_FALSE
146 elif MYPY_FALSE in results:
147 return MYPY_FALSE
148 elif left == right == ALWAYS_TRUE:
149 return ALWAYS_TRUE
150 elif results <= {ALWAYS_TRUE, MYPY_TRUE}:
151 return MYPY_TRUE
152 return TRUTH_VALUE_UNKNOWN
153 else:
154 result = consider_sys_version_info(expr, pyversion)
155 if result == TRUTH_VALUE_UNKNOWN:
156 result = consider_sys_platform(expr, options.platform)
157 if result == TRUTH_VALUE_UNKNOWN:
158 if name == "PY2":
159 result = ALWAYS_FALSE
160 elif name == "PY3":
161 result = ALWAYS_TRUE
162 elif name == "MYPY" or name == "TYPE_CHECKING":
163 result = MYPY_TRUE
164 elif name in options.always_true:
165 result = ALWAYS_TRUE
166 elif name in options.always_false:
167 result = ALWAYS_FALSE
168 return result
169
170
171 def infer_pattern_value(pattern: Pattern) -> int:
172 if isinstance(pattern, AsPattern) and pattern.pattern is None:
173 return ALWAYS_TRUE
174 elif isinstance(pattern, OrPattern) and any(
175 infer_pattern_value(p) == ALWAYS_TRUE for p in pattern.patterns
176 ):
177 return ALWAYS_TRUE
178 else:
179 return TRUTH_VALUE_UNKNOWN
180
181
182 def consider_sys_version_info(expr: Expression, pyversion: tuple[int, ...]) -> int:
183 """Consider whether expr is a comparison involving sys.version_info.
184
185 Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN.
186 """
187 # Cases supported:
188 # - sys.version_info[<int>] <compare_op> <int>
189 # - sys.version_info[:<int>] <compare_op> <tuple_of_n_ints>
190 # - sys.version_info <compare_op> <tuple_of_1_or_2_ints>
191 # (in this case <compare_op> must be >, >=, <, <=, but cannot be ==, !=)
192 if not isinstance(expr, ComparisonExpr):
193 return TRUTH_VALUE_UNKNOWN
194 # Let's not yet support chained comparisons.
195 if len(expr.operators) > 1:
196 return TRUTH_VALUE_UNKNOWN
197 op = expr.operators[0]
198 if op not in ("==", "!=", "<=", ">=", "<", ">"):
199 return TRUTH_VALUE_UNKNOWN
200
201 index = contains_sys_version_info(expr.operands[0])
202 thing = contains_int_or_tuple_of_ints(expr.operands[1])
203 if index is None or thing is None:
204 index = contains_sys_version_info(expr.operands[1])
205 thing = contains_int_or_tuple_of_ints(expr.operands[0])
206 op = reverse_op[op]
207 if isinstance(index, int) and isinstance(thing, int):
208 # sys.version_info[i] <compare_op> k
209 if 0 <= index <= 1:
210 return fixed_comparison(pyversion[index], op, thing)
211 else:
212 return TRUTH_VALUE_UNKNOWN
213 elif isinstance(index, tuple) and isinstance(thing, tuple):
214 lo, hi = index
215 if lo is None:
216 lo = 0
217 if hi is None:
218 hi = 2
219 if 0 <= lo < hi <= 2:
220 val = pyversion[lo:hi]
221 if len(val) == len(thing) or len(val) > len(thing) and op not in ("==", "!="):
222 return fixed_comparison(val, op, thing)
223 return TRUTH_VALUE_UNKNOWN
224
225
226 def consider_sys_platform(expr: Expression, platform: str) -> int:
227 """Consider whether expr is a comparison involving sys.platform.
228
229 Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN.
230 """
231 # Cases supported:
232 # - sys.platform == 'linux'
233 # - sys.platform != 'win32'
234 # - sys.platform.startswith('win')
235 if isinstance(expr, ComparisonExpr):
236 # Let's not yet support chained comparisons.
237 if len(expr.operators) > 1:
238 return TRUTH_VALUE_UNKNOWN
239 op = expr.operators[0]
240 if op not in ("==", "!="):
241 return TRUTH_VALUE_UNKNOWN
242 if not is_sys_attr(expr.operands[0], "platform"):
243 return TRUTH_VALUE_UNKNOWN
244 right = expr.operands[1]
245 if not isinstance(right, StrExpr):
246 return TRUTH_VALUE_UNKNOWN
247 return fixed_comparison(platform, op, right.value)
248 elif isinstance(expr, CallExpr):
249 if not isinstance(expr.callee, MemberExpr):
250 return TRUTH_VALUE_UNKNOWN
251 if len(expr.args) != 1 or not isinstance(expr.args[0], StrExpr):
252 return TRUTH_VALUE_UNKNOWN
253 if not is_sys_attr(expr.callee.expr, "platform"):
254 return TRUTH_VALUE_UNKNOWN
255 if expr.callee.name != "startswith":
256 return TRUTH_VALUE_UNKNOWN
257 if platform.startswith(expr.args[0].value):
258 return ALWAYS_TRUE
259 else:
260 return ALWAYS_FALSE
261 else:
262 return TRUTH_VALUE_UNKNOWN
263
264
265 Targ = TypeVar("Targ", int, str, tuple[int, ...])
266
267
268 def fixed_comparison(left: Targ, op: str, right: Targ) -> int:
269 rmap = {False: ALWAYS_FALSE, True: ALWAYS_TRUE}
270 if op == "==":
271 return rmap[left == right]
272 if op == "!=":
273 return rmap[left != right]
274 if op == "<=":
275 return rmap[left <= right]
276 if op == ">=":
277 return rmap[left >= right]
278 if op == "<":
279 return rmap[left < right]
280 if op == ">":
281 return rmap[left > right]
282 return TRUTH_VALUE_UNKNOWN
283
284
285 def contains_int_or_tuple_of_ints(expr: Expression) -> None | int | tuple[int, ...]:
286 if isinstance(expr, IntExpr):
287 return expr.value
288 if isinstance(expr, TupleExpr):
289 if literal(expr) == LITERAL_YES:
290 thing = []
291 for x in expr.items:
292 if not isinstance(x, IntExpr):
293 return None
294 thing.append(x.value)
295 return tuple(thing)
296 return None
297
298
299 def contains_sys_version_info(expr: Expression) -> None | int | tuple[int | None, int | None]:
300 if is_sys_attr(expr, "version_info"):
301 return (None, None) # Same as sys.version_info[:]
302 if isinstance(expr, IndexExpr) and is_sys_attr(expr.base, "version_info"):
303 index = expr.index
304 if isinstance(index, IntExpr):
305 return index.value
306 if isinstance(index, SliceExpr):
307 if index.stride is not None:
308 if not isinstance(index.stride, IntExpr) or index.stride.value != 1:
309 return None
310 begin = end = None
311 if index.begin_index is not None:
312 if not isinstance(index.begin_index, IntExpr):
313 return None
314 begin = index.begin_index.value
315 if index.end_index is not None:
316 if not isinstance(index.end_index, IntExpr):
317 return None
318 end = index.end_index.value
319 return (begin, end)
320 return None
321
322
323 def is_sys_attr(expr: Expression, name: str) -> bool:
324 # TODO: This currently doesn't work with code like this:
325 # - import sys as _sys
326 # - from sys import version_info
327 if isinstance(expr, MemberExpr) and expr.name == name:
328 if isinstance(expr.expr, NameExpr) and expr.expr.name == "sys":
329 # TODO: Guard against a local named sys, etc.
330 # (Though later passes will still do most checking.)
331 return True
332 return False
333
334
335 def mark_block_unreachable(block: Block) -> None:
336 block.is_unreachable = True
337 block.accept(MarkImportsUnreachableVisitor())
338
339
340 class MarkImportsUnreachableVisitor(TraverserVisitor):
341 """Visitor that flags all imports nested within a node as unreachable."""
342
343 def visit_import(self, node: Import) -> None:
344 node.is_unreachable = True
345
346 def visit_import_from(self, node: ImportFrom) -> None:
347 node.is_unreachable = True
348
349 def visit_import_all(self, node: ImportAll) -> None:
350 node.is_unreachable = True
351
352
353 def mark_block_mypy_only(block: Block) -> None:
354 block.accept(MarkImportsMypyOnlyVisitor())
355
356
357 class MarkImportsMypyOnlyVisitor(TraverserVisitor):
358 """Visitor that sets is_mypy_only (which affects priority)."""
359
360 def visit_import(self, node: Import) -> None:
361 node.is_mypy_only = True
362
363 def visit_import_from(self, node: ImportFrom) -> None:
364 node.is_mypy_only = True
365
366 def visit_import_all(self, node: ImportAll) -> None:
367 node.is_mypy_only = True
368
369 def visit_func_def(self, node: FuncDef) -> None:
370 node.is_mypy_only = True