| 1 |
"""Shared definitions used by different parts of semantic analysis.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from abc import abstractmethod |
| 6 |
from collections.abc import Callable |
| 7 |
from typing import Final, Literal, Protocol, overload |
| 8 |
|
| 9 |
from mypy_extensions import trait |
| 10 |
|
| 11 |
from mypy.errorcodes import LITERAL_REQ, ErrorCode |
| 12 |
from mypy.nodes import ( |
| 13 |
CallExpr, |
| 14 |
ClassDef, |
| 15 |
Context, |
| 16 |
DataclassTransformSpec, |
| 17 |
Decorator, |
| 18 |
Expression, |
| 19 |
FuncDef, |
| 20 |
NameExpr, |
| 21 |
Node, |
| 22 |
OverloadedFuncDef, |
| 23 |
RefExpr, |
| 24 |
SymbolNode, |
| 25 |
SymbolTable, |
| 26 |
SymbolTableNode, |
| 27 |
TypeAlias, |
| 28 |
TypeInfo, |
| 29 |
) |
| 30 |
from mypy.plugin import SemanticAnalyzerPluginInterface |
| 31 |
from mypy.tvar_scope import TypeVarLikeScope |
| 32 |
from mypy.type_visitor import ANY_STRATEGY, BoolTypeQuery |
| 33 |
from mypy.typeops import make_simplified_union |
| 34 |
from mypy.types import ( |
| 35 |
TPDICT_FB_NAMES, |
| 36 |
AnyType, |
| 37 |
FunctionLike, |
| 38 |
Instance, |
| 39 |
Parameters, |
| 40 |
ParamSpecFlavor, |
| 41 |
ParamSpecType, |
| 42 |
PlaceholderType, |
| 43 |
ProperType, |
| 44 |
TupleType, |
| 45 |
Type, |
| 46 |
TypeOfAny, |
| 47 |
TypeVarId, |
| 48 |
TypeVarLikeType, |
| 49 |
TypeVarTupleType, |
| 50 |
UnpackType, |
| 51 |
flatten_nested_tuples, |
| 52 |
get_proper_type, |
| 53 |
) |
| 54 |
|
| 55 |
# Subclasses can override these Var attributes with incompatible types. This can also be |
| 56 |
# set for individual attributes using 'allow_incompatible_override' of Var. |
| 57 |
ALLOW_INCOMPATIBLE_OVERRIDE: Final = ("__slots__", "__deletable__", "__match_args__") |
| 58 |
|
| 59 |
|
| 60 |
# Priorities for ordering of patches within the "patch" phase of semantic analysis |
| 61 |
# (after the main pass): |
| 62 |
|
| 63 |
# Fix fallbacks (does subtype checks). |
| 64 |
PRIORITY_FALLBACKS: Final = 1 |
| 65 |
|
| 66 |
|
| 67 |
@trait |
| 68 |
class SemanticAnalyzerCoreInterface: |
| 69 |
"""A core abstract interface to generic semantic analyzer functionality. |
| 70 |
|
| 71 |
This is implemented by both semantic analyzer passes 2 and 3. |
| 72 |
""" |
| 73 |
|
| 74 |
@abstractmethod |
| 75 |
def lookup_qualified( |
| 76 |
self, name: str, ctx: Context, suppress_errors: bool = False |
| 77 |
) -> SymbolTableNode | None: |
| 78 |
raise NotImplementedError |
| 79 |
|
| 80 |
@abstractmethod |
| 81 |
def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode: |
| 82 |
raise NotImplementedError |
| 83 |
|
| 84 |
@abstractmethod |
| 85 |
def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None: |
| 86 |
raise NotImplementedError |
| 87 |
|
| 88 |
@abstractmethod |
| 89 |
def record_fixed_type(self, fixed: TypeInfo | TypeAlias) -> None: |
| 90 |
raise NotImplementedError |
| 91 |
|
| 92 |
@abstractmethod |
| 93 |
def fail( |
| 94 |
self, |
| 95 |
msg: str, |
| 96 |
ctx: Context, |
| 97 |
serious: bool = False, |
| 98 |
*, |
| 99 |
blocker: bool = False, |
| 100 |
code: ErrorCode | None = None, |
| 101 |
) -> None: |
| 102 |
raise NotImplementedError |
| 103 |
|
| 104 |
@abstractmethod |
| 105 |
def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: |
| 106 |
raise NotImplementedError |
| 107 |
|
| 108 |
@abstractmethod |
| 109 |
def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: |
| 110 |
raise NotImplementedError |
| 111 |
|
| 112 |
@abstractmethod |
| 113 |
def record_incomplete_ref(self) -> None: |
| 114 |
raise NotImplementedError |
| 115 |
|
| 116 |
@abstractmethod |
| 117 |
def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None: |
| 118 |
raise NotImplementedError |
| 119 |
|
| 120 |
@abstractmethod |
| 121 |
def is_incomplete_namespace(self, fullname: str) -> bool: |
| 122 |
"""Is a module or class namespace potentially missing some definitions?""" |
| 123 |
raise NotImplementedError |
| 124 |
|
| 125 |
@property |
| 126 |
@abstractmethod |
| 127 |
def final_iteration(self) -> bool: |
| 128 |
"""Is this the final iteration of semantic analysis?""" |
| 129 |
raise NotImplementedError |
| 130 |
|
| 131 |
@abstractmethod |
| 132 |
def is_future_flag_set(self, flag: str) -> bool: |
| 133 |
"""Is the specific __future__ feature imported""" |
| 134 |
raise NotImplementedError |
| 135 |
|
| 136 |
@property |
| 137 |
@abstractmethod |
| 138 |
def is_stub_file(self) -> bool: |
| 139 |
raise NotImplementedError |
| 140 |
|
| 141 |
@abstractmethod |
| 142 |
def is_func_scope(self) -> bool: |
| 143 |
raise NotImplementedError |
| 144 |
|
| 145 |
@abstractmethod |
| 146 |
def is_nested_within_func_scope(self) -> bool: |
| 147 |
raise NotImplementedError |
| 148 |
|
| 149 |
@property |
| 150 |
@abstractmethod |
| 151 |
def type(self) -> TypeInfo | None: |
| 152 |
raise NotImplementedError |
| 153 |
|
| 154 |
|
| 155 |
@trait |
| 156 |
class SemanticAnalyzerInterface(SemanticAnalyzerCoreInterface): |
| 157 |
"""A limited abstract interface to some generic semantic analyzer pass 2 functionality. |
| 158 |
|
| 159 |
We use this interface for various reasons: |
| 160 |
|
| 161 |
* Looser coupling |
| 162 |
* Cleaner import graph |
| 163 |
* Less need to pass around callback functions |
| 164 |
""" |
| 165 |
|
| 166 |
tvar_scope: TypeVarLikeScope |
| 167 |
|
| 168 |
@abstractmethod |
| 169 |
def lookup( |
| 170 |
self, name: str, ctx: Context, suppress_errors: bool = False |
| 171 |
) -> SymbolTableNode | None: |
| 172 |
raise NotImplementedError |
| 173 |
|
| 174 |
@abstractmethod |
| 175 |
def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance: |
| 176 |
raise NotImplementedError |
| 177 |
|
| 178 |
@abstractmethod |
| 179 |
def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None: |
| 180 |
raise NotImplementedError |
| 181 |
|
| 182 |
@abstractmethod |
| 183 |
def accept(self, node: Node) -> None: |
| 184 |
raise NotImplementedError |
| 185 |
|
| 186 |
@abstractmethod |
| 187 |
def anal_type( |
| 188 |
self, |
| 189 |
typ: Type, |
| 190 |
/, |
| 191 |
*, |
| 192 |
tvar_scope: TypeVarLikeScope | None = None, |
| 193 |
allow_tuple_literal: bool = False, |
| 194 |
allow_unbound_tvars: bool = False, |
| 195 |
allow_typed_dict_special_forms: bool = False, |
| 196 |
allow_placeholder: bool = False, |
| 197 |
report_invalid_types: bool = True, |
| 198 |
prohibit_self_type: str | None = None, |
| 199 |
prohibit_special_class_field_types: str | None = None, |
| 200 |
) -> Type | None: |
| 201 |
raise NotImplementedError |
| 202 |
|
| 203 |
@abstractmethod |
| 204 |
def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]: |
| 205 |
raise NotImplementedError |
| 206 |
|
| 207 |
@abstractmethod |
| 208 |
def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: |
| 209 |
raise NotImplementedError |
| 210 |
|
| 211 |
@abstractmethod |
| 212 |
def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None: |
| 213 |
raise NotImplementedError |
| 214 |
|
| 215 |
@abstractmethod |
| 216 |
def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> bool: |
| 217 |
"""Add node to the current symbol table.""" |
| 218 |
raise NotImplementedError |
| 219 |
|
| 220 |
@abstractmethod |
| 221 |
def current_symbol_table(self) -> SymbolTable: |
| 222 |
"""Get currently active symbol table. |
| 223 |
|
| 224 |
May be module, class, or local namespace. |
| 225 |
""" |
| 226 |
raise NotImplementedError |
| 227 |
|
| 228 |
@abstractmethod |
| 229 |
def add_symbol( |
| 230 |
self, |
| 231 |
name: str, |
| 232 |
node: SymbolNode, |
| 233 |
context: Context, |
| 234 |
module_public: bool = True, |
| 235 |
module_hidden: bool = False, |
| 236 |
can_defer: bool = True, |
| 237 |
) -> bool: |
| 238 |
"""Add symbol to the current symbol table.""" |
| 239 |
raise NotImplementedError |
| 240 |
|
| 241 |
@abstractmethod |
| 242 |
def add_global_symbol(self, name: str, ctx: Context, node: SymbolNode) -> None: |
| 243 |
"""Add symbol directly to the global symbol table.""" |
| 244 |
raise NotImplementedError |
| 245 |
|
| 246 |
@abstractmethod |
| 247 |
def parse_bool(self, expr: Expression) -> bool | None: |
| 248 |
raise NotImplementedError |
| 249 |
|
| 250 |
@abstractmethod |
| 251 |
def qualified_name(self, name: str) -> str: |
| 252 |
raise NotImplementedError |
| 253 |
|
| 254 |
@property |
| 255 |
@abstractmethod |
| 256 |
def is_typeshed_stub_file(self) -> bool: |
| 257 |
raise NotImplementedError |
| 258 |
|
| 259 |
@abstractmethod |
| 260 |
def process_placeholder( |
| 261 |
self, name: str | None, kind: str, ctx: Context, force_progress: bool = False |
| 262 |
) -> None: |
| 263 |
raise NotImplementedError |
| 264 |
|
| 265 |
|
| 266 |
def set_callable_name(sig: Type, fdef: FuncDef) -> ProperType: |
| 267 |
sig = get_proper_type(sig) |
| 268 |
if isinstance(sig, FunctionLike): |
| 269 |
if fdef.info: |
| 270 |
if fdef.info.fullname in TPDICT_FB_NAMES: |
| 271 |
# Avoid exposing the internal _TypedDict name. |
| 272 |
class_name = "TypedDict" |
| 273 |
else: |
| 274 |
class_name = fdef.info.name |
| 275 |
return sig.with_name(f"{fdef.name} of {class_name}") |
| 276 |
else: |
| 277 |
return sig.with_name(fdef.name) |
| 278 |
else: |
| 279 |
return sig |
| 280 |
|
| 281 |
|
| 282 |
def calculate_tuple_fallback(typ: TupleType) -> None: |
| 283 |
"""Calculate a precise item type for the fallback of a tuple type. |
| 284 |
|
| 285 |
This must be called only after the main semantic analysis pass, since joins |
| 286 |
aren't available before that. |
| 287 |
|
| 288 |
Note that there is an apparent chicken and egg problem with respect |
| 289 |
to verifying type arguments against bounds. Verifying bounds might |
| 290 |
require fallbacks, but we might use the bounds to calculate the |
| 291 |
fallbacks. In practice this is not a problem, since the worst that |
| 292 |
can happen is that we have invalid type argument values, and these |
| 293 |
can happen in later stages as well (they will generate errors, but |
| 294 |
we don't prevent their existence). |
| 295 |
""" |
| 296 |
fallback = typ.partial_fallback |
| 297 |
assert fallback.type.fullname == "builtins.tuple" |
| 298 |
items = [] |
| 299 |
for item in flatten_nested_tuples(typ.items): |
| 300 |
# TODO: this duplicates some logic in typeops.tuple_fallback(). |
| 301 |
if isinstance(item, UnpackType): |
| 302 |
unpacked_type = get_proper_type(item.type) |
| 303 |
if isinstance(unpacked_type, TypeVarTupleType): |
| 304 |
unpacked_type = get_proper_type(unpacked_type.upper_bound) |
| 305 |
if ( |
| 306 |
isinstance(unpacked_type, Instance) |
| 307 |
and unpacked_type.type.fullname == "builtins.tuple" |
| 308 |
): |
| 309 |
items.append(unpacked_type.args[0]) |
| 310 |
else: |
| 311 |
# This is called before semanal_typeargs.py fixes broken unpacks, |
| 312 |
# where the error should also be generated. |
| 313 |
items.append(AnyType(TypeOfAny.from_error)) |
| 314 |
else: |
| 315 |
items.append(item) |
| 316 |
fallback.args = (make_simplified_union(items),) |
| 317 |
|
| 318 |
|
| 319 |
class _NamedTypeCallback(Protocol): |
| 320 |
def __call__(self, fullname: str, args: list[Type] | None = None) -> Instance: ... |
| 321 |
|
| 322 |
|
| 323 |
def paramspec_args( |
| 324 |
name: str, |
| 325 |
fullname: str, |
| 326 |
id: TypeVarId, |
| 327 |
*, |
| 328 |
named_type_func: _NamedTypeCallback, |
| 329 |
line: int = -1, |
| 330 |
column: int = -1, |
| 331 |
prefix: Parameters | None = None, |
| 332 |
) -> ParamSpecType: |
| 333 |
return ParamSpecType( |
| 334 |
name, |
| 335 |
fullname, |
| 336 |
id, |
| 337 |
flavor=ParamSpecFlavor.ARGS, |
| 338 |
upper_bound=named_type_func("builtins.tuple", [named_type_func("builtins.object")]), |
| 339 |
default=AnyType(TypeOfAny.from_omitted_generics), |
| 340 |
line=line, |
| 341 |
column=column, |
| 342 |
prefix=prefix, |
| 343 |
) |
| 344 |
|
| 345 |
|
| 346 |
def paramspec_kwargs( |
| 347 |
name: str, |
| 348 |
fullname: str, |
| 349 |
id: TypeVarId, |
| 350 |
*, |
| 351 |
named_type_func: _NamedTypeCallback, |
| 352 |
line: int = -1, |
| 353 |
column: int = -1, |
| 354 |
prefix: Parameters | None = None, |
| 355 |
) -> ParamSpecType: |
| 356 |
return ParamSpecType( |
| 357 |
name, |
| 358 |
fullname, |
| 359 |
id, |
| 360 |
flavor=ParamSpecFlavor.KWARGS, |
| 361 |
upper_bound=named_type_func( |
| 362 |
"builtins.dict", [named_type_func("builtins.str"), named_type_func("builtins.object")] |
| 363 |
), |
| 364 |
default=AnyType(TypeOfAny.from_omitted_generics), |
| 365 |
line=line, |
| 366 |
column=column, |
| 367 |
prefix=prefix, |
| 368 |
) |
| 369 |
|
| 370 |
|
| 371 |
class HasPlaceholders(BoolTypeQuery): |
| 372 |
def __init__(self) -> None: |
| 373 |
super().__init__(ANY_STRATEGY) |
| 374 |
|
| 375 |
def visit_placeholder_type(self, t: PlaceholderType) -> bool: |
| 376 |
return True |
| 377 |
|
| 378 |
|
| 379 |
def has_placeholder(typ: Type) -> bool: |
| 380 |
"""Check if a type contains any placeholder types (recursively).""" |
| 381 |
return typ.accept(HasPlaceholders()) |
| 382 |
|
| 383 |
|
| 384 |
def find_dataclass_transform_spec(node: Node | None) -> DataclassTransformSpec | None: |
| 385 |
""" |
| 386 |
Find the dataclass transform spec for the given node, if any exists. |
| 387 |
|
| 388 |
Per PEP 681 (https://peps.python.org/pep-0681/#the-dataclass-transform-decorator), dataclass |
| 389 |
transforms can be specified in multiple ways, including decorator functions and |
| 390 |
metaclasses/base classes. This function resolves the spec from any of these variants. |
| 391 |
""" |
| 392 |
|
| 393 |
# The spec only lives on the function/class definition itself, so we need to unwrap down to that |
| 394 |
# point |
| 395 |
if isinstance(node, CallExpr): |
| 396 |
# Like dataclasses.dataclass, transform-based decorators can be applied either with or |
| 397 |
# without parameters; ie, both of these forms are accepted: |
| 398 |
# |
| 399 |
# @typing.dataclass_transform |
| 400 |
# class Foo: ... |
| 401 |
# @typing.dataclass_transform(eq=True, order=True, ...) |
| 402 |
# class Bar: ... |
| 403 |
# |
| 404 |
# We need to unwrap the call for the second variant. |
| 405 |
node = node.callee |
| 406 |
|
| 407 |
if isinstance(node, RefExpr): |
| 408 |
node = node.node |
| 409 |
|
| 410 |
if isinstance(node, Decorator): |
| 411 |
# typing.dataclass_transform usage must always result in a Decorator; it always uses the |
| 412 |
# `@dataclass_transform(...)` syntax and never `@dataclass_transform` |
| 413 |
node = node.func |
| 414 |
|
| 415 |
if isinstance(node, OverloadedFuncDef): |
| 416 |
# The dataclass_transform decorator may be attached to any single overload, so we must |
| 417 |
# search them all. |
| 418 |
# Note that using more than one decorator is undefined behavior, so we can just take the |
| 419 |
# first that we find. |
| 420 |
for candidate in node.items: |
| 421 |
spec = find_dataclass_transform_spec(candidate) |
| 422 |
if spec is not None: |
| 423 |
return spec |
| 424 |
return find_dataclass_transform_spec(node.impl) |
| 425 |
|
| 426 |
# For functions, we can directly consult the AST field for the spec |
| 427 |
if isinstance(node, FuncDef): |
| 428 |
return node.dataclass_transform_spec |
| 429 |
|
| 430 |
if isinstance(node, ClassDef): |
| 431 |
node = node.info |
| 432 |
if isinstance(node, TypeInfo): |
| 433 |
# Search all parent classes to see if any are decorated with `typing.dataclass_transform` |
| 434 |
for base in node.mro[1:]: |
| 435 |
if base.dataclass_transform_spec is not None: |
| 436 |
return base.dataclass_transform_spec |
| 437 |
|
| 438 |
# Check if there is a metaclass that is decorated with `typing.dataclass_transform` |
| 439 |
# |
| 440 |
# Note that PEP 681 only discusses using a metaclass that is directly decorated with |
| 441 |
# `typing.dataclass_transform`; subclasses thereof should be treated with dataclass |
| 442 |
# semantics rather than as transforms: |
| 443 |
# |
| 444 |
# > If dataclass_transform is applied to a class, dataclass-like semantics will be assumed |
| 445 |
# > for any class that directly or indirectly derives from the decorated class or uses the |
| 446 |
# > decorated class as a metaclass. |
| 447 |
# |
| 448 |
# The wording doesn't make this entirely explicit, but Pyright (the reference |
| 449 |
# implementation for this PEP) only handles directly-decorated metaclasses. |
| 450 |
metaclass_type = node.metaclass_type |
| 451 |
if metaclass_type is not None and metaclass_type.type.dataclass_transform_spec is not None: |
| 452 |
return metaclass_type.type.dataclass_transform_spec |
| 453 |
|
| 454 |
return None |
| 455 |
|
| 456 |
|
| 457 |
# Never returns `None` if a default is given |
| 458 |
@overload |
| 459 |
def require_bool_literal_argument( |
| 460 |
api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, |
| 461 |
expression: Expression, |
| 462 |
name: str, |
| 463 |
default: Literal[True, False], |
| 464 |
) -> bool: ... |
| 465 |
|
| 466 |
|
| 467 |
@overload |
| 468 |
def require_bool_literal_argument( |
| 469 |
api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, |
| 470 |
expression: Expression, |
| 471 |
name: str, |
| 472 |
default: None = None, |
| 473 |
) -> bool | None: ... |
| 474 |
|
| 475 |
|
| 476 |
def require_bool_literal_argument( |
| 477 |
api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, |
| 478 |
expression: Expression, |
| 479 |
name: str, |
| 480 |
default: bool | None = None, |
| 481 |
) -> bool | None: |
| 482 |
"""Attempt to interpret an expression as a boolean literal, and fail analysis if we can't.""" |
| 483 |
value = parse_bool(expression) |
| 484 |
if value is None: |
| 485 |
api.fail( |
| 486 |
f'"{name}" argument must be a True or False literal', expression, code=LITERAL_REQ |
| 487 |
) |
| 488 |
return default |
| 489 |
|
| 490 |
return value |
| 491 |
|
| 492 |
|
| 493 |
def parse_bool(expr: Expression) -> bool | None: |
| 494 |
if isinstance(expr, NameExpr): |
| 495 |
if expr.fullname == "builtins.True": |
| 496 |
return True |
| 497 |
if expr.fullname == "builtins.False": |
| 498 |
return False |
| 499 |
return None |