Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bad formatting of error messages about EOF in multi-line statements #2343

Merged
merged 10 commits into from Dec 4, 2021
1 change: 1 addition & 0 deletions CHANGES.md
Expand Up @@ -23,6 +23,7 @@
- Fix regression where `R` prefixes would be lowercased for docstrings (#2285)
- Fix handling of named escapes (`\N{...}`) when `--experimental-string-processing` is
used (#2319)
- Fix bad formatting of error messages about EOF in multi-line statements (#2343)

### Integrations

Expand Down
9 changes: 7 additions & 2 deletions src/black/parsing.py
Expand Up @@ -11,6 +11,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 @@ -84,14 +85,18 @@ def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -
result = drv.parse_string(src_txt, True)
break

except ParseError as pe:
lineno, column = pe.context[1]
except (TokenError, ParseError) as err:
if isinstance(err, ParseError):
lineno, column = err.context[1]
else:
lineno, column = err.args[1]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm trying to understand why i'm getting linenumber value as 2 for token error:

(black) bash-3.2$ python -m src.black --check --code "print("
error: cannot format <string>: Cannot parse: 2:0: <line number missing in source>
(black) bash-3.2$ python -m src.black --check --code "print([)" 
error: cannot format <string>: Cannot parse: 1:7: print([)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeahhh that seems to be a bug with the blib2to3 library. We can just ignore that for this PR, it's better if we can just get this landed so while the error message won't be perfect, it should be better than error: cannot format <string>: ('EOF in multi-line statement', (2, 0)) :)

Although a problem is that the source isn't printed at all which is unfortunate since it would be quite useful. Perhaps it would be good to also include that it was an "unexpected EOF" error in the message?

Good catch tho!

lines = src_txt.splitlines()
try:
faulty_line = lines[lineno - 1]
except IndexError:
faulty_line = "<line number missing in source>"
exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {faulty_line}")

else:
raise exc from None

Expand Down