1use super::*;
4
5pub(crate) fn parse_selector(s: &str) -> Option<Selector> {
6 let chain = parse_selector_chain(s)?;
7 if chain.len() == 1 && chain[0].combinator.is_none() {
8 Some(Selector::Simple(chain[0].simple.clone()))
9 } else {
10 Some(Selector::Chain(chain))
11 }
12}
13
14#[inline]
15fn is_ident_byte(b: u8) -> bool {
16 b.is_ascii_alphanumeric() || b == b'-' || b == b'_'
17}
18
19pub(crate) fn parse_simple_selector(s: &str) -> Option<SimpleSelector> {
20 if s.is_empty() {
21 return None;
22 }
23
24 let mut selector = SimpleSelector::default();
25 let bytes = s.as_bytes();
26 let mut i = 0usize;
27 let mut after_pe = 0u8;
29 while i < bytes.len() {
30 match bytes[i] {
31 b'#' => {
32 i += 1;
33 let start = i;
34 while i < bytes.len() && is_ident_byte(bytes[i]) {
35 i += 1;
36 }
37 if start == i && !matches!(bytes.get(i), Some(&b) if b == b'\\' || b >= 0x80) {
39 return None;
40 }
41 if start < i {
42 if let Some(id_str) = s.get(start..i) {
43 selector.id = Some(String::from(id_str));
44 }
45 }
46 }
47 b'.' => {
48 i += 1;
49 let start = i;
50 while i < bytes.len() && is_ident_byte(bytes[i]) {
51 i += 1;
52 }
53 if start == i && !matches!(bytes.get(i), Some(&b) if b == b'\\' || b >= 0x80) {
54 return None;
55 }
56 if start < i {
57 if let Some(cls_str) = s.get(start..i) {
58 selector.class.push(String::from(cls_str));
59 }
60 }
61 }
62 b'*' => {
63 if i > 0 && bytes[i - 1] == b'-' && i > 1 && is_ident_byte(bytes[i - 2]) && bytes[i - 2] != b'.' {
66 i += 1;
67 continue;
68 }
69 if i > 0 && bytes[i - 1] != b'|' && !s.contains('\\') {
70 return None;
71 }
72 selector.universal = true;
73 i += 1;
74 }
75 b'[' => {
76 i += 1;
77 let inner_start = i;
78 while i < bytes.len() && bytes[i] != b']' {
79 i += 1;
80 }
81 let inner = s.get(inner_start..i).unwrap_or("");
82 if i < bytes.len() {
83 i += 1;
84 } if let Some(attr) = parse_attr_selector(inner) {
86 selector.attrs.push(attr);
87 }
88 }
89 b':' => {
90 i += 1;
91 let mut dbl = false;
92 if i < bytes.len() && bytes[i] == b':' {
93 i += 1;
94 dbl = true;
95 }
96 let start = i;
97 while i < bytes.len() && is_ident_byte(bytes[i]) {
98 i += 1;
99 }
100 let name = s.get(start..i).unwrap_or("").to_ascii_lowercase();
101 let mut arg = String::new();
102 let mut has_paren = false;
103 let mut closed = true;
104 if i < bytes.len() && bytes[i] == b'(' {
105 has_paren = true;
106 closed = false;
107 i += 1;
108 let arg_start = i;
109 let mut depth = 1;
110 while i < bytes.len() && depth > 0 {
111 match bytes[i] {
112 b'(' => depth += 1,
113 b')' => {
114 depth -= 1;
115 if depth == 0 {
116 break;
117 }
118 }
119 _ => {}
120 }
121 i += 1;
122 }
123 arg = String::from(s.get(arg_start..i).unwrap_or(""));
124 if i < bytes.len() {
125 i += 1;
126 closed = true;
127 } }
129 match name.as_str() {
131 "file-selector-button" => {
132 selector.pseudo_classes.push(PseudoClass::Unmatchable(String::from("pseudo-element")));
134 if after_pe != 3 {
135 after_pe = 2;
136 }
137 continue;
138 }
139 "part" | "slotted" | "has-slotted" | "state" | "host" | "host-context" | "heading" => {
140 let ok = match name.as_str() {
141 "part" => {
142 dbl && has_paren
143 && closed
144 && !arg.trim().is_empty()
145 && arg.split_ascii_whitespace().all(is_css_ident)
146 }
147 "slotted" => {
148 dbl && has_paren
149 && closed
150 && is_compound_text(&arg)
151 && parse_simple_selector(arg.trim()).is_some()
152 }
153 "has-slotted" => {
154 !dbl && (!has_paren || (closed && valid_has_slotted_arg(&arg)))
155 }
156 "state" => {
157 !dbl && has_paren && closed && is_css_ident(arg.trim())
158 && after_pe != 2
159 && after_pe != 3
160 }
161 "host" | "host-context" => {
162 !dbl
163 && (!has_paren
164 || (closed
165 && is_compound_text(&arg)
166 && parse_simple_selector(arg.trim()).is_some()))
167 && (has_paren || name == "host")
168 }
169 _ => {
170 !dbl && (!has_paren || (closed && parse_heading_levels(&arg).is_some()))
172 }
173 };
174 if !ok {
175 return None;
176 }
177 if after_pe == 3 && !dbl {
179 return None;
180 }
181 if name == "heading" {
182 selector
183 .pseudo_classes
184 .push(PseudoClass::Heading(parse_heading_levels(&arg).unwrap_or_default()));
185 } else {
186 let kind = match name.as_str() {
187 "host-context" => "host",
188 n => n,
189 };
190 selector.pseudo_classes.push(PseudoClass::Unmatchable(String::from(kind)));
191 }
192 match name.as_str() {
193 "part" => after_pe = 1,
194 "slotted" => after_pe = 3,
195 _ => {}
196 }
197 continue;
198 }
199 _ => {}
200 }
201 if !dbl {
202 if after_pe == 3 {
203 return None;
204 }
205 if after_pe == 1
206 && matches!(
207 name.as_str(),
208 "has" | "first-child" | "last-child" | "only-child" | "nth-child" | "nth-last-child"
209 | "first-of-type" | "last-of-type" | "only-of-type" | "nth-of-type"
210 | "nth-last-of-type" | "empty"
211 )
212 {
213 return None;
214 }
215 }
216 if !name.is_empty() {
217 if matches!(
218 name.as_str(),
219 "before" | "after" | "marker" | "placeholder" | "first-line" | "first-letter"
220 | "selection" | "backdrop"
221 ) && after_pe != 3
222 {
223 after_pe = 2;
224 }
225 match name.as_str() {
226 "before" => selector.pseudo_element = Some(PseudoElement::Before),
227 "after" => selector.pseudo_element = Some(PseudoElement::After),
228 "marker" => selector.pseudo_element = Some(PseudoElement::Marker),
229 "placeholder" => selector.pseudo_element = Some(PseudoElement::Placeholder),
230 "first-line" => selector.pseudo_element = Some(PseudoElement::FirstLine),
231 "first-letter" => selector.pseudo_element = Some(PseudoElement::FirstLetter),
232 "selection" => selector.pseudo_element = Some(PseudoElement::Selection),
233 "backdrop" => selector.pseudo_element = Some(PseudoElement::Backdrop),
234 _ => {
235 let pseudo = match name.as_str() {
236 "first-child" => PseudoClass::FirstChild,
237 "last-child" => PseudoClass::LastChild,
238 "nth-child" => {
239 let (a, b, sel) = parse_nth_of(&arg);
240 PseudoClass::NthChild(a, b, sel.map(alloc::boxed::Box::new))
241 }
242 "nth-last-child" => {
243 let (a, b, sel) = parse_nth_of(&arg);
244 PseudoClass::NthLastChild(
245 a,
246 b,
247 sel.map(alloc::boxed::Box::new),
248 )
249 }
250 "not" => {
251 let parts = split_top_level_commas(&arg);
253 let mut list: Vec<SimpleSelector> = Vec::new();
254 for p in &parts {
255 if let Some(x) = parse_simple_selector(p.trim()) {
257 if x.pseudo_element.is_none() {
258 list.push(x);
259 }
260 }
261 }
262 if list.is_empty() || list.len() != parts.len() {
263 match parse_simple_selector(arg.trim()) {
264 Some(inner) if inner.pseudo_element.is_none() => {
265 PseudoClass::Not(alloc::boxed::Box::new(inner))
266 }
267 _ => PseudoClass::Other(name),
268 }
269 } else {
270 let last = list.pop().unwrap_or_default();
271 for x in list {
272 selector
273 .pseudo_classes
274 .push(PseudoClass::Not(alloc::boxed::Box::new(x)));
275 }
276 PseudoClass::Not(alloc::boxed::Box::new(last))
277 }
278 }
279 "is" | "where" | "matches" | "any" => {
280 let is_where = name == "where";
281 let list: Vec<SimpleSelector> = split_top_level_commas(&arg)
282 .iter()
283 .filter_map(|s| parse_simple_selector(s.trim()))
284 .collect();
285 if list.is_empty() {
286 PseudoClass::Other(name)
287 } else if is_where {
288 PseudoClass::Where(list)
289 } else {
290 PseudoClass::Is(list)
291 }
292 }
293 "has" => {
294 if arg.to_ascii_lowercase().contains(":has(") {
296 return None;
297 }
298 let mut bad_arg = false;
299 let list: Vec<(HasCombinator, SimpleSelector)> =
300 split_top_level_commas(&arg)
301 .iter()
302 .filter_map(|s| {
303 let s = s.trim();
304 let (comb, rest) = match s.strip_prefix('>') {
305 Some(r) => (HasCombinator::Child, r.trim()),
306 None => match s.strip_prefix('+') {
307 Some(r) => {
308 (HasCombinator::NextSibling, r.trim())
309 }
310 None => match s.strip_prefix('~') {
311 Some(r) => (
312 HasCombinator::SubsequentSibling,
313 r.trim(),
314 ),
315 None => {
316 (HasCombinator::Descendant, s)
317 }
318 },
319 },
320 };
321 let r = parse_simple_selector(rest).map(|sel| (comb, sel));
322 if r.is_none() {
323 bad_arg = true;
324 }
325 r
326 })
327 .collect();
328 if bad_arg {
329 return None;
330 }
331 if list.is_empty() {
332 PseudoClass::Other(name)
333 } else {
334 PseudoClass::Has(list)
335 }
336 }
337 "checked" => PseudoClass::Checked,
338 "disabled" => PseudoClass::Disabled,
339 "lang" => {
340 let code = arg
341 .trim()
342 .trim_matches(|c| c == '\'' || c == '"')
343 .to_ascii_lowercase();
344 if code.is_empty() {
345 PseudoClass::Other(name)
346 } else {
347 PseudoClass::Lang(code)
348 }
349 }
350 "dir" => {
351 let d = arg.trim().to_ascii_lowercase();
352 if d == "ltr" || d == "rtl" {
353 PseudoClass::Dir(d)
354 } else {
355 PseudoClass::Other(name)
356 }
357 }
358 "first-of-type" => PseudoClass::FirstOfType,
359 "last-of-type" => PseudoClass::LastOfType,
360 "nth-of-type" => {
361 let (a, b) = parse_nth(&arg);
362 PseudoClass::NthOfType(a, b)
363 }
364 "nth-last-of-type" => {
365 let (a, b) = parse_nth(&arg);
366 PseudoClass::NthLastOfType(a, b)
367 }
368 "only-of-type" => PseudoClass::OnlyOfType,
369 "only-child" => PseudoClass::OnlyChild,
370 "target" => PseudoClass::Target,
371 "empty" => PseudoClass::Empty,
372 _ => PseudoClass::Other(name),
373 };
374 selector.pseudo_classes.push(pseudo);
375 }
376 }
377 }
378 }
379 b if is_ident_byte(b) => {
380 let start = i;
381 while i < bytes.len() && is_ident_byte(bytes[i]) {
382 i += 1;
383 }
384 if bytes[start].is_ascii_digit() && !s.contains('\\') {
386 return None;
387 }
388 if start < i {
389 if let Some(tag_str) = s.get(start..i) {
390 selector.tag_name = Some(tag_str.to_ascii_lowercase());
391 }
392 }
393 }
394 _ => i += 1,
395 }
396 }
397
398 if !selector.universal
399 && selector.tag_name.is_none()
400 && selector.id.is_none()
401 && selector.class.is_empty()
402 && selector.pseudo_classes.is_empty()
403 && selector.attrs.is_empty()
404 && selector.pseudo_element.is_none()
405 {
406 None
407 } else {
408 Some(selector)
409 }
410}
411
412fn is_css_ident(t: &str) -> bool {
414 let b = t.as_bytes();
415 if b.is_empty() {
416 return false;
417 }
418 let first_ok = |c: u8| c.is_ascii_alphabetic() || c == b'_' || c >= 0x80 || c == b'\\';
419 let head_ok = if b[0] == b'-' {
420 match b.get(1) {
421 Some(&b'-') => true,
422 Some(&c) => first_ok(c),
423 None => false,
424 }
425 } else {
426 first_ok(b[0])
427 };
428 head_ok && b.iter().all(|&c| is_ident_byte(c) || c >= 0x80 || c == b'\\')
429}
430
431fn is_compound_text(s: &str) -> bool {
433 let t = s.trim();
434 if t.is_empty() {
435 return false;
436 }
437 let b = t.as_bytes();
438 let mut i = 0usize;
439 let mut name_start = 0usize;
440 while i < b.len() {
441 match b[i] {
442 b'[' => {
443 while i < b.len() && b[i] != b']' {
444 i += 1;
445 }
446 }
447 b'(' => {
448 let mut depth = 1;
449 let a = i + 1;
450 i += 1;
451 while i < b.len() && depth > 0 {
452 match b[i] {
453 b'(' => depth += 1,
454 b')' => depth -= 1,
455 _ => {}
456 }
457 i += 1;
458 }
459 let inner = t.get(a..i.saturating_sub(1)).unwrap_or("");
460 let name = t.get(name_start..a - 1).unwrap_or("").to_ascii_lowercase();
461 if matches!(name.as_str(), "not" | "is" | "where" | "matches" | "any")
462 && !split_top_level_commas(inner).iter().all(|p| is_compound_text(p))
463 {
464 return false;
465 }
466 continue;
467 }
468 b' ' | b'\t' | b'\n' | b'>' | b'+' | b'~' => return false,
469 b':' | b'.' | b'#' => name_start = i + 1,
470 _ => {}
471 }
472 i += 1;
473 }
474 true
475}
476
477fn valid_has_slotted_arg(arg: &str) -> bool {
479 if arg.trim().is_empty() {
480 return false;
481 }
482 split_top_level_commas(arg).iter().all(|p| match parse_selector_chain(p.trim()) {
483 Some(steps) => steps.iter().all(|st| st.combinator != Some(Combinator::Child)),
484 None => false,
485 })
486}
487
488fn parse_heading_levels(arg: &str) -> Option<Vec<i64>> {
490 if arg.trim().is_empty() {
491 return None;
492 }
493 let mut v = Vec::new();
494 for p in split_top_level_commas(arg) {
495 let t = p.trim();
496 let digits = t.strip_prefix('-').or_else(|| t.strip_prefix('+')).unwrap_or(t);
497 if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
498 return None;
499 }
500 v.push(t.parse::<i64>().unwrap_or(i64::MAX));
501 }
502 Some(v)
503}
504
505pub(crate) fn parse_attr_selector(inner: &str) -> Option<AttrSelector> {
507 let inner = inner.trim();
508 if inner.is_empty() {
509 return None;
510 }
511 for (token, op) in &[
513 ("^=", AttrOp::Prefix),
514 ("$=", AttrOp::Suffix),
515 ("*=", AttrOp::Contains),
516 ("~=", AttrOp::Word),
517 ("|=", AttrOp::Dash),
518 ("=", AttrOp::Eq),
519 ] {
520 if let Some(pos) = inner.find(token) {
521 let name = inner.get(..pos).unwrap_or("").trim().to_lowercase();
522 let mut raw = inner.get(pos + token.len()..).unwrap_or("").trim();
523 let mut case_insensitive = false;
528 for flag in [" i", " I", " s", " S"] {
529 if let Some(stripped) = raw.strip_suffix(flag) {
530 case_insensitive = flag.eq_ignore_ascii_case(" i");
531 raw = stripped.trim_end();
532 break;
533 }
534 }
535 let value = raw.trim_matches('"').trim_matches('\'').to_string();
536 if name.is_empty() {
537 return None;
538 }
539 return Some(AttrSelector {
540 name,
541 op: op.clone(),
542 value,
543 case_insensitive,
544 });
545 }
546 }
547 Some(AttrSelector {
548 name: inner.to_lowercase(),
549 op: AttrOp::Exists,
550 value: String::new(),
551 case_insensitive: false,
552 })
553}
554
555pub(crate) fn parse_nth_of(arg: &str) -> (i64, i64, Option<SimpleSelector>) {
561 let full = arg.trim();
562 let lower = full.to_lowercase();
563 match lower.find(" of ") {
564 Some(pos) => {
565 let an_b_part = full.get(..pos).unwrap_or(full);
566 let sel_part = full.get(pos + 4..).unwrap_or("");
567 let (a, b) = parse_nth(an_b_part);
568 (a, b, parse_simple_selector(sel_part.trim()))
569 }
570 None => {
571 let (a, b) = parse_nth(full);
572 (a, b, None)
573 }
574 }
575}
576
577pub(crate) fn parse_nth(arg: &str) -> (i64, i64) {
579 let full = arg.trim().to_lowercase();
580 let s = full.split(" of ").next().unwrap_or(&full).trim();
585 match crate::os_lib::dom_selector::parse_nth_formula(s) {
587 Some(f) => (f.a as i64, f.b as i64),
588 None => (0, 0),
589 }
590}
591
592pub(crate) fn parse_selector_chain(s: &str) -> Option<Vec<SelectorStep>> {
593 if s.is_empty() {
594 return None;
595 }
596
597 let mut tokens: Vec<(Option<Combinator>, String)> = Vec::new();
598 let chars: Vec<char> = s.chars().collect();
599 let mut i = 0usize;
600 let mut current = String::new();
601 let mut pending_combinator: Option<Combinator> = None;
602 let mut depth = 0i32; while i < chars.len() {
605 let c = chars[i];
606 if c == '[' || c == '(' {
607 depth += 1;
608 current.push(c);
609 i += 1;
610 continue;
611 }
612 if c == ']' || c == ')' {
613 depth -= 1;
614 current.push(c);
615 i += 1;
616 continue;
617 }
618 if depth > 0 {
619 current.push(c);
620 i += 1;
621 continue;
622 }
623 if c == '>' || c == '+' || c == '~' {
624 if !current.trim().is_empty() {
625 tokens.push((pending_combinator, current.trim().to_string()));
626 current.clear();
627 }
628 pending_combinator = Some(match c {
629 '>' => Combinator::Child,
630 '+' => Combinator::NextSibling,
631 _ => Combinator::SubsequentSibling,
632 });
633 i += 1;
634 while i < chars.len() && chars[i].is_ascii_whitespace() {
635 i += 1;
636 }
637 continue;
638 }
639 if c.is_ascii_whitespace() {
640 if !current.trim().is_empty() {
641 tokens.push((pending_combinator, current.trim().to_string()));
642 current.clear();
643 pending_combinator = Some(Combinator::Descendant);
644 }
645 i += 1;
646 while i < chars.len() && chars[i].is_ascii_whitespace() {
647 i += 1;
648 }
649 continue;
650 }
651 current.push(c);
652 i += 1;
653 }
654 if !current.trim().is_empty() {
655 tokens.push((pending_combinator, current.trim().to_string()));
656 }
657 if tokens.is_empty() {
658 return None;
659 }
660
661 let mut steps = Vec::new();
662 let ntok = tokens.len();
663 for (idx, (comb, tok)) in tokens.into_iter().enumerate() {
664 let simple = parse_simple_selector(&tok)?;
665 if idx + 1 < ntok
667 && simple
668 .pseudo_classes
669 .iter()
670 .any(|p| matches!(p, PseudoClass::Unmatchable(n) if n == "part" || n == "slotted"))
671 {
672 return None;
673 }
674 let combinator = if idx == 0 { None } else { comb };
675 steps.push(SelectorStep { simple, combinator });
676 }
677 Some(steps)
678}
679
680pub(crate) fn is_selector_ident_char(c: char) -> bool {
681 c.is_ascii_alphanumeric() || c == '-' || c == '_'
682}
683
684pub(crate) fn simple_specificity(sel: &SimpleSelector) -> (u32, u32, u32) {
689 let mut spec = (
690 sel.id.as_ref().map_or(0u32, |_| 1),
691 sel.class.len() as u32 + sel.attrs.len() as u32,
692 sel.tag_name.as_ref().map_or(0u32, |_| 1),
693 );
694 for pc in &sel.pseudo_classes {
695 let add = match pc {
696 PseudoClass::Not(inner) => simple_specificity(inner.as_ref()),
697 PseudoClass::Is(list) => list.iter().map(simple_specificity).max().unwrap_or((0, 0, 0)),
698 PseudoClass::Has(list) => list
699 .iter()
700 .map(|(_, sel)| simple_specificity(sel))
701 .max()
702 .unwrap_or((0, 0, 0)),
703 PseudoClass::Where(_) => (0, 0, 0),
704 _ => (0, 1, 0),
705 };
706 spec.0 += add.0;
707 spec.1 += add.1;
708 spec.2 += add.2;
709 }
710 if sel.pseudo_element.is_some() {
714 spec.2 += 1;
715 }
716 spec
717}
718
719pub(crate) fn parse_quotes_pairs(v: &str) -> Option<alloc::vec::Vec<(String, String)>> {
733 let t = v.trim();
734 if t.eq_ignore_ascii_case("none") {
735 return Some(alloc::vec::Vec::new());
736 }
737 let mut lits: alloc::vec::Vec<String> = alloc::vec::Vec::new();
738 let bytes = t.as_bytes();
739 let mut i = 0usize;
740 while i < bytes.len() {
741 if bytes[i] == b'"' || bytes[i] == b'\'' {
742 let quote = bytes[i];
743 let start = i + 1;
744 let mut j = start;
745 while j < bytes.len() && bytes[j] != quote {
746 j += 1;
747 }
748 if let Some(sub) = t.get(start..j) {
749 lits.push(String::from(sub));
750 }
751 i = j + 1;
752 } else {
753 i += 1;
754 }
755 }
756 let mut pairs: alloc::vec::Vec<(String, String)> = alloc::vec::Vec::new();
757 let mut it = lits.into_iter();
758 while let (Some(a), Some(b)) = (it.next(), it.next()) {
759 pairs.push((a, b));
760 }
761 if pairs.is_empty() {
762 None
763 } else {
764 Some(pairs)
765 }
766}
767
768pub(crate) fn unescape_css_string(s: &str) -> String {
775 let mut out = String::with_capacity(s.len());
776 let mut chars = s.chars().peekable();
777 while let Some(c) = chars.next() {
778 if c != '\\' {
779 out.push(c);
780 continue;
781 }
782 let Some(&next) = chars.peek() else {
783 break;
784 };
785 if next.is_ascii_hexdigit() {
786 let mut hex = String::with_capacity(6);
787 while hex.len() < 6 {
788 match chars.peek() {
789 Some(&h) if h.is_ascii_hexdigit() => {
790 hex.push(h);
791 chars.next();
792 }
793 _ => break,
794 }
795 }
796 if let Ok(code) = u32::from_str_radix(&hex, 16) {
797 if let Some(ch) = char::from_u32(code) {
798 out.push(ch);
799 }
800 }
801 if let Some(&w) = chars.peek() {
803 if w.is_ascii_whitespace() {
804 chars.next();
805 }
806 }
807 } else {
808 out.push(next);
809 chars.next();
810 }
811 }
812 out
813}
814
815pub(crate) fn parse_content_value(
816 v: &str,
817 attributes: &BTreeMap<String, String>,
818 counters: &BTreeMap<String, i64>,
819 quotes_pairs: Option<&[(String, String)]>,
820 quote_depth: usize,
821 counter_styles: &[CounterStyleDef],
822) -> String {
823 parse_content_value_with_stack(
824 v,
825 attributes,
826 counters,
827 None,
828 quotes_pairs,
829 quote_depth,
830 counter_styles,
831 )
832}
833
834pub(crate) fn parse_content_value_with_stack(
835 v: &str,
836 attributes: &BTreeMap<String, String>,
837 counters: &BTreeMap<String, i64>,
838 counter_scope: Option<&crate::os_lib::css::counter_scope::CounterScopeStack>,
839 quotes_pairs: Option<&[(String, String)]>,
840 quote_depth: usize,
841 counter_styles: &[CounterStyleDef],
842) -> String {
843 let t = v.trim();
844 let mut out = String::new();
845 let mut i = 0usize;
846 let bytes = t.as_bytes();
847 while i < bytes.len() {
848 if bytes[i].is_ascii_whitespace() {
850 i += 1;
851 continue;
852 }
853 if bytes[i] == b'"' || bytes[i] == b'\'' {
854 let quote = bytes[i];
855 let start = i + 1;
856 let mut j = start;
857 while j < bytes.len() && bytes[j] != quote {
858 j += 1;
859 }
860 if let Some(sub) = t.get(start..j) {
861 out.push_str(&unescape_css_string(sub));
862 }
863 i = j + 1;
864 continue;
865 }
866 if let Some(rest) = t.get(i..).and_then(|r| r.strip_prefix("attr(")) {
867 if let Some(close) = rest.find(')') {
868 if let Some(inner) = rest.get(..close) {
869 let mut parts = inner.splitn(2, ',');
875 let name = parts.next().unwrap_or("").trim();
876 let fallback = parts.next().map(|s| {
877 let s = s.trim();
878 s.trim_matches('"').trim_matches('\'')
879 });
880 match attributes.get(name) {
881 Some(val) => out.push_str(val),
882 None => {
883 if let Some(fb) = fallback {
884 out.push_str(fb);
885 }
886 }
887 }
888 }
889 i += "attr(".len() + close + 1;
890 continue;
891 }
892 }
893 if let Some(rest) = t.get(i..).and_then(|r| r.strip_prefix("counter(")) {
894 if let Some(close) = rest.find(')') {
895 if let Some(inner) = rest.get(..close) {
896 let mut parts = inner.splitn(2, ',');
897 let name = parts.next().unwrap_or("").trim();
898 let style = parts.next().map(|s| s.trim().to_lowercase());
899 if let Some(stack) = counter_scope {
900 let formatted = stack.format_counter(name, style.as_deref(), counter_styles);
901 out.push_str(&formatted);
902 } else {
903 let val = counters.get(name).copied().unwrap_or(0);
904 let val_u32 = val.max(0) as u32;
905 let formatted = match style.as_deref() {
906 Some("upper-roman") => crate::os_lib::util::ordinal::number_to_roman(val_u32, true),
907 Some("lower-roman") => crate::os_lib::util::ordinal::number_to_roman(val_u32, false),
908 Some("upper-alpha") | Some("upper-latin") => {
909 crate::os_lib::util::ordinal::number_to_alpha(val_u32, true)
910 }
911 Some("lower-alpha") | Some("lower-latin") => {
912 crate::os_lib::util::ordinal::number_to_alpha(val_u32, false)
913 }
914 Some(custom) => match counter_styles.iter().find(|d| d.name == custom) {
915 Some(def) => format_with_counter_style(def, val),
916 None => alloc::format!("{}", val),
917 },
918 None => alloc::format!("{}", val),
919 };
920 out.push_str(&formatted);
921 }
922 }
923 i += "counter(".len() + close + 1;
924 continue;
925 }
926 }
927 if let Some(rest) = t.get(i..).and_then(|r| r.strip_prefix("counters(")) {
928 if let Some(close) = rest.find(')') {
929 if let Some(inner) = rest.get(..close) {
930 let mut parts = inner.splitn(3, ',');
931 let name = parts.next().unwrap_or("").trim();
932 let sep = parts.next().map(|s| {
933 s.trim()
934 .trim_matches(|c| c == '"' || c == '\'')
935 .to_string()
936 }).unwrap_or_default();
937 let style = parts.next().map(|s| s.trim().to_lowercase());
938 if let Some(stack) = counter_scope {
939 let formatted = stack.format_counters(name, &sep, style.as_deref(), counter_styles);
940 out.push_str(&formatted);
941 } else {
942 let val = counters.get(name).copied().unwrap_or(0);
943 let val_u32 = val.max(0) as u32;
944 let formatted = match style.as_deref() {
945 Some("upper-roman") => crate::os_lib::util::ordinal::number_to_roman(val_u32, true),
946 Some("lower-roman") => crate::os_lib::util::ordinal::number_to_roman(val_u32, false),
947 Some("upper-alpha") | Some("upper-latin") => {
948 crate::os_lib::util::ordinal::number_to_alpha(val_u32, true)
949 }
950 Some("lower-alpha") | Some("lower-latin") => {
951 crate::os_lib::util::ordinal::number_to_alpha(val_u32, false)
952 }
953 Some(custom) => match counter_styles.iter().find(|d| d.name == custom) {
954 Some(def) => format_with_counter_style(def, val),
955 None => alloc::format!("{}", val),
956 },
957 None => alloc::format!("{}", val),
958 };
959 out.push_str(&formatted);
960 }
961 }
962 i += "counters(".len() + close + 1;
963 continue;
964 }
965 }
966 if let Some(rest) = t.get(i..) {
972 if let Some(r2) = rest.strip_prefix("no-open-quote") {
973 let _ = r2;
974 i += "no-open-quote".len();
975 continue;
976 }
977 if let Some(r2) = rest.strip_prefix("no-close-quote") {
978 let _ = r2;
979 i += "no-close-quote".len();
980 continue;
981 }
982 if rest.starts_with("open-quote") {
983 match quotes_pairs {
984 Some(pairs) if !pairs.is_empty() => {
985 let idx = quote_depth.min(pairs.len() - 1);
986 out.push_str(&pairs[idx].0);
987 }
988 Some(_) => {} None => out.push('\u{201C}'),
990 }
991 i += "open-quote".len();
992 continue;
993 }
994 if rest.starts_with("close-quote") {
995 match quotes_pairs {
996 Some(pairs) if !pairs.is_empty() => {
997 let idx = quote_depth.min(pairs.len() - 1);
998 out.push_str(&pairs[idx].1);
999 }
1000 Some(_) => {} None => out.push('\u{201D}'),
1002 }
1003 i += "close-quote".len();
1004 continue;
1005 }
1006 }
1007 while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
1010 i += 1;
1011 }
1012 }
1013 out
1014}
1015
1016pub(crate) fn parse_counter_decl(v: &str, default: i64) -> alloc::vec::Vec<(String, i64)> {
1020 let t = v.trim();
1021 if t.is_empty() || t.eq_ignore_ascii_case("none") {
1022 return alloc::vec::Vec::new();
1023 }
1024 let tokens: alloc::vec::Vec<&str> = t.split_whitespace().collect();
1025 let mut out = alloc::vec::Vec::new();
1026 let mut i = 0usize;
1027 while i < tokens.len() {
1028 let name = tokens[i];
1029 i += 1;
1030 let value = if i < tokens.len() {
1031 if let Ok(n) = tokens[i].parse::<i64>() {
1032 i += 1;
1033 n
1034 } else {
1035 default
1036 }
1037 } else {
1038 default
1039 };
1040 out.push((name.to_string(), value));
1041 }
1042 out
1043}
1044
1045pub(crate) fn apply_counter_decls(
1052 specified_values: &BTreeMap<String, String>,
1053 counters: &mut BTreeMap<String, i64>,
1054) -> alloc::collections::BTreeSet<String> {
1055 let mut reset_names = alloc::collections::BTreeSet::new();
1056 if let Some(reset) = specified_values.get("counter-reset") {
1057 for (name, value) in parse_counter_decl(reset, 0) {
1058 counters.insert(name.clone(), value);
1059 reset_names.insert(name);
1060 }
1061 }
1062 if let Some(incr) = specified_values.get("counter-increment") {
1063 for (name, value) in parse_counter_decl(incr, 1) {
1064 let cur = counters.get(&name).copied().unwrap_or(0);
1065 counters.insert(name, cur + value);
1066 }
1067 }
1068 reset_names
1069}
1070
1071pub(crate) fn selector_pseudo_element(sel: &Selector) -> Option<PseudoElement> {
1074 match sel {
1075 Selector::Simple(s) => s.pseudo_element,
1076 Selector::Chain(steps) => steps.last().and_then(|s| s.simple.pseudo_element),
1077 }
1078}
1079
1080pub(crate) fn selector_specificity(sel: &Selector) -> (u32, u32, u32) {
1081 match sel {
1082 Selector::Simple(s) => simple_specificity(s),
1083 Selector::Chain(steps) => {
1084 let mut a = 0u32;
1085 let mut b = 0u32;
1086 let mut c = 0u32;
1087 for step in steps {
1088 let (sa, sb, sc) = simple_specificity(&step.simple);
1089 a += sa;
1090 b += sb;
1091 c += sc;
1092 }
1093 (a, b, c)
1094 }
1095 }
1096}
1097
1098fn is_node_disabled(node: &Node, ancestors: &[AncestorContext<'_>]) -> bool {
1099 if let NodeType::Element { attributes, .. } = &node.node_type {
1100 if attributes.contains_key("disabled") {
1101 return true;
1102 }
1103 }
1104 ancestors.last().is_some_and(|a| a.in_disabled_fieldset)
1107}
1108
1109#[allow(clippy::too_many_arguments)]
1110pub(crate) fn matches_simple_selector(
1111 tag_name: &str,
1112 id: &Option<String>,
1113 classes: &Vec<String>,
1114 attributes: &BTreeMap<String, String>,
1115 sel: &SimpleSelector,
1116 sibling_index: Option<usize>,
1117 sibling_count: Option<usize>,
1118 active_pseudo_states: &[&str],
1119 type_index: Option<usize>,
1120 type_count: Option<usize>,
1121 is_empty: bool,
1122 node_ptr: usize,
1123 node_children: &[Node],
1124 own_siblings: Option<&[Node]>,
1125 is_disabled: bool,
1126) -> bool {
1127 if let Some(sel_tag) = &sel.tag_name {
1128 if sel_tag != tag_name {
1129 return false;
1130 }
1131 }
1132 if let Some(sel_id) = &sel.id {
1133 if id.as_ref() != Some(sel_id) {
1134 return false;
1135 }
1136 }
1137 for need in &sel.class {
1138 if !classes.iter().any(|c| c == need) {
1139 return false;
1140 }
1141 }
1142 for attr in &sel.attrs {
1143 if !attr_matches(attr, attributes) {
1144 return false;
1145 }
1146 }
1147 let (sibling_index, sibling_count) = match (own_siblings, sibling_index) {
1152 (Some(sibs), Some(raw))
1153 if sel.pseudo_classes.iter().any(|p| {
1154 matches!(
1155 p,
1156 PseudoClass::FirstChild
1157 | PseudoClass::LastChild
1158 | PseudoClass::NthChild(..)
1159 | PseudoClass::NthLastChild(..)
1160 | PseudoClass::OnlyChild
1161 )
1162 }) =>
1163 {
1164 let is_el = |n: &&Node| matches!(n.node_type, NodeType::Element { .. });
1165 let before = sibs.get(..raw).map_or(0, |b| b.iter().filter(is_el).count());
1166 (Some(before), Some(sibs.iter().filter(is_el).count()))
1167 }
1168 _ => (sibling_index, sibling_count),
1169 };
1170 for pseudo in &sel.pseudo_classes {
1171 match pseudo {
1172 PseudoClass::FirstChild => {
1173 if sibling_index != Some(0) {
1174 return false;
1175 }
1176 }
1177 PseudoClass::LastChild => match (sibling_index, sibling_count) {
1178 (Some(idx), Some(count)) if idx + 1 == count => {}
1179 _ => return false,
1180 },
1181 PseudoClass::NthChild(a, b, filter) => match filter {
1182 Some(sel) => match filtered_sibling_position(own_siblings, node_ptr, sel) {
1183 Some((idx, _count)) => {
1184 if !nth_matches(*a, *b, (idx + 1) as i64) {
1185 return false;
1186 }
1187 }
1188 None => return false,
1189 },
1190 None => match sibling_index {
1191 Some(idx) => {
1192 if !nth_matches(*a, *b, (idx + 1) as i64) {
1193 return false;
1194 }
1195 }
1196 None => return false,
1197 },
1198 },
1199 PseudoClass::NthLastChild(a, b, filter) => match filter {
1200 Some(sel) => match filtered_sibling_position(own_siblings, node_ptr, sel) {
1201 Some((idx, count)) => {
1202 if !nth_matches(*a, *b, (count - idx) as i64) {
1203 return false;
1204 }
1205 }
1206 None => return false,
1207 },
1208 None => match (sibling_index, sibling_count) {
1209 (Some(idx), Some(count)) => {
1210 if !nth_matches(*a, *b, (count - idx) as i64) {
1211 return false;
1212 }
1213 }
1214 _ => return false,
1215 },
1216 },
1217 PseudoClass::Checked => {
1218 if !attributes.contains_key("checked") {
1219 return false;
1220 }
1221 }
1222 PseudoClass::Disabled => {
1234 if !is_disabled {
1235 return false;
1236 }
1237 }
1238 PseudoClass::FirstOfType => {
1239 if type_index != Some(0) {
1240 return false;
1241 }
1242 }
1243 PseudoClass::LastOfType => match (type_index, type_count) {
1244 (Some(idx), Some(count)) if idx + 1 == count => {}
1245 _ => return false,
1246 },
1247 PseudoClass::NthOfType(a, b) => match type_index {
1248 Some(idx) => {
1249 if !nth_matches(*a, *b, (idx + 1) as i64) {
1250 return false;
1251 }
1252 }
1253 None => return false,
1254 },
1255 PseudoClass::NthLastOfType(a, b) => match (type_index, type_count) {
1256 (Some(idx), Some(count)) => {
1257 if !nth_matches(*a, *b, (count - idx) as i64) {
1258 return false;
1259 }
1260 }
1261 _ => return false,
1262 },
1263 PseudoClass::OnlyOfType => match (type_index, type_count) {
1264 (Some(0), Some(1)) => {}
1265 _ => return false,
1266 },
1267 PseudoClass::OnlyChild => match (sibling_index, sibling_count) {
1268 (Some(0), Some(1)) => {}
1269 _ => return false,
1270 },
1271 PseudoClass::Target => {
1272 let current = crate::os_lib::viewport::CURRENT_TARGET_ID.lock();
1273 if current.is_empty() || id.as_deref() != Some(current.as_str()) {
1274 return false;
1275 }
1276 }
1277 PseudoClass::Empty => {
1278 if !is_empty {
1279 return false;
1280 }
1281 }
1282 PseudoClass::Not(inner) => {
1283 if matches_simple_selector(
1284 tag_name,
1285 id,
1286 classes,
1287 attributes,
1288 inner,
1289 sibling_index,
1290 sibling_count,
1291 active_pseudo_states,
1292 type_index,
1293 type_count,
1294 is_empty,
1295 node_ptr,
1296 node_children,
1297 own_siblings,
1298 is_disabled,
1299 ) {
1300 return false;
1301 }
1302 }
1303 PseudoClass::Is(list) | PseudoClass::Where(list) => {
1304 let any_match = list.iter().any(|inner| {
1305 matches_simple_selector(
1306 tag_name,
1307 id,
1308 classes,
1309 attributes,
1310 inner,
1311 sibling_index,
1312 sibling_count,
1313 active_pseudo_states,
1314 type_index,
1315 type_count,
1316 is_empty,
1317 node_ptr,
1318 node_children,
1319 own_siblings,
1320 is_disabled,
1321 )
1322 });
1323 if !any_match {
1324 return false;
1325 }
1326 }
1327 PseudoClass::Unmatchable(_) => return false,
1328 PseudoClass::Heading(levels) => {
1329 let level = match tag_name.as_bytes() {
1330 [b'h', d @ b'1'..=b'6'] => i64::from(*d - b'0'),
1331 _ => return false,
1332 };
1333 if !levels.is_empty() && !levels.contains(&level) {
1334 return false;
1335 }
1336 }
1337 PseudoClass::Has(list) => {
1338 let (sibling_list, descendant_list): (
1339 Vec<&(HasCombinator, SimpleSelector)>,
1340 Vec<&(HasCombinator, SimpleSelector)>,
1341 ) = list.iter().partition(|(comb, _)| {
1342 matches!(comb, HasCombinator::NextSibling | HasCombinator::SubsequentSibling)
1343 });
1344 let sibling_ok = !sibling_list.is_empty()
1345 && own_siblings.zip(sibling_index).is_some_and(|(sibs, my_idx)| {
1346 sibling_list.iter().any(|(comb, sel)| {
1347 has_sibling_match(sibs, my_idx, *comb == HasCombinator::NextSibling, sel)
1348 })
1349 });
1350 let descendant_ok = !descendant_list.is_empty()
1351 && {
1352 let owned: Vec<(bool, SimpleSelector)> = descendant_list
1353 .iter()
1354 .map(|(comb, sel)| (*comb == HasCombinator::Child, sel.clone()))
1355 .collect();
1356 has_descendant_match(node_children, &owned)
1357 };
1358 if !sibling_ok && !descendant_ok {
1359 return false;
1360 }
1361 }
1362 PseudoClass::Dir(target) => {
1363 let effective = attributes
1364 .get("dir")
1365 .map(|v| v.trim().to_lowercase())
1366 .filter(|v| v == "ltr" || v == "rtl")
1367 .unwrap_or_else(|| String::from("ltr"));
1368 if effective != *target {
1369 return false;
1370 }
1371 }
1372 PseudoClass::Lang(target) => {
1373 let own_lang = attributes.get("lang").map(|v| v.to_lowercase());
1374 let effective = match own_lang {
1375 Some(l) if !l.is_empty() => l,
1376 _ => crate::os_lib::viewport::DOCUMENT_LANG.lock().clone(),
1377 };
1378 let matched = !effective.is_empty()
1379 && (effective == *target
1380 || effective.starts_with(&alloc::format!("{}-", target)));
1381 if !matched {
1382 return false;
1383 }
1384 }
1385 PseudoClass::Other(p) => match p.as_str() {
1386 "checked" => {
1389 if !attributes.contains_key("checked") {
1390 return false;
1391 }
1392 }
1393 "disabled" => {
1394 if !is_disabled {
1395 return false;
1396 }
1397 }
1398 "enabled" => {
1402 if is_disabled {
1403 return false;
1404 }
1405 }
1406 "required" => {
1407 if !attributes.contains_key("required") {
1408 return false;
1409 }
1410 }
1411 "optional" => {
1413 if attributes.contains_key("required") {
1414 return false;
1415 }
1416 }
1417 "valid" | "invalid" | "user-valid" | "user-invalid" => {
1440 let value = attributes.get("value").map(|s| s.trim()).unwrap_or("");
1441 let ty = attributes.get("type").map(|s| s.as_str()).unwrap_or("");
1442 let required_empty = if !attributes.contains_key("required") {
1443 false
1444 } else if tag_name == "input" && ty == "checkbox" {
1445 !attributes.contains_key("checked")
1446 } else if tag_name == "input" && ty == "radio" {
1447 let group_checked = attributes.get("name").is_some_and(|nm| {
1448 own_siblings.is_some_and(|sibs| {
1449 sibs.iter().any(|sib| {
1450 if let NodeType::Element {
1451 tag_name: st,
1452 attributes: sa,
1453 ..
1454 } = &sib.node_type
1455 {
1456 st == "input"
1457 && sa.get("type").map(|t| t == "radio").unwrap_or(false)
1458 && sa.get("name") == Some(nm)
1459 && sa.contains_key("checked")
1460 } else {
1461 false
1462 }
1463 })
1464 })
1465 });
1466 !(attributes.contains_key("checked") || group_checked)
1467 } else {
1468 value.is_empty()
1469 };
1470 let min = attributes.get("min").and_then(|v| v.parse::<f64>().ok());
1471 let max = attributes.get("max").and_then(|v| v.parse::<f64>().ok());
1472 let out_of_range = if min.is_some() || max.is_some() {
1473 value.parse::<f64>().ok().map(|v| {
1474 !(min.is_none_or(|m| v >= m) && max.is_none_or(|m| v <= m))
1475 })
1476 } else {
1477 None
1478 }
1479 .unwrap_or(false);
1480 let is_invalid = required_empty || out_of_range;
1481 let is_user_variant = p.as_str().starts_with("user-");
1482 if is_user_variant && !attributes.contains_key("_user_interacted") {
1483 return false;
1484 }
1485 let want_valid = p.as_str() == "valid" || p.as_str() == "user-valid";
1486 if is_invalid == want_valid {
1487 return false;
1488 }
1489 }
1490 "readonly" | "read-only" => {
1491 if !attributes.contains_key("readonly") {
1492 return false;
1493 }
1494 }
1495 "read-write" => {
1499 if attributes.contains_key("readonly") {
1500 return false;
1501 }
1502 }
1503 "indeterminate" => {
1510 let is_indeterminate_progress =
1511 tag_name == "progress" && !attributes.contains_key("value");
1512 let matched = attributes.contains_key("indeterminate")
1513 || attributes.contains_key("_indeterminate")
1514 || is_indeterminate_progress;
1515 if !matched {
1516 return false;
1517 }
1518 }
1519 "focus-visible" => {
1522 if !active_pseudo_states.contains(&"focus") {
1523 return false;
1524 }
1525 }
1526 "focus-within" => {
1530 if !crate::os_lib::viewport::FOCUS_WITHIN_PTRS.lock().contains(&node_ptr) {
1531 return false;
1532 }
1533 }
1534 "link" => {
1539 if !(tag_name == "a" || tag_name == "area") || !attributes.contains_key("href")
1540 {
1541 return false;
1542 }
1543 }
1544 "visited" => {
1545 return false;
1546 }
1547 "defined" => {
1552 if crate::os_lib::custom_elements::is_valid_custom_element_name(tag_name)
1553 && !attributes.contains_key("_defined")
1554 {
1555 return false;
1556 }
1557 }
1558 "fullscreen" => {
1562 if !attributes.contains_key("_fullscreen") {
1563 return false;
1564 }
1565 }
1566 "modal" => {
1572 if !attributes.contains_key("_fullscreen") && !attributes.contains_key("_modal")
1573 {
1574 return false;
1575 }
1576 }
1577 "popover-open" => {
1584 if !attributes.contains_key("_popover_open") {
1585 return false;
1586 }
1587 }
1588 "root" => {
1590 if tag_name != "html" {
1591 return false;
1592 }
1593 }
1594 "placeholder-shown" => {
1599 let has_placeholder = attributes
1600 .get("placeholder")
1601 .map(|p| !p.is_empty())
1602 .unwrap_or(false);
1603 let value_empty = attributes
1604 .get("value")
1605 .map(|v| v.is_empty())
1606 .unwrap_or(true);
1607 if !has_placeholder || !value_empty {
1608 return false;
1609 }
1610 }
1611 "in-range" | "out-of-range" => {
1617 let min = attributes.get("min").and_then(|v| v.parse::<f64>().ok());
1618 let max = attributes.get("max").and_then(|v| v.parse::<f64>().ok());
1619 if min.is_none() && max.is_none() {
1620 return false;
1621 }
1622 let value = attributes.get("value").and_then(|v| v.parse::<f64>().ok());
1623 let in_range = match value {
1624 Some(v) => min.is_none_or(|m| v >= m) && max.is_none_or(|m| v <= m),
1625 None => true,
1627 };
1628 let want_in_range = p.as_str() == "in-range";
1629 if in_range != want_in_range {
1630 return false;
1631 }
1632 }
1633 "default" => {
1640 let is_checkable = attributes
1641 .get("type")
1642 .map(|t| t == "checkbox" || t == "radio")
1643 .unwrap_or(false);
1644 let matched = if tag_name == "option" {
1645 attributes.contains_key("selected")
1646 } else if tag_name == "input" && is_checkable {
1647 attributes.contains_key("checked")
1648 } else {
1649 false
1650 };
1651 if !matched {
1652 return false;
1653 }
1654 }
1655 _ => {
1656 if !active_pseudo_states.contains(&p.as_str()) {
1657 return false;
1658 }
1659 }
1660 },
1661 }
1662 }
1663 true
1664}
1665
1666pub(crate) fn type_sibling_position(
1671 node: &Node,
1672 ancestors: &[AncestorContext<'_>],
1673 sibling_index: Option<usize>,
1674) -> (Option<usize>, Option<usize>) {
1675 let NodeType::Element { tag_name, .. } = &node.node_type else {
1676 return (None, None);
1677 };
1678 let Some(parent_ctx) = ancestors.last() else {
1679 return (Some(0), Some(1));
1680 };
1681 let Some(my_idx) = sibling_index else {
1682 return (None, None);
1683 };
1684 let mut type_idx = None;
1685 let mut type_count = 0usize;
1686 for (i, child) in parent_ctx.node.children.iter().enumerate() {
1687 if let NodeType::Element { tag_name: t, .. } = &child.node_type {
1688 if t == tag_name {
1689 if i == my_idx {
1690 type_idx = Some(type_count);
1691 }
1692 type_count += 1;
1693 }
1694 }
1695 }
1696 (type_idx, Some(type_count))
1697}
1698
1699pub(crate) const TYPE_POSITION_TABLE_MIN_CHILDREN: usize = 32;
1702
1703pub(crate) fn type_positions_of_children(parent: &Node) -> Vec<(Option<usize>, Option<usize>)> {
1709 let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
1710 let mut out: Vec<(Option<usize>, Option<usize>)> = Vec::with_capacity(parent.children.len());
1711 for child in parent.children.iter() {
1712 match &child.node_type {
1713 NodeType::Element { tag_name, .. } => {
1714 let c = counts.entry(tag_name.as_str()).or_insert(0);
1715 out.push((Some(*c), None));
1716 *c += 1;
1717 }
1718 _ => out.push((None, None)),
1719 }
1720 }
1721 for (child, slot) in parent.children.iter().zip(out.iter_mut()) {
1722 if let NodeType::Element { tag_name, .. } = &child.node_type {
1723 slot.1 = counts.get(tag_name.as_str()).copied();
1724 }
1725 }
1726 out
1727}
1728
1729pub(crate) fn nth_matches(a: i64, b: i64, position: i64) -> bool {
1731 if a == 0 {
1732 return position == b;
1733 }
1734 let diff = position - b;
1735 diff % a == 0 && diff / a >= 0
1736}
1737
1738pub(crate) fn attr_matches(attr: &AttrSelector, attributes: &BTreeMap<String, String>) -> bool {
1740 let val = attributes.get(&attr.name).or_else(|| {
1742 attributes
1743 .iter()
1744 .find(|(k, _)| k.to_lowercase() == attr.name)
1745 .map(|(_, v)| v)
1746 });
1747 let val = match val {
1748 Some(v) => v,
1749 None => return false, };
1751 let (val_cmp, need_cmp): (String, String) = if attr.case_insensitive {
1754 (val.to_lowercase(), attr.value.to_lowercase())
1755 } else {
1756 (val.clone(), attr.value.clone())
1757 };
1758 let val = &val_cmp;
1759 let attr_value = &need_cmp;
1760 match attr.op {
1761 AttrOp::Exists => true,
1762 AttrOp::Eq => val == attr_value,
1763 AttrOp::Prefix => !attr_value.is_empty() && val.starts_with(attr_value.as_str()),
1764 AttrOp::Suffix => !attr_value.is_empty() && val.ends_with(attr_value.as_str()),
1765 AttrOp::Contains => !attr_value.is_empty() && val.contains(attr_value.as_str()),
1766 AttrOp::Word => val.split_whitespace().any(|w| w == attr_value),
1767 AttrOp::Dash => {
1768 val == attr_value || val.starts_with(&alloc::format!("{}-", attr_value))
1769 }
1770 }
1771}
1772
1773pub(crate) struct NodeMatchContext<'a> {
1781 pub is_disabled: bool,
1782 pub type_index: Option<usize>,
1783 pub type_count: Option<usize>,
1784 pub own_siblings: Option<&'a [Node]>,
1785}
1786
1787impl<'a> NodeMatchContext<'a> {
1788 pub fn new(
1789 current: &Node,
1790 ancestors: &'a [AncestorContext<'a>],
1791 sibling_index: Option<usize>,
1792 ) -> Self {
1793 Self::with_type_position(current, ancestors, sibling_index, None)
1794 }
1795
1796 pub fn with_type_position(
1799 current: &Node,
1800 ancestors: &'a [AncestorContext<'a>],
1801 sibling_index: Option<usize>,
1802 type_position: Option<(Option<usize>, Option<usize>)>,
1803 ) -> Self {
1804 let is_disabled = is_node_disabled(current, ancestors);
1805 let (type_index, type_count) = match type_position {
1807 Some(p) => p,
1808 None => type_sibling_position(current, ancestors, sibling_index),
1809 };
1810 let own_siblings = ancestors.last().map(|a| a.node.children.as_slice());
1812 Self {
1813 is_disabled,
1814 type_index,
1815 type_count,
1816 own_siblings,
1817 }
1818 }
1819}
1820
1821pub(crate) fn matches_selector(
1822 selector: &Selector,
1823 current: &Node,
1824 ancestors: &[AncestorContext<'_>],
1825 sibling_index: Option<usize>,
1826 sibling_count: Option<usize>,
1827 active_pseudo_states: &[&str],
1828 ctx: &NodeMatchContext<'_>,
1829) -> bool {
1830 let is_disabled = ctx.is_disabled;
1831 let (type_index, type_count) = (ctx.type_index, ctx.type_count);
1832 let own_siblings = ctx.own_siblings;
1833 match selector {
1834 Selector::Simple(simple) => matches_selector_step_node(
1835 current,
1836 simple,
1837 sibling_index,
1838 sibling_count,
1839 active_pseudo_states,
1840 type_index,
1841 type_count,
1842 own_siblings,
1843 is_disabled,
1844 ),
1845 Selector::Chain(steps) => matches_selector_chain(
1846 steps,
1847 current,
1848 ancestors,
1849 sibling_index,
1850 sibling_count,
1851 active_pseudo_states,
1852 type_index,
1853 type_count,
1854 own_siblings,
1855 is_disabled,
1856 ),
1857 }
1858}
1859
1860#[allow(clippy::too_many_arguments)]
1861pub(crate) fn matches_selector_step_node(
1862 node: &Node,
1863 simple: &SimpleSelector,
1864 sibling_index: Option<usize>,
1865 sibling_count: Option<usize>,
1866 active_pseudo_states: &[&str],
1867 type_index: Option<usize>,
1868 type_count: Option<usize>,
1869 own_siblings: Option<&[Node]>,
1870 is_disabled: bool,
1871) -> bool {
1872 match &node.node_type {
1873 NodeType::Element {
1874 tag_name,
1875 classes,
1876 id,
1877 attributes,
1878 } => matches_simple_selector(
1879 tag_name,
1880 id,
1881 classes,
1882 attributes,
1883 simple,
1884 sibling_index,
1885 sibling_count,
1886 active_pseudo_states,
1887 type_index,
1888 type_count,
1889 node.children.is_empty(),
1890 node as *const Node as usize,
1891 &node.children,
1892 own_siblings,
1893 is_disabled,
1894 ),
1895 NodeType::Text(_) => false,
1896 }
1897}
1898
1899pub(crate) fn has_descendant_match(children: &[Node], list: &[(bool, SimpleSelector)]) -> bool {
1907 for child in children {
1908 if let NodeType::Element {
1909 tag_name,
1910 id,
1911 classes,
1912 attributes,
1913 } = &child.node_type
1914 {
1915 for (_, sel) in list {
1916 let is_disabled = attributes.contains_key("disabled");
1917 if matches_simple_selector(
1918 tag_name,
1919 id,
1920 classes,
1921 attributes,
1922 sel,
1923 None,
1924 None,
1925 &[],
1926 None,
1927 None,
1928 child.children.is_empty(),
1929 child as *const Node as usize,
1930 &child.children,
1931 None,
1932 is_disabled,
1933 ) {
1934 return true;
1935 }
1936 }
1937 }
1938 let deeper_list: Vec<(bool, SimpleSelector)> = list
1940 .iter()
1941 .filter(|(direct_only, _)| !direct_only)
1942 .cloned()
1943 .collect();
1944 if !deeper_list.is_empty() && has_descendant_match(&child.children, &deeper_list) {
1945 return true;
1946 }
1947 }
1948 false
1949}
1950
1951pub(crate) fn has_sibling_match(siblings: &[Node], my_idx: usize, adjacent: bool, sel: &SimpleSelector) -> bool {
1955 for sib in siblings.iter().skip(my_idx + 1) {
1956 if let NodeType::Element {
1957 tag_name,
1958 id,
1959 classes,
1960 attributes,
1961 } = &sib.node_type
1962 {
1963 let is_disabled = attributes.contains_key("disabled");
1964 if matches_simple_selector(
1965 tag_name,
1966 id,
1967 classes,
1968 attributes,
1969 sel,
1970 None,
1971 None,
1972 &[],
1973 None,
1974 None,
1975 sib.children.is_empty(),
1976 sib as *const Node as usize,
1977 &sib.children,
1978 None,
1979 is_disabled,
1980 ) {
1981 return true;
1982 }
1983 if adjacent {
1984 return false;
1985 }
1986 }
1987 }
1988 false
1989}
1990
1991pub(crate) fn filtered_sibling_position(
1995 own_siblings: Option<&[Node]>,
1996 node_ptr: usize,
1997 sel: &SimpleSelector,
1998) -> Option<(usize, usize)> {
1999 let siblings = own_siblings?;
2000 let mut my_pos = None;
2001 let mut count = 0usize;
2002 for sib in siblings {
2003 if let NodeType::Element {
2004 tag_name,
2005 id,
2006 classes,
2007 attributes,
2008 } = &sib.node_type
2009 {
2010 let is_disabled = attributes.contains_key("disabled");
2011 let is_match = matches_simple_selector(
2012 tag_name,
2013 id,
2014 classes,
2015 attributes,
2016 sel,
2017 None,
2018 None,
2019 &[],
2020 None,
2021 None,
2022 sib.children.is_empty(),
2023 sib as *const Node as usize,
2024 &sib.children,
2025 None,
2026 is_disabled,
2027 );
2028 if is_match {
2029 if sib as *const Node as usize == node_ptr {
2030 my_pos = Some(count);
2031 }
2032 count += 1;
2033 }
2034 }
2035 }
2036 my_pos.map(|idx| (idx, count))
2037}
2038
2039#[allow(clippy::too_many_arguments)]
2040#[inline]
2047fn ancestor_quick_reject(node: &Node, simple: &SimpleSelector) -> bool {
2048 let NodeType::Element { tag_name, id, classes, .. } = &node.node_type else {
2049 return true;
2050 };
2051 if let Some(want_tag) = &simple.tag_name {
2052 if want_tag != tag_name {
2053 return true;
2054 }
2055 }
2056 if let Some(want_id) = &simple.id {
2057 if id.as_ref() != Some(want_id) {
2058 return true;
2059 }
2060 }
2061 simple.class.iter().any(|c| !c.is_empty() && !classes.iter().any(|h| h == c))
2062}
2063
2064pub(crate) fn matches_selector_chain(
2065 steps: &[SelectorStep],
2066 current: &Node,
2067 ancestors: &[AncestorContext<'_>],
2068 sibling_index: Option<usize>,
2069 sibling_count: Option<usize>,
2070 active_pseudo_states: &[&str],
2071 type_index: Option<usize>,
2072 type_count: Option<usize>,
2073 own_siblings: Option<&[Node]>,
2074 is_disabled: bool,
2075) -> bool {
2076 if steps.is_empty() {
2077 return false;
2078 }
2079 let mut idx = steps.len() - 1;
2080 if !matches_selector_step_node(
2081 current,
2082 &steps[idx].simple,
2083 sibling_index,
2084 sibling_count,
2085 active_pseudo_states,
2086 type_index,
2087 type_count,
2088 own_siblings,
2089 is_disabled,
2090 ) {
2091 return false;
2092 }
2093
2094 let mut anc_pos = ancestors.len();
2095 let mut cur_sib_index = sibling_index;
2097 while idx > 0 {
2098 let comb = steps[idx].combinator.unwrap_or(Combinator::Descendant);
2099 idx -= 1;
2100 match comb {
2101 Combinator::Child => {
2102 if anc_pos == 0 {
2103 return false;
2104 }
2105 anc_pos -= 1;
2106 let anc = &ancestors[anc_pos];
2107 if ancestor_quick_reject(anc.node, &steps[idx].simple) {
2109 return false;
2110 }
2111 let anc_disabled = !steps[idx].simple.pseudo_classes.is_empty()
2112 && is_node_disabled(anc.node, &ancestors[0..anc_pos]);
2113 let anc_siblings = anc_pos.checked_sub(1).and_then(|p| ancestors.get(p)).map(|a| a.node.children.as_slice());
2114 if !matches_selector_step_node(
2117 anc.node,
2118 &steps[idx].simple,
2119 anc.sibling_index,
2120 anc.sibling_count,
2121 active_pseudo_states,
2122 None,
2123 None,
2124 anc_siblings,
2125 anc_disabled,
2126 ) {
2127 return false;
2128 }
2129 cur_sib_index = anc.sibling_index;
2130 }
2131 Combinator::Descendant => {
2132 let mut found = false;
2133 while anc_pos > 0 {
2134 anc_pos -= 1;
2135 let anc = &ancestors[anc_pos];
2136 if ancestor_quick_reject(anc.node, &steps[idx].simple) {
2138 continue;
2139 }
2140 let anc_disabled = !steps[idx].simple.pseudo_classes.is_empty()
2141 && is_node_disabled(anc.node, &ancestors[0..anc_pos]);
2142 let anc_siblings = anc_pos.checked_sub(1).and_then(|p| ancestors.get(p)).map(|a| a.node.children.as_slice());
2143 if matches_selector_step_node(
2144 anc.node,
2145 &steps[idx].simple,
2146 anc.sibling_index,
2147 anc.sibling_count,
2148 active_pseudo_states,
2149 None,
2150 None,
2151 anc_siblings,
2152 anc_disabled,
2153 ) {
2154 found = true;
2155 cur_sib_index = anc.sibling_index;
2156 break;
2157 }
2158 }
2159 if !found {
2160 return false;
2161 }
2162 }
2163 Combinator::NextSibling | Combinator::SubsequentSibling => {
2164 if anc_pos == 0 {
2166 return false;
2167 }
2168 let parent = ancestors[anc_pos - 1].node;
2169 let ci = match cur_sib_index {
2170 Some(i) => i,
2171 None => return false,
2172 };
2173 let count = Some(parent.children.len());
2174 let adjacent = comb == Combinator::NextSibling;
2175 let mut found = false;
2176 let mut j = ci;
2177 while j > 0 {
2178 j -= 1;
2179 if matches!(parent.children[j].node_type, NodeType::Element { .. }) {
2180 let sib_disabled = is_node_disabled(&parent.children[j], &ancestors[0..anc_pos - 1]);
2181 let m = matches_selector_step_node(
2182 &parent.children[j],
2183 &steps[idx].simple,
2184 Some(j),
2185 count,
2186 active_pseudo_states,
2187 None,
2188 None,
2189 Some(parent.children.as_slice()),
2190 sib_disabled,
2191 );
2192 if m {
2193 found = true;
2194 cur_sib_index = Some(j);
2195 break;
2196 }
2197 if adjacent {
2198 break;
2200 }
2201 }
2202 }
2203 if !found {
2204 return false;
2205 }
2206 }
2207 }
2208 }
2209 true
2210}
2211