Skip to main content

atmos/os_lib/css/
selector.rs

1// 分割: css.rs より機械的に移動(2026-07-16 リファクタ フェーズ3)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use 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    // 直前までに現れた疑似要素の種類: 0=なし、1=`::part()`、2=その他の疑似要素、3=`::slotted()`。
28    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                // `#` / `.` の直後に識別子が無いのは構文エラー(`.*`・`# x`)。エスケープ・非 ASCII 文字は識別子の一部。
38                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                // 型セレクタ(`*`)は複合セレクタの先頭(または `ns|*`)にしか置けない。`.foo*` は構文エラー。
64                // 例外: `.foo-*`(クラス接頭辞の一致。試験的な構文)は `-` の直後の `*` を許す(`.-*`・`.foo-**` は不可)。
65                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                } // ']'
85                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                    } // ')'
128                }
129                // シャドウ DOM / カスタム要素 / 見出しの疑似クラス・疑似要素(構文だけ検査する)。
130                match name.as_str() {
131                    "file-selector-button" => {
132                        // 見た目を持たない(`<input type=file>` のボタンは描かない)ので一致しない扱い。
133                        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                                // heading
171                                !dbl && (!has_paren || (closed && parse_heading_levels(&arg).is_some()))
172                            }
173                        };
174                        if !ok {
175                            return None;
176                        }
177                        // `::slotted()` の後ろには疑似クラスを置けない。`::part()` の後ろは構造系を置けない。
178                        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                                    // `:not(a, b)` は `:not(a):not(b)` と同じ。
252                                    let parts = split_top_level_commas(&arg);
253                                    let mut list: Vec<SimpleSelector> = Vec::new();
254                                    for p in &parts {
255                                        // 疑似要素は `:not()` の中に置けない。
256                                        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                                    // `:has()` の中に `:has()` は置けない。
295                                    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                // 識別子は数字では始まらない(`:has(123)` の `123`)。
385                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
412/// CSS の識別子として正しいか(`--x`・`foo`・`-foo`・`_a` は可、`0a`・`-0`・空・引用符・括弧は不可)。
413fn 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
431/// 結合子を含まない(コンパウンドの)セレクタ列か。`:not()`/`:is()`/`:where()` の中は再帰して見る。
432fn 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
477/// `:has-slotted(...)` の引数: 空でなく、各枝が正しいセレクタで、先頭の結合子や `>` を使わない。
478fn 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
488/// `:heading(1, 2)` の引数(整数のカンマ区切り)。不正なら `None`、空文字は呼ばない前提。
489fn 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
505/// `[name]` / `[name op value]` の中身をパース。
506pub(crate) fn parse_attr_selector(inner: &str) -> Option<AttrSelector> {
507    let inner = inner.trim();
508    if inner.is_empty() {
509        return None;
510    }
511    // 演算子を探す(長い順)。
512    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            // `[attr=val i]`/`[attr=val s]`(Selectors Level 4 §6.4.1)。フラグは値の後ろに
524            // 空白で区切って置く。`s`(大文字小文字を区別。既定と同じ)は読み捨てるだけでよい。
525            // クォート付き値なら閉じクォートがフラグの直前に来るため、値中の空白+`i`と
526            // 混同しない(`"show i"` は末尾が `i"` であって ` i` ではないので誤判定しない)。
527            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
555/// `:nth-child(An+B of S)`(Selectors Level 4)用: `of` より前の `An+B` 部分を `parse_nth`
556/// に、`of` より後ろの `S` 部分を `parse_simple_selector` に、それぞれ渡す。`of` が無ければ
557/// 従来どおり `S` は `None`。以前は `parse_nth` が `S` 部分を丸ごと読み捨てるだけで
558/// フィルタ自体が非対応だったため、`:nth-child(2n+1 of .foo)` が `.foo` に関係なく
559/// 単なる `:nth-child(2n+1)` と同じ結果になっていた。
560pub(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
577/// `:nth-child(...)` の引数 `an+b` / `odd` / `even` / `b` を (a, b) に。
578pub(crate) fn parse_nth(arg: &str) -> (i64, i64) {
579    let full = arg.trim().to_lowercase();
580    // Selectors Level 4 の `:nth-child(An+B of S)` 構文: `S` は呼び出し元
581    // (`parse_nth_of`)側で切り出す。ここでは念のため `of` 以降が残っていても
582    // 無害に切り捨てるだけの防御的処理として残す(`parse_nth` 単体呼び出しの
583    // `nth-of-type`/`nth-last-of-type` は `of S` 構文自体を持たないため通常は無関係)。
584    let s = full.split(" of ").next().unwrap_or(&full).trim();
585    // 厳密な An+B(CSS Syntax §6)。不正なら何にも一致しない (0, 0) を返す(位置は 1 始まりなので b=0 は不一致)。
586    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; // [] () の入れ子内では結合子を区切らない。
603
604    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        // `::part()` / `::slotted()` は疑似要素なので、後ろに結合子を続けられない。
666        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
684/// セレクタの特異度 (id数, class/属性/擬似クラス数, タグ数) を算出する。
685/// CSS Selectors Level 4 の規定に従い、`:not()`/`:is()` はその引数の特異度を
686/// (`:is()` は引数中の最大値を)加算し、`:where()` は常に0を加算する
687/// (それ以外の擬似クラスは従来通り class 数として1を加算)。
688pub(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    // 疑似要素(::before/::after 等)はタグ名セレクタと同じ重み(タグ数バケット)で
711    // 特異度に寄与する(CSS Selectors 仕様通り)。以前はここが未加算で、
712    // 疑似要素の有無が特異度計算に一切反映されないバグだった。
713    if sel.pseudo_element.is_some() {
714        spec.2 += 1;
715    }
716    spec
717}
718
719/// `::before` / `::after` の `content` 値を解析する。
720/// 文字列リテラル("..." / '...')、`attr(name)`(対象要素自身の属性値、無ければ空)、
721/// `counter(name)` / `counter(name, style)`(style 引数は無視し常に十進数表記)に対応。
722/// 複数トークンの連結(例 `attr(href) " "`)も可。それ以外の未対応関数形式や
723/// none/normal は「表示なし」として空文字列を返す(テキストとして誤描画しないため)。
724/// `quotes: "«" "»" "‹" "›"` のような文字列リテラルの並びから、入れ子レベルごとの
725/// 全ペア(レベル1, レベル2, ...)を取り出す。以前は最初の1組しか取り出さず、
726/// `open-quote`/`close-quote` の入れ子(`<q>` の入れ子)に対応する複数組指定を
727/// 常に無視していたが、ここで全ペアを保持し、呼び出し側(`quote_depth` を使う
728/// `parse_content_value`)で入れ子レベルに応じたペアを選べるようにする。
729/// 戻り値: `None`=`quotes` 未指定(呼び出し側で既定の二重引用符へフォールバック)、
730/// `Some(vec![])`=`quotes:none`(仕様どおり何も出力しない)、
731/// `Some(pairs)`=ペア列(レベルが手持ちのペア数を超える場合は最後のペアを繰り返す、仕様どおり)。
732pub(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
768/// CSS文字列内のエスケープ(`\` + 1〜6桁16進 + 任意の空白1つ=Unicodeコードポイント、
769/// または `\"` 等の単純なリテラルエスケープ)をデコードする。
770/// FontAwesome等のアイコンフォントは `content: "\f2c9";` のように private-use-area
771/// コードポイントをこの16進エスケープで埋め込むため、これを未対応のまま生バイト列
772/// (バックスラッシュ込みの文字そのまま)として扱うと、アイコン文字が表示されず
773/// 代わりに "\f2c9" という文字列がそのまま描画されてしまう。
774pub(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            // 仕様どおり、16進の直後の空白1つは区切りとして消費する。
802            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        // 空白は連結トークン間の区切りなので読み飛ばす。
849        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                    // `attr(name, fallback)`(CSS Values and Units Level 5)の第2引数
870                    // フォールバックが丸ごと未対応で、それどころかカンマ以降を含めた
871                    // 文字列全体を属性名として扱ってしまい、フォールバック指定時は
872                    // 常に属性名が一致せず空文字列に落ちる(本来の属性値も読めなくなる)
873                    // バグだった。
874                    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        // open-quote/close-quote: `quotes` プロパティが指定されていれば入れ子レベル
967        // (`quote_depth`、祖先の `<q>` の個数から算出、手持ちのペア数を超えたら
968        // 最後のペアを繰り返す仕様どおりの挙動)に応じたペアを使い、無指定なら既定の
969        // 二重引用符(“/”)、`quotes:none` なら何も出力しない。
970        // no-open-quote/no-close-quote は入れ子レベルを追跡しないため何もしない扱い。
971        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(_) => {} // quotes:none — 何も出力しない
989                    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(_) => {} // quotes:none — 何も出力しない
1001                    None => out.push('\u{201D}'),
1002                }
1003                i += "close-quote".len();
1004                continue;
1005            }
1006        }
1007        // 未対応トークンは表示なし扱いで丸ごとスキップする。
1008        // 次のホワイトスペースまで読み飛ばして解析を継続する。
1009        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
1010            i += 1;
1011        }
1012    }
1013    out
1014}
1015
1016/// `counter-reset` / `counter-increment` 宣言をパースし、`name [value]` の
1017/// 空白区切りペア列として (name, value) を返す。value 省略時は `default` を使う
1018/// (reset のデフォルトは 0、increment のデフォルトは 1)。`none` は空を返す。
1019pub(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
1045/// `counter-reset` / `counter-increment` を現在のカウンタ集合に適用する。
1046/// 戻り値は、この要素自身が `counter-reset` した(=新しいスコープを作った)カウンタ名の集合。
1047/// 呼び出し側(`style_tree_with_ancestors_vars`)が、この集合を使って「入れ子の
1048/// `counter-reset` の効果を兄弟要素へ漏らさない」というスコープ復元を行う
1049/// (`apply_counter_decls` 自体はフラットな1つのマップを直接書き換えるだけで、
1050/// スコープの概念は呼び出し側が別途管理する)。
1051pub(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
1071/// セレクタ末尾(サブジェクトのコンパウンドセレクタ)に付与された疑似要素を返す。
1072/// `::before` / `::after` は末尾にのみ意味を持つため最後のステップだけを見る。
1073pub(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    // 【2026-11-18 TODO R5 (e) ④】祖先を全部たどらず、親が持っている「disabled の fieldset の中か」を見る
1105    // (`AncestorContext::in_disabled_fieldset`。親の段で自分と祖先の分をまとめてある)。
1106    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    // 【2026-10-09】`:first-child`/`:nth-child` 等の位置は**要素だけ**を数える(Selectors 4
1148    // §14.4)。呼び出し側の `sibling_index`/`sibling_count` は文字ノードも含む子の通し番号なので、
1149    // 兄弟の一覧があれば要素の位置へ換算する。パーサが要素間の空白を文字ノードとして残す
1150    // ようになり、`section:nth-child(odd)` が forms.htm の見出し帯に誤って当たった。
1151    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            // `:disabled`は要素自身の`disabled`属性だけでなく、祖先の
1223            // `<fieldset disabled>`による暗黙の無効化も反映する必要がある
1224            // (`is_node_disabled`が計算した`is_disabled`パラメータが
1225            // 既にこれを含む)。以前は自身の属性だけを見ていたため、
1226            // `<fieldset disabled><input></fieldset>`のような暗黙無効化
1227            // ケースで`:disabled`がマッチしないバグだった(同じロジックが
1228            // `PseudoClass::Other("disabled")`アームに正しく実装済み
1229            // だったが、パーサが`"disabled"`を専用の`PseudoClass::
1230            // Disabled`列挙子へ先にマッピングするため、そちらのアームが
1231            // 到達不能な死んだコードになっていた)。2026-07-18 発見・
1232            // 修正)。
1233            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`/`:disabled` は要素自身の属性から静的に判定できるため、
1387                // hover のような「動的状態リスト」の受け渡しなしに直接判定する。
1388                "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`(`:disabled` の対)が丸ごと未対応だった。既存の
1399                // `:disabled`/`:read-write` と同じ簡略方針(タグ種別は問わず
1400                // `disabled` 属性の有無だけで判定)に合わせ、単純にその否定とする。
1401                "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` は `:required` の否定(`required` 属性が無いフォーム要素)。
1412                "optional" => {
1413                    if attributes.contains_key("required") {
1414                        return false;
1415                    }
1416                }
1417                // `:valid`/`:invalid` が丸ごと未対応だった。`:checked`/`:required`/
1418                // `:in-range` 等と同じ簡略方針で、静的な HTML 属性のみから判定する
1419                // (`pattern`/`type=email` 等の書式チェックは JS 側の `validate_field`
1420                // に既にあるロジックをそのまま複製することになり css.rs 側の担当範囲を
1421                // 超えるため対象外。ここでは最も頻出する「`required` な空欄」と
1422                // `:in-range`/`:out-of-range` で既に対応済みの min/max 範囲のみを見る)。
1423                // checkbox/radio は「値」でなく「チェック状態」で`required`を判定する
1424                // 別のセマンティクス(JS側の`is_disabled`と対になる`required_satisfied`
1425                // で2026-07-17に修正済みの規則と同じ)。以前はここも他のinputと同じ
1426                // 「value属性が空か」で判定しており、`value`属性を持たないchecked済み
1427                // チェックボックスが常に`:invalid`になる等、チェック状態と無関係な
1428                // 結果になっていた。radioのグループ判定は`own_siblings`(同じ親を持つ
1429                // 兄弟のみ)の範囲に限定する簡略実装(JS側は文書全体を`name`で走査する
1430                // 完全な実装だが、CSSセレクタマッチングはこの関数の他の兄弟系疑似
1431                // クラスと同じスコープに合わせる)。
1432                // `:user-valid`/`:user-invalid`(CSS Selectors Level 4)が丸ごと
1433                // 未対応だった。`:valid`/`:invalid`と同一の妥当性判定ロジックに
1434                // 加え、ユーザーが実際にフォームコントロールを操作したこと
1435                // (`interp.rs`の`dispatch_event`が`input`/`change`発火時に
1436                // 記録する内部専用属性`_user_interacted`。`:indeterminate`の
1437                // `_indeterminate`と同じ方針)も要求する点のみ異なる。
1438                // 2026-07-18 発見・実装。
1439                "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`(`:read-only`/`:readonly` の対)が丸ごと未対応
1496                // だった。既存の `:read-only` と同じ簡略方針(タグ種別は問わず
1497                // `readonly` 属性の有無だけで判定)に合わせ、単純にその否定とする。
1498                "read-write" => {
1499                    if attributes.contains_key("readonly") {
1500                        return false;
1501                    }
1502                }
1503                // `:indeterminate` は本来 JS で設定される DOM プロパティ(HTML属性としては
1504                // 反映されない)。静的 HTML に `indeterminate` 属性が直接書かれている
1505                // ケース、`<progress>`(value 未指定)、そして `checkbox.indeterminate =
1506                // true`(JS の setter が書き込む内部専用の `_indeterminate` 属性キー。
1507                // 実属性 `indeterminate` とは別物で `hasAttribute('indeterminate')` は
1508                // 常に false のまま)の3パターンいずれかで真とする。
1509                "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` はキーボード操作かポインタ操作かを区別する仕組みが
1520                // 無いため、`:focus` と同一視する簡略実装(`:where()`≒`:is()` と同じ方針)。
1521                "focus-visible" => {
1522                    if !active_pseudo_states.contains(&"focus") {
1523                        return false;
1524                    }
1525                }
1526                // `:focus-within` は自分自身、または子孫のいずれかが現在フォーカス中の
1527                // 場合に一致する。id ではなくノード実体のポインタ同一性で判定するため、
1528                // id を持たない要素(`<div>`/`<form>` のラッパー等)でも正しく機能する。
1529                "focus-within" => {
1530                    if !crate::os_lib::viewport::FOCUS_WITHIN_PTRS.lock().contains(&node_ptr) {
1531                        return false;
1532                    }
1533                }
1534                // `:link`/`:visited` は `:checked`/`:disabled` と同様、要素自身の属性から
1535                // 静的に判定できる。閲覧履歴は保持していないため `:visited` は常に不一致
1536                // (プライバシー上安全側の簡略実装。多くの単純なエンジンや履歴を持たない
1537                // 環境と同じ挙動)。
1538                "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`(Selectors Level 4。標準組み込み要素は常に「定義済み」、
1548                // 未定義の`customElements`要素のみ不一致になる仕様)。
1549                // カスタム要素名(ハイフンを含む等)の場合は `_defined` 属性の有無で判定し、
1550                // 通常の組み込み要素(div, span 等)は常に一致する。
1551                "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`が丸ごと未対応だった。`element.requestFullscreen()`が
1559                // 書き込む内部専用属性`_fullscreen`(`_indeterminate`と同じ方針)の
1560                // 有無で判定する。2026-07-18 発見・実装。
1561                "fullscreen" => {
1562                    if !attributes.contains_key("_fullscreen") {
1563                        return false;
1564                    }
1565                }
1566                // `:modal`が丸ごと未対応だった。フルスクリーン要素、および
1567                // `dialog.showModal()`(`.show()`とは区別される。`dom.rs`の
1568                // `dom_dialog_show_modal`が書き込む内部専用属性`_modal`)で
1569                // 開いている`<dialog>`のいずれかに一致する。2026-07-18
1570                // 発見・実装。
1571                "modal" => {
1572                    if !attributes.contains_key("_fullscreen") && !attributes.contains_key("_modal")
1573                    {
1574                        return false;
1575                    }
1576                }
1577                // `:popover-open`が丸ごと未対応だった。`element.showPopover()`/
1578                // `.hidePopover()`/`.togglePopover()`(`dom.rs`)が既に
1579                // 内部専用属性`_popover_open`を書き込んでいたため、CSS側の
1580                // 判定を追加するだけで済んだ(`:fullscreen`/`:modal`と違い
1581                // JS側の新規実装が不要だった兄弟ギャップ)。2026-07-18
1582                // 発見・実装。
1583                "popover-open" => {
1584                    if !attributes.contains_key("_popover_open") {
1585                        return false;
1586                    }
1587                }
1588                // `:root` は文書のルート要素(HTML文書では常に <html>)にのみ一致する。
1589                "root" => {
1590                    if tag_name != "html" {
1591                        return false;
1592                    }
1593                }
1594                // `:placeholder-shown` は `value` が空(または未指定)かつ `placeholder` 属性を
1595                // 持つ input/textarea にのみ一致する。checked/disabled と同様、属性から
1596                // 静的判定できる。**簡略化**: 初期パース時の `value` 属性のみを見るため、
1597                // ユーザーが実際に入力欄へ入力した後の再判定(動的な再マッチング)は非対応。
1598                "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` は `min`/`max` 属性を持つ input の `value` が
1612                // その範囲内/範囲外かで判定する。checked/required 等と同様、静的な HTML 属性
1613                // から判定できる(JS による動的な value 変更後の再判定は非対応の簡略実装)。
1614                // min/max のどちらも指定が無ければ範囲制約自体が存在しないため、どちらにも
1615                // 一致しない(実ブラウザと同じ挙動)。
1616                "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                        // value 未指定は制約違反ではない(実ブラウザ準拠)。
1626                        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` は「グループ内で既定選択された要素」(フォーム送信時にJSが何も
1634                // 変更しなければ選ばれる状態)を指す。`:checked`/`:required` と同じく静的な
1635                // HTML属性から判定する簡略実装: checkbox/radio は `checked` 属性、
1636                // `<option>` は `selected` 属性の有無で判定する(ユーザー操作後の動的な
1637                // 「既定値からの変化」追跡は非対応。実ブラウザは操作後も初期選択を
1638                // `:default` として扱い続けるが、ここでは常に静的属性を見る近似)。
1639                "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
1666/// 親の子ノード一覧の中で、`node` と同じタグ名を持つノードだけを数えた「型フィルタ済み」
1667/// 兄弟位置(0-based)と総数を返す。`:first-of-type`/`:last-of-type`/`:nth-of-type`/
1668/// `:only-of-type` 用。祖先が無い(ルート要素)場合は自分だけの単一グループとして扱う。
1669/// サブジェクト(末尾コンパウンド)位置でのみ計算する(祖先位置での of-type 判定は非対応)。
1670pub(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
1699/// 子の数がこれより多い要素では、子ごとの「同じタグの兄弟の中の位置と数」を親で 1 回だけ数えておく
1700/// ([`type_positions_of_children`]。2026-11-18、TODO R5 (e) ④)。少ない要素ではその場で数えるほうが安い。
1701pub(crate) const TYPE_POSITION_TABLE_MIN_CHILDREN: usize = 32;
1702
1703/// `parent` の子それぞれについて、同じタグ名の兄弟の中での位置と、その数を返す(文字の子は `(None, None)`)。
1704///
1705/// 【2026-11-18 TODO R5 (e) ④】[`type_sibling_position`] は子 1 つごとに兄弟全員を見るので、子が n 個の要素では
1706/// n² 回のタグ名の比較になる。入れ子の深さの上限(512 段)で開かなかったタグが最深の要素の子として約 6 万個並ぶページ
1707/// (`deep4m.html`)では、スタイルの計算だけで 60 秒を過ぎても終わらなかった(`memcmp` が上位)。親で 1 回数えて渡す。
1708pub(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
1729/// nth: position が a*n + b(n>=0)で表せるか。
1730pub(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
1738/// 属性セレクタの照合。
1739pub(crate) fn attr_matches(attr: &AttrSelector, attributes: &BTreeMap<String, String>) -> bool {
1740    // 属性名は小文字保持されている前提(dom 側で lower 化されていなければ線形探索)。
1741    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, // 属性が無ければどの演算子も不一致。
1750    };
1751    // `[attr=val i]`(大文字小文字を無視。Selectors Level 4 §6.4.1)。フラグが無ければ
1752    // 通常どおり大文字小文字を区別して比較する(`val`/`attr.value` をそのまま使う)。
1753    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
1773/// 1 ノードに対して**一度だけ**計算すればよい照合用の前提情報。
1774///
1775/// 【2026-07-27 性能修正】従来これらは `matches_selector` の内部で
1776/// **ルールごとに毎回**計算されていた。実サイト規模(2403 ルール × 365 ノード
1777/// = 約 88 万回)では、祖先を辿る `is_node_disabled` と兄弟を数える
1778/// `type_sibling_position` が支配的なコストになり、1 回のカスケードに
1779/// 約 46 秒を要していた。ノード単位で 1 回計算して使い回す。
1780pub(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    /// `type_position` に親が先に数えた同じタグの兄弟の中の位置([`type_positions_of_children`])を渡せば、
1797    /// 兄弟を数え直さない(2026-11-18、TODO R5 (e) ④)。`None` なら [`type_sibling_position`] で数える。
1798    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        // of-type 系はサブジェクト(末尾コンパウンド)でのみ判定する。
1806        let (type_index, type_count) = match type_position {
1807            Some(p) => p,
1808            None => type_sibling_position(current, ancestors, sibling_index),
1809        };
1810        // `:has(+ sel)`/`:has(~ sel)` 用。サブジェクト位置の自分の兄弟一覧。
1811        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
1899/// `:has(sel1, sel2, ...)` 判定用: `children` 以下にリスト中いずれかの単純セレクタへ
1900/// 一致する要素が存在するかを探索する。タプルの `bool` が true(`> sel` 形式)の枝は
1901/// `children`(直接子)のみを見て、それより深くは再帰しない。false(通常の `:has(.foo)`)の
1902/// 枝は任意の深さまで再帰する。子孫側の疑似クラス判定は sibling_index 等の文脈を持たない
1903/// ため `None`/空リストで簡略化して渡す(`:has(.foo)` のようなタグ/クラス/id/属性ベースの
1904/// 判定が主な実用対象で、`:has(:first-child)` 等の兄弟文脈依存の疑似クラスは子孫探索側では
1905/// 正しく判定できない既知の制約)。
1906pub(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        // 直接子限定(`> sel`)の枝は、これより深い子孫へは適用しない。
1939        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
1951/// `:has(+ sel)`/`:has(~ sel)` 判定用: `siblings`(親の子ノード一覧)中の `my_idx` より
1952/// 後ろの要素ノードで `sel` に一致するものがあるか探索する。`adjacent` が true なら
1953/// 直後の要素兄弟1つのみ(`+`)、false なら以降の要素兄弟いずれか(`~`)を対象にする。
1954pub(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
1991/// `:nth-child(An+B of S)`/`:nth-last-child(An+B of S)` 判定用: `own_siblings`(親の子ノード
1992/// 一覧)のうち `S` に一致する要素だけを数えた「フィルタ済み」0-based 位置と総数を返す。
1993/// 自分自身が `S` に一致しない場合は `None`(=不一致。フィルタ済み集合に属さない)。
1994pub(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/// 祖先位置のコンパウンドが明らかに一致しないか(要素でない・タグ・id・クラスの不一致)。
2041/// 本照合(`matches_selector_step_node`)の前の枝刈り。true なら一致し得ない。
2042///
2043/// 【2026-10-24】従来はタグと id だけを見ていた。YouTube(Polymer)の規則はほぼ
2044/// `.ytd-xxx .yyy` のクラスの子孫セレクタで、祖先ごとに本照合と `disabled` 判定
2045/// (祖先全体をたどる)が走り、深さの二乗の照合になっていた。
2046#[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    // 兄弟結合子用に「現在ノードの兄弟内インデックス」を追跡する。
2096    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                // 【高速化】要素以外の祖先、またはタグ名/IDの事前不一致なら即座に枝刈り
2108                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                // 祖先位置の of-type 判定は非対応(None,None で常に不一致)。実用上は
2115                // サブジェクト位置での使用がほとんどのため許容する。
2116                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                    // 【高速化】要素以外の祖先、またはタグ名/IDの事前不一致なら step_node を呼ばずスキップ
2137                    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                // 親(兄弟を列挙するため)は ancestors の末尾側を消費せず参照する。
2165                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                            // 直後兄弟は最初の要素兄弟のみが対象。一致しなければ失敗。
2199                            break;
2200                        }
2201                    }
2202                }
2203                if !found {
2204                    return false;
2205                }
2206            }
2207        }
2208    }
2209    true
2210}
2211