Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/soupsieve/css_parser.py: 25%
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, Iterator, cast
11from dataclasses import dataclass
12from collections import UserDict
13import threading
15RE_LOCK = threading.Lock()
16SEL_LOCK = threading.RLock()
18UNICODE_REPLACEMENT_CHAR = 0xFFFD
20SELECTOR_LIMIT = 8192
22# Simple pseudo classes that take no parameters
23PSEUDO_SIMPLE = {
24 ":any-link",
25 ":empty",
26 ":first-child",
27 ":first-of-type",
28 ":in-range",
29 ":open",
30 ":out-of-range",
31 ":last-child",
32 ":last-of-type",
33 ":link",
34 ":only-child",
35 ":only-of-type",
36 ":root",
37 ':checked',
38 ':default',
39 ':disabled',
40 ':enabled',
41 ':indeterminate',
42 ':optional',
43 ':placeholder-shown',
44 ':read-only',
45 ':read-write',
46 ':required',
47 ':scope',
48 ':defined',
49 ':muted'
50}
52# Supported, simple pseudo classes that match nothing in the Soup Sieve environment
53PSEUDO_SIMPLE_NO_MATCH = {
54 ':active',
55 ':autofill',
56 ':buffering',
57 ':current',
58 ':focus',
59 ':focus-visible',
60 ':focus-within',
61 ':fullscreen',
62 ':future',
63 ':host',
64 ':hover',
65 ':local-link',
66 ':past',
67 ':paused',
68 ':picture-in-picture',
69 ':playing',
70 ':popover-open',
71 ':seeking',
72 ':stalled',
73 ':target',
74 ':target-within',
75 ':user-invalid',
76 ':volume-locked',
77 ':visited'
78}
80# Complex pseudo classes that take selector lists
81PSEUDO_COMPLEX = {
82 ':contains',
83 ':-soup-contains',
84 ':-soup-contains-own',
85 ':has',
86 ':is',
87 ':matches',
88 ':not',
89 ':where'
90}
92PSEUDO_COMPLEX_NO_MATCH = {
93 ':current',
94 ':host',
95 ':host-context'
96}
98# Complex pseudo classes that take very specific parameters and are handled special
99PSEUDO_SPECIAL = {
100 ':dir',
101 ':lang',
102 ':nth-child',
103 ':nth-last-child',
104 ':nth-last-of-type',
105 ':nth-of-type'
106}
108PSEUDO_SUPPORTED = PSEUDO_SIMPLE | PSEUDO_SIMPLE_NO_MATCH | PSEUDO_COMPLEX | PSEUDO_COMPLEX_NO_MATCH | PSEUDO_SPECIAL
110# Sub-patterns parts
111# Whitespace
112NEWLINE = r'(?:\r\n|(?!\r\n)[\n\f\r])'
113WS = fr'(?:[ \t]|{NEWLINE})'
114# Comments
115COMMENTS = r'(?:/\*(?:[^*]|\*(?!/))*\*/)'
116# Whitespace with comments included
117WSC = fr'(?:{WS}|{COMMENTS})'
118# CSS escapes
119CSS_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}{WS}?|[^\r\n\f]|$))'
120CSS_STRING_ESCAPES = fr'(?:\\(?:[a-f0-9]{{1,6}}{WS}?|[^\r\n\f]|$|{NEWLINE}))'
121# CSS Identifier
122IDENTIFIER = fr'''
123(?:(?:--|-?(?:[^\x00-\x2f\x30-\x40\x5B-\x5E\x60\x7B-\x9f]|{CSS_ESCAPES}))
124(?:[^\x00-\x2c\x2e\x2f\x3A-\x40\x5B-\x5E\x60\x7B-\x9f]|{CSS_ESCAPES})*)
125'''
126# `nth` content
127NTH = fr'(?:[-+])?(?:[0-9]+n?|n)(?:(?<=n){WSC}*(?:[-+]){WSC}*(?:[0-9]+))?'
128# Value: quoted string or identifier
129VALUE = fr'''(?:"(?:\\(?:.|{NEWLINE})|[^\\"\r\n\f])*?"|'(?:\\(?:.|{NEWLINE})|[^\\'\r\n\f])*?'|{IDENTIFIER})'''
130# Attribute value comparison. `!=` is handled special as it is non-standard.
131ATTR = fr'(?:{WSC}*(?P<cmp>[!~^|*$]?=){WSC}*(?P<value>{VALUE})(?:{WSC}*(?P<case>[is]))?)?{WSC}*'
133# Selector patterns
134# IDs (`#id`)
135PAT_ID = fr'\#{IDENTIFIER}'
136# Classes (`.class`)
137PAT_CLASS = fr'\.{IDENTIFIER}'
138# Prefix:Tag (`prefix|tag`)
139PAT_TAG = fr'(?P<tag_ns>(?:{IDENTIFIER}|\*)?\|)?(?P<tag_name>{IDENTIFIER}|\*)'
140# Attributes (`[attr]`, `[attr=value]`, etc.)
141PAT_ATTR = fr'\[{WSC}*(?P<attr_ns>(?:{IDENTIFIER}|\*)?\|)?(?P<attr_name>{IDENTIFIER}){ATTR}\]'
142# Pseudo class (`:pseudo-class`, `:pseudo-class(`)
143PAT_PSEUDO_CLASS = fr'(?P<name>:{IDENTIFIER})(?P<open>\({WSC}*)?'
144# Pseudo class special patterns. Matches `:pseudo-class(` for special case pseudo classes.
145PAT_PSEUDO_CLASS_SPECIAL = fr'(?P<name>:{IDENTIFIER})(?P<open>\({WSC}*)'
146# Custom pseudo class (`:--custom-pseudo`)
147PAT_PSEUDO_CLASS_CUSTOM = fr'(?P<name>:(?=--){IDENTIFIER})'
148# Nesting ampersand selector. Matches `&`
149PAT_AMP = r'&'
150# Closing pseudo group (`)`)
151PAT_PSEUDO_CLOSE = fr'{WSC}*\)'
152# Pseudo element (`::pseudo-element`)
153PAT_PSEUDO_ELEMENT = fr':{PAT_PSEUDO_CLASS}'
154# At rule (`@page`, etc.) (not supported)
155PAT_AT_RULE = fr'@P{IDENTIFIER}'
156# Pseudo class `nth-child` (`:nth-child(an+b [of S]?)`, `:first-child`, etc.)
157PAT_PSEUDO_NTH_CHILD = fr'''
158(?P<pseudo_nth_child>{PAT_PSEUDO_CLASS_SPECIAL}
159(?P<nth_child>{NTH}|even|odd))(?:{WSC}*\)|(?P<of>{COMMENTS}*{WS}{WSC}*of{COMMENTS}*{WS}{WSC}*))
160'''
161# Pseudo class `nth-of-type` (`:nth-of-type(an+b)`, `:first-of-type`, etc.)
162PAT_PSEUDO_NTH_TYPE = fr'''
163(?P<pseudo_nth_type>{PAT_PSEUDO_CLASS_SPECIAL}
164(?P<nth_type>{NTH}|even|odd)){WSC}*\)
165'''
166# Pseudo class language (`:lang("*-de", en)`)
167PAT_PSEUDO_LANG = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P<values>{VALUE}(?:{WSC}*,{WSC}*{VALUE})*){WSC}*\)'
168# Pseudo class direction (`:dir(ltr)`)
169PAT_PSEUDO_DIR = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P<dir>ltr|rtl){WSC}*\)'
170# Combining characters (`>`, `~`, ` `, `+`, `,`)
171PAT_COMBINE = fr'{WSC}*?(?P<relation>[,+>~]|{WS}(?![,+>~])){WSC}*'
172# Extra: Contains (`:contains(text)`)
173PAT_PSEUDO_CONTAINS = fr'{PAT_PSEUDO_CLASS_SPECIAL}(?P<values>{VALUE}(?:{WSC}*,{WSC}*{VALUE})*){WSC}*\)'
175# Regular expressions
176# CSS escape pattern
177RE_CSS_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}{WSC}?)|(\\[^\r\n\f])|(\\$))', re.I)
178RE_CSS_STR_ESC = re.compile(fr'(?:(\\[a-f0-9]{{1,6}}{WS}?)|(\\[^\r\n\f])|(\\$)|(\\{NEWLINE}))', re.I)
179# Pattern to break up `nth` specifiers
180RE_NTH = re.compile(fr'(?P<s1>[-+])?(?P<a>[0-9]+n?|n)(?:(?<=n){WSC}*(?P<s2>[-+]){WSC}*(?P<b>[0-9]+))?', re.I)
181# Pattern to iterate multiple values.
182RE_VALUES = re.compile(fr'(?:(?P<value>{VALUE})|(?P<split>{WSC}*,{WSC}*))', re.X)
183# Whitespace checks
184RE_WS = re.compile(WS)
185RE_WS_BEGIN = re.compile(fr'^{WSC}*')
186RE_WS_END = re.compile(fr'^(?:[ \t]|(?:\n\r|(?!\n\r)[\n\f\r])|{COMMENTS})*')
187RE_CUSTOM = re.compile(fr'^{PAT_PSEUDO_CLASS_CUSTOM}$', re.X)
188RE_PSEUDO_CLASS_SPECIAL = re.compile(PAT_PSEUDO_CLASS_SPECIAL, re.I | re.X | re.U)
190QUOTED = ("'", '"')
192# Constants
193# List split token
194COMMA_COMBINATOR = ','
195# Relation token for descendant
196WS_COMBINATOR = " "
198# Parse flags
199FLG_PSEUDO = 0x01
200FLG_NOT = 0x02
201FLG_RELATIVE = 0x04
202FLG_DEFAULT = 0x08
203FLG_HTML = 0x10
204FLG_INDETERMINATE = 0x20
205FLG_OPEN = 0x40
206FLG_IN_RANGE = 0x80
207FLG_OUT_OF_RANGE = 0x100
208FLG_PLACEHOLDER_SHOWN = 0x200
209FLG_FORGIVE = 0x400
211# Maximum cached patterns to store
212_MAXCACHE = 500
215@lru_cache(maxsize=_MAXCACHE)
216def _cached_css_compile(
217 pattern: str,
218 namespaces: ct.Namespaces | None,
219 custom: ct.CustomSelectors | None,
220 flags: int
221) -> cm.SoupSieve:
222 """Cached CSS compile."""
224 custom_selectors = process_custom(custom)
225 return cm.SoupSieve(
226 pattern,
227 CSSParser(
228 pattern,
229 custom=custom_selectors,
230 flags=flags
231 ).process_selectors(),
232 namespaces,
233 custom,
234 flags
235 )
238def _purge_cache() -> None:
239 """Purge the cache."""
241 _cached_css_compile.cache_clear()
244def process_custom(custom: ct.CustomSelectors | None) -> dict[str, str | ct.SelectorList]:
245 """Process custom."""
247 custom_selectors = {}
248 if custom is not None:
249 for key, value in custom.items():
250 name = util.lower(key)
251 if RE_CUSTOM.match(name) is None:
252 raise SelectorSyntaxError(f"The name '{name}' is not a valid custom pseudo-class name")
253 if name in custom_selectors:
254 raise KeyError(f"The custom selector '{name}' has already been registered")
255 custom_selectors[css_unescape(name)] = value
256 return custom_selectors
259def css_unescape(content: str) -> str:
260 """
261 Unescape CSS value.
263 Strings allow for spanning the value on multiple strings by escaping a new line.
264 """
266 def replace(m: Match[str]) -> str:
267 """Replace with the appropriate substitute."""
269 if m.group(1):
270 codepoint = int(m.group(1)[1:], 16)
271 if codepoint == 0:
272 codepoint = UNICODE_REPLACEMENT_CHAR
273 value = chr(codepoint)
274 elif m.group(2):
275 value = m.group(2)[1:]
276 elif m.group(3):
277 value = '\ufffd'
278 else:
279 value = ''
281 return value
283 quoted = content.startswith(QUOTED)
284 return (RE_CSS_STR_ESC if quoted else RE_CSS_ESC).sub(
285 replace,
286 content[1:-1] if quoted else content
287 )
290def escape(ident: str) -> str:
291 """Escape identifier."""
293 string = []
294 length = len(ident)
295 start_dash = length > 0 and ident[0] == '-'
296 if length == 1 and start_dash:
297 # Need to escape identifier that is a single `-` with no other characters
298 string.append(f'\\{ident}')
299 else:
300 for index, c in enumerate(ident):
301 codepoint = ord(c)
302 if codepoint == 0x00:
303 string.append('\ufffd')
304 elif (0x01 <= codepoint <= 0x1F) or codepoint == 0x7F:
305 string.append(f'\\{codepoint:x} ')
306 elif (index == 0 or (start_dash and index == 1)) and (0x30 <= codepoint <= 0x39):
307 string.append(f'\\{codepoint:x} ')
308 elif (
309 codepoint in (0x2D, 0x5F) or codepoint >= 0x80 or (0x30 <= codepoint <= 0x39) or
310 (0x30 <= codepoint <= 0x39) or (0x41 <= codepoint <= 0x5A) or (0x61 <= codepoint <= 0x7A)
311 ):
312 string.append(c)
313 else:
314 string.append(f'\\{c}')
315 return ''.join(string)
318class SelectorPattern:
319 """Selector pattern."""
321 def __init__(self, name: str, pattern: str) -> None:
322 """Initialize."""
324 self.name = name
325 self.pattern = pattern
326 self._re_pattern: re.Pattern[str] | None = None
328 @property
329 def re_pattern(self) -> re.Pattern[str]:
330 """Retrieve the compiled regular expression pattern."""
332 with RE_LOCK:
333 if self._re_pattern is None:
334 self._re_pattern = re.compile(self.pattern, re.I | re.X | re.U)
335 return self._re_pattern
337 def get_name(self) -> str:
338 """Get name."""
340 return self.name
342 def match(self, selector: str, index: int, flags: int) -> Match[str] | None:
343 """Match the selector."""
345 return self.re_pattern.match(selector, index)
348class SpecialPseudoPattern(SelectorPattern):
349 """Selector pattern."""
351 def __init__(self, patterns: tuple[tuple[str, tuple[str, ...], str, type[SelectorPattern]], ...]) -> None:
352 """Initialize."""
354 self.patterns = {}
355 for p in patterns:
356 name = p[0]
357 pattern = p[3](name, p[2])
358 for pseudo in p[1]:
359 self.patterns[pseudo] = pattern
361 self.matched_name = None # type: SelectorPattern | None
363 def get_name(self) -> str:
364 """Get name."""
366 return '' if self.matched_name is None else self.matched_name.get_name()
368 def match(self, selector: str, index: int, flags: int) -> Match[str] | None:
369 """Match the selector."""
371 pseudo = None
372 m = RE_PSEUDO_CLASS_SPECIAL.match(selector, index)
373 if m:
374 name = util.lower(css_unescape(m.group('name')))
375 pattern = self.patterns.get(name)
376 if pattern:
377 pseudo = pattern.match(selector, index, flags)
378 if pseudo:
379 self.matched_name = pattern
381 return pseudo
384class _Selector:
385 """
386 Intermediate selector class.
388 This stores selector data for a compound selector as we are acquiring them.
389 Once we are done collecting the data for a compound selector, we freeze
390 the data in an object that can be pickled and hashed.
391 """
393 def __init__(self, **kwargs: Any) -> None:
394 """Initialize."""
396 self.tag = kwargs.get('tag', None) # type: ct.SelectorTag | None
397 self.ids = kwargs.get('ids', []) # type: list[str]
398 self.classes = kwargs.get('classes', []) # type: list[str]
399 self.attributes = kwargs.get('attributes', []) # type: list[ct.SelectorAttribute]
400 self.nth = kwargs.get('nth', []) # type: list[ct.SelectorNth]
401 self.selectors = kwargs.get('selectors', []) # type: list[ct.SelectorList]
402 self.relations = kwargs.get('relations', []) # type: list[_Selector]
403 self.rel_type = kwargs.get('rel_type', None) # type: str | None
404 self.contains = kwargs.get('contains', []) # type: list[ct.SelectorContains]
405 self.lang = kwargs.get('lang', []) # type: list[ct.SelectorLang]
406 self.flags = kwargs.get('flags', 0) # type: int
407 self.no_match = kwargs.get('no_match', False) # type: bool
409 def _freeze_relations(self, relations: list[_Selector]) -> ct.SelectorList:
410 """Freeze relation."""
412 if relations:
413 sel = relations[0]
414 sel.relations.extend(relations[1:])
415 return ct.SelectorList([sel.freeze()])
416 else:
417 return ct.SelectorList()
419 def freeze(self) -> ct.Selector | ct.SelectorNull:
420 """Freeze self."""
422 if self.no_match:
423 return ct.SelectorNull()
424 else:
425 return ct.Selector(
426 self.tag,
427 tuple(self.ids),
428 tuple(self.classes),
429 tuple(self.attributes),
430 tuple(self.nth),
431 tuple(self.selectors),
432 self._freeze_relations(self.relations),
433 self.rel_type,
434 tuple(self.contains),
435 tuple(self.lang),
436 self.flags
437 )
439 def __str__(self) -> str: # pragma: no cover
440 """String representation."""
442 return (
443 f'_Selector(tag={self.tag!r}, ids={self.ids!r}, classes={self.classes!r}, attributes={self.attributes!r}, '
444 f'nth={self.nth!r}, selectors={self.selectors!r}, relations={self.relations!r}, '
445 f'rel_type={self.rel_type!r}, contains={self.contains!r}, lang={self.lang!r}, flags={self.flags!r}, '
446 f'no_match={self.no_match!r})'
447 )
449 __repr__ = __str__
452@dataclass
453class CSSPattern:
454 """A CSS pattern that hasn't been processed by `CSSParser` yet."""
456 selector: str
457 flags: int
460class PseudoSelectorMap(UserDict[str, CSSPattern | ct.SelectorList]):
461 """Pseudo selector map."""
463 def __setitem__(self, key: str, value: CSSPattern | ct.SelectorList) -> None:
464 """Set item."""
466 self.data[key] = value
468 def __getitem__(self, key: str) -> ct.SelectorList:
469 """Get item."""
471 with SEL_LOCK:
472 value = self.data[key]
473 if isinstance(value, CSSPattern):
474 value = CSSParser(value.selector).process_selectors(flags=value.flags)
475 self.data[key] = value
477 return value
480# CSS pattern for `:link` and `:any-link`
481CSS_LINK = CSSPattern('html|*:is(a, area)[href]', FLG_PSEUDO | FLG_HTML)
482# CSS pattern for `:checked`
483CSS_CHECKED = CSSPattern(
484 '''
485 html|*:is(input[type=checkbox], input[type=radio])[checked], html|option[selected]
486 ''',
487 FLG_PSEUDO | FLG_HTML
488)
489# CSS pattern for `:default` (must compile CSS_CHECKED first)
490CSS_DEFAULT = CSSPattern(
491 '''
492 :checked,
494 /*
495 This pattern must be at the end.
496 Special logic is applied to the last selector.
497 */
498 html|form html|*:is(button, input)[type="submit"]
499 ''',
500 FLG_PSEUDO | FLG_HTML | FLG_DEFAULT
501)
502# CSS pattern for `:indeterminate`
503CSS_INDETERMINATE = CSSPattern(
504 '''
505 html|input[type="checkbox"][indeterminate],
506 html|input[type="radio"]:is(:not([name]), [name=""]):not([checked]),
507 html|progress:not([value]),
509 /*
510 This pattern must be at the end.
511 Special logic is applied to the last selector.
512 */
513 html|input[type="radio"][name]:not([name='']):not([checked])
514 ''',
515 FLG_PSEUDO | FLG_HTML | FLG_INDETERMINATE
516)
517# CSS pattern for `:disabled`
518CSS_DISABLED = CSSPattern(
519 '''
520 html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset)[disabled],
521 html|optgroup[disabled] > html|option,
522 html|fieldset[disabled] > html|*:is(input:not([type=hidden]), button, select, textarea, fieldset),
523 html|fieldset[disabled] >
524 html|*:not(legend:nth-of-type(1)) html|*:is(input:not([type=hidden]), button, select, textarea, fieldset)
525 ''',
526 FLG_PSEUDO | FLG_HTML
527)
528# CSS pattern for `:enabled`
529CSS_ENABLED = CSSPattern(
530 '''
531 html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset):not(:disabled)
532 ''',
533 FLG_PSEUDO | FLG_HTML
534)
535# CSS pattern for `:required`
536CSS_REQUIRED = CSSPattern('html|*:is(input, textarea, select)[required]', FLG_PSEUDO | FLG_HTML)
537# CSS pattern for `:optional`
538CSS_OPTIONAL = CSSPattern('html|*:is(input, textarea, select):not([required])', FLG_PSEUDO | FLG_HTML)
539# CSS pattern for `:placeholder-shown`
540CSS_PLACEHOLDER_SHOWN = CSSPattern(
541 '''
542 html|input:is(
543 :not([type]),
544 [type=""],
545 [type=text],
546 [type=search],
547 [type=url],
548 [type=tel],
549 [type=email],
550 [type=password],
551 [type=number]
552 )[placeholder]:not([placeholder='']):is(:not([value]), [value=""]),
553 html|textarea[placeholder]:not([placeholder=''])
554 ''',
555 FLG_PSEUDO | FLG_HTML | FLG_PLACEHOLDER_SHOWN
556)
557# CSS pattern for `:read-write` (CSS_DISABLED must be compiled first)
558CSS_READ_WRITE = CSSPattern(
559 '''
560 html|*:is(
561 textarea,
562 input:is(
563 :not([type]),
564 [type=""],
565 [type=text],
566 [type=search],
567 [type=url],
568 [type=tel],
569 [type=email],
570 [type=number],
571 [type=password],
572 [type=date],
573 [type=datetime-local],
574 [type=month],
575 [type=time],
576 [type=week]
577 )
578 ):not([readonly], :disabled),
579 html|*:is([contenteditable=""], [contenteditable="true" i])
580 ''',
581 FLG_PSEUDO | FLG_HTML
582)
583# CSS pattern for `:read-only`
584CSS_READ_ONLY = CSSPattern('html|*:not(:read-write)', FLG_PSEUDO | FLG_HTML)
585# CSS pattern for `:in-range`
586CSS_IN_RANGE = CSSPattern(
587 '''
588 html|input:is(
589 [type="date"],
590 [type="month"],
591 [type="week"],
592 [type="time"],
593 [type="datetime-local"],
594 [type="number"],
595 [type="range"]
596 ):is(
597 [min],
598 [max]
599 )
600 ''',
601 FLG_PSEUDO | FLG_HTML | FLG_IN_RANGE
602)
603# CSS pattern for `:out-of-range`
604CSS_OUT_OF_RANGE = CSSPattern(
605 '''
606 html|input:is(
607 [type="date"],
608 [type="month"],
609 [type="week"],
610 [type="time"],
611 [type="datetime-local"],
612 [type="number"],
613 [type="range"]
614 ):is(
615 [min],
616 [max]
617 )
618 ''',
619 FLG_PSEUDO | FLG_HTML | FLG_OUT_OF_RANGE
620)
621# CSS pattern for :open
622CSS_OPEN = CSSPattern('html|*:is(details, dialog)[open]', FLG_PSEUDO | FLG_HTML)
623# CSS pattern for :muted
624CSS_MUTED = CSSPattern('html|*:is(video, audio)[muted]', FLG_PSEUDO | FLG_HTML)
625# CSS pattern default for `:nth-child` "of S" feature
626CSS_NTH_OF_S_DEFAULT = CSSPattern("*|*", FLG_PSEUDO)
629class CSSParser:
630 """Parse CSS selectors."""
632 CSS_TOKENS = (
633 SelectorPattern("pseudo_close", PAT_PSEUDO_CLOSE),
634 SpecialPseudoPattern(
635 (
636 (
637 "pseudo_contains",
638 (':contains', ':-soup-contains', ':-soup-contains-own'),
639 PAT_PSEUDO_CONTAINS,
640 SelectorPattern
641 ),
642 ("pseudo_nth_child", (':nth-child', ':nth-last-child'), PAT_PSEUDO_NTH_CHILD, SelectorPattern),
643 ("pseudo_nth_type", (':nth-of-type', ':nth-last-of-type'), PAT_PSEUDO_NTH_TYPE, SelectorPattern),
644 ("pseudo_lang", (':lang',), PAT_PSEUDO_LANG, SelectorPattern),
645 ("pseudo_dir", (':dir',), PAT_PSEUDO_DIR, SelectorPattern)
646 )
647 ),
648 SelectorPattern("pseudo_class_custom", PAT_PSEUDO_CLASS_CUSTOM),
649 SelectorPattern("pseudo_class", PAT_PSEUDO_CLASS),
650 SelectorPattern("pseudo_element", PAT_PSEUDO_ELEMENT),
651 SelectorPattern("amp", PAT_AMP),
652 SelectorPattern("at_rule", PAT_AT_RULE),
653 SelectorPattern("id", PAT_ID),
654 SelectorPattern("class", PAT_CLASS),
655 SelectorPattern("tag", PAT_TAG),
656 SelectorPattern("attribute", PAT_ATTR),
657 SelectorPattern("combine", PAT_COMBINE)
658 )
660 # Pseudos that expand to selectors
661 PSEUDO_SELECTORS = PseudoSelectorMap(
662 {
663 ':link': CSS_LINK,
664 ':any-link': CSS_LINK,
665 ':checked': CSS_CHECKED,
666 ':default': CSS_DEFAULT,
667 ':indeterminate': CSS_INDETERMINATE,
668 ':disabled': CSS_DISABLED,
669 ':enabled': CSS_ENABLED,
670 ':required': CSS_REQUIRED,
671 ':muted': CSS_MUTED,
672 ':open': CSS_OPEN,
673 ':optional': CSS_OPTIONAL,
674 ':read-only': CSS_READ_ONLY,
675 ':read-write': CSS_READ_WRITE,
676 ':in-range': CSS_IN_RANGE,
677 ':out-of-range': CSS_OUT_OF_RANGE,
678 ':placeholder-shown': CSS_PLACEHOLDER_SHOWN,
679 '<nth-of-s>': CSS_NTH_OF_S_DEFAULT
680 }
681 )
683 def __init__(
684 self,
685 selector: str,
686 custom: dict[str, str | ct.SelectorList] | None = None,
687 flags: int = 0
688 ) -> None:
689 """Initialize."""
691 self.pattern = selector.replace('\x00', '\ufffd')
692 self.flags = flags
693 self.debug = self.flags & util.DEBUG
694 self.custom = {} if custom is None else custom
695 self.count = 0
697 def increment_count(self, increment: int = 1) -> None:
698 """Check the current selector count."""
700 self.count += increment
701 if self.count > SELECTOR_LIMIT:
702 raise ValueError(f'Selector exceeds pseudo-class nesting limit of {SELECTOR_LIMIT}')
704 def parse_attribute_selector(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
705 """Create attribute selector from the returned regex match."""
707 inverse = False
708 op = m.group('cmp')
709 case = util.lower(m.group('case')) if m.group('case') else None
710 ns = css_unescape(m.group('attr_ns')[:-1]) if m.group('attr_ns') else ''
711 attr = css_unescape(m.group('attr_name'))
712 is_type = False
713 pattern2 = None
714 value = ''
716 if case:
717 flags = (re.I if case == 'i' else 0) | re.DOTALL
718 elif util.lower(attr) == 'type':
719 flags = re.I | re.DOTALL
720 is_type = True
721 else:
722 flags = re.DOTALL
724 if op:
725 value = css_unescape(m.group('value'))
727 if not op:
728 # Attribute name
729 pattern = None
730 elif op.startswith('^'):
731 # Value start with
732 # `^=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
733 value = r'(?!)' if not value else re.escape(value)
734 pattern = re.compile(r'^%s.*' % value, flags)
735 elif op.startswith('$'):
736 # Value ends with
737 # `$=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
738 value = r'(?!)' if not value else re.escape(value)
739 pattern = re.compile(r'.*?%s$' % value, flags)
740 elif op.startswith('*'):
741 # Value contains
742 # `*=` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
743 value = r'(?!)' if not value else re.escape(value)
744 pattern = re.compile(r'.*?%s.*' % value, flags)
745 elif op.startswith('~'):
746 # Value contains word within space separated list
747 # `*~` should match nothing if the value is empty, so use `(?!)` which cannot be matched.
748 value = r'(?!)' if not value or RE_WS.search(value) else re.escape(value)
749 pattern = re.compile(r'.*?(?:(?<=^)|(?<=[ \t\r\n\f]))%s(?=(?:[ \t\r\n\f]|$)).*' % value, flags)
750 elif op.startswith('|'):
751 # Value starts with word in dash separated list
752 pattern = re.compile(r'^%s(?:-.*)?$' % re.escape(value), flags)
753 else:
754 # Value matches
755 pattern = re.compile(r'^%s$' % re.escape(value), flags)
756 if op.startswith('!'):
757 # Equivalent to `:not([attr=value])`
758 inverse = True
759 if is_type and pattern:
760 pattern2 = re.compile(pattern.pattern)
762 # Append the attribute selector
763 sel_attr = ct.SelectorAttribute(attr, ns, pattern, pattern2)
764 if inverse:
765 # If we are using `!=`, we need to nest the pattern under a `:not()`.
766 sub_sel = _Selector()
767 sub_sel.attributes.append(sel_attr)
768 not_list = ct.SelectorList([sub_sel.freeze()], True, False)
769 sel.selectors.append(not_list)
770 else:
771 sel.attributes.append(sel_attr)
773 has_selector = True
774 return has_selector
776 def parse_tag_pattern(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
777 """Parse tag pattern from regex match."""
779 prefix = css_unescape(m.group('tag_ns')[:-1]) if m.group('tag_ns') else None
780 tag = css_unescape(m.group('tag_name'))
781 sel.tag = ct.SelectorTag(tag, prefix)
782 has_selector = True
783 return has_selector
785 def parse_pseudo_class_custom(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
786 """
787 Parse custom pseudo class alias.
789 Compile custom selectors as we need them. When compiling a custom selector,
790 set it to `None` in the dictionary so we can avoid an infinite loop.
791 """
793 pseudo = util.lower(css_unescape(m.group('name')))
794 selector = self.custom.get(pseudo)
795 if selector is None:
796 raise SelectorSyntaxError(
797 f"Undefined custom selector '{pseudo}' found at position {m.end(0)}",
798 self.pattern,
799 m.end(0)
800 )
802 if not isinstance(selector, ct.SelectorList):
803 del self.custom[pseudo]
804 selector = CSSParser(
805 selector, custom=self.custom, flags=self.flags
806 ).process_selectors(flags=FLG_PSEUDO)
807 self.custom[pseudo] = selector
809 self.increment_count(selector.count)
810 sel.selectors.append(selector)
811 has_selector = True
812 return has_selector
814 def parse_pseudo_class(
815 self,
816 sel: _Selector,
817 m: Match[str],
818 has_selector: bool,
819 iselector: Iterator[tuple[str, Match[str]]],
820 is_html: bool
821 ) -> tuple[bool, bool]:
822 """Parse pseudo class."""
824 complex_pseudo = False
825 pseudo = util.lower(css_unescape(m.group('name')))
826 if m.group('open'):
827 complex_pseudo = True
828 if complex_pseudo and pseudo in PSEUDO_COMPLEX:
829 has_selector = self.parse_pseudo_open(sel, pseudo, has_selector, iselector, m.end(0))
830 elif not complex_pseudo and pseudo in PSEUDO_SIMPLE:
831 if pseudo == ':root':
832 sel.flags |= ct.SEL_ROOT
833 elif pseudo == ':defined':
834 sel.flags |= ct.SEL_DEFINED
835 is_html = True
836 elif pseudo == ':scope':
837 sel.flags |= ct.SEL_SCOPE
838 elif pseudo == ':empty':
839 sel.flags |= ct.SEL_EMPTY
840 elif pseudo in self.PSEUDO_SELECTORS:
841 pseudo_selector = self.PSEUDO_SELECTORS[pseudo]
842 self.increment_count(pseudo_selector.count)
843 sel.selectors.append(pseudo_selector)
844 elif pseudo == ':first-child':
845 sel.nth.append(ct.SelectorNth(1, False, 0, False, False, ct.SelectorList()))
846 elif pseudo == ':last-child':
847 sel.nth.append(ct.SelectorNth(1, False, 0, False, True, ct.SelectorList()))
848 elif pseudo == ':first-of-type':
849 sel.nth.append(ct.SelectorNth(1, False, 0, True, False, ct.SelectorList()))
850 elif pseudo == ':last-of-type':
851 sel.nth.append(ct.SelectorNth(1, False, 0, True, True, ct.SelectorList()))
852 elif pseudo == ':only-child':
853 sel.nth.extend(
854 [
855 ct.SelectorNth(1, False, 0, False, False, ct.SelectorList()),
856 ct.SelectorNth(1, False, 0, False, True, ct.SelectorList())
857 ]
858 )
859 elif pseudo == ':only-of-type':
860 sel.nth.extend(
861 [
862 ct.SelectorNth(1, False, 0, True, False, ct.SelectorList()),
863 ct.SelectorNth(1, False, 0, True, True, ct.SelectorList())
864 ]
865 )
866 has_selector = True
867 elif complex_pseudo and pseudo in PSEUDO_COMPLEX_NO_MATCH:
868 self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN)
869 sel.no_match = True
870 has_selector = True
871 elif not complex_pseudo and pseudo in PSEUDO_SIMPLE_NO_MATCH:
872 sel.no_match = True
873 has_selector = True
874 elif pseudo in PSEUDO_SUPPORTED:
875 raise SelectorSyntaxError(
876 f"Invalid syntax for pseudo class '{pseudo}'",
877 self.pattern,
878 m.start(0)
879 )
880 else:
881 raise SelectorSyntaxError(
882 f"'{pseudo}' was detected as a pseudo-class and is either unsupported or invalid. "
883 "If the syntax was not intended to be recognized as a pseudo-class, please escape the colon.",
884 self.pattern,
885 m.start(0)
886 )
888 return has_selector, is_html
890 def parse_pseudo_nth(
891 self,
892 sel: _Selector,
893 m: Match[str],
894 has_selector: bool,
895 iselector: Iterator[tuple[str, Match[str]]]
896 ) -> bool:
897 """Parse `nth` pseudo."""
899 mdict = m.groupdict()
900 if mdict.get('pseudo_nth_child'):
901 postfix = '_child'
902 else:
903 postfix = '_type'
904 mdict['name'] = util.lower(css_unescape(mdict['name']))
905 content = util.lower(mdict.get('nth' + postfix))
906 if content == 'even':
907 # 2n
908 s1 = 2
909 s2 = 0
910 var = True
911 elif content == 'odd':
912 # 2n+1
913 s1 = 2
914 s2 = 1
915 var = True
916 else:
917 nth_parts = cast(Match[str], RE_NTH.match(content))
918 _s1 = '-' if nth_parts.group('s1') and nth_parts.group('s1') == '-' else ''
919 a = nth_parts.group('a')
920 var = a.endswith('n')
921 if a.startswith('n'):
922 _s1 += '1'
923 elif var:
924 _s1 += a[:-1]
925 else:
926 _s1 += a
927 _s2 = '-' if nth_parts.group('s2') and nth_parts.group('s2') == '-' else ''
928 if nth_parts.group('b'):
929 _s2 += nth_parts.group('b')
930 else:
931 _s2 = '0'
932 s1 = int(_s1, 10)
933 s2 = int(_s2, 10)
935 pseudo_sel = mdict['name']
936 if postfix == '_child':
937 if m.group('of'):
938 # Parse the rest of `of S`.
939 nth_sel = self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN)
940 else:
941 # Use default `*|*` for `of S`.
942 nth_sel = self.PSEUDO_SELECTORS['<nth-of-s>']
943 self.increment_count(nth_sel.count)
944 if pseudo_sel == ':nth-child':
945 sel.nth.append(ct.SelectorNth(s1, var, s2, False, False, nth_sel))
946 elif pseudo_sel == ':nth-last-child':
947 sel.nth.append(ct.SelectorNth(s1, var, s2, False, True, nth_sel))
948 else:
949 if pseudo_sel == ':nth-of-type':
950 sel.nth.append(ct.SelectorNth(s1, var, s2, True, False, ct.SelectorList()))
951 elif pseudo_sel == ':nth-last-of-type':
952 sel.nth.append(ct.SelectorNth(s1, var, s2, True, True, ct.SelectorList()))
953 has_selector = True
954 return has_selector
956 def parse_pseudo_open(
957 self,
958 sel: _Selector,
959 name: str,
960 has_selector: bool,
961 iselector: Iterator[tuple[str, Match[str]]],
962 index: int
963 ) -> bool:
964 """Parse pseudo with opening bracket."""
966 flags = FLG_PSEUDO | FLG_OPEN
967 if name == ':not':
968 flags |= FLG_NOT
969 elif name == ':has':
970 flags |= FLG_RELATIVE
971 elif name in (':where', ':is'):
972 flags |= FLG_FORGIVE
974 sel.selectors.append(self.parse_selectors(iselector, index, flags))
975 has_selector = True
977 return has_selector
979 def parse_has_combinator(
980 self,
981 sel: _Selector,
982 m: Match[str],
983 has_selector: bool,
984 selectors: list[_Selector],
985 rel_type: str,
986 index: int
987 ) -> tuple[bool, _Selector, str]:
988 """Parse combinator tokens."""
990 combinator = m.group('relation').strip()
991 if not combinator:
992 combinator = WS_COMBINATOR
993 if combinator == COMMA_COMBINATOR:
994 if not has_selector:
995 raise SelectorSyntaxError(
996 f"The combinator '{combinator}' at position {index}, must have a selector before it",
997 self.pattern,
998 index
999 )
1000 sel.rel_type = rel_type
1001 selectors[-1].relations.append(sel)
1002 rel_type = ":" + WS_COMBINATOR
1003 selectors.append(_Selector())
1004 else:
1005 if has_selector:
1006 # End the current selector and associate the leading combinator with this selector.
1007 sel.rel_type = rel_type
1008 selectors[-1].relations.append(sel)
1009 elif rel_type[1:] != WS_COMBINATOR:
1010 # It's impossible to have two whitespace combinators after each other as the patterns
1011 # will gobble up trailing whitespace. It is also impossible to have a whitespace
1012 # combinator after any other kind for the same reason. But we could have
1013 # multiple non-whitespace combinators. So if the current combinator is not a whitespace,
1014 # then we've hit the multiple combinator case, so we should fail.
1015 raise SelectorSyntaxError(
1016 f'The multiple combinators at position {index}',
1017 self.pattern,
1018 index
1019 )
1021 # Set the leading combinator for the next selector.
1022 rel_type = ':' + combinator
1024 sel = _Selector()
1025 has_selector = False
1026 return has_selector, sel, rel_type
1028 def parse_combinator(
1029 self,
1030 sel: _Selector,
1031 m: Match[str],
1032 has_selector: bool,
1033 selectors: list[_Selector],
1034 relations: list[_Selector],
1035 is_pseudo: bool,
1036 is_forgive: bool,
1037 index: int
1038 ) -> tuple[bool, _Selector]:
1039 """Parse combinator tokens."""
1041 combinator = m.group('relation').strip()
1042 if not combinator:
1043 combinator = WS_COMBINATOR
1044 if not has_selector:
1045 if not is_forgive or combinator != COMMA_COMBINATOR:
1046 raise SelectorSyntaxError(
1047 f"The combinator '{combinator}' at position {index}, must have a selector before it",
1048 self.pattern,
1049 index
1050 )
1052 # If we are in a forgiving pseudo class, just make the selector a "no match"
1053 if combinator == COMMA_COMBINATOR:
1054 self.increment_count()
1055 del relations[:]
1056 else:
1057 if combinator == COMMA_COMBINATOR:
1058 if not sel.tag and not is_pseudo:
1059 # Implied `*`
1060 sel.tag = ct.SelectorTag('*', None)
1061 sel.relations.extend(relations)
1062 selectors.append(sel)
1063 del relations[:]
1064 else:
1065 sel.relations.extend(relations)
1066 sel.rel_type = combinator
1067 del relations[:]
1068 relations.append(sel)
1070 sel = _Selector()
1071 has_selector = False
1073 return has_selector, sel
1075 def parse_class_id(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1076 """Parse HTML classes and ids."""
1078 selector = m.group(0)
1079 if selector.startswith('.'):
1080 sel.classes.append(css_unescape(selector[1:]))
1081 else:
1082 sel.ids.append(css_unescape(selector[1:]))
1083 has_selector = True
1084 return has_selector
1086 def parse_pseudo_contains(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1087 """Parse contains."""
1089 pseudo = util.lower(css_unescape(m.group('name')))
1090 if pseudo == ":contains":
1091 warnings.warn( # noqa: B028
1092 "The pseudo class ':contains' is deprecated, ':-soup-contains' should be used moving forward.",
1093 FutureWarning
1094 )
1095 contains_own = pseudo == ":-soup-contains-own"
1096 patterns = [
1097 css_unescape(token.group('value'))
1098 for token in RE_VALUES.finditer(m.group('values'))
1099 if not token.group('split')
1100 ]
1101 sel.contains.append(ct.SelectorContains(patterns, contains_own))
1102 has_selector = True
1103 return has_selector
1105 def parse_pseudo_lang(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1106 """Parse pseudo language."""
1108 patterns = [
1109 css_unescape(token.group('value'))
1110 for token in RE_VALUES.finditer(m.group('values'))
1111 if not token.group('split')
1112 ]
1113 sel.lang.append(ct.SelectorLang(patterns))
1114 has_selector = True
1116 return has_selector
1118 def parse_pseudo_dir(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool:
1119 """Parse pseudo direction."""
1121 value = ct.SEL_DIR_LTR if util.lower(m.group('dir')) == 'ltr' else ct.SEL_DIR_RTL
1122 sel.flags |= value
1123 has_selector = True
1124 return has_selector
1126 def parse_selectors(
1127 self,
1128 iselector: Iterator[tuple[str, Match[str]]],
1129 index: int = 0,
1130 flags: int = 0
1131 ) -> ct.SelectorList:
1132 """Parse selectors."""
1134 # Initialize important variables
1135 sel = _Selector()
1136 selectors = []
1137 has_selector = False
1138 closed = False
1139 relations = [] # type: list[_Selector]
1140 rel_type = ":" + WS_COMBINATOR
1141 count = self.count
1143 # Setup various flags
1144 is_open = bool(flags & FLG_OPEN)
1145 is_pseudo = bool(flags & FLG_PSEUDO)
1146 is_relative = bool(flags & FLG_RELATIVE)
1147 is_not = bool(flags & FLG_NOT)
1148 is_html = bool(flags & FLG_HTML)
1149 is_default = bool(flags & FLG_DEFAULT)
1150 is_indeterminate = bool(flags & FLG_INDETERMINATE)
1151 is_in_range = bool(flags & FLG_IN_RANGE)
1152 is_out_of_range = bool(flags & FLG_OUT_OF_RANGE)
1153 is_placeholder_shown = bool(flags & FLG_PLACEHOLDER_SHOWN)
1154 is_forgive = bool(flags & FLG_FORGIVE)
1156 # Print out useful debug stuff
1157 if self.debug: # pragma: no cover
1158 if is_pseudo:
1159 print(' is_pseudo: True')
1160 if is_open:
1161 print(' is_open: True')
1162 if is_relative:
1163 print(' is_relative: True')
1164 if is_not:
1165 print(' is_not: True')
1166 if is_html:
1167 print(' is_html: True')
1168 if is_default:
1169 print(' is_default: True')
1170 if is_indeterminate:
1171 print(' is_indeterminate: True')
1172 if is_in_range:
1173 print(' is_in_range: True')
1174 if is_out_of_range:
1175 print(' is_out_of_range: True')
1176 if is_placeholder_shown:
1177 print(' is_placeholder_shown: True')
1178 if is_forgive:
1179 print(' is_forgive: True')
1181 # The algorithm for relative selectors require an initial selector in the selector list
1182 if is_relative:
1183 selectors.append(_Selector())
1185 try:
1186 while True:
1187 key, m = next(iselector)
1189 if key not in ('combine', 'pseudo_close'):
1190 self.increment_count()
1192 # Handle parts
1193 if key == "at_rule":
1194 raise NotImplementedError(f"At-rules found at position {m.start(0)}")
1195 elif key == "amp":
1196 sel.flags |= ct.SEL_SCOPE
1197 has_selector = True
1198 elif key == 'pseudo_class_custom':
1199 has_selector = self.parse_pseudo_class_custom(sel, m, has_selector)
1200 elif key == 'pseudo_class':
1201 has_selector, is_html = self.parse_pseudo_class(sel, m, has_selector, iselector, is_html)
1202 elif key == 'pseudo_element':
1203 raise NotImplementedError(f"Pseudo-element found at position {m.start(0)}")
1204 elif key == 'pseudo_contains':
1205 has_selector = self.parse_pseudo_contains(sel, m, has_selector)
1206 elif key in ('pseudo_nth_type', 'pseudo_nth_child'):
1207 has_selector = self.parse_pseudo_nth(sel, m, has_selector, iselector)
1208 elif key == 'pseudo_lang':
1209 has_selector = self.parse_pseudo_lang(sel, m, has_selector)
1210 elif key == 'pseudo_dir':
1211 has_selector = self.parse_pseudo_dir(sel, m, has_selector)
1212 # Currently only supports HTML
1213 is_html = True
1214 elif key == 'pseudo_close':
1215 if not has_selector:
1216 if not is_forgive:
1217 raise SelectorSyntaxError(
1218 f"Expected a selector at position {m.start(0)}",
1219 self.pattern,
1220 m.start(0)
1221 )
1222 sel.no_match = True
1223 if is_open:
1224 closed = True
1225 break
1226 else:
1227 raise SelectorSyntaxError(
1228 f"Unmatched pseudo-class close at position {m.start(0)}",
1229 self.pattern,
1230 m.start(0)
1231 )
1232 elif key == 'combine':
1233 if is_relative:
1234 has_selector, sel, rel_type = self.parse_has_combinator(
1235 sel, m, has_selector, selectors, rel_type, index
1236 )
1237 else:
1238 has_selector, sel = self.parse_combinator(
1239 sel, m, has_selector, selectors, relations, is_pseudo, is_forgive, index
1240 )
1241 elif key == 'attribute':
1242 has_selector = self.parse_attribute_selector(sel, m, has_selector)
1243 elif key == 'tag':
1244 if has_selector:
1245 raise SelectorSyntaxError(
1246 f"Tag name found at position {m.start(0)} instead of at the start",
1247 self.pattern,
1248 m.start(0)
1249 )
1250 has_selector = self.parse_tag_pattern(sel, m, has_selector)
1251 elif key in ('class', 'id'):
1252 has_selector = self.parse_class_id(sel, m, has_selector)
1254 index = m.end(0)
1255 except StopIteration:
1256 pass
1258 # Handle selectors that are not closed
1259 if is_open and not closed:
1260 raise SelectorSyntaxError(
1261 f"Unclosed pseudo-class at position {index}",
1262 self.pattern,
1263 index
1264 )
1266 # Cleanup completed selector piece
1267 if has_selector:
1268 if not sel.tag and not is_pseudo:
1269 # Implied `*`
1270 sel.tag = ct.SelectorTag('*', None)
1271 if is_relative:
1272 sel.rel_type = rel_type
1273 selectors[-1].relations.append(sel)
1274 else:
1275 sel.relations.extend(relations)
1276 del relations[:]
1277 selectors.append(sel)
1279 # Forgive empty slots in pseudo-classes that have lists (and are forgiving)
1280 elif is_forgive and (not selectors or not relations):
1281 # Handle normal pseudo-classes with empty slots like `:is()` etc.
1282 self.increment_count()
1283 sel.no_match = True
1284 del relations[:]
1285 selectors.append(sel)
1286 has_selector = True
1288 if not has_selector:
1289 # We will always need to finish a selector when `:has()` is used as it leads with combining.
1290 # May apply to others as well.
1291 raise SelectorSyntaxError(
1292 f'Expected a selector at position {index}',
1293 self.pattern,
1294 index
1295 )
1297 # Some patterns require additional logic, such as default. We try to make these the
1298 # last pattern, and append the appropriate flag to that selector which communicates
1299 # to the matcher what additional logic is required.
1300 if is_default:
1301 selectors[-1].flags = ct.SEL_DEFAULT
1302 if is_indeterminate:
1303 selectors[-1].flags = ct.SEL_INDETERMINATE
1304 if is_in_range:
1305 selectors[-1].flags = ct.SEL_IN_RANGE
1306 if is_out_of_range:
1307 selectors[-1].flags = ct.SEL_OUT_OF_RANGE
1308 if is_placeholder_shown:
1309 selectors[-1].flags = ct.SEL_PLACEHOLDER_SHOWN
1311 # Return selector list
1312 return ct.SelectorList([s.freeze() for s in selectors], is_not, is_html, self.count - count)
1314 def selector_iter(self, pattern: str) -> Iterator[tuple[str, Match[str]]]:
1315 """Iterate selector tokens."""
1317 # Ignore whitespace and comments at start and end of pattern
1318 m = RE_WS_BEGIN.search(pattern)
1319 index = m.end(0) if m else 0
1320 m = RE_WS_END.search(pattern[::-1])
1321 offset = m.end(0) if m else 0
1322 end = len(pattern) - (1 + offset)
1324 if self.debug: # pragma: no cover
1325 print(f'## PARSING: {pattern!r}')
1326 while index <= end:
1327 m = None
1328 for v in self.CSS_TOKENS:
1329 m = v.match(pattern, index, self.flags)
1330 if m:
1331 name = v.get_name()
1332 if self.debug: # pragma: no cover
1333 print(f"TOKEN: '{name}' --> {m.group(0)!r} at position {m.start(0)}")
1334 index = m.end(0)
1335 yield name, m
1336 break
1337 if m is None:
1338 c = pattern[index]
1339 # If the character represents the start of one of the known selector types,
1340 # throw an exception mentioning that the known selector type is in error;
1341 # otherwise, report the invalid character.
1342 if c == '[':
1343 msg = f"Malformed attribute selector at position {index}"
1344 elif c == '.':
1345 msg = f"Malformed class selector at position {index}"
1346 elif c == '#':
1347 msg = f"Malformed id selector at position {index}"
1348 elif c == ':':
1349 msg = f"Malformed pseudo-class selector at position {index}"
1350 else:
1351 msg = f"Invalid character {c!r} position {index}"
1352 raise SelectorSyntaxError(msg, self.pattern, index)
1353 if self.debug: # pragma: no cover
1354 print('## END PARSING')
1356 def process_selectors(self, index: int = 0, flags: int = 0) -> ct.SelectorList:
1357 """Process selectors."""
1359 return self.parse_selectors(self.selector_iter(self.pattern), index, flags)