gh-93671: Avoid exponential backtracking in deeply nested sequence patterns in match statements by pablogsal · Pull Request #93680 · python/cpython · GitHub
Skip to content
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
6 changes: 3 additions & 3 deletions Grammar/python.gram
21 changes: 21 additions & 0 deletions Lib/test/test_patma.py
Original file line number Diff line number Diff line change
Expand Up @@ -3151,6 +3151,27 @@ def f(command): # 0
self.assertListEqual(self._trace(f, "go x"), [1, 2, 3])
self.assertListEqual(self._trace(f, "spam"), [1, 2, 3])

def test_parser_deeply_nested_patterns(self):
# Deeply nested patterns can cause exponential backtracking when parsing.
# See gh-93671 for more information.

levels = 100

patterns = [
"A" + "(" * levels + ")" * levels,
"{1:" * levels + "1" + "}" * levels,
"[" * levels + "1" + "]" * levels,
]

for pattern in patterns:
with self.subTest(pattern):
code = inspect.cleandoc("""
match None:
case {}:
pass
""".format(pattern))
compile(code, "<string>", "exec")


if __name__ == "__main__":
"""
Expand Down
10 changes: 10 additions & 0 deletions Parser/parser.c

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.