Skip to content

Commit

Permalink
Don't let TokenError bubble up from lib2to3_parse (GH-2343)
Browse files Browse the repository at this point in the history
error: cannot format <string>: ('EOF in multi-line statement', (2, 0))
   
 ▲ before ▼ after

error: cannot format <string>: Cannot parse: 2:0: EOF in multi-line statement

Co-authored-by: Richard Si <63936253+ichard26@users.noreply.github.com>
  • Loading branch information
tanvimoharir and ichard26 committed Dec 4, 2021
1 parent 136930f commit f52cb0f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Expand Up @@ -19,6 +19,7 @@
- Add `flake8-simplify` and `flake8-comprehensions` plugins (#2653)
- Fix determination of f-string expression spans (#2654)
- Fix parser error location on invalid syntax in a `match` statement (#2649)
- Fix bad formatting of error messages about EOF in multi-line statements (#2343)
- Functions and classes in blocks now have more consistent surrounding spacing (#2472)

## 21.11b1
Expand Down
7 changes: 7 additions & 0 deletions src/black/parsing.py
Expand Up @@ -17,6 +17,7 @@
from blib2to3.pgen2 import driver
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
from blib2to3.pgen2.tokenize import TokenError

from black.mode import TargetVersion, Feature, supports_feature
from black.nodes import syms
Expand Down Expand Up @@ -109,6 +110,12 @@ def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -
except IndexError:
faulty_line = "<line number missing in source>"
exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {faulty_line}")

except TokenError as te:
# In edge cases these are raised; and typically don't have a "faulty_line".
lineno, column = te.args[1]
exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {te.args[0]}")

else:
raise exc from None

Expand Down
9 changes: 9 additions & 0 deletions tests/test_black.py
Expand Up @@ -1557,6 +1557,15 @@ def test_code_option_parent_config(self) -> None:
call_args[0].lower() == str(pyproject_path).lower()
), "Incorrect config loaded."

def test_for_handled_unexpected_eof_error(self) -> None:
"""
Test that an unexpected EOF SyntaxError is nicely presented.
"""
with pytest.raises(black.parsing.InvalidInput) as exc_info:
black.lib2to3_parse("print(", {})

exc_info.match("Cannot parse: 2:0: EOF in multi-line statement")


class TestCaching:
def test_cache_broken_file(self) -> None:
Expand Down

0 comments on commit f52cb0f

Please sign in to comment.