diff --git a/mypy/errors.py b/mypy/errors.py index e95904ce355e0..89e73ae6af587 100644 --- a/mypy/errors.py +++ b/mypy/errors.py @@ -1055,7 +1055,7 @@ def format_messages_default( a.append(s) if self.options.pretty: # Add source code fragment and a location marker. - if severity == "error" and source_lines and line > 0: + if severity == "error" and source_lines and 0 < line <= len(source_lines): source_line = source_lines[line - 1] source_line_expanded = source_line.expandtabs() min_column = len(source_line) - len(source_line.lstrip()) diff --git a/mypy/test/testformatter.py b/mypy/test/testformatter.py index 9f8bb5d824089..e19f2e282a356 100644 --- a/mypy/test/testformatter.py +++ b/mypy/test/testformatter.py @@ -2,10 +2,20 @@ from unittest import TestCase, main +from mypy.errors import Errors +from mypy.options import Options from mypy.util import split_words, trim_source_line class FancyErrorFormattingTestCases(TestCase): + def test_pretty_error_past_end_of_file(self) -> None: + options = Options() + options.pretty = True + errors = Errors(options, read_source=lambda _: ["x = (1,"], hide_error_codes=True) + errors.set_file("main", None, options) + errors.report(2, 1, "Unexpected EOF while parsing") + assert errors.new_messages() == ["main:2: error: Unexpected EOF while parsing"] + def test_trim_source(self) -> None: assert trim_source_line("0123456789abcdef", max_len=16, col=5, min_width=2) == ( "0123456789abcdef",