1extern crate alloc;
8
9use alloc::string::{String, ToString};
10use alloc::vec::Vec;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum AttrOp {
14 Exists,
15 Eq,
16 Prefix,
17 Suffix,
18 Contains,
19 Word,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct AttrSel {
24 pub name: String,
25 pub op: AttrOp,
26 pub value: String,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub struct AttrExt {
33 pub case_insensitive: bool,
35 pub case_sensitive: bool,
37 pub any_ns: bool,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct RelSel {
44 pub combinator: Combinator,
46 pub steps: Vec<SelStep>,
48 pub anchored: Vec<SelStep>,
52}
53
54pub const NEVER_MATCH_TAG: &str = "\u{0}never";
57
58#[derive(Debug, Clone, PartialEq, Eq, Default)]
59pub struct CompoundSel {
60 pub tag: Option<String>,
62 pub tag_raw: Option<String>,
64 pub no_namespace: bool,
66 pub id: Option<String>,
67 pub classes: Vec<String>,
68 pub attrs: Vec<AttrSel>,
69 pub attr_ext: Vec<AttrExt>,
71 pub not: Vec<CompoundSel>,
73 pub not_complex: Vec<Vec<SelStep>>,
75 pub is_list: Vec<CompoundSel>,
77 pub is_complex: Vec<Vec<SelStep>>,
80 pub has: Vec<RelSel>,
82 pub is_has_anchor: bool,
84 pub pos: Vec<PosPseudo>,
86 pub pos_of_type: Vec<PosPseudo>,
88 pub is_scope: bool,
90 pub is_empty: bool,
92 pub is_root: bool,
94 pub is_checked: bool,
96 pub is_disabled: bool,
98 pub is_enabled: bool,
100 pub is_valid: bool,
102 pub is_invalid: bool,
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct NthFormula {
108 pub a: i32,
109 pub b: i32,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum PosPseudo {
114 First,
115 Last,
116 Only,
117 Nth(NthFormula),
118 NthLast(NthFormula),
120}
121
122pub fn parse_nth_formula(s: &str) -> Option<NthFormula> {
126 let s = s.trim_matches([' ', '\t', '\n', '\r', '\x0c']);
127 let lower = s.to_ascii_lowercase();
128 if lower == "odd" {
129 return Some(NthFormula { a: 2, b: 1 });
130 }
131 if lower == "even" {
132 return Some(NthFormula { a: 2, b: 0 });
133 }
134 let bytes = lower.as_bytes();
135 let mut i = 0usize;
136 let mut neg = false;
137 if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
138 neg = bytes[i] == b'-';
139 i += 1;
140 }
141 let d0 = i;
142 while i < bytes.len() && bytes[i].is_ascii_digit() {
143 i += 1;
144 }
145 let digits = lower.get(d0..i).unwrap_or("");
146 if i >= bytes.len() || bytes[i] != b'n' {
147 if i != bytes.len() || digits.is_empty() {
149 return None;
150 }
151 let v = digits.parse::<i32>().ok()?;
152 return Some(NthFormula { a: 0, b: if neg { -v } else { v } });
153 }
154 let mag = if digits.is_empty() { 1 } else { digits.parse::<i32>().ok()? };
155 let a = if neg { -mag } else { mag };
156 i += 1; let mut rest = lower.get(i..).unwrap_or("");
159 rest = rest.trim_start_matches([' ', '\t', '\n', '\r', '\x0c']);
160 if rest.is_empty() {
161 return Some(NthFormula { a, b: 0 });
162 }
163 let rb = rest.as_bytes();
164 let bneg = match rb[0] {
165 b'+' => false,
166 b'-' => true,
167 _ => return None,
168 };
169 let num = rest
170 .get(1..)
171 .unwrap_or("")
172 .trim_start_matches([' ', '\t', '\n', '\r', '\x0c']);
173 if num.is_empty() || !num.bytes().all(|c| c.is_ascii_digit()) {
174 return None;
175 }
176 let v = num.parse::<i32>().ok()?;
177 Some(NthFormula { a, b: if bneg { -v } else { v } })
178}
179
180pub fn nth_formula_matches(f: NthFormula, position: usize) -> bool {
182 let p = position as i32;
183 if f.a == 0 {
184 return p == f.b;
185 }
186 let diff = p - f.b;
187 diff % f.a == 0 && diff / f.a >= 0
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub enum Combinator {
192 Descendant,
193 Child,
194 Adjacent,
195 General,
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct SelStep {
200 pub compound: CompoundSel,
201 pub combinator: Option<Combinator>,
203}
204
205fn consume_css_escape(chars: &[char], idx: usize) -> (char, usize) {
208 let mut i = idx + 1;
209 if i >= chars.len() {
210 return ('\u{FFFD}', i);
212 }
213 if chars[i].is_ascii_hexdigit() {
214 let mut val: u32 = 0;
215 let mut count = 0;
216 while i < chars.len() && count < 6 && chars[i].is_ascii_hexdigit() {
217 let d = chars[i].to_digit(16).unwrap_or(0);
218 val = (val << 4) | d;
219 i += 1;
220 count += 1;
221 }
222 if i < chars.len() {
224 match chars[i] {
225 '\r' => {
226 i += 1;
227 if i < chars.len() && chars[i] == '\n' {
228 i += 1;
229 }
230 }
231 ' ' | '\t' | '\n' | '\x0C' => {
232 i += 1;
233 }
234 _ => {}
235 }
236 }
237 let ch = if val == 0 || (0xD800..=0xDFFF).contains(&val) || val > 0x10FFFF {
238 '\u{FFFD}'
239 } else {
240 char::from_u32(val).unwrap_or('\u{FFFD}')
241 };
242 (ch, i)
243 } else {
244 let ch = if chars[i] == '\0' { '\u{FFFD}' } else { chars[i] };
245 (ch, i + 1)
246 }
247}
248
249fn copy_raw_escape(chars: &[char], idx: usize, out: &mut String) -> usize {
252 out.push(chars[idx]);
253 let mut i = idx + 1;
254 if i >= chars.len() {
255 return i;
256 }
257 if chars[i].is_ascii_hexdigit() {
258 let mut count = 0;
259 while i < chars.len() && count < 6 && chars[i].is_ascii_hexdigit() {
260 out.push(chars[i]);
261 i += 1;
262 count += 1;
263 }
264 if i < chars.len() {
265 match chars[i] {
266 '\r' => {
267 out.push(chars[i]);
268 i += 1;
269 if i < chars.len() && chars[i] == '\n' {
270 out.push(chars[i]);
271 i += 1;
272 }
273 }
274 ' ' | '\t' | '\n' | '\x0C' => {
275 out.push(chars[i]);
276 i += 1;
277 }
278 _ => {}
279 }
280 }
281 i
282 } else {
283 out.push(chars[i]);
284 i + 1
285 }
286}
287
288fn is_css_ws(c: char) -> bool {
290 matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c')
291}
292
293fn is_name_start(c: char) -> bool {
295 c.is_ascii_alphabetic() || c == '_' || c == '\0' || (c as u32) >= 0x80
296}
297
298fn is_name_char(c: char) -> bool {
300 is_name_start(c) || c.is_ascii_digit() || c == '-'
301}
302
303fn is_valid_escape(a: Option<char>, b: Option<char>) -> bool {
305 a == Some('\\') && !matches!(b, Some('\n' | '\r' | '\x0c'))
306}
307
308fn would_start_ident(c1: Option<char>, c2: Option<char>, c3: Option<char>) -> bool {
310 match c1 {
311 Some('-') => matches!(c2, Some(c) if is_name_start(c) || c == '-') || is_valid_escape(c2, c3),
312 Some('\\') => is_valid_escape(c1, c2),
313 Some(c) => is_name_start(c),
314 None => false,
315 }
316}
317
318fn skip_css_ws(chars: &[char], i: &mut usize) {
319 while *i < chars.len() && is_css_ws(chars[*i]) {
320 *i += 1;
321 }
322}
323
324fn consume_ident_chars(chars: &[char], i: &mut usize) -> String {
326 let mut out = String::new();
327 while *i < chars.len() {
328 let ch = chars[*i];
329 if ch == '\\' {
330 if !is_valid_escape(Some(ch), chars.get(*i + 1).copied()) {
331 break;
332 }
333 let (c, next) = consume_css_escape(chars, *i);
334 out.push(c);
335 *i = next;
336 } else if is_name_char(ch) {
337 out.push(if ch == '\0' { '\u{FFFD}' } else { ch });
338 *i += 1;
339 } else {
340 break;
341 }
342 }
343 out
344}
345
346pub fn unescape_css_ident(s: &str) -> String {
348 let chars: Vec<char> = s.chars().collect();
349 let mut out = String::with_capacity(s.len());
350 let mut i = 0;
351 while i < chars.len() {
352 if chars[i] == '\\' {
353 let (ch, next_i) = consume_css_escape(&chars, i);
354 out.push(ch);
355 i = next_i;
356 } else if chars[i] == '\0' {
357 out.push('\u{FFFD}');
358 i += 1;
359 } else {
360 out.push(chars[i]);
361 i += 1;
362 }
363 }
364 out
365}
366
367enum ParsedAttr {
369 Single(AttrSel, AttrExt),
370 DashMatch(AttrSel, AttrExt),
373 Never,
375}
376
377fn parse_attr_full(inner: &str) -> ParsedAttr {
380 let chars: Vec<char> = inner.chars().collect();
381 let n = chars.len();
382 let mut i = 0usize;
383 let mut ext = AttrExt::default();
384 let mut never = false;
385 skip_css_ws(&chars, &mut i);
386 let next_is_eq = |k: usize| chars.get(k + 1) == Some(&'=');
387 if i + 1 < n && chars[i] == '*' && chars[i + 1] == '|' && !next_is_eq(i + 1) {
388 ext.any_ns = true;
389 i += 2;
390 } else if i < n && chars[i] == '|' && !next_is_eq(i) {
391 i += 1;
393 }
394 let mut name = consume_ident_chars(&chars, &mut i);
395 if !ext.any_ns && !name.is_empty() && i < n && chars[i] == '|' && !next_is_eq(i) {
396 never = true;
398 i += 1;
399 name = consume_ident_chars(&chars, &mut i);
400 }
401 while i < n
403 && !is_css_ws(chars[i])
404 && chars[i] != '='
405 && chars[i] != '|'
406 && !(matches!(chars[i], '^' | '$' | '*' | '~') && next_is_eq(i))
407 {
408 name.push(chars[i]);
409 i += 1;
410 name.push_str(&consume_ident_chars(&chars, &mut i));
411 }
412 if name.is_empty() {
413 return ParsedAttr::Never;
414 }
415 skip_css_ws(&chars, &mut i);
416 if i >= n {
417 if never {
418 return ParsedAttr::Never;
419 }
420 return ParsedAttr::Single(AttrSel { name, op: AttrOp::Exists, value: String::new() }, ext);
421 }
422 let mut dash = false;
423 let op = match chars[i] {
424 '=' => {
425 i += 1;
426 AttrOp::Eq
427 }
428 c @ ('^' | '$' | '*' | '~' | '|') if i + 1 < n && chars[i + 1] == '=' => {
429 i += 2;
430 match c {
431 '^' => AttrOp::Prefix,
432 '$' => AttrOp::Suffix,
433 '*' => AttrOp::Contains,
434 '~' => AttrOp::Word,
435 _ => {
436 dash = true;
437 AttrOp::Eq
438 }
439 }
440 }
441 _ => return ParsedAttr::Never,
442 };
443 skip_css_ws(&chars, &mut i);
444 let value = if i < n && (chars[i] == '"' || chars[i] == '\'') {
445 let q = chars[i];
447 i += 1;
448 let mut v = String::new();
449 while i < n && chars[i] != q {
450 if chars[i] == '\\' {
451 match chars.get(i + 1) {
452 None => i += 1,
453 Some('\n' | '\x0c') => i += 2,
454 Some('\r') => {
455 i += 2;
456 if chars.get(i) == Some(&'\n') {
457 i += 1;
458 }
459 }
460 Some(_) => {
461 let (c, next) = consume_css_escape(&chars, i);
462 v.push(c);
463 i = next;
464 }
465 }
466 } else {
467 v.push(if chars[i] == '\0' { '\u{FFFD}' } else { chars[i] });
468 i += 1;
469 }
470 }
471 if i < n {
472 i += 1; }
474 v
475 } else {
476 let mut v = String::new();
479 while i < n && !is_css_ws(chars[i]) {
480 if chars[i] == '\\' {
481 let (c, next) = consume_css_escape(&chars, i);
482 v.push(c);
483 i = next;
484 } else {
485 v.push(if chars[i] == '\0' { '\u{FFFD}' } else { chars[i] });
486 i += 1;
487 }
488 }
489 if v.is_empty() {
490 return ParsedAttr::Never;
491 }
492 v
493 };
494 skip_css_ws(&chars, &mut i);
495 if i < n {
496 match chars[i] {
497 'i' | 'I' => ext.case_insensitive = true,
498 's' | 'S' => ext.case_sensitive = true,
499 _ => return ParsedAttr::Never,
500 }
501 i += 1;
502 skip_css_ws(&chars, &mut i);
503 if i < n {
504 return ParsedAttr::Never;
505 }
506 }
507 if never {
508 return ParsedAttr::Never;
509 }
510 let sel = AttrSel { name, op, value };
511 if dash {
512 ParsedAttr::DashMatch(sel, ext)
513 } else {
514 ParsedAttr::Single(sel, ext)
515 }
516}
517
518pub fn parse_attr_sel(inner: &str) -> Option<AttrSel> {
520 match parse_attr_full(inner) {
521 ParsedAttr::Single(a, _) | ParsedAttr::DashMatch(a, _) => Some(a),
522 ParsedAttr::Never => None,
523 }
524}
525
526fn dash_match_compound(a: AttrSel, ext: AttrExt) -> CompoundSel {
529 let mut eq = CompoundSel::default();
530 eq.attrs.push(AttrSel { name: a.name.clone(), op: AttrOp::Eq, value: a.value.clone() });
531 eq.attr_ext.push(ext);
532 let mut pre = CompoundSel::default();
533 let mut v = a.value;
534 v.push('-');
535 pre.attrs.push(AttrSel { name: a.name, op: AttrOp::Prefix, value: v });
536 pre.attr_ext.push(ext);
537 CompoundSel { not: alloc::vec![eq, pre], ..CompoundSel::default() }
538}
539
540fn trim_selector_whitespace(s: &str) -> &str {
542 let s = s.trim_start_matches(is_css_ws);
543 let bytes = s.as_bytes();
544 let mut end = bytes.len();
545 while end > 0 && matches!(bytes[end - 1], b' ' | b'\t' | b'\n' | b'\r' | 0x0c) {
546 let mut bs = 0usize;
547 let mut idx = end - 1;
548 while idx > 0 && bytes[idx - 1] == b'\\' {
549 bs += 1;
550 idx -= 1;
551 }
552 if bs % 2 == 1 {
553 break;
554 }
555 end -= 1;
556 }
557 s.get(..end).unwrap_or(s)
558}
559
560pub fn parse_compound(s: &str) -> Option<CompoundSel> {
562 let s = trim_selector_whitespace(s);
563 if s.is_empty() {
564 return None;
565 }
566 if s == "*" {
567 return Some(CompoundSel::default());
568 }
569 let mut c = CompoundSel::default();
570 let mut cur = String::new();
571 let mut has_token = false;
572 let mut had_escape = false;
573 let mut mode = 't'; let chars: Vec<char> = s.chars().collect();
575 let mut i = 0;
576 let mut saw_type = false;
578 let mut ns_state = 0u8;
580 let mut never = false;
582 let flush = |mode: char,
583 cur: &mut String,
584 has_token: &mut bool,
585 had_escape: &mut bool,
586 saw_type: &mut bool,
587 c: &mut CompoundSel| {
588 if !*has_token {
589 cur.clear();
590 *had_escape = false;
591 return;
592 }
593 match mode {
594 't' if *had_escape || cur.as_str() != "*" => {
595 c.tag = Some(cur.to_lowercase());
596 c.tag_raw = Some(cur.clone());
597 *saw_type = true;
598 }
599 't' => *saw_type = true,
600 '#' => c.id = Some(cur.clone()),
601 '.' => c.classes.push(cur.clone()),
602 _ => {}
603 }
604 cur.clear();
605 *has_token = false;
606 *had_escape = false;
607 };
608 while i < chars.len() {
609 let ch = chars[i];
610 match ch {
611 '|' if mode == 't' && chars.get(i + 1) != Some(&'|') => {
612 ns_state = if ns_state != 0 {
614 3
615 } else if !has_token {
616 2
617 } else if !had_escape && cur == "*" {
618 1
619 } else {
620 3
621 };
622 cur.clear();
623 has_token = false;
624 had_escape = false;
625 i += 1;
626 }
627 '\\' => {
628 let (unescaped, next_i) = consume_css_escape(&chars, i);
629 cur.push(unescaped);
630 has_token = true;
631 had_escape = true;
632 i = next_i;
633 }
634 '\0' => {
635 cur.push('\u{FFFD}');
636 has_token = true;
637 i += 1;
638 }
639 '#' | '.' => {
640 flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
641 mode = ch;
642 i += 1;
643 }
644 '[' => {
645 flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
646 let start = i + 1;
647 let mut depth = 1;
648 let mut in_quote: Option<char> = None;
649 let mut j = start;
650 while j < chars.len() && depth > 0 {
651 let cj = chars[j];
652 if cj == '\\' {
653 let (_, next_j) = consume_css_escape(&chars, j);
654 j = next_j;
655 continue;
656 }
657 if let Some(q) = in_quote {
658 if cj == q {
659 in_quote = None;
660 }
661 j += 1;
662 continue;
663 }
664 match cj {
665 '"' | '\'' => in_quote = Some(cj),
666 '[' => depth += 1,
667 ']' => depth -= 1,
668 _ => {}
669 }
670 if depth > 0 {
671 j += 1;
672 }
673 }
674 let inner: String = chars[start..j.min(chars.len())].iter().collect();
675 match parse_attr_full(&inner) {
676 ParsedAttr::Single(attr, ext) => {
677 c.attrs.push(attr);
678 c.attr_ext.push(ext);
679 }
680 ParsedAttr::DashMatch(attr, ext) => c.not.push(dash_match_compound(attr, ext)),
681 ParsedAttr::Never => never = true,
682 }
683 i = if j < chars.len() { j + 1 } else { j };
684 mode = ' ';
685 }
686 ':' => {
687 flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
688 let mut j = i + 1;
689 let name_start = j;
690 while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '-') {
691 j += 1;
692 }
693 let name: String = chars[name_start..j].iter().collect::<String>().to_lowercase();
694 if j < chars.len() && chars[j] == '(' {
695 let paren_start = j + 1;
696 let mut depth = 1;
697 let mut in_quote: Option<char> = None;
698 let mut k = paren_start;
699 while k < chars.len() && depth > 0 {
700 let ck = chars[k];
701 if ck == '\\' {
702 let (_, next_k) = consume_css_escape(&chars, k);
703 k = next_k;
704 continue;
705 }
706 if let Some(q) = in_quote {
707 if ck == q {
708 in_quote = None;
709 }
710 k += 1;
711 continue;
712 }
713 match ck {
714 '"' | '\'' => in_quote = Some(ck),
715 '(' => depth += 1,
716 ')' => depth -= 1,
717 _ => {}
718 }
719 if depth > 0 {
720 k += 1;
721 }
722 }
723 if name == "not" {
724 let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
725 for part in split_top_level_commas(&inner) {
726 let mut steps = parse_complex(&part);
727 if steps.len() == 1 {
728 if let Some(step) = steps.pop() {
729 c.not.push(step.compound);
730 }
731 } else if !steps.is_empty() {
732 c.not_complex.push(steps);
733 }
734 }
735 } else if name == "has" {
736 let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
737 for part in split_top_level_commas(&inner) {
738 if let Some(rel) = parse_relative(&part) {
739 c.has.push(rel);
740 }
741 }
742 } else if name == "nth-child" {
743 let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
744 if let Some(formula) = parse_nth_formula(&inner) {
745 c.pos.push(PosPseudo::Nth(formula));
746 }
747 } else if name == "nth-of-type" {
748 let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
749 if let Some(formula) = parse_nth_formula(&inner) {
750 c.pos_of_type.push(PosPseudo::Nth(formula));
751 }
752 } else if name == "nth-last-child" {
753 let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
754 if let Some(formula) = parse_nth_formula(&inner) {
755 c.pos.push(PosPseudo::NthLast(formula));
756 }
757 } else if name == "nth-last-of-type" {
758 let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
759 if let Some(formula) = parse_nth_formula(&inner) {
760 c.pos_of_type.push(PosPseudo::NthLast(formula));
761 }
762 } else if name == "is" || name == "where" {
763 let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
764 for part in split_top_level_commas(&inner) {
766 let mut steps = parse_complex(&part);
767 if steps.len() == 1 {
768 if let Some(step) = steps.pop() {
769 c.is_list.push(step.compound);
770 }
771 } else if !steps.is_empty() {
772 c.is_complex.push(steps);
773 }
774 }
775 if c.is_list.is_empty() && !c.is_complex.is_empty() {
776 c.is_list.push(CompoundSel {
778 tag: Some(String::from(NEVER_MATCH_TAG)),
779 ..CompoundSel::default()
780 });
781 }
782 }
783 j = if k < chars.len() { k + 1 } else { k };
784 } else {
785 match name.as_str() {
786 "first-child" => c.pos.push(PosPseudo::First),
787 "last-child" => c.pos.push(PosPseudo::Last),
788 "only-child" => c.pos.push(PosPseudo::Only),
789 "first-of-type" => c.pos_of_type.push(PosPseudo::First),
790 "last-of-type" => c.pos_of_type.push(PosPseudo::Last),
791 "only-of-type" => c.pos_of_type.push(PosPseudo::Only),
792 "scope" => c.is_scope = true,
793 "empty" => c.is_empty = true,
794 "root" => c.is_root = true,
795 "checked" => c.is_checked = true,
796 "disabled" => c.is_disabled = true,
797 "enabled" => c.is_enabled = true,
798 "valid" => c.is_valid = true,
799 "invalid" => c.is_invalid = true,
800 _ => {}
801 }
802 }
803 i = j;
804 mode = ' ';
805 }
806 _ => {
807 cur.push(ch);
808 has_token = true;
809 i += 1;
810 }
811 }
812 }
813 flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
814 match ns_state {
815 2 => c.no_namespace = true,
816 3 => never = true,
817 _ => {}
818 }
819 if never {
820 c.tag = Some(String::from(NEVER_MATCH_TAG));
821 c.tag_raw = Some(String::from(NEVER_MATCH_TAG));
822 }
823 if c.tag.is_none()
824 && !saw_type
825 && !c.no_namespace
826 && c.id.is_none()
827 && c.classes.is_empty()
828 && c.attrs.is_empty()
829 && c.not.is_empty()
830 && c.not_complex.is_empty()
831 && c.is_list.is_empty()
832 && c.is_complex.is_empty()
833 && c.has.is_empty()
834 && c.pos.is_empty()
835 && c.pos_of_type.is_empty()
836 && !c.is_scope
837 && !c.is_empty
838 && !c.is_root
839 && !c.is_checked
840 && !c.is_disabled
841 && !c.is_enabled
842 && !c.is_valid
843 && !c.is_invalid
844 {
845 return None;
846 }
847 Some(c)
848}
849
850pub fn split_top_level_commas(s: &str) -> Vec<String> {
852 let chars: Vec<char> = s.chars().collect();
853 let mut parts = Vec::new();
854 let mut cur = String::new();
855 let mut depth = 0i32;
856 let mut in_quote: Option<char> = None;
857 let mut i = 0;
858 while i < chars.len() {
859 let ch = chars[i];
860 if ch == '\\' {
861 i = copy_raw_escape(&chars, i, &mut cur);
862 continue;
863 }
864 if let Some(q) = in_quote {
865 cur.push(ch);
866 if ch == q {
867 in_quote = None;
868 }
869 i += 1;
870 continue;
871 }
872 match ch {
873 '"' | '\'' => {
874 in_quote = Some(ch);
875 cur.push(ch);
876 }
877 '[' | '(' => {
878 depth += 1;
879 cur.push(ch);
880 }
881 ']' | ')' => {
882 depth -= 1;
883 cur.push(ch);
884 }
885 ',' if depth == 0 => {
886 parts.push(core::mem::take(&mut cur));
887 }
888 c if c.is_whitespace() && !is_css_ws(c) => {
889 push_hex_escape(&mut cur, c);
892 }
893 _ => cur.push(ch),
894 }
895 i += 1;
896 }
897 parts.push(cur);
898 parts
899}
900
901fn push_hex_escape(out: &mut String, c: char) {
903 const HEX: &[u8; 16] = b"0123456789abcdef";
904 out.push('\\');
905 let v = c as u32;
906 let mut started = false;
907 for shift in (0..6).rev() {
908 let d = ((v >> (shift * 4)) & 0xF) as usize;
909 if d != 0 || started || shift == 0 {
910 started = true;
911 out.push(HEX[d] as char);
912 }
913 }
914 out.push(' ');
915}
916
917fn parse_complex(part: &str) -> Vec<SelStep> {
919 build_steps(&tokenize_selector_group(trim_selector_whitespace(part)))
920}
921
922fn parse_relative(part: &str) -> Option<RelSel> {
924 let tokens = tokenize_selector_group(trim_selector_whitespace(part));
925 let (combinator, rest) = match tokens.first().map(String::as_str) {
926 Some(">") => (Combinator::Child, tokens.get(1..).unwrap_or(&[])),
927 Some("+") => (Combinator::Adjacent, tokens.get(1..).unwrap_or(&[])),
928 Some("~") => (Combinator::General, tokens.get(1..).unwrap_or(&[])),
929 _ => (Combinator::Descendant, &tokens[..]),
930 };
931 let steps = build_steps(rest);
932 if steps.is_empty() {
933 return None;
934 }
935 let mut anchored = alloc::vec![SelStep {
936 compound: CompoundSel { is_has_anchor: true, ..CompoundSel::default() },
937 combinator: None,
938 }];
939 for (k, step) in steps.iter().enumerate() {
940 let mut s = step.clone();
941 if k == 0 {
942 s.combinator = Some(combinator);
943 }
944 anchored.push(s);
945 }
946 Some(RelSel { combinator, steps, anchored })
947}
948
949pub fn tokenize_selector_group(s: &str) -> Vec<String> {
951 let chars: Vec<char> = s.chars().collect();
952 let mut tokens = Vec::new();
953 let mut cur = String::new();
954 let mut depth = 0i32;
955 let mut in_quote: Option<char> = None;
956 let mut i = 0;
957 while i < chars.len() {
958 let ch = chars[i];
959 if ch == '\\' {
960 i = copy_raw_escape(&chars, i, &mut cur);
961 continue;
962 }
963 if let Some(q) = in_quote {
964 cur.push(ch);
965 if ch == q {
966 in_quote = None;
967 }
968 i += 1;
969 continue;
970 }
971 match ch {
972 '"' | '\'' => {
973 in_quote = Some(ch);
974 cur.push(ch);
975 }
976 '[' | '(' => {
977 depth += 1;
978 cur.push(ch);
979 }
980 ']' | ')' => {
981 depth -= 1;
982 cur.push(ch);
983 }
984 '>' | '+' | '~' if depth == 0 => {
985 if !cur.is_empty() {
986 tokens.push(core::mem::take(&mut cur));
987 }
988 tokens.push(ch.to_string());
989 }
990 c if is_css_ws(c) && depth == 0 => {
991 if !cur.is_empty() {
992 tokens.push(core::mem::take(&mut cur));
993 }
994 }
995 _ => cur.push(ch),
996 }
997 i += 1;
998 }
999 if !cur.is_empty() {
1000 tokens.push(cur);
1001 }
1002 tokens
1003}
1004
1005pub fn build_steps(tokens: &[String]) -> Vec<SelStep> {
1007 let mut steps: Vec<SelStep> = Vec::new();
1008 let mut pending: Option<Combinator> = None;
1009 for tok in tokens {
1010 match tok.as_str() {
1011 ">" => pending = Some(Combinator::Child),
1012 "+" => pending = Some(Combinator::Adjacent),
1013 "~" => pending = Some(Combinator::General),
1014 _ => {
1015 let p = pending.take();
1017 let combinator = if steps.is_empty() {
1018 None
1019 } else {
1020 Some(p.unwrap_or(Combinator::Descendant))
1021 };
1022 if let Some(compound) = parse_compound(tok) {
1023 steps.push(SelStep { compound, combinator });
1024 }
1025 }
1026 }
1027 }
1028 steps
1029}
1030
1031pub fn html_attr_value_is_case_insensitive(name: &str) -> bool {
1036 matches!(
1037 name.to_ascii_lowercase().as_str(),
1038 "accept" | "accept-charset" | "align" | "alink" | "axis" | "bgcolor" | "charset" | "checked"
1039 | "clear" | "codetype" | "color" | "compact" | "declare" | "defer" | "dir" | "direction"
1040 | "disabled" | "enctype" | "face" | "frame" | "hreflang" | "http-equiv" | "lang"
1041 | "language" | "link" | "media" | "method" | "multiple" | "nohref" | "noresize"
1042 | "noshade" | "nowrap" | "readonly" | "rel" | "rev" | "rules" | "scope" | "scrolling"
1043 | "selected" | "shape" | "target" | "text" | "type" | "valign" | "valuetype" | "vlink"
1044 )
1045}
1046
1047pub fn attr_lookup_name(sel_name: &str, html_element_in_html_doc: bool) -> String {
1050 if html_element_in_html_doc {
1051 sel_name.to_ascii_lowercase()
1052 } else {
1053 String::from(sel_name)
1054 }
1055}
1056
1057pub fn attr_qname_has_local_name(qname: &str, local: &str) -> bool {
1059 match qname.split_once(':') {
1060 Some((_, l)) => l == local || qname == local,
1061 None => qname == local,
1062 }
1063}
1064
1065pub fn attr_value_matches(op: AttrOp, sel_value: &str, actual: &str, ext: AttrExt, html_default_ci: bool) -> bool {
1069 let ci = !ext.case_sensitive && (ext.case_insensitive || html_default_ci);
1070 let (want, got) = if ci {
1071 (sel_value.to_ascii_lowercase(), actual.to_ascii_lowercase())
1072 } else {
1073 (String::from(sel_value), String::from(actual))
1074 };
1075 match op {
1076 AttrOp::Exists => true,
1077 AttrOp::Eq => got == want,
1078 AttrOp::Prefix => !want.is_empty() && got.starts_with(want.as_str()),
1079 AttrOp::Suffix => !want.is_empty() && got.ends_with(want.as_str()),
1080 AttrOp::Contains => !want.is_empty() && got.contains(want.as_str()),
1081 AttrOp::Word => {
1082 !want.is_empty() && !want.chars().any(is_css_ws) && got.split(is_css_ws).any(|w| w == want)
1083 }
1084 }
1085}
1086
1087pub fn type_selector_matches(c: &CompoundSel, local_name: &str, html_element_in_html_doc: bool) -> bool {
1090 let Some(tag) = &c.tag else { return true };
1091 if tag == NEVER_MATCH_TAG {
1092 return false;
1093 }
1094 if html_element_in_html_doc {
1095 local_name.eq_ignore_ascii_case(tag)
1096 } else {
1097 c.tag_raw.as_deref().unwrap_or(tag) == local_name
1098 }
1099}
1100
1101pub fn selector_syntax_error(sel: &str) -> bool {
1110 #[derive(Clone, Copy, PartialEq, Eq)]
1111 enum Ctx {
1112 Sel,
1114 Forgiving,
1116 Other,
1118 }
1119 let chars: Vec<char> = sel.chars().collect();
1120 let n = chars.len();
1121 let at = |k: usize| chars.get(k).copied();
1122 let mut stack: Vec<Ctx> = Vec::new();
1123 let mut quote: Option<char> = None;
1124 let mut in_attr = false;
1125 let mut attr_name_part = false;
1127 let mut i = 0usize;
1128 while i < n {
1129 let ch = chars[i];
1130 if ch == '\\' {
1131 i += 2;
1132 continue;
1133 }
1134 if let Some(q) = quote {
1135 if ch == q {
1136 quote = None;
1137 }
1138 i += 1;
1139 continue;
1140 }
1141 let checking =
1142 !stack.contains(&Ctx::Forgiving) && stack.last().is_none_or(|c| *c == Ctx::Sel);
1143 match ch {
1144 '"' | '\'' => quote = Some(ch),
1145 '[' if !in_attr => {
1146 in_attr = true;
1147 attr_name_part = true;
1148 }
1149 ']' if in_attr => in_attr = false,
1150 '=' if in_attr => attr_name_part = false,
1151 '^' | '$' | '*' | '~' if in_attr && at(i + 1) == Some('=') => attr_name_part = false,
1152 '|' => {
1153 if !in_attr && at(i + 1) == Some('|') {
1154 i += 2;
1156 continue;
1157 }
1158 if in_attr && at(i + 1) == Some('=') {
1159 attr_name_part = false;
1160 i += 2;
1161 continue;
1162 }
1163 if checking && (!in_attr || attr_name_part) {
1164 if let Some(p) = i.checked_sub(1).and_then(at) {
1166 if p != '*' && is_name_char(p) {
1167 return true;
1168 }
1169 }
1170 }
1171 }
1172 '#' | '.' if !in_attr && checking && !would_start_ident(at(i + 1), at(i + 2), at(i + 3)) => {
1173 return true;
1174 }
1175 '(' if !in_attr => {
1176 let mut s = i;
1177 while s > 0 && is_name_char(chars[s - 1]) {
1178 s -= 1;
1179 }
1180 let is_pseudo = s > 0 && chars[s - 1] == ':';
1181 let name: String = chars[s..i].iter().collect::<String>().to_ascii_lowercase();
1182 let ctx = if !is_pseudo {
1183 Ctx::Other
1184 } else {
1185 match name.as_str() {
1186 "is" | "where" | "matches" | "any" | "-webkit-any" => Ctx::Forgiving,
1187 "not" | "has" | "host" | "host-context" => Ctx::Sel,
1188 _ => Ctx::Other,
1189 }
1190 };
1191 stack.push(ctx);
1192 }
1193 ')' if !in_attr => {
1194 stack.pop();
1195 }
1196 _ => {}
1197 }
1198 i += 1;
1199 }
1200 false
1201}