Skip to content

Commit cf198fc

Browse files
committed
Fix inefficient trimming of comments and white space
@kaimandalic
1 parent ce44e49 commit cf198fc

3 files changed

Lines changed: 11 additions & 4 deletions

File tree

‎docs/src/markdown/about/changelog.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ icon: lucide/scroll-text
99
- **NEW**: Lazy compile selector patterns to improve initial import speed.
1010
- **FIX**: Correct `:nth-child`/`:nth-of-type` (and `-last-` variants) for `An+B` values whose sequence steps onto index 0 or onto the last child (e.g. `:nth-child(2n-2)`, `:nth-child(n-1)`, `:nth-child(n+5)`), which previously matched the wrong elements or nothing at all (@gaoflow).
1111
- **FIX**: More efficient CSS ID matching (@kaimandalic).
12+
- **FIX**: Fix inefficient trimming of comments and white space (@kaimandalic).
1213

1314
## 2.8.4
1415

‎soupsieve/css_parser.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@
112112
NEWLINE = r'(?:\r\n|(?!\r\n)[\n\f\r])'
113113
WS = fr'(?:[ \t]|{NEWLINE})'
114114
# Comments
115-
COMMENTS = r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)'
115+
COMMENTS = r'(?:/\*(?:[^*]|\*(?!/))*\*/)'
116116
# Whitespace with comments included
117117
WSC = fr'(?:{WS}|{COMMENTS})'
118118
# CSS escapes
@@ -183,7 +183,7 @@
183183
# Whitespace checks
184184
RE_WS = re.compile(WS)
185185
RE_WS_BEGIN = re.compile(fr'^{WSC}*')
186-
RE_WS_END = re.compile(fr'{WSC}*$')
186+
RE_WS_END = re.compile(fr'^(?:[ \t]|(?:\n\r|(?!\n\r)[\n\f\r])|{COMMENTS})*')
187187
RE_CUSTOM = re.compile(fr'^{PAT_PSEUDO_CLASS_CUSTOM}$', re.X)
188188
RE_PSEUDO_CLASS_SPECIAL = re.compile(PAT_PSEUDO_CLASS_SPECIAL, re.I | re.X | re.U)
189189

@@ -1321,8 +1321,9 @@ def selector_iter(self, pattern: str) -> Iterator[tuple[str, Match[str]]]:
13211321
# Ignore whitespace and comments at start and end of pattern
13221322
m = RE_WS_BEGIN.search(pattern)
13231323
index = m.end(0) if m else 0
1324-
m = RE_WS_END.search(pattern)
1325-
end = (m.start(0) - 1) if m else (len(pattern) - 1)
1324+
m = RE_WS_END.search(pattern[::-1])
1325+
offset = m.end(0) if m else 0
1326+
end = len(pattern) - (1 + offset)
13261327

13271328
if self.debug: # pragma: no cover
13281329
print(f'## PARSING: {pattern!r}')

‎tests/test_performance.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,8 @@ def test_performance_caase(self):
5454
self.assert_performance("a" * n + "!")
5555

5656
self.assert_performance("[a=" + "a" * 12000)
57+
58+
for n in (2000, 4000, 8000, 16000):
59+
self.assert_performance("a" + " " * n + "b")
60+
61+
self.assert_performance("a" + " " * 20000 + "b")

0 commit comments

Comments
 (0)