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
11 changes: 11 additions & 0 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 @@ -92,6 +93,16 @@ 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:
lineno, column = te.args[1]
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}")

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 have tried to keep the format consistent with ParseError above but still need to correct the values for lineno,column and faulty_line (which are currently wrong)

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think we can do without the duplication of code by conditionalizing (made that up right now :p) the lineno. and col. information extraction code. So in the end it would look something like this (warning: untested):

        try:
            result = drv.parse_string(src_txt, True)
            break

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

            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}")

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks I will try this. I had initially thought of making changes here https://github.com/psf/black/blob/main/src/blib2to3/pgen2/tokenize.py#L177

else:
raise exc from None

Expand Down