Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/soupsieve/css_parser.py: 88%

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

603 statements  

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, Iterable, cast 

11from dataclasses import dataclass 

12from collections import UserDict 

13import threading 

14 

15RE_LOCK = threading.Lock() 

16SEL_LOCK = threading.RLock() 

17 

18UNICODE_REPLACEMENT_CHAR = 0xFFFD 

19 

20SELECTOR_LIMIT = 8192 

21 

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} 

51 

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} 

79 

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} 

91 

92PSEUDO_COMPLEX_NO_MATCH = { 

93 ':current', 

94 ':host', 

95 ':host-context' 

96} 

97 

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} 

107 

108PSEUDO_SUPPORTED = PSEUDO_SIMPLE | PSEUDO_SIMPLE_NO_MATCH | PSEUDO_COMPLEX | PSEUDO_COMPLEX_NO_MATCH | PSEUDO_SPECIAL 

109 

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}*' 

132 

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}*\)' 

174 

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) 

189RE_PSEUDO_IGNORE = re.compile(PAT_PSEUDO_CLASS, re.X | re.I | re.U) 

190 

191QUOTED = ("'", '"') 

192 

193# Constants 

194# List split token 

195COMMA_COMBINATOR = ',' 

196# Relation token for descendant 

197WS_COMBINATOR = " " 

198 

199# Parse flags 

200FLG_PSEUDO = 0x01 

201FLG_NOT = 0x02 

202FLG_RELATIVE = 0x04 

203FLG_DEFAULT = 0x08 

204FLG_HTML = 0x10 

205FLG_INDETERMINATE = 0x20 

206FLG_OPEN = 0x40 

207FLG_IN_RANGE = 0x80 

208FLG_OUT_OF_RANGE = 0x100 

209FLG_PLACEHOLDER_SHOWN = 0x200 

210FLG_FORGIVE = 0x400 

211 

212# Maximum cached patterns to store 

213_MAXCACHE = 500 

214 

215 

216@lru_cache(maxsize=_MAXCACHE) 

217def _cached_css_compile( 

218 pattern: str, 

219 namespaces: ct.Namespaces | None, 

220 custom: ct.CustomSelectors | None, 

221 ignore: tuple[str] | None = None, 

222 flags: int = 0 

223) -> cm.SoupSieve: 

224 """Cached CSS compile.""" 

225 

226 custom_selectors = process_custom(custom) 

227 return cm.SoupSieve( 

228 pattern, 

229 CSSParser( 

230 pattern, 

231 custom=custom_selectors, 

232 ignore=ignore, 

233 flags=flags 

234 ).process_selectors(), 

235 namespaces, 

236 custom, 

237 flags 

238 ) 

239 

240 

241def _purge_cache() -> None: 

242 """Purge the cache.""" 

243 

244 _cached_css_compile.cache_clear() 

245 

246 

247def process_custom(custom: ct.CustomSelectors | None) -> dict[str, str | ct.SelectorList]: 

248 """Process custom.""" 

249 

250 custom_selectors = {} 

251 if custom is not None: 

252 for key, value in custom.items(): 

253 name = util.lower(key) 

254 if RE_CUSTOM.match(name) is None: 

255 raise SelectorSyntaxError(f"The name '{name}' is not a valid custom pseudo-class name") 

256 if name in custom_selectors: 

257 raise KeyError(f"The custom selector '{name}' has already been registered") 

258 custom_selectors[css_unescape(name)] = value 

259 return custom_selectors 

260 

261 

262def css_unescape(content: str) -> str: 

263 """ 

264 Unescape CSS value. 

265 

266 Strings allow for spanning the value on multiple strings by escaping a new line. 

267 """ 

268 

269 def replace(m: Match[str]) -> str: 

270 """Replace with the appropriate substitute.""" 

271 

272 if m.group(1): 

273 codepoint = int(m.group(1)[1:], 16) 

274 if codepoint == 0: 

275 codepoint = UNICODE_REPLACEMENT_CHAR 

276 value = chr(codepoint) 

277 elif m.group(2): 

278 value = m.group(2)[1:] 

279 elif m.group(3): 

280 value = '\ufffd' 

281 else: 

282 value = '' 

283 

284 return value 

285 

286 quoted = content.startswith(QUOTED) 

287 return (RE_CSS_STR_ESC if quoted else RE_CSS_ESC).sub( 

288 replace, 

289 content[1:-1] if quoted else content 

290 ) 

291 

292 

293def escape(ident: str) -> str: 

294 """Escape identifier.""" 

295 

296 string = [] 

297 length = len(ident) 

298 start_dash = length > 0 and ident[0] == '-' 

299 if length == 1 and start_dash: 

300 # Need to escape identifier that is a single `-` with no other characters 

301 string.append(f'\\{ident}') 

302 else: 

303 for index, c in enumerate(ident): 

304 codepoint = ord(c) 

305 if codepoint == 0x00: 

306 string.append('\ufffd') 

307 elif (0x01 <= codepoint <= 0x1F) or codepoint == 0x7F: 

308 string.append(f'\\{codepoint:x} ') 

309 elif (index == 0 or (start_dash and index == 1)) and (0x30 <= codepoint <= 0x39): 

310 string.append(f'\\{codepoint:x} ') 

311 elif ( 

312 codepoint in (0x2D, 0x5F) or codepoint >= 0x80 or (0x30 <= codepoint <= 0x39) or 

313 (0x30 <= codepoint <= 0x39) or (0x41 <= codepoint <= 0x5A) or (0x61 <= codepoint <= 0x7A) 

314 ): 

315 string.append(c) 

316 else: 

317 string.append(f'\\{c}') 

318 return ''.join(string) 

319 

320 

321class SelectorPattern: 

322 """Selector pattern.""" 

323 

324 def __init__(self, name: str, pattern: str) -> None: 

325 """Initialize.""" 

326 

327 self.name = name 

328 self.pattern = pattern 

329 self._re_pattern: re.Pattern[str] | None = None 

330 

331 @property 

332 def re_pattern(self) -> re.Pattern[str]: 

333 """Retrieve the compiled regular expression pattern.""" 

334 

335 with RE_LOCK: 

336 if self._re_pattern is None: 

337 self._re_pattern = re.compile(self.pattern, re.I | re.X | re.U) 

338 return self._re_pattern 

339 

340 def get_name(self) -> str: 

341 """Get name.""" 

342 

343 return self.name 

344 

345 def match(self, selector: str, index: int, flags: int) -> Match[str] | None: 

346 """Match the selector.""" 

347 

348 return self.re_pattern.match(selector, index) 

349 

350 

351class SpecialPseudoPattern(SelectorPattern): 

352 """Selector pattern.""" 

353 

354 def __init__(self, patterns: tuple[tuple[str, tuple[str, ...], str, type[SelectorPattern]], ...]) -> None: 

355 """Initialize.""" 

356 

357 self.patterns = {} 

358 for p in patterns: 

359 name = p[0] 

360 pattern = p[3](name, p[2]) 

361 for pseudo in p[1]: 

362 self.patterns[pseudo] = pattern 

363 

364 self.matched_name = None # type: SelectorPattern | None 

365 

366 def get_name(self) -> str: 

367 """Get name.""" 

368 

369 return '' if self.matched_name is None else self.matched_name.get_name() 

370 

371 def match(self, selector: str, index: int, flags: int) -> Match[str] | None: 

372 """Match the selector.""" 

373 

374 pseudo = None 

375 m = RE_PSEUDO_CLASS_SPECIAL.match(selector, index) 

376 if m: 

377 name = util.lower(css_unescape(m.group('name'))) 

378 pattern = self.patterns.get(name) 

379 if pattern: 

380 pseudo = pattern.match(selector, index, flags) 

381 if pseudo: 

382 self.matched_name = pattern 

383 

384 return pseudo 

385 

386 

387class _Selector: 

388 """ 

389 Intermediate selector class. 

390 

391 This stores selector data for a compound selector as we are acquiring them. 

392 Once we are done collecting the data for a compound selector, we freeze 

393 the data in an object that can be pickled and hashed. 

394 """ 

395 

396 def __init__(self, **kwargs: Any) -> None: 

397 """Initialize.""" 

398 

399 self.tag = kwargs.get('tag', None) # type: ct.SelectorTag | None 

400 self.ids = kwargs.get('ids', []) # type: list[str] 

401 self.classes = kwargs.get('classes', []) # type: list[str] 

402 self.attributes = kwargs.get('attributes', []) # type: list[ct.SelectorAttribute] 

403 self.nth = kwargs.get('nth', []) # type: list[ct.SelectorNth] 

404 self.selectors = kwargs.get('selectors', []) # type: list[ct.SelectorList] 

405 self.relations = kwargs.get('relations', []) # type: list[_Selector] 

406 self.rel_type = kwargs.get('rel_type', None) # type: str | None 

407 self.contains = kwargs.get('contains', []) # type: list[ct.SelectorContains] 

408 self.lang = kwargs.get('lang', []) # type: list[ct.SelectorLang] 

409 self.flags = kwargs.get('flags', 0) # type: int 

410 self.no_match = kwargs.get('no_match', False) # type: bool 

411 

412 def _freeze_relations(self, relations: list[_Selector]) -> ct.SelectorList: 

413 """Freeze relation.""" 

414 

415 if relations: 

416 sel = relations[0] 

417 sel.relations.extend(relations[1:]) 

418 return ct.SelectorList([sel.freeze()]) 

419 else: 

420 return ct.SelectorList() 

421 

422 def freeze(self) -> ct.Selector | ct.SelectorNull: 

423 """Freeze self.""" 

424 

425 if self.no_match: 

426 return ct.Null 

427 else: 

428 return ct.Selector( 

429 self.tag, 

430 tuple(self.ids), 

431 tuple(self.classes), 

432 tuple(self.attributes), 

433 tuple(self.nth), 

434 tuple(self.selectors), 

435 self._freeze_relations(self.relations), 

436 self.rel_type, 

437 tuple(self.contains), 

438 tuple(self.lang), 

439 self.flags 

440 ) 

441 

442 def __str__(self) -> str: # pragma: no cover 

443 """String representation.""" 

444 

445 return ( 

446 f'_Selector(tag={self.tag!r}, ids={self.ids!r}, classes={self.classes!r}, attributes={self.attributes!r}, ' 

447 f'nth={self.nth!r}, selectors={self.selectors!r}, relations={self.relations!r}, ' 

448 f'rel_type={self.rel_type!r}, contains={self.contains!r}, lang={self.lang!r}, flags={self.flags!r}, ' 

449 f'no_match={self.no_match!r})' 

450 ) 

451 

452 __repr__ = __str__ 

453 

454 

455@dataclass 

456class CSSPattern: 

457 """A CSS pattern that hasn't been processed by `CSSParser` yet.""" 

458 

459 selector: str 

460 flags: int 

461 

462 

463class PseudoSelectorMap(UserDict[str, CSSPattern | ct.SelectorList]): 

464 """Pseudo selector map.""" 

465 

466 def __setitem__(self, key: str, value: CSSPattern | ct.SelectorList) -> None: 

467 """Set item.""" 

468 

469 self.data[key] = value 

470 

471 def __getitem__(self, key: str) -> ct.SelectorList: 

472 """Get item.""" 

473 

474 with SEL_LOCK: 

475 value = self.data[key] 

476 if isinstance(value, CSSPattern): 

477 value = CSSParser(value.selector).process_selectors(flags=value.flags) 

478 self.data[key] = value 

479 

480 return value 

481 

482 

483# CSS pattern for `:link` and `:any-link` 

484CSS_LINK = CSSPattern('html|*:is(a, area)[href]', FLG_PSEUDO | FLG_HTML) 

485# CSS pattern for `:checked` 

486CSS_CHECKED = CSSPattern( 

487 ''' 

488 html|*:is(input[type=checkbox], input[type=radio])[checked], html|option[selected] 

489 ''', 

490 FLG_PSEUDO | FLG_HTML 

491) 

492# CSS pattern for `:default` (must compile CSS_CHECKED first) 

493CSS_DEFAULT = CSSPattern( 

494 ''' 

495 :checked, 

496 

497 /* 

498 This pattern must be at the end. 

499 Special logic is applied to the last selector. 

500 */ 

501 html|form html|*:is(button, input)[type="submit"] 

502 ''', 

503 FLG_PSEUDO | FLG_HTML | FLG_DEFAULT 

504) 

505# CSS pattern for `:indeterminate` 

506CSS_INDETERMINATE = CSSPattern( 

507 ''' 

508 html|input[type="checkbox"][indeterminate], 

509 html|input[type="radio"]:is(:not([name]), [name=""]):not([checked]), 

510 html|progress:not([value]), 

511 

512 /* 

513 This pattern must be at the end. 

514 Special logic is applied to the last selector. 

515 */ 

516 html|input[type="radio"][name]:not([name='']):not([checked]) 

517 ''', 

518 FLG_PSEUDO | FLG_HTML | FLG_INDETERMINATE 

519) 

520# CSS pattern for `:disabled` 

521CSS_DISABLED = CSSPattern( 

522 ''' 

523 html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset)[disabled], 

524 html|optgroup[disabled] > html|option, 

525 html|fieldset[disabled] > html|*:is(input:not([type=hidden]), button, select, textarea, fieldset), 

526 html|fieldset[disabled] > 

527 html|*:not(legend:nth-of-type(1)) html|*:is(input:not([type=hidden]), button, select, textarea, fieldset) 

528 ''', 

529 FLG_PSEUDO | FLG_HTML 

530) 

531# CSS pattern for `:enabled` 

532CSS_ENABLED = CSSPattern( 

533 ''' 

534 html|*:is(input:not([type=hidden]), button, select, textarea, fieldset, optgroup, option, fieldset):not(:disabled) 

535 ''', 

536 FLG_PSEUDO | FLG_HTML 

537) 

538# CSS pattern for `:required` 

539CSS_REQUIRED = CSSPattern('html|*:is(input, textarea, select)[required]', FLG_PSEUDO | FLG_HTML) 

540# CSS pattern for `:optional` 

541CSS_OPTIONAL = CSSPattern('html|*:is(input, textarea, select):not([required])', FLG_PSEUDO | FLG_HTML) 

542# CSS pattern for `:placeholder-shown` 

543CSS_PLACEHOLDER_SHOWN = CSSPattern( 

544 ''' 

545 html|input:is( 

546 :not([type]), 

547 [type=""], 

548 [type=text], 

549 [type=search], 

550 [type=url], 

551 [type=tel], 

552 [type=email], 

553 [type=password], 

554 [type=number] 

555 )[placeholder]:not([placeholder='']):is(:not([value]), [value=""]), 

556 html|textarea[placeholder]:not([placeholder='']) 

557 ''', 

558 FLG_PSEUDO | FLG_HTML | FLG_PLACEHOLDER_SHOWN 

559) 

560# CSS pattern for `:read-write` (CSS_DISABLED must be compiled first) 

561CSS_READ_WRITE = CSSPattern( 

562 ''' 

563 html|*:is( 

564 textarea, 

565 input:is( 

566 :not([type]), 

567 [type=""], 

568 [type=text], 

569 [type=search], 

570 [type=url], 

571 [type=tel], 

572 [type=email], 

573 [type=number], 

574 [type=password], 

575 [type=date], 

576 [type=datetime-local], 

577 [type=month], 

578 [type=time], 

579 [type=week] 

580 ) 

581 ):not([readonly], :disabled), 

582 html|*:is([contenteditable=""], [contenteditable="true" i]) 

583 ''', 

584 FLG_PSEUDO | FLG_HTML 

585) 

586# CSS pattern for `:read-only` 

587CSS_READ_ONLY = CSSPattern('html|*:not(:read-write)', FLG_PSEUDO | FLG_HTML) 

588# CSS pattern for `:in-range` 

589CSS_IN_RANGE = CSSPattern( 

590 ''' 

591 html|input:is( 

592 [type="date"], 

593 [type="month"], 

594 [type="week"], 

595 [type="time"], 

596 [type="datetime-local"], 

597 [type="number"], 

598 [type="range"] 

599 ):is( 

600 [min], 

601 [max] 

602 ) 

603 ''', 

604 FLG_PSEUDO | FLG_HTML | FLG_IN_RANGE 

605) 

606# CSS pattern for `:out-of-range` 

607CSS_OUT_OF_RANGE = CSSPattern( 

608 ''' 

609 html|input:is( 

610 [type="date"], 

611 [type="month"], 

612 [type="week"], 

613 [type="time"], 

614 [type="datetime-local"], 

615 [type="number"], 

616 [type="range"] 

617 ):is( 

618 [min], 

619 [max] 

620 ) 

621 ''', 

622 FLG_PSEUDO | FLG_HTML | FLG_OUT_OF_RANGE 

623) 

624# CSS pattern for :open 

625CSS_OPEN = CSSPattern('html|*:is(details, dialog)[open]', FLG_PSEUDO | FLG_HTML) 

626# CSS pattern for :muted 

627CSS_MUTED = CSSPattern('html|*:is(video, audio)[muted]', FLG_PSEUDO | FLG_HTML) 

628# CSS pattern default for `:nth-child` "of S" feature 

629CSS_NTH_OF_S_DEFAULT = CSSPattern("*|*", FLG_PSEUDO) 

630 

631 

632class CSSParser: 

633 """Parse CSS selectors.""" 

634 

635 CSS_TOKENS = ( 

636 SelectorPattern("pseudo_close", PAT_PSEUDO_CLOSE), 

637 SpecialPseudoPattern( 

638 ( 

639 ( 

640 "pseudo_contains", 

641 (':contains', ':-soup-contains', ':-soup-contains-own'), 

642 PAT_PSEUDO_CONTAINS, 

643 SelectorPattern 

644 ), 

645 ("pseudo_nth_child", (':nth-child', ':nth-last-child'), PAT_PSEUDO_NTH_CHILD, SelectorPattern), 

646 ("pseudo_nth_type", (':nth-of-type', ':nth-last-of-type'), PAT_PSEUDO_NTH_TYPE, SelectorPattern), 

647 ("pseudo_lang", (':lang',), PAT_PSEUDO_LANG, SelectorPattern), 

648 ("pseudo_dir", (':dir',), PAT_PSEUDO_DIR, SelectorPattern) 

649 ) 

650 ), 

651 SelectorPattern("pseudo_class_custom", PAT_PSEUDO_CLASS_CUSTOM), 

652 SelectorPattern("pseudo_class", PAT_PSEUDO_CLASS), 

653 SelectorPattern("pseudo_element", PAT_PSEUDO_ELEMENT), 

654 SelectorPattern("amp", PAT_AMP), 

655 SelectorPattern("at_rule", PAT_AT_RULE), 

656 SelectorPattern("id", PAT_ID), 

657 SelectorPattern("class", PAT_CLASS), 

658 SelectorPattern("tag", PAT_TAG), 

659 SelectorPattern("attribute", PAT_ATTR), 

660 SelectorPattern("combine", PAT_COMBINE) 

661 ) 

662 

663 # Pseudos that expand to selectors 

664 PSEUDO_SELECTORS = PseudoSelectorMap( 

665 { 

666 ':link': CSS_LINK, 

667 ':any-link': CSS_LINK, 

668 ':checked': CSS_CHECKED, 

669 ':default': CSS_DEFAULT, 

670 ':indeterminate': CSS_INDETERMINATE, 

671 ':disabled': CSS_DISABLED, 

672 ':enabled': CSS_ENABLED, 

673 ':required': CSS_REQUIRED, 

674 ':muted': CSS_MUTED, 

675 ':open': CSS_OPEN, 

676 ':optional': CSS_OPTIONAL, 

677 ':read-only': CSS_READ_ONLY, 

678 ':read-write': CSS_READ_WRITE, 

679 ':in-range': CSS_IN_RANGE, 

680 ':out-of-range': CSS_OUT_OF_RANGE, 

681 ':placeholder-shown': CSS_PLACEHOLDER_SHOWN, 

682 '<nth-of-s>': CSS_NTH_OF_S_DEFAULT 

683 } 

684 ) 

685 

686 def __init__( 

687 self, 

688 selector: str, 

689 *, 

690 custom: dict[str, str | ct.SelectorList] | None = None, 

691 ignore: Iterable[str] | None = None, 

692 flags: int = 0 

693 ) -> None: 

694 """Initialize.""" 

695 

696 self.pattern = selector.replace('\x00', '\ufffd') 

697 self.flags = flags 

698 self.debug = self.flags & util.DEBUG 

699 self.custom = {} if custom is None else custom 

700 self.ignore = frozenset([] if ignore is None else ignore) 

701 self.count = 0 

702 

703 def increment_count(self, increment: int = 1) -> None: 

704 """Check the current selector count.""" 

705 

706 self.count += increment 

707 if self.count > SELECTOR_LIMIT: 

708 raise ValueError(f'Selector exceeds pseudo-class nesting limit of {SELECTOR_LIMIT}') 

709 

710 def parse_attribute_selector(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: 

711 """Create attribute selector from the returned regex match.""" 

712 

713 inverse = False 

714 op = m.group('cmp') 

715 case = util.lower(m.group('case')) if m.group('case') else None 

716 ns = css_unescape(m.group('attr_ns')[:-1]) if m.group('attr_ns') else '' 

717 attr = css_unescape(m.group('attr_name')) 

718 is_type = False 

719 pattern2 = None 

720 value = '' 

721 

722 if case: 

723 flags = (re.I if case == 'i' else 0) | re.DOTALL 

724 elif util.lower(attr) == 'type': 

725 flags = re.I | re.DOTALL 

726 is_type = True 

727 else: 

728 flags = re.DOTALL 

729 

730 if op: 

731 value = css_unescape(m.group('value')) 

732 

733 if not op: 

734 # Attribute name 

735 pattern = None 

736 elif op.startswith('^'): 

737 # Value start with 

738 # `^=` should match nothing if the value is empty, so use `(?!)` which cannot be matched. 

739 value = r'(?!)' if not value else re.escape(value) 

740 pattern = re.compile(r'^%s.*' % value, flags) 

741 elif op.startswith('$'): 

742 # Value ends with 

743 # `$=` should match nothing if the value is empty, so use `(?!)` which cannot be matched. 

744 value = r'(?!)' if not value else re.escape(value) 

745 pattern = re.compile(r'.*?%s$' % value, flags) 

746 elif op.startswith('*'): 

747 # Value contains 

748 # `*=` should match nothing if the value is empty, so use `(?!)` which cannot be matched. 

749 value = r'(?!)' if not value else re.escape(value) 

750 pattern = re.compile(r'.*?%s.*' % value, flags) 

751 elif op.startswith('~'): 

752 # Value contains word within space separated list 

753 # `*~` should match nothing if the value is empty, so use `(?!)` which cannot be matched. 

754 value = r'(?!)' if not value or RE_WS.search(value) else re.escape(value) 

755 pattern = re.compile(r'.*?(?:(?<=^)|(?<=[ \t\r\n\f]))%s(?=(?:[ \t\r\n\f]|$)).*' % value, flags) 

756 elif op.startswith('|'): 

757 # Value starts with word in dash separated list 

758 pattern = re.compile(r'^%s(?:-.*)?$' % re.escape(value), flags) 

759 else: 

760 # Value matches 

761 pattern = re.compile(r'^%s$' % re.escape(value), flags) 

762 if op.startswith('!'): 

763 # Equivalent to `:not([attr=value])` 

764 inverse = True 

765 if is_type and pattern: 

766 pattern2 = re.compile(pattern.pattern) 

767 

768 # Append the attribute selector 

769 sel_attr = ct.SelectorAttribute(attr, ns, pattern, pattern2) 

770 if inverse: 

771 # If we are using `!=`, we need to nest the pattern under a `:not()`. 

772 sub_sel = _Selector() 

773 sub_sel.attributes.append(sel_attr) 

774 not_list = ct.SelectorList([sub_sel.freeze()], True, False) 

775 sel.selectors.append(not_list) 

776 else: 

777 sel.attributes.append(sel_attr) 

778 

779 has_selector = True 

780 return has_selector 

781 

782 def parse_tag_pattern(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: 

783 """Parse tag pattern from regex match.""" 

784 

785 prefix = css_unescape(m.group('tag_ns')[:-1]) if m.group('tag_ns') else None 

786 tag = css_unescape(m.group('tag_name')) 

787 sel.tag = ct.SelectorTag(tag, prefix) 

788 has_selector = True 

789 return has_selector 

790 

791 def parse_pseudo_class_custom(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: 

792 """ 

793 Parse custom pseudo class alias. 

794 

795 Compile custom selectors as we need them. When compiling a custom selector, 

796 set it to `None` in the dictionary so we can avoid an infinite loop. 

797 """ 

798 

799 pseudo = util.lower(css_unescape(m.group('name'))) 

800 selector = self.custom.get(pseudo) 

801 if selector is None: 

802 raise SelectorSyntaxError( 

803 f"Undefined custom selector '{pseudo}' found at position {m.end(0)}", 

804 self.pattern, 

805 m.end(0) 

806 ) 

807 

808 if not isinstance(selector, ct.SelectorList): 

809 del self.custom[pseudo] 

810 selector = CSSParser( 

811 selector, custom=self.custom, flags=self.flags, ignore=self.ignore 

812 ).process_selectors(flags=FLG_PSEUDO) 

813 self.custom[pseudo] = selector 

814 

815 self.increment_count(selector.count) 

816 sel.selectors.append(selector) 

817 has_selector = True 

818 return has_selector 

819 

820 def parse_pseudo_class( 

821 self, 

822 sel: _Selector, 

823 m: Match[str], 

824 has_selector: bool, 

825 iselector: Iterator[tuple[str, Match[str]]], 

826 is_html: bool 

827 ) -> tuple[bool, bool]: 

828 """Parse pseudo class.""" 

829 

830 complex_pseudo = False 

831 pseudo = util.lower(css_unescape(m.group('name'))) 

832 if m.group('open'): 

833 complex_pseudo = True 

834 if complex_pseudo and pseudo in PSEUDO_COMPLEX: 

835 has_selector = self.parse_pseudo_open(sel, pseudo, has_selector, iselector, m.end(0)) 

836 elif not complex_pseudo and pseudo in PSEUDO_SIMPLE: 

837 if pseudo == ':root': 

838 sel.flags |= ct.SEL_ROOT 

839 elif pseudo == ':defined': 

840 sel.flags |= ct.SEL_DEFINED 

841 is_html = True 

842 elif pseudo == ':scope': 

843 sel.flags |= ct.SEL_SCOPE 

844 elif pseudo == ':empty': 

845 sel.flags |= ct.SEL_EMPTY 

846 elif pseudo in self.PSEUDO_SELECTORS: 

847 pseudo_selector = self.PSEUDO_SELECTORS[pseudo] 

848 self.increment_count(pseudo_selector.count) 

849 sel.selectors.append(pseudo_selector) 

850 elif pseudo == ':first-child': 

851 sel.nth.append(ct.SelectorNth(0, False, 1, False, False, ct.SelectorList())) 

852 elif pseudo == ':last-child': 

853 sel.nth.append(ct.SelectorNth(0, False, 1, False, True, ct.SelectorList())) 

854 elif pseudo == ':first-of-type': 

855 sel.nth.append(ct.SelectorNth(0, False, 1, True, False, ct.SelectorList())) 

856 elif pseudo == ':last-of-type': 

857 sel.nth.append(ct.SelectorNth(0, False, 1, True, True, ct.SelectorList())) 

858 elif pseudo == ':only-child': 

859 sel.nth.extend( 

860 [ 

861 ct.SelectorNth(0, False, 1, False, False, ct.SelectorList()), 

862 ct.SelectorNth(0, False, 1, False, True, ct.SelectorList()) 

863 ] 

864 ) 

865 elif pseudo == ':only-of-type': 

866 sel.nth.extend( 

867 [ 

868 ct.SelectorNth(0, False, 1, True, False, ct.SelectorList()), 

869 ct.SelectorNth(0, False, 1, True, True, ct.SelectorList()) 

870 ] 

871 ) 

872 has_selector = True 

873 elif complex_pseudo and pseudo in PSEUDO_COMPLEX_NO_MATCH: 

874 self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN) 

875 sel.no_match = True 

876 has_selector = True 

877 elif not complex_pseudo and pseudo in PSEUDO_SIMPLE_NO_MATCH: 

878 sel.no_match = True 

879 has_selector = True 

880 elif pseudo in PSEUDO_SUPPORTED: 

881 raise SelectorSyntaxError( 

882 f"Invalid syntax for pseudo class '{pseudo}'", 

883 self.pattern, 

884 m.start(0) 

885 ) 

886 else: 

887 raise SelectorSyntaxError( 

888 f"'{pseudo}' was detected as a pseudo-class and is either unsupported or invalid. " 

889 "If the syntax was not intended to be recognized as a pseudo-class, please escape the colon.", 

890 self.pattern, 

891 m.start(0) 

892 ) 

893 

894 return has_selector, is_html 

895 

896 def parse_pseudo_nth( 

897 self, 

898 sel: _Selector, 

899 m: Match[str], 

900 has_selector: bool, 

901 iselector: Iterator[tuple[str, Match[str]]] 

902 ) -> bool: 

903 """Parse `nth` pseudo.""" 

904 

905 mdict = m.groupdict() 

906 if mdict.get('pseudo_nth_child'): 

907 postfix = '_child' 

908 else: 

909 postfix = '_type' 

910 mdict['name'] = util.lower(css_unescape(mdict['name'])) 

911 content = util.lower(mdict.get('nth' + postfix)) 

912 if content == 'even': 

913 # 2n 

914 s1 = 2 

915 s2 = 0 

916 var = True 

917 elif content == 'odd': 

918 # 2n+1 

919 s1 = 2 

920 s2 = 1 

921 var = True 

922 else: 

923 nth_parts = cast(Match[str], RE_NTH.match(content)) 

924 _s1 = '-' if nth_parts.group('s1') and nth_parts.group('s1') == '-' else '' 

925 _s2 = '' 

926 a = nth_parts.group('a') 

927 var = a.endswith('n') 

928 if a.startswith('n'): 

929 _s1 += '1' 

930 elif var: 

931 _s1 += a[:-1] 

932 else: 

933 _s2 = _s1 + a 

934 _s1 = '' 

935 if nth_parts.group('s2') and nth_parts.group('s2') == '-': 

936 _s2 = '-' 

937 if nth_parts.group('b'): 

938 _s2 += nth_parts.group('b') 

939 s1 = int(_s1, 10) if _s1 else 0 

940 s2 = int(_s2, 10) if _s2 else 0 

941 

942 pseudo_sel = mdict['name'] 

943 if postfix == '_child': 

944 if m.group('of'): 

945 # Parse the rest of `of S`. 

946 nth_sel = self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN) 

947 else: 

948 # Use default `*|*` for `of S`. 

949 nth_sel = self.PSEUDO_SELECTORS['<nth-of-s>'] 

950 self.increment_count(nth_sel.count) 

951 if pseudo_sel == ':nth-child': 

952 sel.nth.append(ct.SelectorNth(s1, var, s2, False, False, nth_sel)) 

953 elif pseudo_sel == ':nth-last-child': 

954 sel.nth.append(ct.SelectorNth(s1, var, s2, False, True, nth_sel)) 

955 else: 

956 if pseudo_sel == ':nth-of-type': 

957 sel.nth.append(ct.SelectorNth(s1, var, s2, True, False, ct.SelectorList())) 

958 elif pseudo_sel == ':nth-last-of-type': 

959 sel.nth.append(ct.SelectorNth(s1, var, s2, True, True, ct.SelectorList())) 

960 has_selector = True 

961 return has_selector 

962 

963 def parse_pseudo_open( 

964 self, 

965 sel: _Selector, 

966 name: str, 

967 has_selector: bool, 

968 iselector: Iterator[tuple[str, Match[str]]], 

969 index: int 

970 ) -> bool: 

971 """Parse pseudo with opening bracket.""" 

972 

973 flags = FLG_PSEUDO | FLG_OPEN 

974 if name == ':not': 

975 flags |= FLG_NOT 

976 elif name == ':has': 

977 flags |= FLG_RELATIVE 

978 elif name in (':where', ':is'): 

979 flags |= FLG_FORGIVE 

980 

981 sel.selectors.append(self.parse_selectors(iselector, index, flags)) 

982 has_selector = True 

983 

984 return has_selector 

985 

986 def parse_has_combinator( 

987 self, 

988 sel: _Selector, 

989 m: Match[str], 

990 has_selector: bool, 

991 selectors: list[_Selector], 

992 rel_type: str, 

993 index: int 

994 ) -> tuple[bool, _Selector, str]: 

995 """Parse combinator tokens.""" 

996 

997 combinator = m.group('relation').strip() 

998 if not combinator: 

999 combinator = WS_COMBINATOR 

1000 if combinator == COMMA_COMBINATOR: 

1001 if not has_selector: 

1002 raise SelectorSyntaxError( 

1003 f"The combinator '{combinator}' at position {index}, must have a selector before it", 

1004 self.pattern, 

1005 index 

1006 ) 

1007 sel.rel_type = rel_type 

1008 selectors[-1].relations.append(sel) 

1009 rel_type = ":" + WS_COMBINATOR 

1010 selectors.append(_Selector()) 

1011 else: 

1012 if has_selector: 

1013 # End the current selector and associate the leading combinator with this selector. 

1014 sel.rel_type = rel_type 

1015 selectors[-1].relations.append(sel) 

1016 elif rel_type[1:] != WS_COMBINATOR: 

1017 # It's impossible to have two whitespace combinators after each other as the patterns 

1018 # will gobble up trailing whitespace. It is also impossible to have a whitespace 

1019 # combinator after any other kind for the same reason. But we could have 

1020 # multiple non-whitespace combinators. So if the current combinator is not a whitespace, 

1021 # then we've hit the multiple combinator case, so we should fail. 

1022 raise SelectorSyntaxError( 

1023 f'The multiple combinators at position {index}', 

1024 self.pattern, 

1025 index 

1026 ) 

1027 

1028 # Set the leading combinator for the next selector. 

1029 rel_type = ':' + combinator 

1030 

1031 sel = _Selector() 

1032 has_selector = False 

1033 return has_selector, sel, rel_type 

1034 

1035 def parse_combinator( 

1036 self, 

1037 sel: _Selector, 

1038 m: Match[str], 

1039 has_selector: bool, 

1040 selectors: list[_Selector], 

1041 relations: list[_Selector], 

1042 is_pseudo: bool, 

1043 is_forgive: bool, 

1044 index: int 

1045 ) -> tuple[bool, _Selector]: 

1046 """Parse combinator tokens.""" 

1047 

1048 combinator = m.group('relation').strip() 

1049 if not combinator: 

1050 combinator = WS_COMBINATOR 

1051 if not has_selector: 

1052 if not is_forgive or combinator != COMMA_COMBINATOR: 

1053 raise SelectorSyntaxError( 

1054 f"The combinator '{combinator}' at position {index}, must have a selector before it", 

1055 self.pattern, 

1056 index 

1057 ) 

1058 

1059 # If we are in a forgiving pseudo class, just make the selector a "no match" 

1060 if combinator == COMMA_COMBINATOR: 

1061 self.increment_count() 

1062 del relations[:] 

1063 else: 

1064 if combinator == COMMA_COMBINATOR: 

1065 if not sel.tag and not is_pseudo: 

1066 # Implied `*` 

1067 sel.tag = ct.SelectorTag('*', None) 

1068 sel.relations.extend(relations) 

1069 selectors.append(sel) 

1070 del relations[:] 

1071 else: 

1072 sel.relations.extend(relations) 

1073 sel.rel_type = combinator 

1074 del relations[:] 

1075 relations.append(sel) 

1076 

1077 sel = _Selector() 

1078 has_selector = False 

1079 

1080 return has_selector, sel 

1081 

1082 def parse_class_id(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: 

1083 """Parse HTML classes and ids.""" 

1084 

1085 selector = m.group(0) 

1086 if selector.startswith('.'): 

1087 sel.classes.append(css_unescape(selector[1:])) 

1088 else: 

1089 sel.ids.append(css_unescape(selector[1:])) 

1090 has_selector = True 

1091 return has_selector 

1092 

1093 def parse_pseudo_contains(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: 

1094 """Parse contains.""" 

1095 

1096 pseudo = util.lower(css_unescape(m.group('name'))) 

1097 if pseudo == ":contains": 

1098 warnings.warn( # noqa: B028 

1099 "The pseudo class ':contains' is deprecated, ':-soup-contains' should be used moving forward.", 

1100 FutureWarning 

1101 ) 

1102 contains_own = pseudo == ":-soup-contains-own" 

1103 patterns = [ 

1104 css_unescape(token.group('value')) 

1105 for token in RE_VALUES.finditer(m.group('values')) 

1106 if not token.group('split') 

1107 ] 

1108 sel.contains.append(ct.SelectorContains(patterns, contains_own)) 

1109 has_selector = True 

1110 return has_selector 

1111 

1112 def parse_pseudo_lang(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: 

1113 """Parse pseudo language.""" 

1114 

1115 patterns = [ 

1116 css_unescape(token.group('value')) 

1117 for token in RE_VALUES.finditer(m.group('values')) 

1118 if not token.group('split') 

1119 ] 

1120 sel.lang.append(ct.SelectorLang(patterns)) 

1121 has_selector = True 

1122 

1123 return has_selector 

1124 

1125 def parse_pseudo_dir(self, sel: _Selector, m: Match[str], has_selector: bool) -> bool: 

1126 """Parse pseudo direction.""" 

1127 

1128 value = ct.SEL_DIR_LTR if util.lower(m.group('dir')) == 'ltr' else ct.SEL_DIR_RTL 

1129 sel.flags |= value 

1130 has_selector = True 

1131 return has_selector 

1132 

1133 def parse_selectors( 

1134 self, 

1135 iselector: Iterator[tuple[str, Match[str]]], 

1136 index: int = 0, 

1137 flags: int = 0 

1138 ) -> ct.SelectorList: 

1139 """Parse selectors.""" 

1140 

1141 # Initialize important variables 

1142 sel = _Selector() 

1143 selectors = [] 

1144 has_selector = False 

1145 closed = False 

1146 relations = [] # type: list[_Selector] 

1147 rel_type = ":" + WS_COMBINATOR 

1148 count = self.count 

1149 

1150 # Setup various flags 

1151 is_open = bool(flags & FLG_OPEN) 

1152 is_pseudo = bool(flags & FLG_PSEUDO) 

1153 is_relative = bool(flags & FLG_RELATIVE) 

1154 is_not = bool(flags & FLG_NOT) 

1155 is_html = bool(flags & FLG_HTML) 

1156 is_default = bool(flags & FLG_DEFAULT) 

1157 is_indeterminate = bool(flags & FLG_INDETERMINATE) 

1158 is_in_range = bool(flags & FLG_IN_RANGE) 

1159 is_out_of_range = bool(flags & FLG_OUT_OF_RANGE) 

1160 is_placeholder_shown = bool(flags & FLG_PLACEHOLDER_SHOWN) 

1161 is_forgive = bool(flags & FLG_FORGIVE) 

1162 

1163 # Print out useful debug stuff 

1164 if self.debug: # pragma: no cover 

1165 if is_pseudo: 

1166 print(' is_pseudo: True') 

1167 if is_open: 

1168 print(' is_open: True') 

1169 if is_relative: 

1170 print(' is_relative: True') 

1171 if is_not: 

1172 print(' is_not: True') 

1173 if is_html: 

1174 print(' is_html: True') 

1175 if is_default: 

1176 print(' is_default: True') 

1177 if is_indeterminate: 

1178 print(' is_indeterminate: True') 

1179 if is_in_range: 

1180 print(' is_in_range: True') 

1181 if is_out_of_range: 

1182 print(' is_out_of_range: True') 

1183 if is_placeholder_shown: 

1184 print(' is_placeholder_shown: True') 

1185 if is_forgive: 

1186 print(' is_forgive: True') 

1187 

1188 # The algorithm for relative selectors require an initial selector in the selector list 

1189 if is_relative: 

1190 selectors.append(_Selector()) 

1191 

1192 try: 

1193 while True: 

1194 key, m = next(iselector) 

1195 

1196 if key not in ('combine', 'pseudo_close'): 

1197 self.increment_count() 

1198 

1199 # Handle parts 

1200 if self.ignore: 

1201 mi = RE_PSEUDO_IGNORE.match(m.group(0)) 

1202 if mi is not None and mi.group('name').lower() in self.ignore: 

1203 raise SelectorSyntaxError( 

1204 f"The selector '{mi.group('name')}' at position {m.start(0)}, has been disallowed", 

1205 self.pattern, 

1206 m.start(0) 

1207 ) 

1208 if key == "at_rule": 

1209 raise NotImplementedError(f"At-rules found at position {m.start(0)}") 

1210 elif key == "amp": 

1211 sel.flags |= ct.SEL_SCOPE 

1212 has_selector = True 

1213 elif key == 'pseudo_class_custom': 

1214 has_selector = self.parse_pseudo_class_custom(sel, m, has_selector) 

1215 elif key == 'pseudo_class': 

1216 has_selector, is_html = self.parse_pseudo_class(sel, m, has_selector, iselector, is_html) 

1217 elif key == 'pseudo_element': 

1218 raise NotImplementedError(f"Pseudo-element found at position {m.start(0)}") 

1219 elif key == 'pseudo_contains': 

1220 has_selector = self.parse_pseudo_contains(sel, m, has_selector) 

1221 elif key in ('pseudo_nth_type', 'pseudo_nth_child'): 

1222 has_selector = self.parse_pseudo_nth(sel, m, has_selector, iselector) 

1223 elif key == 'pseudo_lang': 

1224 has_selector = self.parse_pseudo_lang(sel, m, has_selector) 

1225 elif key == 'pseudo_dir': 

1226 has_selector = self.parse_pseudo_dir(sel, m, has_selector) 

1227 # Currently only supports HTML 

1228 is_html = True 

1229 elif key == 'pseudo_close': 

1230 if not has_selector: 

1231 if not is_forgive: 

1232 raise SelectorSyntaxError( 

1233 f"Expected a selector at position {m.start(0)}", 

1234 self.pattern, 

1235 m.start(0) 

1236 ) 

1237 sel.no_match = True 

1238 if is_open: 

1239 closed = True 

1240 break 

1241 else: 

1242 raise SelectorSyntaxError( 

1243 f"Unmatched pseudo-class close at position {m.start(0)}", 

1244 self.pattern, 

1245 m.start(0) 

1246 ) 

1247 elif key == 'combine': 

1248 if is_relative: 

1249 has_selector, sel, rel_type = self.parse_has_combinator( 

1250 sel, m, has_selector, selectors, rel_type, index 

1251 ) 

1252 else: 

1253 has_selector, sel = self.parse_combinator( 

1254 sel, m, has_selector, selectors, relations, is_pseudo, is_forgive, index 

1255 ) 

1256 elif key == 'attribute': 

1257 has_selector = self.parse_attribute_selector(sel, m, has_selector) 

1258 elif key == 'tag': 

1259 if has_selector: 

1260 raise SelectorSyntaxError( 

1261 f"Tag name found at position {m.start(0)} instead of at the start", 

1262 self.pattern, 

1263 m.start(0) 

1264 ) 

1265 has_selector = self.parse_tag_pattern(sel, m, has_selector) 

1266 elif key in ('class', 'id'): 

1267 has_selector = self.parse_class_id(sel, m, has_selector) 

1268 

1269 index = m.end(0) 

1270 except StopIteration: 

1271 pass 

1272 

1273 # Handle selectors that are not closed 

1274 if is_open and not closed: 

1275 raise SelectorSyntaxError( 

1276 f"Unclosed pseudo-class at position {index}", 

1277 self.pattern, 

1278 index 

1279 ) 

1280 

1281 # Cleanup completed selector piece 

1282 if has_selector: 

1283 if not sel.tag and not is_pseudo: 

1284 # Implied `*` 

1285 sel.tag = ct.SelectorTag('*', None) 

1286 if is_relative: 

1287 sel.rel_type = rel_type 

1288 selectors[-1].relations.append(sel) 

1289 else: 

1290 sel.relations.extend(relations) 

1291 del relations[:] 

1292 selectors.append(sel) 

1293 

1294 # Forgive empty slots in pseudo-classes that have lists (and are forgiving) 

1295 elif is_forgive and (not selectors or not relations): 

1296 # Handle normal pseudo-classes with empty slots like `:is()` etc. 

1297 self.increment_count() 

1298 sel.no_match = True 

1299 del relations[:] 

1300 selectors.append(sel) 

1301 has_selector = True 

1302 

1303 if not has_selector: 

1304 # We will always need to finish a selector when `:has()` is used as it leads with combining. 

1305 # May apply to others as well. 

1306 raise SelectorSyntaxError( 

1307 f'Expected a selector at position {index}', 

1308 self.pattern, 

1309 index 

1310 ) 

1311 

1312 # Some patterns require additional logic, such as default. We try to make these the 

1313 # last pattern, and append the appropriate flag to that selector which communicates 

1314 # to the matcher what additional logic is required. 

1315 if is_default: 

1316 selectors[-1].flags = ct.SEL_DEFAULT 

1317 if is_indeterminate: 

1318 selectors[-1].flags = ct.SEL_INDETERMINATE 

1319 if is_in_range: 

1320 selectors[-1].flags = ct.SEL_IN_RANGE 

1321 if is_out_of_range: 

1322 selectors[-1].flags = ct.SEL_OUT_OF_RANGE 

1323 if is_placeholder_shown: 

1324 selectors[-1].flags = ct.SEL_PLACEHOLDER_SHOWN 

1325 

1326 # Return selector list 

1327 return ct.SelectorList([s.freeze() for s in selectors], is_not, is_html, self.count - count) 

1328 

1329 def selector_iter(self, pattern: str) -> Iterator[tuple[str, Match[str]]]: 

1330 """Iterate selector tokens.""" 

1331 

1332 # Ignore whitespace and comments at start and end of pattern 

1333 m = RE_WS_BEGIN.search(pattern) 

1334 index = m.end(0) if m else 0 

1335 m = RE_WS_END.search(pattern[::-1]) 

1336 offset = m.end(0) if m else 0 

1337 end = len(pattern) - (1 + offset) 

1338 

1339 if self.debug: # pragma: no cover 

1340 print(f'## PARSING: {pattern!r}') 

1341 while index <= end: 

1342 m = None 

1343 for v in self.CSS_TOKENS: 

1344 m = v.match(pattern, index, self.flags) 

1345 if m: 

1346 name = v.get_name() 

1347 if self.debug: # pragma: no cover 

1348 print(f"TOKEN: '{name}' --> {m.group(0)!r} at position {m.start(0)}") 

1349 index = m.end(0) 

1350 yield name, m 

1351 break 

1352 if m is None: 

1353 c = pattern[index] 

1354 # If the character represents the start of one of the known selector types, 

1355 # throw an exception mentioning that the known selector type is in error; 

1356 # otherwise, report the invalid character. 

1357 if c == '[': 

1358 msg = f"Malformed attribute selector at position {index}" 

1359 elif c == '.': 

1360 msg = f"Malformed class selector at position {index}" 

1361 elif c == '#': 

1362 msg = f"Malformed id selector at position {index}" 

1363 elif c == ':': 

1364 msg = f"Malformed pseudo-class selector at position {index}" 

1365 else: 

1366 msg = f"Invalid character {c!r} position {index}" 

1367 raise SelectorSyntaxError(msg, self.pattern, index) 

1368 if self.debug: # pragma: no cover 

1369 print('## END PARSING') 

1370 

1371 def process_selectors(self, index: int = 0, flags: int = 0) -> ct.SelectorList: 

1372 """Process selectors.""" 

1373 

1374 return self.parse_selectors(self.selector_iter(self.pattern), index, flags)