Skip to main content

atmos/os_lib/css/
rule_index.rs

1//! セレクタ右端キーによるルールインデックス(カスケード高速化)。
2//!
3//! ## 背景
4//! カスケードは「全ルール × 全ノード」を総当たりで `matches_selector` に掛けていた。
5//! 実サイト(www.sugi-lab.net)では Font Awesome を含めて **2403 ルール**あり、
6//! ノード数 365 との組み合わせで 1 回のレイアウトに約 50 秒かかっていた。
7//! JS タイマーが毎フレーム DOM を dirty にするため、この 50 秒が延々と繰り返され、
8//! ページが一度も描画完了しない状態になっていた。
9//!
10//! ## 手法
11//! ブラウザ実装と同じく、セレクタの**右端コンパウンド**から絞り込みキーを 1 つ取り、
12//! `#id` / `.class` / `tag` のバケットへ振り分けておく。ある要素に対しては
13//! 「その要素の id / class / タグ名に対応するバケット」+「ユニバーサルバケット」
14//! だけを照合すればよく、`.fa-xxx` のような数千件のアイコンルールは
15//! 対象要素がそのクラスを持たない限り一切触らない。
16//!
17//! キーの選択は右端コンパウンド内で **id > class > tag > universal** の順。
18//! 右端が `:hover` や `[attr]` だけで id/class/tag を持たない場合は
19//! **必ず universal 扱い**にする(絞り込みで取りこぼすと描画が壊れるため、
20//! 判断がつかないものは常に照合する側へ倒す)。
21//!
22//! 本モジュールはグローバル状態にもハードウェアにも依存しない純粋ロジックのみで構成し、
23//! ホスト側の単体試験で契約を固定する。
24
25extern crate alloc;
26
27use super::types::{PseudoClass, Rule, Selector, SimpleSelector};
28use alloc::string::{String, ToString};
29use alloc::vec::Vec;
30
31/// ルールを振り分けるバケットの種類。
32#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
33pub enum RuleKey {
34    /// 右端が `#id` を含む。
35    Id(String),
36    /// 右端が `.class` を含む(id は含まない)。`rightmost_key` は最初のクラス、索引の構築では
37    /// スタイルシート内で最も出現の少ないクラスを代表キーにする。
38    Class(String),
39    /// 右端がタグ名のみ(id/class 無し)。
40    Tag(String),
41    /// 右端から絞り込みキーを決められない(`*`、擬似クラスのみ、属性のみ 等)。
42    /// このバケットのルールは全要素に対して照合する。
43    Universal,
44}
45
46/// インデックス操作の引数が不正だった場合のエラー。
47#[derive(Debug, PartialEq, Eq, Clone)]
48pub enum IndexError {
49    /// 要素のタグ名が空。要素ノードには必ずタグ名がある前提が崩れている。
50    EmptyTagName,
51}
52
53/// 右端コンパウンドから絞り込みキーを決める。
54fn 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            // HTML のタグ名は大文字小文字を区別しないので正規化する。
66            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    // `*` / 擬似クラスのみ / 属性のみ → 絞り込めないので全件照合側へ。
75    RuleKey::Universal
76}
77
78/// 祖先ブルームフィルタ(WebKit/Blink の ancestor filter と同じ考え方)。
79///
80/// 祖先の要素が持つタグ・id・クラスのハッシュを 1024 ビットに落としたもの。子孫セレクタ
81/// (`.ytd-watch-flexy .x`)の左側に必要な特徴が祖先に無ければ、祖先をたどる照合を省ける。
82/// 偽陽性(無いのにあると言う)はあるが偽陰性は無い。
83/// 【2026-10-24】YouTube の視聴ページ(約 2,700 要素 × 23,000 規則)のカスケード高速化。
84#[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    /// ハッシュ `h` の特徴を持つ祖先があり得るか。
98    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    /// 要素 1 つの特徴(タグ・id・クラス)を加える。
104    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
115/// 特徴(種別 + 名前)のハッシュ(FNV-1a)。
116fn 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
127/// セレクタの一致に「祖先に必要な特徴」のハッシュ(最大 4 個)。右から見て、子孫・子の結合子で
128/// 繋がる左側コンパウンドの id/class/tag。兄弟結合子に出会ったら止める(安全側)。
129fn 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/// 祖先に必要な特徴のハッシュ(最大 4 個)を確保なしで持つ(2026-11-05。`Vec<u32>` だと YouTube の約 2 万規則で
156/// 規則ごと・セレクタごとに確保していた)。
157#[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
178/// 要素に決して一致しないコンパウンドか(`::view-transition-*`・`::-webkit-scrollbar*` を含む)。
179/// これらは未知の疑似クラスとして読まれ、照合では動的状態(hover 等)でない限り偽になる。
180fn 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
189/// 右端が属性だけ(id・class・tag 無し)なら、振り分けに使う最初の属性名(小文字)。
190fn 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
201/// セレクタの右端コンパウンド。
202fn 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
209/// セレクタ 1 本の絞り込みキーを返す。チェーンなら**右端**のステップを見る。
210pub 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            // 空チェーンは本来あり得ないが、取りこぼすより全件照合が安全。
216            None => RuleKey::Universal,
217        },
218    }
219}
220
221/// 名前(id・class・タグ・属性名)→ 規則の添字の表。ハッシュで引く(2026-11-05。`BTreeMap` だと YouTube の
222/// 長い共通の接頭辞を持つ class 名〔`style-scope ytd-…`〕で 1 回の検索に十数回の文字列の比較〔`memcmp`〕が要った)。
223type KeyMap = indexmap::IndexMap<String, Vec<usize>, core::hash::BuildHasherDefault<crate::os_lib::util::fnv::FnvHasher>>;
224
225/// スタイルシート内のルールを右端キーで振り分けた索引。
226/// 保持するのは元の `rules` スライスに対する**添字**のみで、ルール本体は複製しない。
227#[derive(Debug, Default)]
228pub struct RuleIndex {
229    by_id: KeyMap,
230    by_class: KeyMap,
231    by_tag: KeyMap,
232    /// 右端が属性だけ(`[dark]` 等。id/class/tag 無し)の規則を、最初の属性名で振り分けたもの。
233    by_attr: KeyMap,
234    /// `by_attr` の全規則(昇順・重複なし)。属性を渡さない問い合わせで取りこぼさないために使う。
235    all_attr_rules: Vec<usize>,
236    /// 規則ごと・セレクタごとの「祖先に必要な特徴」のハッシュ(`AncestorBloom` で照合前に枝刈り)。
237    /// 全規則のセレクタの分を平らに並べ、規則 `r` の分は `ancestor_starts[r]..ancestor_starts[r + 1]`。
238    ancestor_reqs: Vec<AncReqs>,
239    ancestor_starts: Vec<u32>,
240    universal: Vec<usize>,
241    rule_count: usize,
242    /// ルールごとの動的疑似クラス使用ビット(bit0=hover, bit1=focus, bit2=active)。
243    ///
244    /// 「そのルールが `:hover` を使うか」は**ノードに依存しない**。
245    /// 以前はカスケードがノードごとに候補ルール全部へ `rule_uses_state` を
246    /// 呼んでおり、同じ答えを N×C 回計算し直していた。
247    /// 索引を作るのと同じ 1 回の走査で求めておく。
248    state_masks: Vec<u8>,
249    /// 右端以外のコンパウンドが兄弟全員の中身に依存する規則がある(使い回しの鍵に常に兄弟全員の特徴を入れる)。
250    full_siblings: bool,
251    /// `+`・`~` の左側のコンパウンドの id・class・タグ(使い回しの鍵に前の兄弟の特徴を入れるかの判定。`sibling_relevant`)。
252    sib_left: KeyMap,
253    /// `+`・`~` の左側に id・class・タグで絞れないコンパウンドがある(前の兄弟の特徴を常に入れる)。
254    sib_left_any: bool,
255    /// 右端以外で位置(`:first-child` 等)や前の兄弟(`+`・`~` の右側)に依存するコンパウンドの id・class・タグ
256    /// (子孫へ渡す使い回しの鍵に、祖先の位置と兄弟の文脈を入れるかの判定。`ancestor_ctx_relevant`)。
257    /// 3 種(位置・前の兄弟〔`+`・`~` の右側〕・子の有無〔`:empty`〕)それぞれの表と「絞れないものがある」。
258    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    /// スタイルシート内の全セレクタ(`:not()` / `:is()` / `:where()` / `:has()` 内や左側の段を含む)に
265    /// 現れる属性名の集合(小文字)。JS が `setAttribute` / `removeAttribute` した属性が
266    /// ここに無く、かつ HTML の固有表示属性でもなければ、スタイル計算の結果は一切変わらない(TODO P4b)。
267    referenced_attrs: alloc::collections::BTreeSet<String>,
268    /// 全ルールの `state_masks` のビット論理和(`:has()` や動的疑似クラスがシート内に 1 つでも存在するか O(1) 判定用)。
269    any_state_masks: u8,
270}
271
272/// 祖先の文脈のうち、子孫のスタイルに効き得るもの(`RuleIndex::ancestor_needs`)。
273#[derive(Clone, Copy, Default)]
274pub struct AncestorNeeds {
275    /// 兄弟の中の順番・数(`:first-child` 等)。
276    pub position: bool,
277    /// 前の兄弟の特徴(`+`・`~` の右側)。
278    pub siblings: bool,
279    /// 子の有無(`:empty`)。
280    pub children: bool,
281}
282
283/// `state_masks` のビット位置。
284pub const STATE_HOVER: u8 = 1 << 0;
285pub const STATE_FOCUS: u8 = 1 << 1;
286pub const STATE_ACTIVE: u8 = 1 << 2;
287/// 規則の右端のコンパウンドが `:has()` を使う(要素の子孫の内容で結果が変わる。使い回すときは鍵に子孫の要約を入れる)。
288pub const STATE_HAS: u8 = 1 << 3;
289/// 規則の右端以外(祖先・兄弟)のコンパウンドが `:has()` を使う(祖先の子孫の内容に依存するので使い回さない)。
290pub const STATE_HAS_ANC: u8 = 1 << 4;
291/// 規則の右端のコンパウンドの一致が兄弟全員の中身に依存する(`pseudo_state::simple_needs_all_siblings`)。
292pub const STATE_SIB_ALL: u8 = 1 << 5;
293/// 候補ルールの解決不能・異常時フォールバックを示すビット(`StyleMemo::features_states` 番兵)。
294pub const STATE_INVALID: u8 = 1 << 7;
295
296impl RuleIndex {
297    /// 前の兄弟 `n` の特徴が、後ろの兄弟(とその子孫)のスタイルに効き得るか(`+`・`~` の左側に一致し得るか)。
298    /// 効かない兄弟は使い回しの鍵に種類(タグ)だけを入れる。
299    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    /// 祖先 `n` の位置・兄弟の文脈・子の有無のうち、子孫のスタイルに効き得るもの(右端以外の `:first-child`・`+` の右側・
304    /// `:empty` に一致し得るか)。効かないものは子孫へ渡す鍵に入れない。
305    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    /// 使い回しの鍵に常に兄弟全員の特徴を入れる必要があるか(`STATE_SIB_ALL` の祖先版)。
341    pub fn needs_full_siblings(&self) -> bool {
342        self.full_siblings
343    }
344
345    /// 与えられた候補ルール群が使う動的疑似クラスのビットを OR して返す。
346    ///
347    /// 範囲外の添字が混ざっていたら `None`。呼び出し側は
348    /// 「全状態を計算する」へフォールバックする(取りこぼしより遅い方を選ぶ)。
349    ///
350    /// 計算量: **O(C)**。
351    ///
352    /// 【2026-08-05】グローバルの `ACTIVE` を介さずに問い合わせられるよう、
353    /// `active_states_of` から本体をこちらへ移した。
354    /// 試験がグローバル状態に依存していたため、**並列実行される他の試験が
355    /// `clear_active()` した瞬間に `None` が返って落ちていた**
356    /// (実測: 8 回に 1 回程度。`spec/logging_policy.md` T-1 の再発)。
357    /// 索引そのものの性質は索引だけで確かめられる。
358    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    /// ルール列から索引を構築する。
373    ///
374    /// 1 ルールが複数セレクタ(`a, b, c`)を持つ場合、**いずれか**のセレクタが
375    /// マッチすればそのルールは適用対象なので、全セレクタのキーへ登録する。
376    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        // 右端コンパウンドに現れるクラスの出現数。クラスで振り分けるときは、コンパウンド内で
470        // **最も出現の少ないクラス**を代表キーにする(【2026-10-24】先頭のクラスにしていたため、
471        // Polymer(YouTube)の `.style-scope.ytd-xxx` 形式の規則がほぼ全部 `style-scope` の
472        // バケットに入り、全要素で数千件を照合していた。どのクラスで振り分けても、要素が規則の
473        // クラスをすべて持たない限りマッチしないので取りこぼしは無い)。
474        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                // セレクタが無いルールは判定不能。取りこぼさないよう全件照合側へ。
488                idx.universal.push(i);
489                continue;
490            }
491            for sel in &rule.selectors {
492                // 要素に決して一致しない疑似要素だけの右端は索引に入れない(全要素での照合を省く)。
493                if rightmost_simple(sel).is_some_and(never_matches_element) {
494                    continue;
495                }
496                // 右端が属性だけなら属性名で振り分ける(その属性を持つ要素だけが照合する)。
497                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                // `rightmost_key` と同じ振り分けを、名前を写さずに行う(表に無い名前のときだけ写す)。
502                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                    // HTML のタグ名は大文字小文字を区別しないので正規化する。
517                    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    /// スタイルシート内のいずれかのセレクタがこの属性名(小文字)を参照しているか(TODO P4b)。
547    pub fn uses_attr(&self, name_lower: &str) -> bool {
548        self.referenced_attrs.contains(name_lower)
549    }
550
551    /// スタイルシート内のセレクタが参照している全属性名(小文字)の集合。
552    pub fn referenced_attrs(&self) -> &alloc::collections::BTreeSet<String> {
553        &self.referenced_attrs
554    }
555
556    /// 規則 `rule` のセレクタ `sel` が、祖先の特徴 `bloom` の下で一致し得るか。
557    /// false なら確実に一致しない(祖先に必要な id/class/tag が無い)。不明なときは true。
558    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    /// 索引が対象としているルール総数。
570    /// スタイルシート内の全ルールの `state_masks` の論理和(`STATE_*` ビット)。
571    #[inline]
572    pub fn any_state_masks(&self) -> u8 {
573        self.any_state_masks
574    }
575
576    /// 索引が対象としているルール総数。
577    pub fn rule_count(&self) -> usize {
578        self.rule_count
579    }
580
581    /// 常時照合が必要な(絞り込めなかった)ルール数。
582    /// これが総数に近いほど索引の効果は薄い。
583    pub fn universal_count(&self) -> usize {
584        self.universal.len()
585    }
586
587    /// ある要素について照合すべきルールの添字を**昇順・重複なし**で `out` バッファへ格納する。
588    /// 昇順なのはカスケードの後勝ち規則(同特異度なら後のルールが勝つ)を
589    /// 元の宣言順のまま保つため。バッファを再利用することでヒープ確保をゼロ化する。
590    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        // 属性名が分からない問い合わせなので、属性の規則は全部候補にする(取りこぼさない)。
610        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    /// `candidates_into` に要素の属性名を加えた版。属性だけの規則は、要素が持つ属性名の
618    /// バケットだけを候補にする(カスケードはこちらを使う)。
619    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    /// `candidates_into_with_attrs` の Vec を返す版(試験用)。
659    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    /// id・クラス・タグのバケットを `out` へ足す(並べ替え・重複除去は呼び出し側)。
672    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        // タグ名が既に小文字なら一時 String 確保を行わない
689        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    /// ある要素について照合すべきルールの添字を**昇順・重複なし**で返す。
702    /// 昇順なのはカスケードの後勝ち規則(同特異度なら後のルールが勝つ)を
703    /// 元の宣言順のまま保つため。
704    ///
705    /// 引数が不正(タグ名が空)なときは黙って戻らず、エラーログを出して `Err` を返す。
706    /// 呼び出し側は「全ルールを照合する」従来動作へフォールバックすること
707    /// (絞り込みを誤って描画が欠けるより、遅くても正しい方を選ぶ)。
708    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
720/// 既に末尾にある添字は積まない(同一ルールが複数セレクタで同じバケットへ来る場合)。
721fn 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
774/// `RuleKey` を人が読める文字列にする(診断ログ用)。
775impl 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}