Skip to content

bpo-46707: Avoid potential exponential backtracking in some syntax errors #31241

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

Merged
merged 1 commit into from
Feb 10, 2022
Merged
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
4 changes: 3 additions & 1 deletion Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -1095,13 +1095,15 @@ invalid_expression:
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") }
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }

invalid_left_assignment_prefixes(memo): list|tuple|genexp|'True'|'None'|'False'

invalid_named_expression:
| a=expression ':=' expression {
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
a, "cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) }
| a=NAME '=' b=bitwise_or !('='|':=') {
p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?") }
| !(list|tuple|genexp|'True'|'None'|'False') a=bitwise_or b='=' bitwise_or !('='|':=') {
| !invalid_left_assignment_prefixes a=bitwise_or b='=' bitwise_or !('='|':=') {
p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot assign to %s here. Maybe you meant '==' instead of '='?",
_PyPegen_get_expr_name(a)) }

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -1770,6 +1770,14 @@ def test_error_on_parser_stack_overflow(self):
with self.assertRaises(MemoryError):
compile(source, "<string>", mode)

@support.cpython_only
def test_deep_invalid_rule(self):
# Check that a very deep invalid rule in the PEG
# parser doesn't have exponential backtracking.
source = "d{{{{{{{{{{{{{{{{{{{{{{{{{```{{{{{{{ef f():y"
with self.assertRaises(SyntaxError):
compile(source, "<string>", "exec")


def load_tests(loader, tests, pattern):
tests.addTest(doctest.DocTestSuite())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Avoid potential exponential backtracking when producing some syntax errors
involving lots of brackets. Patch by Pablo Galindo.
Loading