From 623e2f6690680a68db01f79a2210eb25cfa932ea Mon Sep 17 00:00:00 2001 From: Sai Asish Y Date: Tue, 12 May 2026 15:29:15 -0700 Subject: [PATCH] fix: report parser errors instead of crashing with IndexError --- CHANGELOG.md | 2 ++ yapf/yapflib/errors.py | 5 +++++ yapftests/yapf_test.py | 6 ++++++ 3 files changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccc8726c9..cbffb9886 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/yapf/yapflib/errors.py b/yapf/yapflib/errors.py index 3a0102368..748c3bda7 100644 --- a/yapf/yapflib/errors.py +++ b/yapf/yapflib/errors.py @@ -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 @@ -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) diff --git a/yapftests/yapf_test.py b/yapftests/yapf_test.py index a9ca01188..177e0460f 100644 --- a/yapftests/yapf_test.py +++ b/yapftests/yapf_test.py @@ -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):