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
5 changes: 5 additions & 0 deletions Lib/fnmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ def _translate(pat, star, question_mark):
star_indices = []

i, n = 0, len(pat)
last_close = pat.rfind(']')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This adds some overhead to the cases where no [ or ']` is involved. Can you benchmark some relevant cases?

while i < n:
c = pat[i]
i = i+1
Expand All @@ -111,6 +112,10 @@ def _translate(pat, star, question_mark):
elif c == '?':
add(question_mark)
elif c == '[':
if i > last_close:
# No ']' after this point: every later '[' is a literal too.
add('\\[')
continue
j = i
if j < n and pat[j] == '!':
j = j+1
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_fnmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,18 @@ def test_translate(self):
self.assertTrue(re.match(fatre, 'cbabcaxc'))
self.assertFalse(re.match(fatre, 'dabccbad'))

def test_translate_unclosed_brackets(self):
# An unclosed '[' is a literal. Many of them used to take quadratic
# time, because each one scanned to the end of the pattern (gh-163137).
self.assertEqual(translate('[!a[b'), r'(?s:\[!a\[b)\z')
self.assertEqual(translate('[a]b[c'), r'(?s:[a]b\[c)\z')
self.assertEqual(translate(']['), r'(?s:\]\[)\z')
self.assertEqual(translate('[!]'), r'(?s:\[!\])\z')
self.assertEqual(translate('a[]b['), r'(?s:a\[\]b\[)\z')
n = 30_000
self.assertEqual(translate('[!' * n), '(?s:' + r'\[!' * n + r')\z')
self.assertTrue(fnmatch('[!' * n, '[!' * n))

def test_translate_wildcards(self):
for pattern, expect in [
('ab*', r'(?s:ab.*)\z'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix quadratic time in :func:`fnmatch.translate` and the functions that use
it, such as :func:`fnmatch.fnmatch`, :func:`glob.translate` and
:meth:`pathlib.PurePath.full_match`, for patterns with many unclosed ``[``.
Patch by Kamal Kumar Modi.
Loading