|
369 | 369 | # string literal as a type expression. |
370 | 370 | _MULTIPLE_WORDS_NONTYPE_RE = re.compile(r'\s*[^\s.\'"|\[]+\s+[^\s.\'"|\[]') |
371 | 371 |
|
| 372 | +# Characters which never appear in a valid type expression. |
| 373 | +# NOTE: Allows '*' for (PEP 646 Unpack) and '+' for (Literal[+N]) |
| 374 | +# NOTE: Stored as a tuple of single-character strings (rather than a str) |
| 375 | +# so that iterating it does not allocate a new string per character |
| 376 | +# when compiled with mypyc. |
| 377 | +_NONTYPE_CHARS: Final = tuple("!:/<>@%$^?;&~`\\") |
| 378 | + |
372 | 379 |
|
373 | 380 | class SemanticAnalyzer( |
374 | 381 | NodeVisitor[None], SemanticAnalyzerInterface, SemanticAnalyzerPluginInterface, SplittingVisitor |
@@ -8150,57 +8157,15 @@ def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> None: |
8150 | 8157 | # and only lazily in contexts where a TypeForm is expected |
8151 | 8158 | return |
8152 | 8159 | elif isinstance(maybe_type_expr, StrExpr): |
8153 | | - str_value = maybe_type_expr.value # cache |
8154 | | - # Filter out string literals which look like an identifier but |
8155 | | - # cannot be a type expression, for a few common reasons |
8156 | | - if str_value.isidentifier(): |
8157 | | - sym = self.lookup(str_value, UnboundType(str_value), suppress_errors=True) |
8158 | | - if sym is None: |
8159 | | - # Does not refer to anything in the local symbol table |
8160 | | - maybe_type_expr.as_type = None |
8161 | | - return |
8162 | | - else: # sym is not None |
8163 | | - node = sym.node # cache |
8164 | | - if isinstance(node, PlaceholderNode) and not node.becomes_typeinfo: |
8165 | | - # Either: |
8166 | | - # 1. f'Cannot resolve name "{t.name}" (possible cyclic definition)' |
8167 | | - # 2. Reference to an unknown placeholder node. |
8168 | | - maybe_type_expr.as_type = None |
8169 | | - return |
8170 | | - unbound_tvar_or_paramspec = ( |
8171 | | - isinstance(node, (TypeVarExpr, TypeVarTupleExpr, ParamSpecExpr)) |
8172 | | - and self.tvar_scope.get_binding(sym) is None |
8173 | | - ) |
8174 | | - if unbound_tvar_or_paramspec: |
8175 | | - # Either: |
8176 | | - # 1. unbound_tvar: 'Type variable "{}" is unbound' [codes.VALID_TYPE] |
8177 | | - # 2. unbound_paramspec: f'ParamSpec "{name}" is unbound' [codes.VALID_TYPE] |
8178 | | - maybe_type_expr.as_type = None |
8179 | | - return |
8180 | | - else: # does not look like an identifier |
8181 | | - if '"' in str_value or "'" in str_value: |
8182 | | - # Only valid inside a Literal[...] or Annotated[..., ...] type |
8183 | | - if "[" not in str_value: |
8184 | | - # Cannot be a Literal[...] or Annotated[..., ...] type |
8185 | | - maybe_type_expr.as_type = None |
8186 | | - return |
8187 | | - elif len(str_value) < 2 or str_value.isspace(): |
8188 | | - # Whitespace-only strings cannot be valid types. Very short strings can |
8189 | | - # only be valid if they are identifiers, but we already checked for those. |
8190 | | - maybe_type_expr.as_type = None |
8191 | | - return |
8192 | | - # Filter out string literals with common patterns that could not |
8193 | | - # possibly be in a type expression |
8194 | | - if _MULTIPLE_WORDS_NONTYPE_RE.match(str_value): |
8195 | | - # A common pattern in string literals containing a sentence. |
8196 | | - # But cannot be a type expression. |
8197 | | - maybe_type_expr.as_type = None |
8198 | | - return |
| 8160 | + if not self.string_could_be_type_expression(maybe_type_expr): |
| 8161 | + # Not a valid type. |
| 8162 | + maybe_type_expr.as_type = None |
| 8163 | + return |
8199 | 8164 | elif isinstance(maybe_type_expr, IndexExpr): |
8200 | 8165 | if isinstance(maybe_type_expr.base, NameExpr): |
8201 | 8166 | if isinstance( |
8202 | 8167 | maybe_type_expr.base.node, Var |
8203 | | - ) and not self.var_is_typing_special_form(maybe_type_expr.base.node): |
| 8168 | + ) and not self.var_could_be_typing_special_form(maybe_type_expr.base.node): |
8204 | 8169 | # Leftmost part of IndexExpr refers to a Var. Not a valid type. |
8205 | 8170 | maybe_type_expr.as_type = None |
8206 | 8171 | return |
@@ -8212,9 +8177,7 @@ def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> None: |
8212 | 8177 | break |
8213 | 8178 | next_leftmost = leftmost |
8214 | 8179 | if isinstance(leftmost, NameExpr): |
8215 | | - if isinstance(leftmost.node, Var) and not self.var_is_typing_special_form( |
8216 | | - leftmost.node |
8217 | | - ): |
| 8180 | + if isinstance(leftmost.node, Var): |
8218 | 8181 | # Leftmost part of IndexExpr refers to a Var. Not a valid type. |
8219 | 8182 | maybe_type_expr.as_type = None |
8220 | 8183 | return |
@@ -8262,21 +8225,117 @@ def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> None: |
8262 | 8225 |
|
8263 | 8226 | maybe_type_expr.as_type = t |
8264 | 8227 |
|
| 8228 | + def string_could_be_type_expression(self, maybe_type_expr: StrExpr) -> bool: |
| 8229 | + str_value = maybe_type_expr.value # cache |
| 8230 | + if str_value.isidentifier(): |
| 8231 | + # Filter out string literals which look like an identifier but |
| 8232 | + # cannot be a type expression, for a few common reasons |
| 8233 | + sym = self.lookup(str_value, UnboundType(str_value), suppress_errors=True) |
| 8234 | + if sym is None: |
| 8235 | + # Does not refer to anything in the local symbol table |
| 8236 | + return False |
| 8237 | + else: # sym is not None |
| 8238 | + node = sym.node # cache |
| 8239 | + # The following early-reject checks are mutually exclusive, |
| 8240 | + # ordered by decreasing rejection frequency (measured on |
| 8241 | + # mypy's self-check) so the commonest rejections exit first. |
| 8242 | + # - TypeVarExpr, TypeVarTupleExpr, ParamSpecExpr (~951) |
| 8243 | + # - Var (~157) |
| 8244 | + # - FuncDef, OverloadedFuncDef, MypyFile (~48) |
| 8245 | + # - PlaceholderNode (~23) |
| 8246 | + unbound_tvar_or_paramspec = ( |
| 8247 | + isinstance(node, (TypeVarExpr, TypeVarTupleExpr, ParamSpecExpr)) |
| 8248 | + and self.tvar_scope.get_binding(sym) is None |
| 8249 | + ) |
| 8250 | + if unbound_tvar_or_paramspec: |
| 8251 | + # Either: |
| 8252 | + # 1. unbound_tvar: 'Type variable "{}" is unbound' [codes.VALID_TYPE] |
| 8253 | + # 2. unbound_paramspec: f'ParamSpec "{name}" is unbound' [codes.VALID_TYPE] |
| 8254 | + return False |
| 8255 | + if ( |
| 8256 | + isinstance(node, Var) |
| 8257 | + and self.var_type_is_known(node) |
| 8258 | + and not self.var_could_be_typing_special_form(node) |
| 8259 | + ): |
| 8260 | + # Var whose type is known and is not a special form. |
| 8261 | + # It is a value, not a type expression. |
| 8262 | + return False |
| 8263 | + if isinstance(node, (FuncDef, OverloadedFuncDef, MypyFile)): |
| 8264 | + # Functions and modules are never type expressions. |
| 8265 | + return False |
| 8266 | + if isinstance(node, PlaceholderNode) and not node.becomes_typeinfo: |
| 8267 | + # Either: |
| 8268 | + # 1. f'Cannot resolve name "{t.name}" (possible cyclic definition)' |
| 8269 | + # 2. Reference to an unknown placeholder node. |
| 8270 | + return False |
| 8271 | + elif (leftmost_name := dotted_identifier_leftmost(str_value)) is not None: |
| 8272 | + # Dotted-name string (e.g. "builtins.tuple", "typing.Mapping"). |
| 8273 | + # Look up the leftmost component; if it cannot be a type prefix |
| 8274 | + # then the whole dotted name cannot spell a type. Mirrors the |
| 8275 | + # IndexExpr-with-MemberExpr-base filter logic below. |
| 8276 | + sym = self.lookup(leftmost_name, UnboundType(leftmost_name), suppress_errors=True) |
| 8277 | + if sym is None: |
| 8278 | + # Leftmost component does not refer to anything in scope |
| 8279 | + return False |
| 8280 | + node = sym.node # cache |
| 8281 | + if isinstance(node, PlaceholderNode) and not node.becomes_typeinfo: |
| 8282 | + # Either: |
| 8283 | + # 1. f'Cannot resolve name "{t.name}" (possible cyclic definition)' |
| 8284 | + # 2. Reference to an unknown placeholder node. |
| 8285 | + return False |
| 8286 | + if isinstance(node, Var): |
| 8287 | + # Leftmost component is a Var: it is a value, so it cannot be |
| 8288 | + # the module or class prefix of a dotted type name. |
| 8289 | + return False |
| 8290 | + else: # does not look like an identifier or dotted identifier |
| 8291 | + if '"' in str_value or "'" in str_value: |
| 8292 | + # Only valid inside a Literal[...] or Annotated[..., ...] type |
| 8293 | + if "[" not in str_value: |
| 8294 | + # Cannot be a Literal[...] or Annotated[..., ...] type |
| 8295 | + return False |
| 8296 | + elif len(str_value) < 2 or str_value.isspace(): |
| 8297 | + # Whitespace-only strings cannot be valid types. Very short strings can |
| 8298 | + # only be valid if they are identifiers, but we already checked for those. |
| 8299 | + return False |
| 8300 | + # Filter out string literals with common patterns that could not |
| 8301 | + # possibly be in a type expression |
| 8302 | + if _MULTIPLE_WORDS_NONTYPE_RE.match(str_value): |
| 8303 | + # A common pattern in string literals containing a sentence. |
| 8304 | + # But cannot be a type expression. |
| 8305 | + return False |
| 8306 | + # Skip some checks when a non-zero even number of single or double quotes |
| 8307 | + # signals a possible Literal[...] component, whose quoted content |
| 8308 | + # could contain anything: symbols or identifiers that would be |
| 8309 | + # incorrectly processed by some checks. |
| 8310 | + sq = str_value.count("'") |
| 8311 | + dq = str_value.count('"') |
| 8312 | + if not ((sq > 0 and sq % 2 == 0) or (dq > 0 and dq % 2 == 0)): |
| 8313 | + # Filter out string literals containing characters or boundary |
| 8314 | + # patterns that never appear in valid type expressions: |
| 8315 | + # - Leading '.' (incomplete dotted name, file extension, etc) |
| 8316 | + # - Trailing '.' (incomplete dotted name, file extension, etc) |
| 8317 | + # - Characters never valid in a type expression (e.g. '/', ':', '<', '>', '@') |
| 8318 | + # - '-' not directly preceded by '[' (which can occur in Literal[-N]) |
| 8319 | + # NOTE: str_value is never empty here. Branches above return |
| 8320 | + # for every string shorter than 2 characters. |
| 8321 | + if str_value[0] == "." or str_value[-1] == "." or has_nontype_char(str_value): |
| 8322 | + return False |
| 8323 | + return True |
| 8324 | + |
8265 | 8325 | @staticmethod |
8266 | | - def var_is_typing_special_form(var: Var) -> bool: |
8267 | | - return var.fullname.startswith("typing") and var.fullname in [ |
8268 | | - "typing.Annotated", |
8269 | | - "typing_extensions.Annotated", |
8270 | | - "typing.Callable", |
8271 | | - "typing.Literal", |
8272 | | - "typing_extensions.Literal", |
8273 | | - "typing.Optional", |
8274 | | - "typing.TypeGuard", |
8275 | | - "typing_extensions.TypeGuard", |
8276 | | - "typing.TypeIs", |
8277 | | - "typing_extensions.TypeIs", |
8278 | | - "typing.Union", |
8279 | | - ] |
| 8326 | + def var_could_be_typing_special_form(var: Var) -> bool: |
| 8327 | + return ( |
| 8328 | + var.fullname.startswith("typing.") |
| 8329 | + or var.fullname.startswith("typing_extensions.") |
| 8330 | + or var.fullname.startswith("mypy_extensions.") |
| 8331 | + ) |
| 8332 | + |
| 8333 | + @staticmethod |
| 8334 | + def var_type_is_known(var: Var) -> bool: |
| 8335 | + return not ( |
| 8336 | + (var_typ_p := get_proper_type(var.type)) is None |
| 8337 | + or isinstance(var_typ_p, (AnyType, PlaceholderType, UnboundType)) |
| 8338 | + ) |
8280 | 8339 |
|
8281 | 8340 | @contextmanager |
8282 | 8341 | def isolated_error_analysis(self) -> Iterator[None]: |
@@ -8534,3 +8593,67 @@ def erase_func_annotations(func: FuncDef) -> None: |
8534 | 8593 | arg.variable.type = None |
8535 | 8594 | func.type = None |
8536 | 8595 | func.unanalyzed_type = None |
| 8596 | + |
| 8597 | + |
| 8598 | +def dotted_identifier_leftmost(s: str) -> str | None: |
| 8599 | + """The leftmost component of s, if s is a dotted identifier, else None. |
| 8600 | +
|
| 8601 | + A dotted identifier is two or more identifiers joined by ".", such as |
| 8602 | + "builtins.tuple" or "typing.Mapping". A bare identifier is not a dotted |
| 8603 | + identifier: callers are expected to handle that case separately. |
| 8604 | +
|
| 8605 | + Returns the leftmost component (which is never empty) so that callers |
| 8606 | + need not split s a second time to obtain it. |
| 8607 | + """ |
| 8608 | + # NOTE: Scanning with find() rather than s.split(".") avoids allocating a |
| 8609 | + # list, since only the leftmost component is ever needed. |
| 8610 | + dot = s.find(".") |
| 8611 | + if dot == -1: |
| 8612 | + return None |
| 8613 | + leftmost = s[:dot] |
| 8614 | + if not leftmost.isidentifier(): |
| 8615 | + return None |
| 8616 | + start = dot + 1 |
| 8617 | + while True: |
| 8618 | + dot = s.find(".", start) |
| 8619 | + if dot == -1: |
| 8620 | + if not s[start:].isidentifier(): |
| 8621 | + return None |
| 8622 | + return leftmost |
| 8623 | + if not s[start:dot].isidentifier(): |
| 8624 | + return None |
| 8625 | + start = dot + 1 |
| 8626 | + |
| 8627 | + |
| 8628 | +def has_nontype_char(s: str) -> bool: |
| 8629 | + """Whether s contains a character that cannot appear in a type expression. |
| 8630 | +
|
| 8631 | + Callers must exclude strings that may contain a quoted Literal[...] |
| 8632 | + component first, since quoted content can hold arbitrary characters. |
| 8633 | + """ |
| 8634 | + # Look for _NONTYPE_CHARS |
| 8635 | + # NOTE: Iterating over s first (instead of _NONTYPE_CHARS) is NOT faster. |
| 8636 | + # NOTE: set.isdisjoint() is faster in interpreted-mypy (-22% runtime) |
| 8637 | + # but slower in compiled-mypy (+16% runtime) |
| 8638 | + for ch in _NONTYPE_CHARS: |
| 8639 | + if ch in s: |
| 8640 | + return True |
| 8641 | + |
| 8642 | + # Look for "-". |
| 8643 | + # It is valid only as a unary minus introducing a Literal[...] element, |
| 8644 | + # which is to say only where the preceding non-space character is a "[" |
| 8645 | + # (as in Literal[-1]) or a "," (as in Literal[-1, -2]). |
| 8646 | + # A "-" anywhere else means s cannot be a type. |
| 8647 | + i = s.find("-") |
| 8648 | + while i != -1: |
| 8649 | + # Look for a preceding "[" or "," (skipping whitespace) |
| 8650 | + j = i - 1 |
| 8651 | + while j >= 0 and s[j] == " ": |
| 8652 | + j -= 1 |
| 8653 | + if j < 0 or (s[j] != "[" and s[j] != ","): |
| 8654 | + return True |
| 8655 | + |
| 8656 | + # Continue to the next "-" |
| 8657 | + i = s.find("-", i + 1) |
| 8658 | + |
| 8659 | + return False |