1extern crate alloc;
26
27use super::types::{PseudoClass, Rule, Selector, SimpleSelector};
28use alloc::string::{String, ToString};
29use alloc::vec::Vec;
30
31#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
33pub enum RuleKey {
34 Id(String),
36 Class(String),
39 Tag(String),
41 Universal,
44}
45
46#[derive(Debug, PartialEq, Eq, Clone)]
48pub enum IndexError {
49 EmptyTagName,
51}
52
53fn key_from_simple(s: &SimpleSelector) -> RuleKey {
55 if let Some(id) = &s.id {
56 if !id.is_empty() {
57 return RuleKey::Id(id.clone());
58 }
59 }
60 if let Some(c) = s.class.iter().find(|c| !c.is_empty()) {
61 return RuleKey::Class(c.clone());
62 }
63 if let Some(t) = &s.tag_name {
64 if !t.is_empty() {
65 let norm = if t.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
67 t.to_lowercase()
68 } else {
69 t.clone()
70 };
71 return RuleKey::Tag(norm);
72 }
73 }
74 RuleKey::Universal
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85#[derive(Default)]
86pub struct AncestorBloom {
87 bits: [u64; 16],
88}
89
90
91impl AncestorBloom {
92 fn insert(&mut self, h: u32) {
93 let b = (h & 1023) as usize;
94 self.bits[b >> 6] |= 1u64 << (b & 63);
95 }
96
97 pub fn may_contain(&self, h: u32) -> bool {
99 let b = (h & 1023) as usize;
100 self.bits[b >> 6] & (1u64 << (b & 63)) != 0
101 }
102
103 pub fn insert_element(&mut self, tag: &str, id: Option<&str>, classes: &[String]) {
105 self.insert(feature_hash(b't', tag));
106 if let Some(id) = id.filter(|v| !v.is_empty()) {
107 self.insert(feature_hash(b'#', id));
108 }
109 for c in classes.iter().filter(|c| !c.is_empty()) {
110 self.insert(feature_hash(b'.', c));
111 }
112 }
113}
114
115fn feature_hash(kind: u8, s: &str) -> u32 {
117 let mut h: u32 = 0x811c_9dc5;
118 h ^= u32::from(kind);
119 h = h.wrapping_mul(0x0100_0193);
120 for b in s.bytes() {
121 h ^= u32::from(b);
122 h = h.wrapping_mul(0x0100_0193);
123 }
124 h ^ (h >> 15)
125}
126
127fn ancestor_requirements(sel: &Selector) -> AncReqs {
130 let mut out = AncReqs::default();
131 let Selector::Chain(steps) = sel else {
132 return out;
133 };
134 let mut i = steps.len();
135 while i > 1 && out.len() < 4 {
136 i -= 1;
137 match steps[i].combinator.unwrap_or(super::types::Combinator::Descendant) {
138 super::types::Combinator::Descendant | super::types::Combinator::Child => {}
139 _ => break,
140 }
141 let s = &steps[i - 1].simple;
142 if let Some(id) = s.id.as_deref().filter(|v| !v.is_empty()) {
143 out.push(feature_hash(b'#', id));
144 }
145 if let Some(c) = s.class.iter().find(|c| !c.is_empty()) {
146 out.push(feature_hash(b'.', c));
147 }
148 if let Some(t) = s.tag_name.as_deref().filter(|t| !t.is_empty()) {
149 out.push(feature_hash(b't', t));
150 }
151 }
152 out
153}
154
155#[derive(Debug, Default, Clone, Copy)]
158struct AncReqs {
159 h: [u32; 4],
160 n: u8,
161}
162
163impl AncReqs {
164 fn len(&self) -> usize {
165 usize::from(self.n)
166 }
167 fn push(&mut self, v: u32) {
168 if let Some(slot) = self.h.get_mut(usize::from(self.n)) {
169 *slot = v;
170 self.n += 1;
171 }
172 }
173 fn as_slice(&self) -> &[u32] {
174 self.h.get(..usize::from(self.n)).unwrap_or(&[])
175 }
176}
177
178fn never_matches_element(s: &SimpleSelector) -> bool {
181 s.pseudo_classes.iter().any(|p| match p {
182 PseudoClass::Other(name) => {
183 name.starts_with("view-transition") || name.starts_with("-webkit-scrollbar")
184 }
185 _ => false,
186 })
187}
188
189fn attr_only_key(s: &SimpleSelector) -> Option<String> {
191 if s.id.as_deref().is_some_and(|v| !v.is_empty())
192 || s.class.iter().any(|c| !c.is_empty())
193 || s.tag_name.as_deref().is_some_and(|t| !t.is_empty())
194 {
195 return None;
196 }
197 let a = s.attrs.iter().find(|a| !a.name.is_empty())?;
198 Some(a.name.to_ascii_lowercase())
199}
200
201fn rightmost_simple(sel: &Selector) -> Option<&SimpleSelector> {
203 match sel {
204 Selector::Simple(s) => Some(s),
205 Selector::Chain(steps) => steps.last().map(|st| &st.simple),
206 }
207}
208
209pub fn rightmost_key(sel: &Selector) -> RuleKey {
211 match sel {
212 Selector::Simple(s) => key_from_simple(s),
213 Selector::Chain(steps) => match steps.last() {
214 Some(step) => key_from_simple(&step.simple),
215 None => RuleKey::Universal,
217 },
218 }
219}
220
221type KeyMap = indexmap::IndexMap<String, Vec<usize>, core::hash::BuildHasherDefault<crate::os_lib::util::fnv::FnvHasher>>;
224
225#[derive(Debug, Default)]
228pub struct RuleIndex {
229 by_id: KeyMap,
230 by_class: KeyMap,
231 by_tag: KeyMap,
232 by_attr: KeyMap,
234 all_attr_rules: Vec<usize>,
236 ancestor_reqs: Vec<AncReqs>,
239 ancestor_starts: Vec<u32>,
240 universal: Vec<usize>,
241 rule_count: usize,
242 state_masks: Vec<u8>,
249 full_siblings: bool,
251 sib_left: KeyMap,
253 sib_left_any: bool,
255 anc_pos: KeyMap,
259 anc_pos_any: bool,
260 anc_sib: KeyMap,
261 anc_sib_any: bool,
262 anc_empty: KeyMap,
263 anc_empty_any: bool,
264 referenced_attrs: alloc::collections::BTreeSet<String>,
268 any_state_masks: u8,
270}
271
272#[derive(Clone, Copy, Default)]
274pub struct AncestorNeeds {
275 pub position: bool,
277 pub siblings: bool,
279 pub children: bool,
281}
282
283pub const STATE_HOVER: u8 = 1 << 0;
285pub const STATE_FOCUS: u8 = 1 << 1;
286pub const STATE_ACTIVE: u8 = 1 << 2;
287pub const STATE_HAS: u8 = 1 << 3;
289pub const STATE_HAS_ANC: u8 = 1 << 4;
291pub const STATE_SIB_ALL: u8 = 1 << 5;
293pub const STATE_INVALID: u8 = 1 << 7;
295
296impl RuleIndex {
297 pub fn sibling_relevant(&self, n: &crate::os_lib::dom::Node) -> bool {
300 Self::may_match_keys(&self.sib_left, self.sib_left_any, n)
301 }
302
303 pub fn ancestor_needs(&self, n: &crate::os_lib::dom::Node) -> AncestorNeeds {
306 AncestorNeeds {
307 position: Self::may_match_keys(&self.anc_pos, self.anc_pos_any, n),
308 siblings: Self::may_match_keys(&self.anc_sib, self.anc_sib_any, n),
309 children: Self::may_match_keys(&self.anc_empty, self.anc_empty_any, n),
310 }
311 }
312
313 fn may_match_keys(map: &KeyMap, any: bool, n: &crate::os_lib::dom::Node) -> bool {
314 let crate::os_lib::dom::NodeType::Element { tag_name, id, classes, .. } = &n.node_type else {
315 return false;
316 };
317 if any {
318 return true;
319 }
320 if map.is_empty() {
321 return false;
322 }
323 let mut buf = String::new();
324 let mut has = |prefix: &str, v: &str| {
325 buf.clear();
326 buf.push_str(prefix);
327 buf.push_str(v);
328 map.contains_key(buf.as_str())
329 };
330 let tag_hit = if tag_name.bytes().any(|b| b.is_ascii_uppercase()) {
331 has("", &tag_name.to_ascii_lowercase())
332 } else {
333 has("", tag_name)
334 };
335 tag_hit
336 || id.as_deref().is_some_and(|v| has("#", v))
337 || classes.iter().any(|c| has(".", c))
338 }
339
340 pub fn needs_full_siblings(&self) -> bool {
342 self.full_siblings
343 }
344
345 pub fn states_of(&self, cands: &[usize]) -> Option<u8> {
359 let mut m = 0u8;
360 for &i in cands {
361 match self.state_masks.get(i) {
362 Some(bits) => m |= bits,
363 None => return None,
364 }
365 if m == STATE_HOVER | STATE_FOCUS | STATE_ACTIVE | STATE_HAS | STATE_HAS_ANC | STATE_SIB_ALL {
366 break;
367 }
368 }
369 Some(m)
370 }
371
372 pub fn build(rules: &[Rule]) -> Self {
377 let mut idx = RuleIndex {
378 rule_count: rules.len(),
379 ..Default::default()
380 };
381 let mut full_siblings = false;
382 idx.state_masks = rules
383 .iter()
384 .map(|r| {
385 let mut m = 0u8;
386 if super::pseudo_state::rule_uses_state(r, "hover") {
387 m |= STATE_HOVER;
388 }
389 if super::pseudo_state::rule_uses_state(r, "focus") {
390 m |= STATE_FOCUS;
391 }
392 if super::pseudo_state::rule_uses_state(r, "active") {
393 m |= STATE_ACTIVE;
394 }
395 for sel in &r.selectors {
396 match sel {
397 super::types::Selector::Simple(s) => {
398 if super::pseudo_state::simple_uses_state(s, "has") {
399 m |= STATE_HAS;
400 }
401 if super::pseudo_state::simple_needs_all_siblings(s) {
402 m |= STATE_SIB_ALL;
403 }
404 }
405 super::types::Selector::Chain(steps) => {
406 let n = steps.len();
407 for (i, st) in steps.iter().enumerate() {
408 if super::pseudo_state::simple_uses_state(&st.simple, "has") {
409 m |= if i + 1 == n { STATE_HAS } else { STATE_HAS_ANC };
410 }
411 if super::pseudo_state::simple_needs_all_siblings(&st.simple) {
412 if i + 1 == n {
413 m |= STATE_SIB_ALL;
414 } else {
415 full_siblings = true;
416 }
417 }
418 }
419 }
420 }
421 }
422 m
423 })
424 .collect();
425 idx.any_state_masks = idx.state_masks.iter().fold(0u8, |acc, &m| acc | m);
426 idx.full_siblings = full_siblings;
427 for rule in rules {
428 for sel in &rule.selectors {
429 let super::types::Selector::Chain(steps) = sel else { continue };
430 for st in steps.iter().take(steps.len().saturating_sub(1)) {
431 let sib_right = matches!(
432 st.combinator,
433 Some(super::types::Combinator::NextSibling | super::types::Combinator::SubsequentSibling)
434 );
435 let kinds = [
436 (sib_right, &mut idx.anc_sib, &mut idx.anc_sib_any),
437 (super::pseudo_state::simple_uses_position(&st.simple), &mut idx.anc_pos, &mut idx.anc_pos_any),
438 (super::pseudo_state::simple_uses_empty(&st.simple), &mut idx.anc_empty, &mut idx.anc_empty_any),
439 ];
440 for (on, map, any) in kinds {
441 if !on {
442 continue;
443 }
444 match key_from_simple(&st.simple) {
445 RuleKey::Id(v) => push_key(map, &alloc::format!("#{}", v), 0),
446 RuleKey::Class(v) => push_key(map, &alloc::format!(".{}", v), 0),
447 RuleKey::Tag(v) => push_key(map, &v, 0),
448 RuleKey::Universal => *any = true,
449 }
450 }
451 }
452 for w in steps.windows(2) {
453 let (Some(left), Some(right)) = (w.first(), w.get(1)) else { continue };
454 if !matches!(
455 right.combinator,
456 Some(super::types::Combinator::NextSibling | super::types::Combinator::SubsequentSibling)
457 ) {
458 continue;
459 }
460 match key_from_simple(&left.simple) {
461 RuleKey::Id(v) => push_key(&mut idx.sib_left, &alloc::format!("#{}", v), 0),
462 RuleKey::Class(v) => push_key(&mut idx.sib_left, &alloc::format!(".{}", v), 0),
463 RuleKey::Tag(v) => push_key(&mut idx.sib_left, &v, 0),
464 RuleKey::Universal => idx.sib_left_any = true,
465 }
466 }
467 }
468 }
469 let mut class_freq: indexmap::IndexMap<&str, usize, core::hash::BuildHasherDefault<crate::os_lib::util::fnv::FnvHasher>> =
475 indexmap::IndexMap::default();
476 for rule in rules {
477 for sel in &rule.selectors {
478 if let Some(simple) = rightmost_simple(sel) {
479 for c in simple.class.iter().filter(|c| !c.is_empty()) {
480 *class_freq.entry(c.as_str()).or_default() += 1;
481 }
482 }
483 }
484 }
485 for (i, rule) in rules.iter().enumerate() {
486 if rule.selectors.is_empty() {
487 idx.universal.push(i);
489 continue;
490 }
491 for sel in &rule.selectors {
492 if rightmost_simple(sel).is_some_and(never_matches_element) {
494 continue;
495 }
496 if let Some(attr) = rightmost_simple(sel).and_then(attr_only_key) {
498 push_key(&mut idx.by_attr, &attr, i);
499 continue;
500 }
501 let Some(simple) = rightmost_simple(sel) else {
503 push_unique(&mut idx.universal, i);
504 continue;
505 };
506 if let Some(id) = simple.id.as_deref().filter(|v| !v.is_empty()) {
507 push_key(&mut idx.by_id, id, i);
508 } else if let Some(c) = simple
509 .class
510 .iter()
511 .filter(|c| !c.is_empty())
512 .min_by_key(|c| class_freq.get(c.as_str()).copied().unwrap_or(0))
513 {
514 push_key(&mut idx.by_class, c, i);
515 } else if let Some(t) = simple.tag_name.as_deref().filter(|t| !t.is_empty()) {
516 if t.bytes().any(|b| b.is_ascii_uppercase()) {
518 push_key(&mut idx.by_tag, &t.to_lowercase(), i);
519 } else {
520 push_key(&mut idx.by_tag, t, i);
521 }
522 } else {
523 push_unique(&mut idx.universal, i);
524 }
525 }
526 }
527 idx.ancestor_starts.reserve(rules.len() + 1);
528 idx.ancestor_reqs.reserve(rules.len());
529 for r in rules {
530 idx.ancestor_starts.push(idx.ancestor_reqs.len() as u32);
531 idx.ancestor_reqs.extend(r.selectors.iter().map(ancestor_requirements));
532 }
533 idx.ancestor_starts.push(idx.ancestor_reqs.len() as u32);
534 let mut all: Vec<usize> = idx.by_attr.values().flatten().copied().collect();
535 all.sort_unstable();
536 all.dedup();
537 idx.all_attr_rules = all;
538 for r in rules {
539 for sel in &r.selectors {
540 collect_selector_attrs(sel, &mut idx.referenced_attrs);
541 }
542 }
543 idx
544 }
545
546 pub fn uses_attr(&self, name_lower: &str) -> bool {
548 self.referenced_attrs.contains(name_lower)
549 }
550
551 pub fn referenced_attrs(&self) -> &alloc::collections::BTreeSet<String> {
553 &self.referenced_attrs
554 }
555
556 pub fn ancestors_may_match(&self, rule: usize, sel: usize, bloom: &AncestorBloom) -> bool {
559 let at = match (self.ancestor_starts.get(rule), self.ancestor_starts.get(rule + 1)) {
560 (Some(&a), Some(&b)) if (a as usize) + sel < b as usize => Some(a as usize + sel),
561 _ => None,
562 };
563 match at.and_then(|i| self.ancestor_reqs.get(i)) {
564 Some(reqs) => reqs.as_slice().iter().all(|&h| bloom.may_contain(h)),
565 None => true,
566 }
567 }
568
569 #[inline]
572 pub fn any_state_masks(&self) -> u8 {
573 self.any_state_masks
574 }
575
576 pub fn rule_count(&self) -> usize {
578 self.rule_count
579 }
580
581 pub fn universal_count(&self) -> usize {
584 self.universal.len()
585 }
586
587 pub fn candidates_into(
591 &self,
592 tag: &str,
593 id: Option<&str>,
594 classes: &[String],
595 out: &mut Vec<usize>,
596 ) -> Result<(), IndexError> {
597 if tag.trim().is_empty() {
598 crate::error!(
599 "[CSS][RULEIDX] 要素のタグ名が空です (id={:?} classes={})。全ルール照合へフォールバックします",
600 id,
601 classes.len()
602 );
603 return Err(IndexError::EmptyTagName);
604 }
605
606 out.clear();
607 out.reserve(self.universal.len() + self.all_attr_rules.len() + 16);
608 out.extend_from_slice(&self.universal);
609 out.extend_from_slice(&self.all_attr_rules);
611 self.extend_keyed(tag, id, classes, out);
612 out.sort_unstable();
613 out.dedup();
614 Ok(())
615 }
616
617 pub fn candidates_into_with_attrs<'b, I>(
620 &self,
621 tag: &str,
622 id: Option<&str>,
623 classes: &[String],
624 attr_names: I,
625 out: &mut Vec<usize>,
626 ) -> Result<(), IndexError>
627 where
628 I: IntoIterator<Item = &'b str>,
629 {
630 if tag.trim().is_empty() {
631 crate::error!(
632 "[CSS][RULEIDX] 要素のタグ名が空です (id={:?} classes={})。全ルール照合へフォールバックします",
633 id,
634 classes.len()
635 );
636 return Err(IndexError::EmptyTagName);
637 }
638 out.clear();
639 out.reserve(self.universal.len() + 16);
640 out.extend_from_slice(&self.universal);
641 if !self.by_attr.is_empty() {
642 for a in attr_names {
643 if let Some(v) = self.by_attr.get(a) {
644 out.extend_from_slice(v);
645 } else if a.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
646 if let Some(v) = self.by_attr.get(&a.to_ascii_lowercase()) {
647 out.extend_from_slice(v);
648 }
649 }
650 }
651 }
652 self.extend_keyed(tag, id, classes, out);
653 out.sort_unstable();
654 out.dedup();
655 Ok(())
656 }
657
658 pub fn candidates_with_attrs(
660 &self,
661 tag: &str,
662 id: Option<&str>,
663 classes: &[String],
664 attr_names: &[String],
665 ) -> Result<Vec<usize>, IndexError> {
666 let mut list = Vec::new();
667 self.candidates_into_with_attrs(tag, id, classes, attr_names.iter().map(String::as_str), &mut list)?;
668 Ok(list)
669 }
670
671 fn extend_keyed(&self, tag: &str, id: Option<&str>, classes: &[String], out: &mut Vec<usize>) {
673 if let Some(id) = id {
674 if !id.is_empty() {
675 if let Some(v) = self.by_id.get(id) {
676 out.extend_from_slice(v);
677 }
678 }
679 }
680 for c in classes {
681 if !c.is_empty() {
682 if let Some(v) = self.by_class.get(c) {
683 out.extend_from_slice(v);
684 }
685 }
686 }
687
688 let has_upper = tag.as_bytes().iter().any(|b| b.is_ascii_uppercase());
690 if has_upper {
691 if let Some(v) = self.by_tag.get(&tag.to_lowercase()) {
692 out.extend_from_slice(v);
693 }
694 } else {
695 if let Some(v) = self.by_tag.get(tag) {
696 out.extend_from_slice(v);
697 }
698 }
699 }
700
701 pub fn candidates(
709 &self,
710 tag: &str,
711 id: Option<&str>,
712 classes: &[String],
713 ) -> Result<Vec<usize>, IndexError> {
714 let mut list = Vec::new();
715 self.candidates_into(tag, id, classes, &mut list)?;
716 Ok(list)
717 }
718}
719
720fn push_key(map: &mut KeyMap, key: &str, i: usize) {
722 match map.get_mut(key) {
723 Some(v) => push_unique(v, i),
724 None => {
725 map.insert(String::from(key), alloc::vec![i]);
726 }
727 }
728}
729
730fn push_unique(v: &mut Vec<usize>, i: usize) {
731 if v.last() != Some(&i) {
732 v.push(i);
733 }
734}
735
736fn collect_simple_attrs(s: &SimpleSelector, out: &mut alloc::collections::BTreeSet<String>) {
737 for a in &s.attrs {
738 if !a.name.is_empty() {
739 out.insert(a.name.to_ascii_lowercase());
740 }
741 }
742 for pc in &s.pseudo_classes {
743 match pc {
744 PseudoClass::Not(inner) => collect_simple_attrs(inner, out),
745 PseudoClass::Is(list) | PseudoClass::Where(list) => {
746 for x in list {
747 collect_simple_attrs(x, out);
748 }
749 }
750 PseudoClass::NthChild(_, _, Some(of)) | PseudoClass::NthLastChild(_, _, Some(of)) => {
751 collect_simple_attrs(of, out);
752 }
753 PseudoClass::Has(branches) => {
754 for (_, x) in branches {
755 collect_simple_attrs(x, out);
756 }
757 }
758 _ => {}
759 }
760 }
761}
762
763fn collect_selector_attrs(sel: &Selector, out: &mut alloc::collections::BTreeSet<String>) {
764 match sel {
765 Selector::Simple(s) => collect_simple_attrs(s, out),
766 Selector::Chain(steps) => {
767 for st in steps {
768 collect_simple_attrs(&st.simple, out);
769 }
770 }
771 }
772}
773
774impl RuleKey {
776 pub fn describe(&self) -> String {
777 match self {
778 RuleKey::Id(v) => {
779 let mut s = String::from("#");
780 s.push_str(v);
781 s
782 }
783 RuleKey::Class(v) => {
784 let mut s = String::from(".");
785 s.push_str(v);
786 s
787 }
788 RuleKey::Tag(v) => v.clone(),
789 RuleKey::Universal => "*".to_string(),
790 }
791 }
792}