Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
by taking precedence over SPLIT_BEFORE_NAMED_ASSIGNS.
- Fix SPLIT_ALL_COMMA_SEPARATED_VALUES and SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES
being too agressive for lambdas and unpacking.
- Report parser errors as a `YapfError` with a location instead of crashing with
an unrelated `IndexError`.

## [0.40.2] 2023-09-22
### Changes
Expand Down
5 changes: 5 additions & 0 deletions yapf/yapflib/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.
"""YAPF error objects."""

from yapf_third_party._ylib2to3.pgen2 import parse
from yapf_third_party._ylib2to3.pgen2 import tokenize


Expand All @@ -34,6 +35,10 @@ def FormatErrorMsg(e):
if isinstance(e, tokenize.TokenError):
return '{}:{}:{}: {}'.format(e.filename, e.args[1][0], e.args[1][1],
e.args[0])
if isinstance(e, parse.ParseError):
lineno, column = e.context[1]
return '{}:{}:{}: {}'.format(
getattr(e, 'filename', None), lineno, column, str(e))
return '{}:{}:{}: {}'.format(e.args[1][0], e.args[1][1], e.args[1][2], e.msg)


Expand Down
6 changes: 6 additions & 0 deletions yapftests/yapf_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1565,6 +1565,12 @@ def testBadCode(self):
code = 'x = """hello\n'
self.assertRaises(errors.YapfError, yapf_api.FormatCode, code)

def testParseErrorReportedAsYapfError(self):
code = 'f"{tab["SOME_STRING"]}"\n'
with self.assertRaises(errors.YapfError) as ctx:
yapf_api.FormatCode(code)
self.assertRegex(str(ctx.exception), r':\d+:\d+: ')


class DiffIndentTest(yapf_test_helper.YAPFTest):

Expand Down