Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/soupsieve/css_parser.py: 90%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""CSS selector parser."""
2from __future__ import annotations
3import re
4from functools import lru_cache
5from . import util
6from . import css_match as cm
7from . import css_types as ct
8from .util import SelectorSyntaxError
9import warnings
10from typing import Match, Any, Callable, Iterator, Iterable, Mapping, cast
11from dataclasses import dataclass
12from collections import UserDict
13import threading
15__all__ = ('SelectorSyntaxError',)
17RE_LOCK = threading.Lock()
18SEL_LOCK = threading.RLock()
20UNICODE_REPLACEMENT_CHAR = 0xFFFD
22# Non-ASCII identifier code point ranges (inclusive): https://drafts.csswg.org/css-syntax-3/#non-ascii-ident-code-point
23NON_ASCII_IDENT_RANGES = (
24 (0x00B7, 0x00B7),
25 (0x00C0, 0x00D6),
26 (0x00D8, 0x00F6),
27 (0x00F8, 0x037D),
28 (0x037F, 0x1FFF),
29 (0x200C, 0x200D),
30 (0x203F, 0x2040),
31 (0x2070, 0x218F),
32 (0x2C00, 0x2FEF),
33 (0x3001, 0xD7FF),
34 (0xF900, 0xFDCF),
35 (0xFDF0, 0xFFFD),
36 (0x10000, 0x10FFFF)
37)
39SELECTOR_LIMIT = 8192
41# Simple pseudo classes that take no parameters
42PSEUDO_SIMPLE = {
43 ":any-link",
44 ":empty",
45 ":first-child",
46 ":first-of-type",
47 ":in-range",
48 ":open",
49 ":out-of-range",
50 ":last-child",
51 ":last-of-type",
52 ":link",
53 ":only-child",
54 ":only-of-type",
55 ":root",
56 ':checked',
57 ':default',
58 ':disabled',
59 ':enabled',
60 ':indeterminate',
61 ':optional',
62 ':placeholder-shown',
63 ':read-only',
64 ':read-write',
65 ':required',
66 ':scope',
67 ':defined',
68 ':muted'
69}
71# Supported, simple pseudo classes that match nothing in the Soup Sieve environment
72PSEUDO_SIMPLE_NO_MATCH = {
73 ':active',
74 ':autofill',
75 ':buffering',
76 ':current',
77 ':focus',
78 ':focus-visible',
79 ':focus-within',
80 ':fullscreen',
81 ':future',
82 ':host',
83 ':hover',
84 ':local-link',
85 ':past',
86 ':paused',
87 ':picture-in-picture',
88 ':playing',
89 ':popover-open',
90 ':seeking',
91 ':stalled',
92 ':target',
93 ':target-within',
94 ':user-invalid',
95 ':volume-locked',
96 ':visited'
97}
99# Attributes whose values are matched case insensitively on HTML elements in HTML documents
100# https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
101HTML_CASE_INSENSITIVE_ATTRIBUTES = frozenset(
102 (
103 'accept', 'accept-charset', 'align', 'alink', 'axis', 'bgcolor', 'charset', 'checked', 'clear',
104 'codetype', 'color', 'compact', 'declare', 'defer', 'dir', 'direction', 'disabled', 'enctype',
105 'face', 'frame', 'hreflang', 'http-equiv', 'lang', 'language', 'link', 'media', 'method',
106 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap', 'readonly', 'rel', 'rev', 'rules', 'scope',
107 'scrolling', 'selected', 'shape', 'target', 'text', 'type', 'valign', 'valuetype', 'vlink'
108 )
109)
111# Complex pseudo classes that take selector lists
112PSEUDO_COMPLEX = {
113 ':contains',
114 ':-soup-contains',
115 ':-soup-contains-own',
116 ':has',
117 ':is',
118 ':matches',
119 ':not',
120 ':where'
121}
123PSEUDO_COMPLEX_NO_MATCH = {
124 ':current',
125 ':host',
126 ':host-context'
127}
129# Complex pseudo classes that take very specific parameters and are handled special
130PSEUDO_SPECIAL = {
131 ':dir',
132 ':lang',
133 ':nth-child',
134 ':nth-last-child',
135 ':nth-last-of-type',
136 ':nth-of-type'
137}
139PSEUDO_SUPPORTED = PSEUDO_SIMPLE | PSEUDO_SIMPLE_NO_MATCH | PSEUDO_COMPLEX | PSEUDO_COMPLEX_NO_MATCH | PSEUDO_SPECIAL
141# Sub-patterns parts
142# Whitespace
143NEWLINE = r'(?>\r\n|[\n\f\r])'
144WS = fr'(?:[ \t]|{NEWLINE})'
145# Comments
146COMMENTS = r'(?:/\*(?:[^*]|\*(?!/))*+\*/)'
147# Whitespace with comments included
148WSC = fr'(?:{WS}|{COMMENTS})'
149# CSS escapes
150CSS_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}+{WS}?+|[^\r\n\f]|$))'
151CSS_STRING_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}+{WS}?+|{NEWLINE}|[^\r\n\f]|$))'
152# CSS identifier code points (browsers treat all non-ASCII code points as identifier code points)
153IDENT_START = r'[A-Za-z_\x80-\U0010ffff]'
154IDENT_CHAR = r'[-0-9A-Za-z_\x80-\U0010ffff]'
155# CSS Identifier
156IDENTIFIER = fr'''
157(?:(?:--|-?+(?:{IDENT_START}|{CSS_ESCAPES}))
158(?:{IDENT_CHAR}|{CSS_ESCAPES})*+)
159'''
160# `nth` content
161NTH = fr'[-+]?+(?:[0-9]++n?+|n)(?:(?<=n){WSC}*+[-+]{WSC}*+[0-9]++)?+'
162# Value: quoted string or identifier
163VALUE = fr'''
164(?:"(?:\\(?:{NEWLINE}|[^\r\n\f])|[^\\"\r\n\f])*+"|
165'(?:\\(?:{NEWLINE}|[^\r\n\f])|[^\\'\r\n\f])*+'|
166{IDENTIFIER})
167'''
168# Attribute value comparison. `!=` is handled special as it is non-standard.
169ATTR = fr'(?:{WSC}*+(?P<cmp>[!~^|*$]?+=){WSC}*+(?P<value>{VALUE})(?:{WSC}*+(?P<case>[is]))?+)?+'
171# Selector patterns
172# IDs (`#id`)
173PAT_ID = fr'\#{IDENTIFIER}'
174# Classes (`.class`)
175PAT_CLASS = fr'\.{IDENTIFIER}'
176# Prefix:Tag (`prefix|tag`)
177PAT_TAG = fr'(?P<tag_ns>(?:{IDENTIFIER}|\*)?+\|)?+(?P<tag_name>{IDENTIFIER}|\*)'
178# Attributes (`[attr]`, `[attr=value]`, etc.)
179PAT_ATTR = fr'\[{WSC}*+(?P<attr_ns>(?:{IDENTIFIER}|\*)?+\|(?!=))?+(?P<attr_name>{IDENTIFIER}){ATTR}{WSC}*+\]'
180# Pseudo class (`:pseudo-class`, `:pseudo-class(`)
181PAT_PSEUDO_CLASS = fr'(?P<name>:{IDENTIFIER})(?P<open>\({WSC}*+)?+'
182# Pseudo class special patterns. Matches `:pseudo-class(` for special case pseudo classes.
183PAT_PSEUDO_CLASS_SPECIAL = fr'(?P<name>:{IDENTIFIER})(?P<open>\({WSC}*+)'
184# Custom pseudo class (`:--custom-pseudo`)
185PAT_PSEUDO_CLASS_CUSTOM = fr'(?P<name>:(?=--){IDENTIFIER})'
186# Nesting ampersand selector. Matches `&`
187PAT_AMP = r'&'
188# Closing pseudo group (`)`)
189PAT_PSEUDO_CLOSE = fr'{WSC}*+\)'
190# Pseudo element (`::pseudo-element`)
191PAT_PSEUDO_ELEMENT = fr':{PAT_PSEUDO_CLASS}'
192# At rule (`@page`, etc.) (not supported)
193PAT_AT_RULE = fr'@P{IDENTIFIER}'
194# Pseudo class `nth-child` (`:nth-child(an+b [of S]?)`, `:first-child`, etc.)
195PAT_PSEUDO_NTH_CHILD = fr'''
196(?P<pseudo_nth_child>{PAT_PSEUDO_CLASS_SPECIAL}
197(?P<nth_child>{NTH}|even|odd))(?:{WSC}*+\)|(?P<of>{COMMENTS}*+{WS}{WSC}*+of{COMMENTS}*+{WS}{WSC}*+))
198'''
199# Pseudo class `nth-of-type` (`:nth-of-type(an+b)`, `:first-of-type`, etc.)
200PAT_PSEUDO_NTH_TYPE = fr'''
201(?P<pseudo_nth_type>{PAT_PSEUDO_CLASS_SPECIAL}
202(?P<nth_type>{NTH}|even|odd)){WSC}*+\)
203'''
204# Pseudo class language (`:lang("*-de", en)`)
205PAT_PSEUDO_LANG = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P<values>{VALUE}(?:{WSC}*+,{WSC}*+{VALUE})*+){WSC}*+\)'
206# Pseudo class direction (`:dir(ltr)`)
207PAT_PSEUDO_DIR = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P<dir>{IDENTIFIER}){WSC}*+\)'
208# Combining characters (`>`, `~`, ` `, `+`, `,`) along with any comments and whitespace around them.
209# A run of comments and whitespace is matched all at once. `ws` captures whether the run has whitespace
210# before the relation, as a run of only comments does not combine selectors.
211PAT_COMBINE = fr'''
212(?=[,+>~]|{WS}|/\*){COMMENTS}*+(?:(?P<ws>{WS}){WSC}*+)?+(?P<relation>[,+>~])?+{WSC}*+
213'''
214# Extra: Contains (`:contains(text)`)
215PAT_PSEUDO_CONTAINS = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P<values>{VALUE}(?:{WSC}*+,{WSC}*+{VALUE})*+){WSC}*+\)'
217# Regular expressions
218# CSS escape pattern
219RE_CSS_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}+{WSC}?+)|(\\[^\r\n\f])|(\\$))', re.I)
220RE_CSS_STR_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}+{WS}?+)|(\\[^\r\n\f])|(\\$)|(\\{NEWLINE}))', re.I)
221# Pattern to break up `nth` specifiers
222RE_NTH = re.compile(fr'(?P<s1>[-+])?+(?P<a>[0-9]++n?+|n)(?:(?<=n){WSC}*+(?P<s2>[-+]){WSC}*+(?P<b>[0-9]++))?+', re.I)
223# Pattern to iterate multiple values.
224RE_VALUES = re.compile(fr'(?:(?P<value>{VALUE})|(?P<split>{WSC}*+,{WSC}*+))', re.X)
225# Whitespace checks
226RE_WS = re.compile(WS)
227RE_CUSTOM = re.compile(fr'^{PAT_PSEUDO_CLASS_CUSTOM}$', re.X)
228RE_PSEUDO_CLASS_SPECIAL = re.compile(PAT_PSEUDO_CLASS_SPECIAL, re.I | re.X | re.U)
229RE_PSEUDO_IGNORE = re.compile(PAT_PSEUDO_CLASS, re.X | re.I | re.U)
231QUOTED = ("'", '"')
233# Constants
234# List split token
235COMMA_COMBINATOR = ','
236# Relation token for descendant
237WS_COMBINATOR = " "
239# Parse flags
240FLG_PSEUDO = 0x01
241FLG_NOT = 0x02
242FLG_RELATIVE = 0x04
243FLG_DEFAULT = 0x08
244FLG_HTML = 0x10
245FLG_INDETERMINATE = 0x20
246FLG_OPEN = 0x40
247FLG_IN_RANGE = 0x80
248FLG_OUT_OF_RANGE = 0x100
249FLG_PLACEHOLDER_SHOWN = 0x200
250FLG_FORGIVE = 0x400
251FLG_EDITABLE = 0x800
252FLG_CHECKED = 0x1000
254# Maximum cached patterns to store
255_MAXCACHE = 500
258@lru_cache(maxsize=_MAXCACHE)
259def _cached_css_compile(
260 pattern: str,
261 namespaces: ct.Namespaces | None,
262 custom: ct.CustomSelectors | None,
263 ignore: tuple[str] | None = None,
264 flags: int = 0,
265 max_selectors: int = SELECTOR_LIMIT
266) -> cm.SoupSieve:
267 """Cached CSS compile."""
269 return cm.SoupSieve(
270 pattern,
271 CSSParser(
272 pattern,
273 custom=custom,
274 ignore=ignore,
275 flags=flags,
276 max_selectors=max_selectors
277 ).process_selectors(),
278 namespaces,
279 custom,
280 flags
281 )
284def _purge_cache() -> None:
285 """Purge the cache."""
287 _cached_css_compile.cache_clear()
290def css_unescape(content: str) -> str:
291 """
292 Unescape CSS value.
294 Strings allow for spanning the value on multiple strings by escaping a new line.
295 """
297 def replace(m: Match[str]) -> str:
298 """Replace with the appropriate substitute."""
300 if m.group(1):
301 codepoint = int(m.group(1)[1:], 16)
302 # A surrogate, or a value past Unicode, is `U+FFFD`. Zero already is.
303 if (
304 codepoint == 0
305 or codepoint > 0x10FFFF
306 or 0xD800 <= codepoint <= 0xDFFF
307 ):
308 codepoint = UNICODE_REPLACEMENT_CHAR
309 value = chr(codepoint)
310 elif m.group(2):
311 value = m.group(2)[1:]
312 elif m.group(3):
313 value = '\ufffd'
314 else:
315 value = ''
317 return value
319 quoted = content.startswith(QUOTED)
320 return (RE_CSS_STR_ESC if quoted else RE_CSS_ESC).sub(
321 replace,
322 content[1:-1] if quoted else content
323 )
326def escape(ident: str) -> str:
327 """Escape identifier."""
329 string = []
330 length = len(ident)
331 start_dash = length > 0 and ident[0] == '-'
332 if length == 1 and start_dash:
333 # Need to escape identifier that is a single `-` with no other characters
334 string.append(f'\\{ident}')
335 else:
336 for index, c in enumerate(ident):
337 codepoint = ord(c)
338 if codepoint == 0x00:
339 string.append('\ufffd')
340 elif (0x01 <= codepoint <= 0x1F) or codepoint == 0x7F:
341 string.append(f'\\{codepoint:x} ')
342 elif (index == 0 or (start_dash and index == 1)) and (0x30 <= codepoint <= 0x39):
343 string.append(f'\\{codepoint:x} ')
344 elif (
345 codepoint in (0x2D, 0x5F) or (0x30 <= codepoint <= 0x39) or
346 (0x41 <= codepoint <= 0x5A) or (0x61 <= codepoint <= 0x7A) or
347 (codepoint >= 0x80 and any(start <= codepoint <= end for start, end in NON_ASCII_IDENT_RANGES))
348 ):
349 string.append(c)
350 else:
351 string.append(f'\\{c}')
352 return ''.join(string)
355class SelectorPattern:
356 """
357 Selector pattern.
359 Patterns are shared by all parsers, so they must not hold any per-match state.
360 `match` returns the token name along with the match; a name of `None` means the
361 match is consumed without being processed further.
362 """
364 def __init__(self, name: str, pattern: str) -> None:
365 """Initialize."""
367 self.name = name
368 self.pattern = pattern
369 self._re_pattern: re.Pattern[str] | None = None
371 @property
372 def re_pattern(self) -> re.Pattern[str]:
373 """Retrieve the compiled regular expression pattern."""
375 with RE_LOCK:
376 if self._re_pattern is None:
377 self._re_pattern = re.compile(self.pattern, re.I | re.X | re.U)
378 return self._re_pattern
380 def match(self, selector: str, index: int, flags: int) -> tuple[str | None, Match[str]] | None:
381 """Match the selector."""
383 m = self.re_pattern.match(selector, index)
384 return None if m is None else (self.name, m)
387class SelectorPatternCombinator(SelectorPattern):
388 """
389 A run of comments and whitespace might be a combinator or might just be consumed.
391 Process all combinators except whitespace at the start or end, and runs of only comments.
392 """
394 def match(self, selector: str, index: int, flags: int) -> tuple[str | None, Match[str]] | None:
395 """
396 Match the selector.
398 If we match at the start or end of the string and have a non-whitespace combinator, the match is bogus.
399 If we are at the start or end and the combinator is white space, then it can be consumed with no further
400 processing. Comments are not whitespace, so a run of only comments is consumed as well.
401 """
403 m = self.re_pattern.match(selector, index)
404 # An unterminated comment matches nothing, which must not be consumed or the parser would never advance.
405 if m is None or m.end(0) == index:
406 return None
407 relation = m.group('relation')
408 if m.start(0) == 0 or m.end(0) == len(selector):
409 return None if relation else (None, m)
410 return (self.name if relation or m.group('ws') else None), m
413class SpecialPseudoPattern(SelectorPattern):
414 """Selector pattern."""
416 def __init__(self, patterns: tuple[tuple[str, tuple[str, ...], str, type[SelectorPattern]], ...]) -> None:
417 """Initialize."""
419 self.patterns = {}
420 for p in patterns:
421 name = p[0]
422 pattern = p[3](name, p[2])
423 for pseudo in p[1]:
424 self.patterns[pseudo] = pattern
426 def match(self, selector: str, index: int, flags: int) -> tuple[str | None, Match[str]] | None:
427 """Match the selector."""
429 m = RE_PSEUDO_CLASS_SPECIAL.match(selector, index)
430 if m:
431 pattern = self.patterns.get(util.lower(css_unescape(m.group('name'))))
432 if pattern:
433 return pattern.match(selector, index, flags)
434 return None
437class _Selector:
438 """
439 Intermediate selector class.
441 This stores selector data for a compound selector as we are acquiring them.
442 Once we are done collecting the data for a compound selector, we freeze
443 the data in an object that can be pickled and hashed.
444 """
446 def __init__(self, **kwargs: Any) -> None:
447 """Initialize."""
449 self.tag: ct.SelectorTag | None = kwargs.get('tag', None)
450 self.ids: list[str] = kwargs.get('ids', [])
451 self.classes: list[str] = kwargs.get('classes', [])
452 self.attributes: list[ct.SelectorAttribute] = kwargs.get('attributes', [])
453 self.nth: list[ct.SelectorNth] = kwargs.get('nth', [])
454 self.selectors: list[ct.SelectorList] = kwargs.get('selectors', [])
455 self.relations: list[_Selector] = kwargs.get('relations', [])
456 self.rel_type: str | None = kwargs.get('rel_type', None)
457 self.contains: list[ct.SelectorContains] = kwargs.get('contains', [])
458 self.lang: list[ct.SelectorLang] = kwargs.get('lang', [])
459 self.flags: int = kwargs.get('flags', 0)
460 self.no_match: bool = kwargs.get('no_match', False)
462 def _freeze(self, relation: ct.SelectorList) -> ct.Selector | ct.SelectorNull:
463 """Freeze self with an already frozen relation."""
465 if self.no_match:
466 return ct.Null
467 else:
468 return ct.Selector(
469 self.tag,
470 tuple(self.ids),
471 tuple(self.classes),
472 tuple(self.attributes),
473 tuple(self.nth),
474 tuple(self.selectors),
475 relation,
476 self.rel_type,
477 tuple(self.contains),
478 tuple(self.lang),
479 self.flags
480 )
482 def freeze(self) -> ct.Selector | ct.SelectorNull:
483 """
484 Freeze self.
486 Relations form a chain where each selector's first relation is the next link and any
487 remaining relations are carried down to follow it. As the far end of the chain must be
488 frozen first, flatten the chain and then freeze it in reverse to avoid recursion.
489 """
491 chain: list[_Selector] = []
492 pending = [self]
493 while pending:
494 sel = pending.pop()
495 chain.append(sel)
496 if sel.no_match:
497 break
498 pending.extend(reversed(sel.relations))
500 relation = ct.SelectorList()
501 for sel in reversed(chain):
502 frozen = sel._freeze(relation)
503 relation = ct.SelectorList([frozen])
504 return frozen
506 def __str__(self) -> str: # pragma: no cover
507 """String representation."""
509 return (
510 f'_Selector(tag={self.tag!r}, ids={self.ids!r}, classes={self.classes!r}, attributes={self.attributes!r}, '
511 f'nth={self.nth!r}, selectors={self.selectors!r}, relations={self.relations!r}, '
512 f'rel_type={self.rel_type!r}, contains={self.contains!r}, lang={self.lang!r}, flags={self.flags!r}, '
513 f'no_match={self.no_match!r})'
514 )
516 __repr__ = __str__
519class _SelectorContext:
520 """
521 Parsing state for a selector list.
523 Context are created for each nesting level to avoid recursion.
524 """
526 def __init__(
527 self,
528 flags: int,
529 index: int,
530 count: int,
531 on_close: Callable[[ct.SelectorList], None] | None = None
532 ) -> None:
533 """Initialize."""
535 self.sel = _Selector()
536 self.selectors: list[_Selector] = []
537 self.relations: list[_Selector] = []
538 self.has_selector = False
539 self.rel_type = ":" + WS_COMBINATOR
540 self.index = index
541 self.count = count
542 # Receives the frozen selector list when an open pseudo-class is closed.
543 self.on_close = on_close
545 # Setup various flags
546 self.is_open = bool(flags & FLG_OPEN)
547 self.is_pseudo = bool(flags & FLG_PSEUDO)
548 self.is_relative = bool(flags & FLG_RELATIVE)
549 self.is_not = bool(flags & FLG_NOT)
550 self.is_html = bool(flags & FLG_HTML)
551 self.is_default = bool(flags & FLG_DEFAULT)
552 self.is_indeterminate = bool(flags & FLG_INDETERMINATE)
553 self.is_in_range = bool(flags & FLG_IN_RANGE)
554 self.is_out_of_range = bool(flags & FLG_OUT_OF_RANGE)
555 self.is_placeholder_shown = bool(flags & FLG_PLACEHOLDER_SHOWN)
556 self.is_forgive = bool(flags & FLG_FORGIVE)
557 self.is_editable = bool(flags & FLG_EDITABLE)
558 self.is_checked = bool(flags & FLG_CHECKED)
560 # The algorithm for relative selectors require an initial selector in the selector list
561 if self.is_relative:
562 self.selectors.append(_Selector())
564 def debug(self) -> None: # pragma: no cover
565 """Print out useful debug stuff."""
567 for name in (
568 'is_pseudo', 'is_open', 'is_relative', 'is_not', 'is_html', 'is_default', 'is_indeterminate',
569 'is_in_range', 'is_out_of_range', 'is_placeholder_shown', 'is_forgive', 'is_editable', 'is_checked'
570 ):
571 if getattr(self, name):
572 print(f' {name}: True')
575@dataclass
576class CSSPattern:
577 """A CSS pattern that hasn't been processed by `CSSParser` yet."""
579 selector: str
580 flags: int
583class PseudoSelectorMap(UserDict[str, CSSPattern | ct.SelectorList]):
584 """Pseudo selector map."""
586 def __setitem__(self, key: str, value: CSSPattern | ct.SelectorList) -> None:
587 """Set item."""
589 self.data[key] = value
591 def __getitem__(self, key: str) -> ct.SelectorList:
592 """Get item."""
594 with SEL_LOCK:
595 value = self.data[key]
596 if isinstance(value, CSSPattern):
597 value = CSSParser(value.selector).process_selectors(flags=value.flags)
598 self.data[key] = value
600 return value
603# An `input` is in the Text state when its `type` is missing, `text`, or not one of
604# the other keywords, so an invalid value like `type="foo"` is a text input:
605# https://html.spec.whatwg.org/multipage/input.html#attr-input-type
606INPUT_TEXT_STATE = (
607 ':not([type=hidden], [type=search], [type=tel], [type=url], [type=email], [type=password], '
608 '[type=date], [type=month], [type=week], [type=time], [type=datetime-local], [type=number], '
609 '[type=range], [type=color], [type=checkbox], [type=radio], [type=file], [type=submit], '
610 '[type=image], [type=reset], [type=button])'
611)
613# CSS pattern for `:link` and `:any-link`
614CSS_LINK = CSSPattern('html|*:is(a, area)[href]', FLG_PSEUDO | FLG_HTML)
615# CSS pattern for `:checked`
616CSS_CHECKED = CSSPattern(
617 '''
618 html|input[type=checkbox][checked],
620 /*
621 This pattern must be at the end.
622 Special logic is applied to the last selector.
623 */
624 html|*:is(input[type=radio][checked], option)
625 ''',
626 FLG_PSEUDO | FLG_HTML | FLG_CHECKED
627)
628# CSS pattern for `:default`
629CSS_DEFAULT = CSSPattern(
630 '''
631 html|*:is(input[type=checkbox], input[type=radio])[checked],
632 html|option[selected],
634 /*
635 This pattern must be at the end.
636 Special logic is applied to the last selector.
637 */
638 html|*:is(
639 button:is([type=submit], :not([type=button], [type=reset], [commandfor], [command])),
640 input:is([type=submit], [type=image])
641 )
642 ''',
643 FLG_PSEUDO | FLG_HTML | FLG_DEFAULT
644)
645# CSS pattern for `:indeterminate`
646CSS_INDETERMINATE = CSSPattern(
647 '''
648 html|input[type="checkbox"][indeterminate],
649 html|input[type="radio"]:is(:not([name]), [name=""]):not([checked]),
650 html|progress:not([value]),
652 /*
653 This pattern must be at the end.
654 Special logic is applied to the last selector.
655 */
656 html|input[type="radio"][name]:not([name='']):not([checked])
657 ''',
658 FLG_PSEUDO | FLG_HTML | FLG_INDETERMINATE
659)
660# CSS pattern for `:disabled`
661CSS_DISABLED = CSSPattern(
662 '''
663 html|*:is(input, button, select, textarea, fieldset, optgroup, option, fieldset)[disabled],
664 html|optgroup[disabled] > html|option,
665 html|fieldset[disabled] > html|*:is(input, button, select, textarea, fieldset),
666 html|fieldset[disabled] >
667 html|*:not(legend:nth-of-type(1)) html|*:is(input, button, select, textarea, fieldset),
668 html|*:is(
669 html|select[disabled],
670 html|fieldset[disabled] > html|select,
671 html|fieldset[disabled] > html|*:not(legend:nth-of-type(1)) html|select
672 ) html|*:is(optgroup, option)
673 ''',
674 FLG_PSEUDO | FLG_HTML
675)
676# CSS pattern for `:enabled`
677CSS_ENABLED = CSSPattern(
678 '''
679 html|*:is(input, button, select, textarea, fieldset, optgroup, option, fieldset):not(:disabled)
680 ''',
681 FLG_PSEUDO | FLG_HTML
682)
683# CSS pattern for `:required`
684# The `required` attribute does not apply to `input` elements of these types.
685INPUT_REQUIRED_NOT_APPLIES = (
686 '[type=hidden], [type=range], [type=color], [type=submit], [type=image], [type=reset], [type=button]'
687)
688CSS_REQUIRED = CSSPattern(
689 f'''
690 html|input:not({INPUT_REQUIRED_NOT_APPLIES})[required],
691 html|*:is(textarea, select)[required]
692 ''',
693 FLG_PSEUDO | FLG_HTML
694)
695# CSS pattern for `:optional`
696CSS_OPTIONAL = CSSPattern(
697 f'''
698 html|*:is(input, textarea, select):not([required]),
699 html|input:is({INPUT_REQUIRED_NOT_APPLIES})
700 ''',
701 FLG_PSEUDO | FLG_HTML
702)
703# CSS pattern for `:placeholder-shown`
704CSS_PLACEHOLDER_SHOWN = CSSPattern(
705 f'''
706 html|*:is(
707 input:is(
708 {INPUT_TEXT_STATE},
709 [type=search],
710 [type=url],
711 [type=tel],
712 [type=email],
713 [type=password],
714 [type=number]
715 ),
716 textarea
717 )[placeholder]:not([placeholder=''])
718 ''',
719 FLG_PSEUDO | FLG_HTML | FLG_PLACEHOLDER_SHOWN
720)
721# CSS pattern for `:read-write` (CSS_DISABLED must be compiled first)
722CSS_READ_WRITE = CSSPattern(
723 f'''
724 html|*:is(
725 textarea,
726 input:is(
727 {INPUT_TEXT_STATE},
728 [type=search],
729 [type=url],
730 [type=tel],
731 [type=email],
732 [type=number],
733 [type=password],
734 [type=date],
735 [type=datetime-local],
736 [type=month],
737 [type=time],
738 [type=week]
739 )
740 ):not([readonly], :disabled),
741 html|*:not(input, textarea, [contenteditable="false" i])
742 ''',
743 FLG_PSEUDO | FLG_HTML | FLG_EDITABLE
744)
745# CSS pattern for `:read-only`
746CSS_READ_ONLY = CSSPattern('html|*:not(:read-write)', FLG_PSEUDO | FLG_HTML)
747# `:in-range` and `:out-of-range` only consider an input that has range limitations and is a candidate
748# for constraint validation. See `CSSMatch.match_range()` for the full rules and where they follow
749# browsers instead of the letter of the HTML spec.
750#
751# - A `range` input always has range limitations: its minimum and maximum default to 0 and 100.
752# The other types need a `min` or `max`; `match_range()` rejects one that does not parse.
753# - An input that is disabled (including through a disabled `fieldset`, outside its first `legend`),
754# `readonly`, or inside a `datalist` is barred from constraint validation and matches neither.
755# The spec says `readonly` does not apply to `range` and so does not bar it, but all browsers
756# treat a `readonly` `range` input as barred, so we do too.
757RANGE_INPUT = """
758 html|input:is(
759 :is(
760 [type="date"],
761 [type="month"],
762 [type="week"],
763 [type="time"],
764 [type="datetime-local"],
765 [type="number"]
766 ):is(
767 [min],
768 [max]
769 ),
770 [type="range"]
771 ):not(:disabled, [readonly], html|datalist html|*)
772"""
773# CSS pattern for `:in-range`
774CSS_IN_RANGE = CSSPattern(RANGE_INPUT, FLG_PSEUDO | FLG_HTML | FLG_IN_RANGE)
775# CSS pattern for `:out-of-range`
776CSS_OUT_OF_RANGE = CSSPattern(RANGE_INPUT, FLG_PSEUDO | FLG_HTML | FLG_OUT_OF_RANGE)
777# CSS pattern for :open
778CSS_OPEN = CSSPattern('html|*:is(details, dialog)[open]', FLG_PSEUDO | FLG_HTML)
779# CSS pattern for :muted
780CSS_MUTED = CSSPattern('html|*:is(video, audio)[muted]', FLG_PSEUDO | FLG_HTML)
781# CSS pattern default for `:nth-child` "of S" feature
782CSS_NTH_OF_S_DEFAULT = CSSPattern("*|*", FLG_PSEUDO)
785class CSSParser:
786 """Parse CSS selectors."""
788 CSS_TOKENS = (
789 SelectorPattern("pseudo_close", PAT_PSEUDO_CLOSE),
790 SpecialPseudoPattern(
791 (
792 (
793 "pseudo_contains",
794 (':contains', ':-soup-contains', ':-soup-contains-own'),
795 PAT_PSEUDO_CONTAINS,
796 SelectorPattern
797 ),
798 ("pseudo_nth_child", (':nth-child', ':nth-last-child'), PAT_PSEUDO_NTH_CHILD, SelectorPattern),
799 ("pseudo_nth_type", (':nth-of-type', ':nth-last-of-type'), PAT_PSEUDO_NTH_TYPE, SelectorPattern),
800 ("pseudo_lang", (':lang',), PAT_PSEUDO_LANG, SelectorPattern),
801 ("pseudo_dir", (':dir',), PAT_PSEUDO_DIR, SelectorPattern)
802 )
803 ),
804 SelectorPattern("pseudo_class_custom", PAT_PSEUDO_CLASS_CUSTOM),
805 SelectorPattern("pseudo_class", PAT_PSEUDO_CLASS),
806 SelectorPattern("pseudo_element", PAT_PSEUDO_ELEMENT),
807 SelectorPattern("amp", PAT_AMP),
808 SelectorPattern("at_rule", PAT_AT_RULE),
809 SelectorPattern("id", PAT_ID),
810 SelectorPattern("class", PAT_CLASS),
811 SelectorPattern("tag", PAT_TAG),
812 SelectorPattern("attribute", PAT_ATTR),
813 SelectorPatternCombinator("combine", PAT_COMBINE)
814 )
816 # Pseudos that expand to selectors
817 PSEUDO_SELECTORS = PseudoSelectorMap(
818 {
819 ':link': CSS_LINK,
820 ':any-link': CSS_LINK,
821 ':checked': CSS_CHECKED,
822 ':default': CSS_DEFAULT,
823 ':indeterminate': CSS_INDETERMINATE,
824 ':disabled': CSS_DISABLED,
825 ':enabled': CSS_ENABLED,
826 ':required': CSS_REQUIRED,
827 ':muted': CSS_MUTED,
828 ':open': CSS_OPEN,
829 ':optional': CSS_OPTIONAL,
830 ':read-only': CSS_READ_ONLY,
831 ':read-write': CSS_READ_WRITE,
832 ':in-range': CSS_IN_RANGE,
833 ':out-of-range': CSS_OUT_OF_RANGE,
834 ':placeholder-shown': CSS_PLACEHOLDER_SHOWN,
835 '<nth-of-s>': CSS_NTH_OF_S_DEFAULT
836 }
837 )
839 def __init__(
840 self,
841 selector: str,
842 *,
843 custom: Mapping[str, ct.SelectorList] | None = None,
844 ignore: Iterable[str] | None = None,
845 flags: int = 0,
846 max_selectors: int = SELECTOR_LIMIT
847 ) -> None:
848 """Initialize."""
850 self.pattern = selector.replace('\x00', '\ufffd')
851 self.flags = flags
852 self.debug = self.flags & util.DEBUG
853 self.nostrict = self.flags & util.NOSTRICT
854 self.custom = custom
855 # Names are compared as the parser recognizes pseudo-classes: with CSS escapes resolved and ASCII letters in
856 # lowercase. Otherwise, writing a name with an escape, such as `:h\61 s()`, would get past it.
857 self.ignore = frozenset([] if ignore is None else (util.lower(css_unescape(name)) for name in ignore))
858 self.count = 0
859 self.maxsel = max_selectors
861 def increment_count(self, increment: int = 1) -> None:
862 """Check the current selector count."""
864 self.count += increment
865 if self.count > self.maxsel:
866 raise ValueError(f'Selector exceeds pseudo-class nesting limit of {self.maxsel}')
868 def parse_attribute_selector(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
869 """Create attribute selector from the returned regex match."""
871 op = m.group('cmp')
872 case = util.lower(m.group('case')) if m.group('case') else None
873 ns = css_unescape(m.group('attr_ns')[:-1]) if m.group('attr_ns') else ''
874 attr = css_unescape(m.group('attr_name'))
875 html_insensitive = False
876 pattern = None
877 pattern2 = None
878 inverse = False
880 if case:
881 ignore_case = case == 'i'
882 elif util.lower(attr) in HTML_CASE_INSENSITIVE_ATTRIBUTES:
883 ignore_case = True
884 html_insensitive = True
885 else:
886 ignore_case = False
888 if op:
889 value = css_unescape(m.group('value'))
890 pattern = self.parse_attribute_pattern(op, util.lower(value) if ignore_case else value)
891 if html_insensitive:
892 # Outside HTML, the value is matched case sensitive.
893 pattern2 = self.parse_attribute_pattern(op, value)
894 inverse = op.startswith('!')
896 # Append the attribute selector
897 sel_attr = ct.SelectorAttribute(attr, ns, pattern, pattern2, inverse, ignore_case)
898 sel.attributes.append(sel_attr)
900 has_selector = True
901 return has_selector
903 @staticmethod
904 def parse_attribute_pattern(op: str, value: str) -> re.Pattern[str]:
905 """
906 Create the pattern for an attribute selector's value.
908 The pattern is applied with `search()`, so it must not need a leading `.*?` to find the value, which would make
909 the regular expression engine retry the value at every position instead of scanning for it as a literal.
911 A case insensitive pattern is compiled case sensitive for the value converted to ASCII lowercase and is matched
912 against the attribute value converted the same way. We purposely avoid using `re.I` as the regular expression
913 engine cannot then scan as a literal, making the search take quadratic time depending on the pattern.
914 """
916 if op.startswith('^'):
917 # Value start with
918 # `^=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
919 source = r'^(?!)' if not value else fr'^{re.escape(value)}'
920 elif op.startswith('$'):
921 # Value ends with
922 # `$=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
923 source = r'(?!)' if not value else fr'{re.escape(value)}\Z'
924 elif op.startswith('*'):
925 # Value contains
926 # `*=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
927 source = r'(?!)' if not value else re.escape(value)
928 elif op.startswith('~'):
929 # Value contains word within space separated list
930 # `~=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
931 value = r'(?!)' if not value or RE_WS.search(value) else re.escape(value)
932 source = fr'(?:(?<=^)|(?<=[ \t\r\n\f])){value}(?=(?:[ \t\r\n\f]|\Z))'
933 elif op.startswith('|'):
934 # Value starts with word in dash separated list
935 source = fr'^{re.escape(value)}(?:-.*)?\Z'
936 elif op.startswith('!'):
937 # Value does not matches
938 source = fr'^(?!{re.escape(value)}\Z)'
939 else:
940 # Value matches
941 source = fr'^{re.escape(value)}\Z'
942 return re.compile(source, re.DOTALL)
944 def parse_tag_pattern(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
945 """Parse tag pattern from regex match."""
947 prefix = css_unescape(m.group('tag_ns')[:-1]) if m.group('tag_ns') else None
948 tag = css_unescape(m.group('tag_name'))
949 sel.tag = ct.SelectorTag(tag, prefix)
950 has_selector = True
951 return has_selector
953 def parse_pseudo_class_custom(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
954 """
955 Parse custom pseudo class alias.
957 Compile custom selectors as we need them. When compiling a custom selector,
958 set it to `None` in the dictionary so we can avoid an infinite loop.
959 """
961 pseudo = util.lower(css_unescape(m.group('name')))
962 selector = self.custom.get(pseudo) if self.custom is not None else None
963 if selector is None:
964 raise SelectorSyntaxError(
965 f"Undefined custom selector '{pseudo}' found at position {m.end(0)}",
966 self.pattern,
967 m.end(0)
968 )
970 self.increment_count(selector.count)
971 sel.selectors.append(selector)
972 has_selector = True
973 return has_selector
975 def parse_pseudo_class(
976 self,
977 sel: _Selector,
978 m: Match[str],
979 has_selector: bool,
980 is_relative: bool
981 ) -> tuple[bool, _SelectorContext | None]:
982 """
983 Parse pseudo class.
985 If the pseudo-class opens a selector list, a new context is returned to parse its contents.
986 """
988 context = None
989 complex_pseudo = False
990 pseudo = util.lower(css_unescape(m.group('name')))
991 if m.group('open'):
992 complex_pseudo = True
993 if complex_pseudo and pseudo in PSEUDO_COMPLEX:
994 context = self.parse_pseudo_open(pseudo, m.end(0), sel.selectors.append, is_relative)
995 has_selector = True
996 elif not complex_pseudo and pseudo in PSEUDO_SIMPLE:
997 if pseudo == ':root':
998 sel.flags |= ct.SEL_ROOT
999 elif pseudo == ':defined':
1000 sel.flags |= ct.SEL_DEFINED
1001 elif pseudo == ':scope':
1002 sel.flags |= ct.SEL_SCOPE
1003 elif pseudo == ':empty':
1004 sel.flags |= ct.SEL_EMPTY
1005 elif pseudo in self.PSEUDO_SELECTORS:
1006 pseudo_selector = self.PSEUDO_SELECTORS[pseudo]
1007 self.increment_count(pseudo_selector.count)
1008 sel.selectors.append(pseudo_selector)
1009 elif pseudo == ':first-child':
1010 sel.nth.append(ct.SelectorNth(0, False, 1, False, False, ct.SelectorList()))
1011 elif pseudo == ':last-child':
1012 sel.nth.append(ct.SelectorNth(0, False, 1, False, True, ct.SelectorList()))
1013 elif pseudo == ':first-of-type':
1014 sel.nth.append(ct.SelectorNth(0, False, 1, True, False, ct.SelectorList()))
1015 elif pseudo == ':last-of-type':
1016 sel.nth.append(ct.SelectorNth(0, False, 1, True, True, ct.SelectorList()))
1017 elif pseudo == ':only-child':
1018 sel.nth.extend(
1019 [
1020 ct.SelectorNth(0, False, 1, False, False, ct.SelectorList()),
1021 ct.SelectorNth(0, False, 1, False, True, ct.SelectorList())
1022 ]
1023 )
1024 elif pseudo == ':only-of-type':
1025 sel.nth.extend(
1026 [
1027 ct.SelectorNth(0, False, 1, True, False, ct.SelectorList()),
1028 ct.SelectorNth(0, False, 1, True, True, ct.SelectorList())
1029 ]
1030 )
1031 has_selector = True
1032 elif complex_pseudo and pseudo in PSEUDO_COMPLEX_NO_MATCH:
1033 context = self.parse_pseudo_open(pseudo, m.end(0))
1034 sel.no_match = True
1035 has_selector = True
1036 elif not complex_pseudo and pseudo in PSEUDO_SIMPLE_NO_MATCH:
1037 sel.no_match = True
1038 has_selector = True
1039 elif pseudo in PSEUDO_SUPPORTED:
1040 raise SelectorSyntaxError(
1041 f"Invalid syntax for pseudo class '{pseudo}'",
1042 self.pattern,
1043 m.start(0)
1044 )
1045 else:
1046 raise SelectorSyntaxError(
1047 f"'{pseudo}' was detected as a pseudo-class and is either unsupported or invalid. "
1048 "If the syntax was not intended to be recognized as a pseudo-class, please escape the colon.",
1049 self.pattern,
1050 m.start(0)
1051 )
1053 return has_selector, context
1055 def parse_pseudo_nth(
1056 self,
1057 sel: _Selector,
1058 m: Match[str],
1059 has_selector: bool
1060 ) -> tuple[bool, _SelectorContext | None]:
1061 """
1062 Parse `nth` pseudo.
1064 If `of S` is specified, a new context is returned to parse `S`.
1065 """
1067 context = None
1068 mdict = m.groupdict()
1069 if mdict.get('pseudo_nth_child'):
1070 postfix = '_child'
1071 else:
1072 postfix = '_type'
1073 mdict['name'] = util.lower(css_unescape(mdict['name']))
1074 content = util.lower(mdict.get('nth' + postfix))
1075 if content == 'even':
1076 # 2n
1077 s1 = 2
1078 s2 = 0
1079 var = True
1080 elif content == 'odd':
1081 # 2n+1
1082 s1 = 2
1083 s2 = 1
1084 var = True
1085 else:
1086 nth_parts = cast(Match[str], RE_NTH.match(content))
1087 _s1 = '-' if nth_parts.group('s1') and nth_parts.group('s1') == '-' else ''
1088 _s2 = ''
1089 a = nth_parts.group('a')
1090 var = a.endswith('n')
1091 if a.startswith('n'):
1092 _s1 += '1'
1093 elif var:
1094 _s1 += a[:-1]
1095 else:
1096 _s2 = _s1 + a
1097 _s1 = ''
1098 if nth_parts.group('s2') and nth_parts.group('s2') == '-':
1099 _s2 = '-'
1100 if nth_parts.group('b'):
1101 _s2 += nth_parts.group('b')
1102 try:
1103 s1 = int(_s1, 10) if _s1 else 0
1104 s2 = int(_s2, 10) if _s2 else 0
1105 except ValueError as e:
1106 # `int()` refuses strings with more digits than `sys.get_int_max_str_digits()`.
1107 raise SelectorSyntaxError(
1108 f"Value in '{mdict['name']}' is too large",
1109 self.pattern,
1110 m.start(0)
1111 ) from e
1113 pseudo_sel = mdict['name']
1114 if postfix == '_child':
1115 last = pseudo_sel == ':nth-last-child'
1117 def append_nth(nth_sel: ct.SelectorList) -> None:
1118 """Append to this selector's `nth` attribute."""
1120 sel.nth.append(ct.SelectorNth(s1, var, s2, False, last, nth_sel))
1122 if m.group('of'):
1123 # Parse the rest of `of S`.
1124 context = self.parse_pseudo_open(pseudo_sel, m.end(0), append_nth)
1125 else:
1126 # Use default `*|*` for `of S`.
1127 nth_sel = self.PSEUDO_SELECTORS['<nth-of-s>']
1128 self.increment_count(nth_sel.count)
1129 append_nth(nth_sel)
1130 else:
1131 if pseudo_sel == ':nth-of-type':
1132 sel.nth.append(ct.SelectorNth(s1, var, s2, True, False, ct.SelectorList()))
1133 elif pseudo_sel == ':nth-last-of-type':
1134 sel.nth.append(ct.SelectorNth(s1, var, s2, True, True, ct.SelectorList()))
1135 has_selector = True
1136 return has_selector, context
1138 def parse_pseudo_open(
1139 self,
1140 name: str,
1141 index: int,
1142 on_close: Callable[[ct.SelectorList], None] | None = None,
1143 is_relative: bool = False
1144 ) -> _SelectorContext:
1145 """Create a new context for nested pseudo-class selectors."""
1147 flags = FLG_PSEUDO | FLG_OPEN
1148 if name == ':not':
1149 flags |= FLG_NOT
1150 elif name == ':has':
1151 if is_relative and not self.nostrict:
1152 raise SelectorSyntaxError(
1153 f":has() was found to be nested under :has() at position {index}",
1154 self.pattern,
1155 index
1156 )
1157 flags |= FLG_RELATIVE
1158 elif name in (':where', ':is'):
1159 flags |= FLG_FORGIVE
1161 return self.create_context(flags, index, on_close)
1163 def create_context(
1164 self,
1165 flags: int,
1166 index: int,
1167 on_close: Callable[[ct.SelectorList], None] | None = None
1168 ) -> _SelectorContext:
1169 """Create a new selector context."""
1171 context = _SelectorContext(flags, index, self.count, on_close)
1172 if self.debug: # pragma: no cover
1173 context.debug()
1174 return context
1176 def parse_has_combinator(
1177 self,
1178 sel: _Selector,
1179 m: Match[str],
1180 has_selector: bool,
1181 selectors: list[_Selector],
1182 rel_type: str,
1183 index: int
1184 ) -> tuple[bool, _Selector, str]:
1185 """Parse combinator tokens."""
1187 combinator = m.group('relation')
1188 if not combinator:
1189 combinator = WS_COMBINATOR
1190 if combinator == COMMA_COMBINATOR:
1191 if not has_selector:
1192 raise SelectorSyntaxError(
1193 f"The combinator '{combinator}' at position {index}, must have a selector before it",
1194 self.pattern,
1195 index
1196 )
1197 sel.rel_type = rel_type
1198 selectors[-1].relations.append(sel)
1199 rel_type = ":" + WS_COMBINATOR
1200 selectors.append(_Selector())
1201 else:
1202 if has_selector and self.nostrict:
1203 # End the current selector and associate the leading combinator with this selector.
1204 sel.rel_type = rel_type
1205 selectors[-1].relations.append(sel)
1206 elif has_selector:
1207 raise SelectorSyntaxError(
1208 f'Using strict rules as proposed by CSS, the complex selectors at postition {index} is not allowed',
1209 self.pattern,
1210 index
1211 )
1212 elif rel_type[1:] != WS_COMBINATOR:
1213 # It's impossible to have two whitespace combinators after each other as the patterns
1214 # will gobble up trailing whitespace. It is also impossible to have a whitespace
1215 # combinator after any other kind for the same reason. But we could have
1216 # multiple non-whitespace combinators. So if the current combinator is not a whitespace,
1217 # then we've hit the multiple combinator case, so we should fail.
1218 raise SelectorSyntaxError(
1219 f'The multiple combinators at position {index}',
1220 self.pattern,
1221 index
1222 )
1224 # Set the leading combinator for the next selector.
1225 rel_type = ':' + combinator
1227 sel = _Selector()
1228 has_selector = False
1229 return has_selector, sel, rel_type
1231 def parse_combinator(
1232 self,
1233 sel: _Selector,
1234 m: Match[str],
1235 has_selector: bool,
1236 selectors: list[_Selector],
1237 relations: list[_Selector],
1238 is_pseudo: bool,
1239 is_forgive: bool,
1240 index: int
1241 ) -> tuple[bool, _Selector]:
1242 """Parse combinator tokens."""
1244 combinator = m.group('relation')
1245 if not combinator:
1246 combinator = WS_COMBINATOR
1247 if not has_selector:
1248 if not is_forgive or combinator != COMMA_COMBINATOR:
1249 raise SelectorSyntaxError(
1250 f"The combinator '{combinator}' at position {index}, must have a selector before it",
1251 self.pattern,
1252 index
1253 )
1255 # If we are in a forgiving pseudo class, just make the selector a "no match"
1256 if combinator == COMMA_COMBINATOR:
1257 self.increment_count()
1258 del relations[:]
1259 else:
1260 if combinator == COMMA_COMBINATOR:
1261 if not sel.tag and not is_pseudo:
1262 # Implied `*`
1263 sel.tag = ct.SelectorTag('*', None)
1264 sel.relations.extend(relations)
1265 selectors.append(sel)
1266 del relations[:]
1267 else:
1268 sel.relations.extend(relations)
1269 sel.rel_type = combinator
1270 del relations[:]
1271 relations.append(sel)
1273 sel = _Selector()
1274 has_selector = False
1276 return has_selector, sel
1278 def parse_class_id(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1279 """Parse HTML classes and ids."""
1281 selector = m.group(0)
1282 if selector.startswith('.'):
1283 sel.classes.append(css_unescape(selector[1:]))
1284 else:
1285 sel.ids.append(css_unescape(selector[1:]))
1286 has_selector = True
1287 return has_selector
1289 def parse_pseudo_contains(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1290 """Parse contains."""
1292 pseudo = util.lower(css_unescape(m.group('name')))
1293 if pseudo == ":contains":
1294 warnings.warn( # noqa: B028
1295 "The pseudo class ':contains' is deprecated, ':-soup-contains' should be used moving forward.",
1296 FutureWarning
1297 )
1298 contains_own = pseudo == ":-soup-contains-own"
1299 patterns = [
1300 css_unescape(token.group('value'))
1301 for token in RE_VALUES.finditer(m.group('values'))
1302 if not token.group('split')
1303 ]
1304 sel.contains.append(ct.SelectorContains(patterns, contains_own))
1305 has_selector = True
1306 return has_selector
1308 def parse_pseudo_lang(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1309 """Parse pseudo language."""
1311 patterns = [
1312 css_unescape(token.group('value'))
1313 for token in RE_VALUES.finditer(m.group('values'))
1314 if not token.group('split')
1315 ]
1316 sel.lang.append(ct.SelectorLang(patterns))
1317 has_selector = True
1319 return has_selector
1321 def parse_pseudo_dir(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1322 """Parse pseudo direction."""
1324 value = util.lower(css_unescape(m.group('dir')))
1325 if value == 'ltr':
1326 sel.flags |= ct.SEL_DIR_LTR
1327 elif value == 'rtl':
1328 sel.flags |= ct.SEL_DIR_RTL
1329 else:
1330 # Any other identifier is valid, but does not match anything.
1331 sel.no_match = True
1332 has_selector = True
1333 return has_selector
1335 def parse_selectors(
1336 self,
1337 iselector: Iterator[tuple[str, Match[str]]],
1338 index: int = 0,
1339 flags: int = 0
1340 ) -> ct.SelectorList:
1341 """
1342 Parse selectors.
1344 Pseudo-classes that open a nested selector list push a new context onto a stack,
1345 and closing them pops back to the parent context, so nesting does not recurse.
1346 """
1348 ctx = self.create_context(flags, index)
1349 stack: list[_SelectorContext] = []
1351 for key, m in iselector:
1352 child: _SelectorContext | None = None
1354 if key not in ('combine', 'pseudo_close'):
1355 self.increment_count()
1357 # Handle parts
1358 if self.ignore:
1359 mi = RE_PSEUDO_IGNORE.match(m.group(0))
1360 if mi is not None and util.lower(css_unescape(mi.group('name'))) in self.ignore:
1361 raise SelectorSyntaxError(
1362 f"The selector '{mi.group('name')}' at position {m.start(0)}, has been disallowed",
1363 self.pattern,
1364 m.start(0)
1365 )
1366 if key == "at_rule":
1367 raise NotImplementedError(f"At-rules found at position {m.start(0)}")
1368 elif key == "amp":
1369 ctx.sel.flags |= ct.SEL_SCOPE
1370 ctx.has_selector = True
1371 elif key == 'pseudo_class_custom':
1372 ctx.has_selector = self.parse_pseudo_class_custom(ctx.sel, m, ctx.has_selector)
1373 elif key == 'pseudo_class':
1374 ctx.has_selector, child = self.parse_pseudo_class(ctx.sel, m, ctx.has_selector, ctx.is_relative)
1375 elif key == 'pseudo_element':
1376 raise NotImplementedError(f"Pseudo-element found at position {m.start(0)}")
1377 elif key == 'pseudo_contains':
1378 ctx.has_selector = self.parse_pseudo_contains(ctx.sel, m, ctx.has_selector)
1379 elif key in ('pseudo_nth_type', 'pseudo_nth_child'):
1380 ctx.has_selector, child = self.parse_pseudo_nth(ctx.sel, m, ctx.has_selector)
1381 elif key == 'pseudo_lang':
1382 ctx.has_selector = self.parse_pseudo_lang(ctx.sel, m, ctx.has_selector)
1383 elif key == 'pseudo_dir':
1384 ctx.has_selector = self.parse_pseudo_dir(ctx.sel, m, ctx.has_selector)
1385 elif key == 'pseudo_close':
1386 if not ctx.has_selector:
1387 if not ctx.is_forgive:
1388 raise SelectorSyntaxError(
1389 f"Expected a selector at position {m.start(0)}",
1390 self.pattern,
1391 m.start(0)
1392 )
1393 ctx.sel.no_match = True
1394 if not ctx.is_open:
1395 raise SelectorSyntaxError(
1396 f"Unmatched pseudo-class close at position {m.start(0)}",
1397 self.pattern,
1398 m.start(0)
1399 )
1401 # Hand the completed selector list to the parent and resume parsing the parent.
1402 selectors = self.finalize_selectors(ctx)
1403 if ctx.on_close is not None:
1404 ctx.on_close(selectors)
1405 ctx = stack.pop()
1406 continue
1407 elif key == 'combine':
1408 if ctx.is_relative:
1409 ctx.has_selector, ctx.sel, ctx.rel_type = self.parse_has_combinator(
1410 ctx.sel, m, ctx.has_selector, ctx.selectors, ctx.rel_type, ctx.index
1411 )
1412 else:
1413 ctx.has_selector, ctx.sel = self.parse_combinator(
1414 ctx.sel, m, ctx.has_selector, ctx.selectors, ctx.relations,
1415 ctx.is_pseudo, ctx.is_forgive, ctx.index
1416 )
1417 elif key == 'attribute':
1418 ctx.has_selector = self.parse_attribute_selector(ctx.sel, m, ctx.has_selector)
1419 elif key == 'tag':
1420 if ctx.has_selector:
1421 raise SelectorSyntaxError(
1422 f"Tag name found at position {m.start(0)} instead of at the start",
1423 self.pattern,
1424 m.start(0)
1425 )
1426 ctx.has_selector = self.parse_tag_pattern(ctx.sel, m, ctx.has_selector)
1427 elif key in ('class', 'id'):
1428 ctx.has_selector = self.parse_class_id(ctx.sel, m, ctx.has_selector)
1430 ctx.index = m.end(0)
1432 # A pseudo-class opened a nested selector list, parse it before resuming this one.
1433 if child is not None:
1434 stack.append(ctx)
1435 ctx = child
1437 # Handle selectors that are not closed
1438 if ctx.is_open:
1439 raise SelectorSyntaxError(
1440 f"Unclosed pseudo-class at position {ctx.index}",
1441 self.pattern,
1442 ctx.index
1443 )
1445 return self.finalize_selectors(ctx)
1447 def finalize_selectors(self, ctx: _SelectorContext) -> ct.SelectorList:
1448 """Complete the selector list of a context and freeze it."""
1450 sel = ctx.sel
1451 selectors = ctx.selectors
1452 relations = ctx.relations
1453 has_selector = ctx.has_selector
1455 # Cleanup completed selector piece
1456 if has_selector:
1457 if not sel.tag and not ctx.is_pseudo:
1458 # Implied `*`
1459 sel.tag = ct.SelectorTag('*', None)
1460 if ctx.is_relative:
1461 sel.rel_type = ctx.rel_type
1462 selectors[-1].relations.append(sel)
1463 else:
1464 sel.relations.extend(relations)
1465 del relations[:]
1466 selectors.append(sel)
1468 # Forgive empty slots in pseudo-classes that have lists (and are forgiving)
1469 elif ctx.is_forgive and (not selectors or not relations):
1470 # Handle normal pseudo-classes with empty slots like `:is()` etc.
1471 self.increment_count()
1472 sel.no_match = True
1473 del relations[:]
1474 selectors.append(sel)
1475 has_selector = True
1477 if not has_selector:
1478 # We will always need to finish a selector when `:has()` is used as it leads with combining.
1479 # May apply to others as well.
1480 raise SelectorSyntaxError(
1481 f'Expected a selector at position {ctx.index}',
1482 self.pattern,
1483 ctx.index
1484 )
1486 # Some patterns require additional logic, such as default. We try to make these the
1487 # last pattern, and append the appropriate flag to that selector which communicates
1488 # to the matcher what additional logic is required.
1489 if ctx.is_default:
1490 selectors[-1].flags = ct.SEL_DEFAULT
1491 if ctx.is_indeterminate:
1492 selectors[-1].flags = ct.SEL_INDETERMINATE
1493 if ctx.is_in_range:
1494 selectors[-1].flags = ct.SEL_IN_RANGE
1495 if ctx.is_out_of_range:
1496 selectors[-1].flags = ct.SEL_OUT_OF_RANGE
1497 if ctx.is_placeholder_shown:
1498 selectors[-1].flags = ct.SEL_PLACEHOLDER_SHOWN
1499 if ctx.is_editable:
1500 selectors[-1].flags = ct.SEL_EDITABLE
1501 if ctx.is_checked:
1502 selectors[-1].flags = ct.SEL_CHECKED
1504 # Return selector list
1505 return ct.SelectorList([s.freeze() for s in selectors], ctx.is_not, ctx.is_html, self.count - ctx.count)
1507 def selector_iter(self, pattern: str) -> Iterator[tuple[str, Match[str]]]:
1508 """Iterate selector tokens."""
1510 index = 0
1511 end = len(pattern) - 1
1513 if self.debug: # pragma: no cover
1514 print(f'## PARSING: {pattern!r}')
1515 while index <= end:
1516 token = None
1517 for v in self.CSS_TOKENS:
1518 token = v.match(pattern, index, self.flags)
1519 if token is not None:
1520 name, m = token
1521 if self.debug: # pragma: no cover
1522 print(f"TOKEN: '{name or 'consumed'}' --> {m.group(0)!r} at position {m.start(0)}")
1523 index = m.end(0)
1524 if name is not None:
1525 yield name, m
1526 break
1527 if token is None:
1528 c = pattern[index]
1529 # If the character represents the start of one of the known selector types,
1530 # throw an exception mentioning that the known selector type is in error;
1531 # otherwise, report the invalid character.
1532 if c == '[':
1533 msg = f"Malformed attribute selector at position {index}"
1534 elif c == '.':
1535 msg = f"Malformed class selector at position {index}"
1536 elif c == '#':
1537 msg = f"Malformed id selector at position {index}"
1538 elif c == ':':
1539 msg = f"Malformed pseudo-class selector at position {index}"
1540 else:
1541 msg = f"Invalid character {c!r} position {index}"
1542 raise SelectorSyntaxError(msg, self.pattern, index)
1543 if self.debug: # pragma: no cover
1544 print('## END PARSING')
1546 def process_selectors(self, index: int = 0, flags: int = 0) -> ct.SelectorList:
1547 """Process selectors."""
1549 return self.parse_selectors(self.selector_iter(self.pattern), index, flags)