Skip to content

Commit a182dec

Browse files
tyrallaesarp
authored andcommitted
Combine the revealed types of multiple iteration steps in a more robust manner. (#19324)
This PR fixes a regression introduced in #19118 and discussed in #19270. The combination of the revealed types of individual iteration steps now relies on collecting the original type objects instead of parts of preliminary `revealed_type` notes. As @JukkaL suspected, this approach is much more straightforward than introducing a sufficiently complete `revealed_type` note parser. Please note that I appended a commit that refactors already existing code. It is mainly code-moving, so I hope it does not complicate the review of this PR.
1 parent ab4fd57 commit a182dec

File tree

8 files changed

+95
-80
lines changed

8 files changed

+95
-80
lines changed

mypy/checker.py

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -612,7 +612,7 @@ def accept_loop(
612612
if on_enter_body is not None:
613613
on_enter_body()
614614

615-
with IterationErrorWatcher(self.msg.errors, iter_errors) as watcher:
615+
with IterationErrorWatcher(self.msg.errors, iter_errors):
616616
self.accept(body)
617617

618618
partials_new = sum(len(pts.map) for pts in self.partial_types)
@@ -635,10 +635,7 @@ def accept_loop(
635635
if iter == 20:
636636
raise RuntimeError("Too many iterations when checking a loop")
637637

638-
for error_info in watcher.yield_error_infos():
639-
self.msg.fail(*error_info[:2], code=error_info[2])
640-
for note_info in watcher.yield_note_infos(self.options):
641-
self.note(*note_info)
638+
self.msg.iteration_dependent_errors(iter_errors)
642639

643640
# If exit_condition is set, assume it must be False on exit from the loop:
644641
if exit_condition:
@@ -3027,7 +3024,7 @@ def is_noop_for_reachability(self, s: Statement) -> bool:
30273024
if isinstance(s.expr, EllipsisExpr):
30283025
return True
30293026
elif isinstance(s.expr, CallExpr):
3030-
with self.expr_checker.msg.filter_errors():
3027+
with self.expr_checker.msg.filter_errors(filter_revealed_type=True):
30313028
typ = get_proper_type(
30323029
self.expr_checker.accept(
30333030
s.expr, allow_none_return=True, always_allow_any=True
@@ -4943,7 +4940,7 @@ def visit_try_stmt(self, s: TryStmt) -> None:
49434940
if s.finally_body:
49444941
# First we check finally_body is type safe on all abnormal exit paths
49454942
iter_errors = IterationDependentErrors()
4946-
with IterationErrorWatcher(self.msg.errors, iter_errors) as watcher:
4943+
with IterationErrorWatcher(self.msg.errors, iter_errors):
49474944
self.accept(s.finally_body)
49484945

49494946
if s.finally_body:
@@ -4960,13 +4957,9 @@ def visit_try_stmt(self, s: TryStmt) -> None:
49604957
# that follows the try statement.)
49614958
assert iter_errors is not None
49624959
if not self.binder.is_unreachable():
4963-
with IterationErrorWatcher(self.msg.errors, iter_errors) as watcher:
4960+
with IterationErrorWatcher(self.msg.errors, iter_errors):
49644961
self.accept(s.finally_body)
4965-
4966-
for error_info in watcher.yield_error_infos():
4967-
self.msg.fail(*error_info[:2], code=error_info[2])
4968-
for note_info in watcher.yield_note_infos(self.options):
4969-
self.msg.note(*note_info)
4962+
self.msg.iteration_dependent_errors(iter_errors)
49704963

49714964
def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None:
49724965
"""Type check a try statement, ignoring the finally block.

mypy/errors.py

Lines changed: 46 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from mypy.nodes import Context
1616
from mypy.options import Options
1717
from mypy.scope import Scope
18+
from mypy.types import Type
1819
from mypy.util import DEFAULT_SOURCE_OFFSET, is_typeshed_file
1920
from mypy.version import __version__ as mypy_version
2021

@@ -166,18 +167,24 @@ class ErrorWatcher:
166167
out by one of the ErrorWatcher instances.
167168
"""
168169

170+
# public attribute for the special treatment of `reveal_type` by
171+
# `MessageBuilder.reveal_type`:
172+
filter_revealed_type: bool
173+
169174
def __init__(
170175
self,
171176
errors: Errors,
172177
*,
173178
filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,
174179
save_filtered_errors: bool = False,
175180
filter_deprecated: bool = False,
181+
filter_revealed_type: bool = False,
176182
) -> None:
177183
self.errors = errors
178184
self._has_new_errors = False
179185
self._filter = filter_errors
180186
self._filter_deprecated = filter_deprecated
187+
self.filter_revealed_type = filter_revealed_type
181188
self._filtered: list[ErrorInfo] | None = [] if save_filtered_errors else None
182189

183190
def __enter__(self) -> Self:
@@ -236,15 +243,41 @@ class IterationDependentErrors:
236243
# the error report occurs but really all unreachable lines.
237244
unreachable_lines: list[set[int]]
238245

239-
# One set of revealed types for each `reveal_type` statement. Each created set can
240-
# grow during the iteration. Meaning of the tuple items: function_or_member, line,
241-
# column, end_line, end_column:
242-
revealed_types: dict[tuple[str | None, int, int, int, int], set[str]]
246+
# One list of revealed types for each `reveal_type` statement. Each created list
247+
# can grow during the iteration. Meaning of the tuple items: line, column,
248+
# end_line, end_column:
249+
revealed_types: dict[tuple[int, int, int | None, int | None], list[Type]]
243250

244251
def __init__(self) -> None:
245252
self.uselessness_errors = []
246253
self.unreachable_lines = []
247-
self.revealed_types = defaultdict(set)
254+
self.revealed_types = defaultdict(list)
255+
256+
def yield_uselessness_error_infos(self) -> Iterator[tuple[str, Context, ErrorCode]]:
257+
"""Report only those `unreachable`, `redundant-expr`, and `redundant-casts`
258+
errors that could not be ruled out in any iteration step."""
259+
260+
persistent_uselessness_errors = set()
261+
for candidate in set(chain(*self.uselessness_errors)):
262+
if all(
263+
(candidate in errors) or (candidate[2] in lines)
264+
for errors, lines in zip(self.uselessness_errors, self.unreachable_lines)
265+
):
266+
persistent_uselessness_errors.add(candidate)
267+
for error_info in persistent_uselessness_errors:
268+
context = Context(line=error_info[2], column=error_info[3])
269+
context.end_line = error_info[4]
270+
context.end_column = error_info[5]
271+
yield error_info[1], context, error_info[0]
272+
273+
def yield_revealed_type_infos(self) -> Iterator[tuple[list[Type], Context]]:
274+
"""Yield all types revealed in at least one iteration step."""
275+
276+
for note_info, types in self.revealed_types.items():
277+
context = Context(line=note_info[0], column=note_info[1])
278+
context.end_line = note_info[2]
279+
context.end_column = note_info[3]
280+
yield types, context
248281

249282

250283
class IterationErrorWatcher(ErrorWatcher):
@@ -287,53 +320,8 @@ def on_error(self, file: str, info: ErrorInfo) -> bool:
287320
iter_errors.unreachable_lines[-1].update(range(info.line, info.end_line + 1))
288321
return True
289322

290-
if info.code == codes.MISC and info.message.startswith("Revealed type is "):
291-
key = info.function_or_member, info.line, info.column, info.end_line, info.end_column
292-
types = info.message.split('"')[1]
293-
if types.startswith("Union["):
294-
iter_errors.revealed_types[key].update(types[6:-1].split(", "))
295-
else:
296-
iter_errors.revealed_types[key].add(types)
297-
return True
298-
299323
return super().on_error(file, info)
300324

301-
def yield_error_infos(self) -> Iterator[tuple[str, Context, ErrorCode]]:
302-
"""Report only those `unreachable`, `redundant-expr`, and `redundant-casts`
303-
errors that could not be ruled out in any iteration step."""
304-
305-
persistent_uselessness_errors = set()
306-
iter_errors = self.iteration_dependent_errors
307-
for candidate in set(chain(*iter_errors.uselessness_errors)):
308-
if all(
309-
(candidate in errors) or (candidate[2] in lines)
310-
for errors, lines in zip(
311-
iter_errors.uselessness_errors, iter_errors.unreachable_lines
312-
)
313-
):
314-
persistent_uselessness_errors.add(candidate)
315-
for error_info in persistent_uselessness_errors:
316-
context = Context(line=error_info[2], column=error_info[3])
317-
context.end_line = error_info[4]
318-
context.end_column = error_info[5]
319-
yield error_info[1], context, error_info[0]
320-
321-
def yield_note_infos(self, options: Options) -> Iterator[tuple[str, Context]]:
322-
"""Yield all types revealed in at least one iteration step."""
323-
324-
for note_info, types in self.iteration_dependent_errors.revealed_types.items():
325-
sorted_ = sorted(types, key=lambda typ: typ.lower())
326-
if len(types) == 1:
327-
revealed = sorted_[0]
328-
elif options.use_or_syntax():
329-
revealed = " | ".join(sorted_)
330-
else:
331-
revealed = f"Union[{', '.join(sorted_)}]"
332-
context = Context(line=note_info[1], column=note_info[2])
333-
context.end_line = note_info[3]
334-
context.end_column = note_info[4]
335-
yield f'Revealed type is "{revealed}"', context
336-
337325

338326
class Errors:
339327
"""Container for compile errors.
@@ -596,18 +584,19 @@ def _add_error_info(self, file: str, info: ErrorInfo) -> None:
596584
if info.code in (IMPORT, IMPORT_UNTYPED, IMPORT_NOT_FOUND):
597585
self.seen_import_error = True
598586

587+
def get_watchers(self) -> Iterator[ErrorWatcher]:
588+
"""Yield the `ErrorWatcher` stack from top to bottom."""
589+
i = len(self._watchers)
590+
while i > 0:
591+
i -= 1
592+
yield self._watchers[i]
593+
599594
def _filter_error(self, file: str, info: ErrorInfo) -> bool:
600595
"""
601596
process ErrorWatcher stack from top to bottom,
602597
stopping early if error needs to be filtered out
603598
"""
604-
i = len(self._watchers)
605-
while i > 0:
606-
i -= 1
607-
w = self._watchers[i]
608-
if w.on_error(file, info):
609-
return True
610-
return False
599+
return any(w.on_error(file, info) for w in self.get_watchers())
611600

612601
def add_error_info(self, info: ErrorInfo) -> None:
613602
file, lines = info.origin

mypy/messages.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@
2323
from mypy import errorcodes as codes, message_registry
2424
from mypy.erasetype import erase_type
2525
from mypy.errorcodes import ErrorCode
26-
from mypy.errors import ErrorInfo, Errors, ErrorWatcher
26+
from mypy.errors import (
27+
ErrorInfo,
28+
Errors,
29+
ErrorWatcher,
30+
IterationDependentErrors,
31+
IterationErrorWatcher,
32+
)
2733
from mypy.nodes import (
2834
ARG_NAMED,
2935
ARG_NAMED_OPT,
@@ -188,12 +194,14 @@ def filter_errors(
188194
filter_errors: bool | Callable[[str, ErrorInfo], bool] = True,
189195
save_filtered_errors: bool = False,
190196
filter_deprecated: bool = False,
197+
filter_revealed_type: bool = False,
191198
) -> ErrorWatcher:
192199
return ErrorWatcher(
193200
self.errors,
194201
filter_errors=filter_errors,
195202
save_filtered_errors=save_filtered_errors,
196203
filter_deprecated=filter_deprecated,
204+
filter_revealed_type=filter_revealed_type,
197205
)
198206

199207
def add_errors(self, errors: list[ErrorInfo]) -> None:
@@ -1735,6 +1743,24 @@ def invalid_signature_for_special_method(
17351743
)
17361744

17371745
def reveal_type(self, typ: Type, context: Context) -> None:
1746+
1747+
# Search for an error watcher that modifies the "normal" behaviour (we do not
1748+
# rely on the normal `ErrorWatcher` filtering approach because we might need to
1749+
# collect the original types for a later unionised response):
1750+
for watcher in self.errors.get_watchers():
1751+
# The `reveal_type` statement should be ignored:
1752+
if watcher.filter_revealed_type:
1753+
return
1754+
# The `reveal_type` statement might be visited iteratively due to being
1755+
# placed in a loop or so. Hence, we collect the respective types of
1756+
# individual iterations so that we can report them all in one step later:
1757+
if isinstance(watcher, IterationErrorWatcher):
1758+
watcher.iteration_dependent_errors.revealed_types[
1759+
(context.line, context.column, context.end_line, context.end_column)
1760+
].append(typ)
1761+
return
1762+
1763+
# Nothing special here; just create the note:
17381764
visitor = TypeStrVisitor(options=self.options)
17391765
self.note(f'Revealed type is "{typ.accept(visitor)}"', context)
17401766

@@ -2478,6 +2504,12 @@ def match_statement_inexhaustive_match(self, typ: Type, context: Context) -> Non
24782504
code=codes.EXHAUSTIVE_MATCH,
24792505
)
24802506

2507+
def iteration_dependent_errors(self, iter_errors: IterationDependentErrors) -> None:
2508+
for error_info in iter_errors.yield_uselessness_error_infos():
2509+
self.fail(*error_info[:2], code=error_info[2])
2510+
for types, context in iter_errors.yield_revealed_type_infos():
2511+
self.reveal_type(mypy.typeops.make_simplified_union(types), context)
2512+
24812513

24822514
def quote_type_string(type_string: str) -> str:
24832515
"""Quotes a type representation for use in messages."""

test-data/unit/check-inference.test

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ for var2 in [g, h, i, j, k, l]:
343343
reveal_type(var2) # N: Revealed type is "Union[builtins.int, builtins.str]"
344344

345345
for var3 in [m, n, o, p, q, r]:
346-
reveal_type(var3) # N: Revealed type is "Union[Any, builtins.int]"
346+
reveal_type(var3) # N: Revealed type is "Union[builtins.int, Any]"
347347

348348
T = TypeVar("T", bound=Type[Foo])
349349

@@ -1247,7 +1247,7 @@ class X(TypedDict):
12471247

12481248
x: X
12491249
for a in ("hourly", "daily"):
1250-
reveal_type(a) # N: Revealed type is "Union[Literal['daily']?, Literal['hourly']?]"
1250+
reveal_type(a) # N: Revealed type is "Union[Literal['hourly']?, Literal['daily']?]"
12511251
reveal_type(x[a]) # N: Revealed type is "builtins.int"
12521252
reveal_type(a.upper()) # N: Revealed type is "builtins.str"
12531253
c = a

test-data/unit/check-narrowing.test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2346,7 +2346,7 @@ def f() -> bool: ...
23462346

23472347
y = None
23482348
while f():
2349-
reveal_type(y) # N: Revealed type is "Union[builtins.int, None]"
2349+
reveal_type(y) # N: Revealed type is "Union[None, builtins.int]"
23502350
y = 1
23512351
reveal_type(y) # N: Revealed type is "Union[builtins.int, None]"
23522352

test-data/unit/check-redefine2.test

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,7 @@ def f1() -> None:
628628
def f2() -> None:
629629
x = None
630630
while int():
631-
reveal_type(x) # N: Revealed type is "Union[builtins.str, None]"
631+
reveal_type(x) # N: Revealed type is "Union[None, builtins.str]"
632632
if int():
633633
x = ""
634634
reveal_type(x) # N: Revealed type is "Union[None, builtins.str]"
@@ -923,7 +923,7 @@ class X(TypedDict):
923923

924924
x: X
925925
for a in ("hourly", "daily"):
926-
reveal_type(a) # N: Revealed type is "Union[Literal['daily']?, Literal['hourly']?]"
926+
reveal_type(a) # N: Revealed type is "Union[Literal['hourly']?, Literal['daily']?]"
927927
reveal_type(x[a]) # N: Revealed type is "builtins.int"
928928
reveal_type(a.upper()) # N: Revealed type is "builtins.str"
929929
c = a

test-data/unit/check-typevar-tuple.test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -989,7 +989,7 @@ from typing_extensions import Unpack
989989

990990
def pipeline(*xs: Unpack[Tuple[int, Unpack[Tuple[float, ...]], bool]]) -> None:
991991
for x in xs:
992-
reveal_type(x) # N: Revealed type is "Union[builtins.float, builtins.int]"
992+
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.float]"
993993
[builtins fixtures/tuple.pyi]
994994

995995
[case testFixedUnpackItemInInstanceArguments]

test-data/unit/check-union-error-syntax.test

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,17 +62,18 @@ x = 3 # E: Incompatible types in assignment (expression has type "Literal[3]", v
6262
try:
6363
x = 1
6464
x = ""
65+
x = {1: ""}
6566
finally:
66-
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str]"
67+
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str, builtins.dict[builtins.int, builtins.str]]"
6768
[builtins fixtures/isinstancelist.pyi]
6869

6970
[case testOrSyntaxRecombined]
7071
# flags: --python-version 3.10 --no-force-union-syntax --allow-redefinition-new --local-partial-types
7172
# The following revealed type is recombined because the finally body is visited twice.
72-
# ToDo: Improve this recombination logic, especially (but not only) for the "or syntax".
7373
try:
7474
x = 1
7575
x = ""
76+
x = {1: ""}
7677
finally:
77-
reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | builtins.str"
78+
reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | builtins.dict[builtins.int, builtins.str]"
7879
[builtins fixtures/isinstancelist.pyi]

0 commit comments

Comments
 (0)