| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from collections import defaultdict |
| 4 |
from collections.abc import Iterator |
| 5 |
from contextlib import contextmanager |
| 6 |
from typing import Final, Literal, TypeAlias as _TypeAlias |
| 7 |
|
| 8 |
from mypy.erasetype import remove_instance_last_known_values |
| 9 |
from mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash, subkeys |
| 10 |
from mypy.nodes import ( |
| 11 |
LITERAL_NO, |
| 12 |
Expression, |
| 13 |
IndexExpr, |
| 14 |
MemberExpr, |
| 15 |
NameExpr, |
| 16 |
RefExpr, |
| 17 |
TypeInfo, |
| 18 |
Var, |
| 19 |
) |
| 20 |
from mypy.options import Options |
| 21 |
from mypy.subtypes import is_same_type, is_subtype |
| 22 |
from mypy.typeops import make_simplified_union |
| 23 |
from mypy.types import ( |
| 24 |
AnyType, |
| 25 |
Instance, |
| 26 |
NoneType, |
| 27 |
PartialType, |
| 28 |
ProperType, |
| 29 |
TupleType, |
| 30 |
Type, |
| 31 |
TypeOfAny, |
| 32 |
TypeType, |
| 33 |
TypeVarType, |
| 34 |
UnionType, |
| 35 |
UnpackType, |
| 36 |
find_unpack_in_list, |
| 37 |
flatten_nested_unions, |
| 38 |
get_proper_type, |
| 39 |
) |
| 40 |
from mypy.typevars import fill_typevars_with_any |
| 41 |
|
| 42 |
BindableExpression: _TypeAlias = IndexExpr | MemberExpr | NameExpr |
| 43 |
|
| 44 |
|
| 45 |
class CurrentType: |
| 46 |
def __init__(self, type: Type, from_assignment: bool) -> None: |
| 47 |
self.type: Final = type |
| 48 |
self.from_assignment: Final = from_assignment |
| 49 |
|
| 50 |
|
| 51 |
class Frame: |
| 52 |
"""A Frame represents a specific point in the execution of a program. |
| 53 |
|
| 54 |
It carries information about the current types of expressions at |
| 55 |
that point, arising either from assignments to those expressions |
| 56 |
or the result of isinstance checks and other type narrowing |
| 57 |
operations. It also records whether it is possible to reach that |
| 58 |
point at all. |
| 59 |
|
| 60 |
We add a new frame wherenever there is a new scope or control flow |
| 61 |
branching. |
| 62 |
|
| 63 |
This information is not copied into a new Frame when it is pushed |
| 64 |
onto the stack, so a given Frame only has information about types |
| 65 |
that were assigned in that frame. |
| 66 |
|
| 67 |
Expressions are stored in dicts using 'literal hashes' as keys (type |
| 68 |
"Key"). These are hashable values derived from expression AST nodes |
| 69 |
(only those that can be narrowed). literal_hash(expr) is used to |
| 70 |
calculate the hashes. Note that this isn't directly related to literal |
| 71 |
types -- the concept predates literal types. |
| 72 |
""" |
| 73 |
|
| 74 |
def __init__(self, id: int, conditional_frame: bool = False) -> None: |
| 75 |
self.id = id |
| 76 |
self.types: dict[Key, CurrentType] = {} |
| 77 |
self.unreachable = False |
| 78 |
self.conditional_frame = conditional_frame |
| 79 |
self.suppress_unreachable_warnings = False |
| 80 |
|
| 81 |
def __repr__(self) -> str: |
| 82 |
return f"Frame({self.id}, {self.types}, {self.unreachable}, {self.conditional_frame})" |
| 83 |
|
| 84 |
|
| 85 |
Assigns = defaultdict[Expression, list[tuple[Type, Type | None]]] |
| 86 |
|
| 87 |
|
| 88 |
class FrameContext: |
| 89 |
"""Context manager pushing a Frame to ConditionalTypeBinder. |
| 90 |
|
| 91 |
See frame_context() below for documentation on parameters. We use this class |
| 92 |
instead of @contextmanager as a mypyc-specific performance optimization. |
| 93 |
""" |
| 94 |
|
| 95 |
def __init__( |
| 96 |
self, |
| 97 |
binder: ConditionalTypeBinder, |
| 98 |
can_skip: bool, |
| 99 |
fall_through: int, |
| 100 |
break_frame: int, |
| 101 |
continue_frame: int, |
| 102 |
conditional_frame: bool, |
| 103 |
try_frame: bool, |
| 104 |
discard: bool, |
| 105 |
) -> None: |
| 106 |
self.binder = binder |
| 107 |
self.can_skip = can_skip |
| 108 |
self.fall_through = fall_through |
| 109 |
self.break_frame = break_frame |
| 110 |
self.continue_frame = continue_frame |
| 111 |
self.conditional_frame = conditional_frame |
| 112 |
self.try_frame = try_frame |
| 113 |
self.discard = discard |
| 114 |
|
| 115 |
def __enter__(self) -> Frame: |
| 116 |
assert len(self.binder.frames) > 1 |
| 117 |
|
| 118 |
if self.break_frame: |
| 119 |
self.binder.break_frames.append(len(self.binder.frames) - self.break_frame) |
| 120 |
if self.continue_frame: |
| 121 |
self.binder.continue_frames.append(len(self.binder.frames) - self.continue_frame) |
| 122 |
if self.try_frame: |
| 123 |
self.binder.try_frames.add(len(self.binder.frames) - 1) |
| 124 |
|
| 125 |
new_frame = self.binder.push_frame(self.conditional_frame) |
| 126 |
if self.try_frame: |
| 127 |
# An exception may occur immediately |
| 128 |
self.binder.allow_jump(-1) |
| 129 |
return new_frame |
| 130 |
|
| 131 |
def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]: |
| 132 |
self.binder.pop_frame(self.can_skip, self.fall_through, discard=self.discard) |
| 133 |
|
| 134 |
if self.break_frame: |
| 135 |
self.binder.break_frames.pop() |
| 136 |
if self.continue_frame: |
| 137 |
self.binder.continue_frames.pop() |
| 138 |
if self.try_frame: |
| 139 |
self.binder.try_frames.remove(len(self.binder.frames) - 1) |
| 140 |
return False |
| 141 |
|
| 142 |
|
| 143 |
class ConditionalTypeBinder: |
| 144 |
"""Keep track of conditional types of variables. |
| 145 |
|
| 146 |
NB: Variables are tracked by literal hashes of expressions, so it is |
| 147 |
possible to confuse the binder when there is aliasing. Example: |
| 148 |
|
| 149 |
class A: |
| 150 |
a: int | str |
| 151 |
|
| 152 |
x = A() |
| 153 |
lst = [x] |
| 154 |
reveal_type(x.a) # int | str |
| 155 |
x.a = 1 |
| 156 |
reveal_type(x.a) # int |
| 157 |
reveal_type(lst[0].a) # int | str |
| 158 |
lst[0].a = 'a' |
| 159 |
reveal_type(x.a) # int |
| 160 |
reveal_type(lst[0].a) # str |
| 161 |
""" |
| 162 |
|
| 163 |
# Stored assignments for situations with tuple/list lvalue and rvalue of union type. |
| 164 |
# This maps an expression to a list of bound types for every item in the union type. |
| 165 |
type_assignments: Assigns | None = None |
| 166 |
|
| 167 |
def __init__(self, options: Options) -> None: |
| 168 |
# Each frame gets an increasing, distinct id. |
| 169 |
self.next_id = 1 |
| 170 |
|
| 171 |
# The stack of frames currently used. These map |
| 172 |
# literal_hash(expr) -- literals like 'foo.bar' -- |
| 173 |
# to types. The last element of this list is the |
| 174 |
# top-most, current frame. Each earlier element |
| 175 |
# records the state as of when that frame was last |
| 176 |
# on top of the stack. |
| 177 |
self.frames = [Frame(self._get_id())] |
| 178 |
|
| 179 |
# For frames higher in the stack, we record the set of |
| 180 |
# Frames that can escape there, either by falling off |
| 181 |
# the end of the frame or by a loop control construct |
| 182 |
# or raised exception. The last element of self.frames |
| 183 |
# has no corresponding element in this list. |
| 184 |
self.options_on_return: list[list[Frame]] = [] |
| 185 |
|
| 186 |
# Maps literal_hash(expr) to get_declaration(expr) |
| 187 |
# for every expr stored in the binder |
| 188 |
self.declarations: dict[Key, Type | None] = {} |
| 189 |
# Set of other keys to invalidate if a key is changed, e.g. x -> {x.a, x[0]} |
| 190 |
# Whenever a new key (e.g. x.a.b) is added, we update this |
| 191 |
self.dependencies: dict[Key, set[Key]] = {} |
| 192 |
|
| 193 |
# Whether the last pop changed the newly top frame on exit |
| 194 |
self.last_pop_changed = False |
| 195 |
|
| 196 |
# These are used to track control flow in try statements and loops. |
| 197 |
self.try_frames: set[int] = set() |
| 198 |
self.break_frames: list[int] = [] |
| 199 |
self.continue_frames: list[int] = [] |
| 200 |
|
| 201 |
# If True, initial assignment to a simple variable (e.g. "x", but not "x.y") |
| 202 |
# is added to the binder. This allows more precise narrowing and more |
| 203 |
# flexible inference of variable types (--allow-redefinition). |
| 204 |
self.bind_all = options.allow_redefinition |
| 205 |
|
| 206 |
# This tracks any externally visible changes in binder to invalidate |
| 207 |
# expression caches when needed. |
| 208 |
self.version = 0 |
| 209 |
|
| 210 |
def _get_id(self) -> int: |
| 211 |
self.next_id += 1 |
| 212 |
return self.next_id |
| 213 |
|
| 214 |
def _add_dependencies(self, key: Key, value: Key | None = None) -> None: |
| 215 |
if value is None: |
| 216 |
value = key |
| 217 |
else: |
| 218 |
self.dependencies.setdefault(key, set()).add(value) |
| 219 |
for elt in subkeys(key): |
| 220 |
self._add_dependencies(elt, value) |
| 221 |
|
| 222 |
def push_frame(self, conditional_frame: bool = False) -> Frame: |
| 223 |
"""Push a new frame into the binder.""" |
| 224 |
f = Frame(self._get_id(), conditional_frame) |
| 225 |
self.frames.append(f) |
| 226 |
self.options_on_return.append([]) |
| 227 |
return f |
| 228 |
|
| 229 |
def _put(self, key: Key, type: Type, from_assignment: bool, index: int = -1) -> None: |
| 230 |
self.version += 1 |
| 231 |
self.frames[index].types[key] = CurrentType(type, from_assignment) |
| 232 |
|
| 233 |
def _get(self, key: Key, index: int = -1) -> CurrentType | None: |
| 234 |
if index < 0: |
| 235 |
index += len(self.frames) |
| 236 |
for i in range(index, -1, -1): |
| 237 |
if key in self.frames[i].types: |
| 238 |
return self.frames[i].types[key] |
| 239 |
return None |
| 240 |
|
| 241 |
@classmethod |
| 242 |
def can_put_directly(cls, expr: Expression) -> bool: |
| 243 |
"""Will `.put()` on this expression be successful? |
| 244 |
|
| 245 |
This is inlined in `.put()` because the logic is rather hot and must be kept |
| 246 |
in sync. |
| 247 |
""" |
| 248 |
return isinstance(expr, (IndexExpr, MemberExpr, NameExpr)) and literal(expr) > LITERAL_NO |
| 249 |
|
| 250 |
def put(self, expr: Expression, typ: Type, *, from_assignment: bool = True) -> None: |
| 251 |
"""Directly set the narrowed type of expression (if it supports it). |
| 252 |
|
| 253 |
This is used for isinstance() etc. Assignments should go through assign_type(). |
| 254 |
""" |
| 255 |
if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)): |
| 256 |
return |
| 257 |
if not literal(expr): |
| 258 |
return |
| 259 |
key = literal_hash(expr) |
| 260 |
assert key is not None, "Internal error: binder tried to put non-literal" |
| 261 |
if key not in self.declarations: |
| 262 |
self.declarations[key] = get_declaration(expr) |
| 263 |
self._add_dependencies(key) |
| 264 |
self._put(key, typ, from_assignment) |
| 265 |
|
| 266 |
def unreachable(self) -> None: |
| 267 |
self.version += 1 |
| 268 |
self.frames[-1].unreachable = True |
| 269 |
|
| 270 |
def suppress_unreachable_warnings(self) -> None: |
| 271 |
self.frames[-1].suppress_unreachable_warnings = True |
| 272 |
|
| 273 |
def get(self, expr: Expression) -> Type | None: |
| 274 |
key = literal_hash(expr) |
| 275 |
assert key is not None, "Internal error: binder tried to get non-literal" |
| 276 |
found = self._get(key) |
| 277 |
if found is None: |
| 278 |
return None |
| 279 |
return found.type |
| 280 |
|
| 281 |
def is_unreachable(self) -> bool: |
| 282 |
# TODO: Copy the value of unreachable into new frames to avoid |
| 283 |
# this traversal on every statement? |
| 284 |
return any(f.unreachable for f in self.frames) |
| 285 |
|
| 286 |
def is_unreachable_warning_suppressed(self) -> bool: |
| 287 |
return any(f.suppress_unreachable_warnings for f in self.frames) |
| 288 |
|
| 289 |
def cleanse(self, expr: Expression) -> None: |
| 290 |
"""Remove all references to a Node from the binder.""" |
| 291 |
key = literal_hash(expr) |
| 292 |
assert key is not None, "Internal error: binder tried cleanse non-literal" |
| 293 |
self._cleanse_key(key) |
| 294 |
|
| 295 |
def _cleanse_key(self, key: Key) -> None: |
| 296 |
"""Remove all references to a key from the binder.""" |
| 297 |
for frame in self.frames: |
| 298 |
if key in frame.types: |
| 299 |
del frame.types[key] |
| 300 |
|
| 301 |
def update_from_options(self, frames: list[Frame]) -> bool: |
| 302 |
"""Update the frame to reflect that each key will be updated |
| 303 |
as in one of the frames. Return whether any item changes. |
| 304 |
|
| 305 |
If a key is declared as AnyType, only update it if all the |
| 306 |
options are the same. |
| 307 |
""" |
| 308 |
all_reachable = all(not f.unreachable for f in frames) |
| 309 |
if not all_reachable: |
| 310 |
frames = [f for f in frames if not f.unreachable] |
| 311 |
changed = False |
| 312 |
keys = [key for f in frames for key in f.types] |
| 313 |
if len(keys) > 1: |
| 314 |
keys = list(set(keys)) |
| 315 |
for key in keys: |
| 316 |
current_value = self._get(key) |
| 317 |
resulting_values = [f.types.get(key, current_value) for f in frames] |
| 318 |
# Keys can be narrowed using two different semantics. The new semantics |
| 319 |
# is enabled for inferred variables when bind_all is true, and it allows |
| 320 |
# variable types to be widened using subsequent assignments. This is |
| 321 |
# not allowed for instance attributes and annotated variables. |
| 322 |
var = extract_var_from_literal_hash(key) |
| 323 |
old_semantics = ( |
| 324 |
not self.bind_all or var is None or not var.is_inferred and not var.is_argument |
| 325 |
) |
| 326 |
if old_semantics and any(x is None for x in resulting_values): |
| 327 |
# We didn't know anything about key before |
| 328 |
# (current_value must be None), and we still don't |
| 329 |
# know anything about key in at least one possible frame. |
| 330 |
continue |
| 331 |
|
| 332 |
resulting_values = [x for x in resulting_values if x is not None] |
| 333 |
|
| 334 |
if all_reachable and all(not x.from_assignment for x in resulting_values): |
| 335 |
# Do not synthesize a new type if we encountered a conditional block |
| 336 |
# (if, while or match-case) without assignments. |
| 337 |
# See check-isinstance.test::testNoneCheckDoesNotMakeTypeVarOptional |
| 338 |
# This is a safe assumption: the fact that we checked something with `is` |
| 339 |
# or `isinstance` does not change the type of the value. |
| 340 |
continue |
| 341 |
|
| 342 |
# Remove exact duplicates to save pointless work later, this is |
| 343 |
# a micro-optimization for --allow-redefinition. |
| 344 |
seen_types = set() |
| 345 |
resulting_types = [] |
| 346 |
for rv in resulting_values: |
| 347 |
assert rv is not None |
| 348 |
if rv.type in seen_types: |
| 349 |
continue |
| 350 |
resulting_types.append(rv.type) |
| 351 |
seen_types.add(rv.type) |
| 352 |
|
| 353 |
type = resulting_types[0] |
| 354 |
declaration_type = get_proper_type(self.declarations.get(key)) |
| 355 |
if isinstance(declaration_type, AnyType): |
| 356 |
# At this point resulting values can't contain None, see continue above |
| 357 |
if not all(is_same_type(type, t) for t in resulting_types[1:]): |
| 358 |
type = AnyType(TypeOfAny.from_another_any, source_any=declaration_type) |
| 359 |
else: |
| 360 |
possible_types = [] |
| 361 |
for t in resulting_types: |
| 362 |
assert t is not None |
| 363 |
possible_types.append(t) |
| 364 |
if len(possible_types) == 1: |
| 365 |
# This is to avoid calling get_proper_type() unless needed, as this may |
| 366 |
# interfere with our (hacky) TypeGuard support. |
| 367 |
type = possible_types[0] |
| 368 |
else: |
| 369 |
type = make_simplified_union(possible_types) |
| 370 |
# Legacy guard for corner case when the original type is TypeVarType. |
| 371 |
if isinstance(declaration_type, TypeVarType) and not is_subtype( |
| 372 |
type, declaration_type |
| 373 |
): |
| 374 |
type = declaration_type |
| 375 |
# Try simplifying resulting type for unions involving variadic tuples. |
| 376 |
# Technically, everything is still valid without this step, but if we do |
| 377 |
# not do this, this may create long unions after exiting an if check like: |
| 378 |
# x: tuple[int, ...] |
| 379 |
# if len(x) < 10: |
| 380 |
# ... |
| 381 |
# We want the type of x to be tuple[int, ...] after this block (if it is |
| 382 |
# still equivalent to such type). |
| 383 |
if isinstance(type, UnionType): |
| 384 |
type = collapse_variadic_union(type) |
| 385 |
if ( |
| 386 |
old_semantics |
| 387 |
and isinstance(type, ProperType) |
| 388 |
and isinstance(type, UnionType) |
| 389 |
): |
| 390 |
# Simplify away any extra Any's that were added to the declared |
| 391 |
# type when popping a frame. |
| 392 |
simplified = UnionType.make_union( |
| 393 |
[t for t in type.items if not isinstance(get_proper_type(t), AnyType)] |
| 394 |
) |
| 395 |
if simplified == self.declarations[key]: |
| 396 |
type = simplified |
| 397 |
if ( |
| 398 |
current_value is None |
| 399 |
or not is_same_type(type, current_value.type) |
| 400 |
# Manually carry over any narrowing from hasattr() from inner frames. This is |
| 401 |
# a bit ad-hoc, but our handling of hasattr() is on best effort basis anyway. |
| 402 |
or isinstance(p_type := get_proper_type(type), Instance) |
| 403 |
and p_type.extra_attrs |
| 404 |
): |
| 405 |
self._put(key, type, from_assignment=True) |
| 406 |
if current_value is not None or extract_var_from_literal_hash(key) is None: |
| 407 |
# We definitely learned something new |
| 408 |
changed = True |
| 409 |
elif not changed: |
| 410 |
# If there is no current value compare with the declaration. This prevents |
| 411 |
# reporting false changes in cases like this: |
| 412 |
# x: int |
| 413 |
# if foo(): |
| 414 |
# x = 1 |
| 415 |
# else: |
| 416 |
# x = 2 |
| 417 |
# We check partial types and widening in accept_loop() separately, so |
| 418 |
# this should be safe. |
| 419 |
changed = declaration_type is not None and not is_same_type( |
| 420 |
type, declaration_type |
| 421 |
) |
| 422 |
|
| 423 |
self.frames[-1].unreachable = not frames |
| 424 |
|
| 425 |
return changed |
| 426 |
|
| 427 |
def pop_frame(self, can_skip: bool, fall_through: int, *, discard: bool = False) -> Frame: |
| 428 |
"""Pop a frame and return it. |
| 429 |
|
| 430 |
See frame_context() for documentation of fall_through and discard. |
| 431 |
""" |
| 432 |
|
| 433 |
if fall_through > 0: |
| 434 |
self.allow_jump(-fall_through) |
| 435 |
|
| 436 |
result = self.frames.pop() |
| 437 |
options = self.options_on_return.pop() |
| 438 |
|
| 439 |
if discard: |
| 440 |
self.last_pop_changed = False |
| 441 |
return result |
| 442 |
|
| 443 |
if can_skip: |
| 444 |
options.insert(0, self.frames[-1]) |
| 445 |
|
| 446 |
self.last_pop_changed = self.update_from_options(options) |
| 447 |
|
| 448 |
return result |
| 449 |
|
| 450 |
@contextmanager |
| 451 |
def accumulate_type_assignments(self) -> Iterator[Assigns]: |
| 452 |
"""Push a new map to collect assigned types in multiassign from union. |
| 453 |
|
| 454 |
If this map is not None, actual binding is deferred until all items in |
| 455 |
the union are processed (a union of collected items is later bound |
| 456 |
manually by the caller). |
| 457 |
""" |
| 458 |
old_assignments = None |
| 459 |
if self.type_assignments is not None: |
| 460 |
old_assignments = self.type_assignments |
| 461 |
self.type_assignments = defaultdict(list) |
| 462 |
yield self.type_assignments |
| 463 |
self.type_assignments = old_assignments |
| 464 |
|
| 465 |
def assign_type(self, expr: Expression, type: Type, declared_type: Type | None) -> None: |
| 466 |
"""Narrow type of expression through an assignment. |
| 467 |
|
| 468 |
Do nothing if the expression doesn't support narrowing. |
| 469 |
|
| 470 |
When not narrowing though an assignment (isinstance() etc.), use put() |
| 471 |
directly. This omits some special-casing logic for assignments. |
| 472 |
""" |
| 473 |
# We should erase last known value in binder, because if we are using it, |
| 474 |
# it means that the target is not final, and therefore can't hold a literal. |
| 475 |
type = remove_instance_last_known_values(type) |
| 476 |
|
| 477 |
if self.type_assignments is not None: |
| 478 |
# We are in a multiassign from union, defer the actual binding, |
| 479 |
# just collect the types. |
| 480 |
self.type_assignments[expr].append((type, declared_type)) |
| 481 |
return |
| 482 |
if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)): |
| 483 |
return |
| 484 |
if not literal(expr): |
| 485 |
return |
| 486 |
self.invalidate_dependencies(expr) |
| 487 |
|
| 488 |
if declared_type is None: |
| 489 |
# Not sure why this happens. It seems to mainly happen in |
| 490 |
# member initialization. |
| 491 |
return |
| 492 |
if not is_subtype(type, declared_type): |
| 493 |
# Pretty sure this is only happens when there's a type error. |
| 494 |
|
| 495 |
# Ideally this function wouldn't be called if the |
| 496 |
# expression has a type error, though -- do other kinds of |
| 497 |
# errors cause this function to get called at invalid |
| 498 |
# times? |
| 499 |
return |
| 500 |
|
| 501 |
p_declared = get_proper_type(declared_type) |
| 502 |
p_type = get_proper_type(type) |
| 503 |
if isinstance(p_type, AnyType): |
| 504 |
# Any type requires some special casing, for both historical reasons, |
| 505 |
# and to optimise user experience without sacrificing correctness too much. |
| 506 |
if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred: |
| 507 |
# First case: a local/global variable without explicit annotation, |
| 508 |
# in this case we just assign Any (essentially following the SSA logic). |
| 509 |
self.put(expr, type) |
| 510 |
elif isinstance(p_declared, UnionType): |
| 511 |
all_items = flatten_nested_unions(p_declared.items) |
| 512 |
if any(isinstance(get_proper_type(item), NoneType) for item in all_items): |
| 513 |
# Second case: explicit optional type, in this case we optimize for |
| 514 |
# a common pattern when an untyped value used as a fallback replacing None. |
| 515 |
new_items = [ |
| 516 |
type if isinstance(get_proper_type(item), NoneType) else item |
| 517 |
for item in all_items |
| 518 |
] |
| 519 |
self.put(expr, UnionType(new_items)) |
| 520 |
elif any(isinstance(get_proper_type(item), AnyType) for item in all_items): |
| 521 |
# Third case: a union already containing Any (most likely from |
| 522 |
# an un-imported name), in this case we allow assigning Any as well. |
| 523 |
self.put(expr, type) |
| 524 |
else: |
| 525 |
# In all other cases we don't narrow to Any to minimize false negatives. |
| 526 |
self.put(expr, declared_type) |
| 527 |
else: |
| 528 |
self.put(expr, declared_type) |
| 529 |
elif isinstance(p_declared, AnyType): |
| 530 |
# Mirroring the first case above, we don't narrow to a precise type if the variable |
| 531 |
# has an explicit `Any` type annotation. |
| 532 |
if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred: |
| 533 |
self.put(expr, type) |
| 534 |
else: |
| 535 |
self.put(expr, declared_type) |
| 536 |
else: |
| 537 |
self.put(expr, type) |
| 538 |
|
| 539 |
for i in self.try_frames: |
| 540 |
# XXX This should probably not copy the entire frame, but |
| 541 |
# just copy this variable into a single stored frame. |
| 542 |
self.allow_jump(i) |
| 543 |
|
| 544 |
def invalidate_dependencies(self, expr: BindableExpression) -> None: |
| 545 |
"""Invalidate knowledge of types that include expr, but not expr itself. |
| 546 |
|
| 547 |
For example, when expr is foo.bar, invalidate foo.bar.baz. |
| 548 |
|
| 549 |
It is overly conservative: it invalidates globally, including |
| 550 |
in code paths unreachable from here. |
| 551 |
""" |
| 552 |
key = literal_hash(expr) |
| 553 |
assert key is not None |
| 554 |
for dep in self.dependencies.get(key, set()): |
| 555 |
self._cleanse_key(dep) |
| 556 |
|
| 557 |
def allow_jump(self, index: int) -> None: |
| 558 |
# self.frames and self.options_on_return have different lengths |
| 559 |
# so make sure the index is positive |
| 560 |
if index < 0: |
| 561 |
index += len(self.options_on_return) |
| 562 |
frame = Frame(self._get_id()) |
| 563 |
for f in self.frames[index + 1 :]: |
| 564 |
frame.types.update(f.types) |
| 565 |
if f.unreachable: |
| 566 |
frame.unreachable = True |
| 567 |
self.options_on_return[index].append(frame) |
| 568 |
|
| 569 |
def handle_break(self) -> None: |
| 570 |
self.allow_jump(self.break_frames[-1]) |
| 571 |
self.unreachable() |
| 572 |
|
| 573 |
def handle_continue(self) -> None: |
| 574 |
self.allow_jump(self.continue_frames[-1]) |
| 575 |
self.unreachable() |
| 576 |
|
| 577 |
def frame_context( |
| 578 |
self, |
| 579 |
*, |
| 580 |
can_skip: bool, |
| 581 |
fall_through: int = 1, |
| 582 |
break_frame: int = 0, |
| 583 |
continue_frame: int = 0, |
| 584 |
conditional_frame: bool = False, |
| 585 |
try_frame: bool = False, |
| 586 |
discard: bool = False, |
| 587 |
) -> FrameContext: |
| 588 |
"""Return a context manager that pushes/pops frames on enter/exit. |
| 589 |
|
| 590 |
If can_skip is True, control flow is allowed to bypass the |
| 591 |
newly-created frame. |
| 592 |
|
| 593 |
If fall_through > 0, then it will allow control flow that |
| 594 |
falls off the end of the frame to escape to its ancestor |
| 595 |
`fall_through` levels higher. Otherwise, control flow ends |
| 596 |
at the end of the frame. |
| 597 |
|
| 598 |
If break_frame > 0, then 'break' statements within this frame |
| 599 |
will jump out to the frame break_frame levels higher than the |
| 600 |
frame created by this call to frame_context. Similarly, for |
| 601 |
continue_frame and 'continue' statements. |
| 602 |
|
| 603 |
If try_frame is true, then execution is allowed to jump at any |
| 604 |
point within the newly created frame (or its descendants) to |
| 605 |
its parent (i.e., to the frame that was on top before this |
| 606 |
call to frame_context). |
| 607 |
|
| 608 |
If discard is True, then this is a temporary throw-away frame |
| 609 |
(used e.g. for isolation) and its effect will be discarded on pop. |
| 610 |
|
| 611 |
After the context manager exits, self.last_pop_changed indicates |
| 612 |
whether any types changed in the newly-topmost frame as a result |
| 613 |
of popping this frame. |
| 614 |
""" |
| 615 |
return FrameContext( |
| 616 |
self, |
| 617 |
can_skip=can_skip, |
| 618 |
fall_through=fall_through, |
| 619 |
break_frame=break_frame, |
| 620 |
continue_frame=continue_frame, |
| 621 |
conditional_frame=conditional_frame, |
| 622 |
try_frame=try_frame, |
| 623 |
discard=discard, |
| 624 |
) |
| 625 |
|
| 626 |
@contextmanager |
| 627 |
def top_frame_context(self) -> Iterator[Frame]: |
| 628 |
"""A variant of frame_context for use at the top level of |
| 629 |
a namespace (module, function, or class). |
| 630 |
""" |
| 631 |
assert len(self.frames) == 1 |
| 632 |
yield self.push_frame() |
| 633 |
self.pop_frame(True, 0) |
| 634 |
assert len(self.frames) == 1 |
| 635 |
|
| 636 |
|
| 637 |
def get_declaration(expr: BindableExpression) -> Type | None: |
| 638 |
"""Get the declared or inferred type of a RefExpr expression. |
| 639 |
|
| 640 |
Return None if there is no type or the expression is not a RefExpr. |
| 641 |
This can return None if the type hasn't been inferred yet. |
| 642 |
""" |
| 643 |
if isinstance(expr, RefExpr): |
| 644 |
if isinstance(expr.node, Var): |
| 645 |
type = expr.node.type |
| 646 |
if not isinstance(get_proper_type(type), PartialType): |
| 647 |
return type |
| 648 |
elif isinstance(expr.node, TypeInfo): |
| 649 |
return TypeType(fill_typevars_with_any(expr.node)) |
| 650 |
return None |
| 651 |
|
| 652 |
|
| 653 |
def collapse_variadic_union(typ: UnionType) -> Type: |
| 654 |
"""Simplify a union involving variadic tuple if possible. |
| 655 |
|
| 656 |
This will collapse a type like e.g. |
| 657 |
tuple[X, Z] | tuple[X, Y, Z] | tuple[X, Y, Y, *tuple[Y, ...], Z] |
| 658 |
back to |
| 659 |
tuple[X, *tuple[Y, ...], Z] |
| 660 |
which is equivalent, but much simpler form of the same type. |
| 661 |
""" |
| 662 |
tuple_items = [] |
| 663 |
other_items = [] |
| 664 |
for t in typ.items: |
| 665 |
p_t = get_proper_type(t) |
| 666 |
if isinstance(p_t, TupleType): |
| 667 |
tuple_items.append(p_t) |
| 668 |
else: |
| 669 |
other_items.append(t) |
| 670 |
if len(tuple_items) <= 1: |
| 671 |
# This type cannot be simplified further. |
| 672 |
return typ |
| 673 |
tuple_items = sorted(tuple_items, key=lambda t: len(t.items)) |
| 674 |
first = tuple_items[0] |
| 675 |
last = tuple_items[-1] |
| 676 |
unpack_index = find_unpack_in_list(last.items) |
| 677 |
if unpack_index is None: |
| 678 |
return typ |
| 679 |
unpack = last.items[unpack_index] |
| 680 |
assert isinstance(unpack, UnpackType) |
| 681 |
unpacked = get_proper_type(unpack.type) |
| 682 |
if not isinstance(unpacked, Instance): |
| 683 |
return typ |
| 684 |
assert unpacked.type.fullname == "builtins.tuple" |
| 685 |
suffix = last.items[unpack_index + 1 :] |
| 686 |
|
| 687 |
# Check that first item matches the expected pattern and infer prefix. |
| 688 |
if len(first.items) < len(suffix): |
| 689 |
return typ |
| 690 |
if suffix and first.items[-len(suffix) :] != suffix: |
| 691 |
return typ |
| 692 |
if suffix: |
| 693 |
prefix = first.items[: -len(suffix)] |
| 694 |
else: |
| 695 |
prefix = first.items |
| 696 |
|
| 697 |
# Check that all middle types match the expected pattern as well. |
| 698 |
arg = unpacked.args[0] |
| 699 |
for i, it in enumerate(tuple_items[1:-1]): |
| 700 |
if it.items != prefix + [arg] * (i + 1) + suffix: |
| 701 |
return typ |
| 702 |
|
| 703 |
# Check the last item (the one with unpack), and choose an appropriate simplified type. |
| 704 |
if last.items != prefix + [arg] * (len(typ.items) - 1) + [unpack] + suffix: |
| 705 |
return typ |
| 706 |
if len(first.items) == 0: |
| 707 |
simplified: Type = unpacked.copy_modified() |
| 708 |
else: |
| 709 |
simplified = TupleType(prefix + [unpack] + suffix, fallback=last.partial_fallback) |
| 710 |
return UnionType.make_union([simplified] + other_items) |