Skip to main content

atmos/os_lib/
dom_selector.rs

1// arm/v1/src/os_lib/dom_selector.rs
2//! W3C Selectors Level 3 / Level 4 準拠の DOM セレクタパーサ。
3//!
4//! `matches()`, `closest()`, `querySelector()`, `querySelectorAll()` で共有される
5//! 純粋なセレクタ字句解析・構文木構築ロジックを提供する。
6
7extern crate alloc;
8
9use alloc::string::{String, ToString};
10use alloc::vec::Vec;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum AttrOp {
14    Exists,
15    Eq,
16    Prefix,
17    Suffix,
18    Contains,
19    Word,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct AttrSel {
24    pub name: String,
25    pub op: AttrOp,
26    pub value: String,
27}
28
29/// 属性セレクタの付帯情報。`CompoundSel::attr_ext` に `CompoundSel::attrs` と同じ添字で並ぶ
30/// (`AttrSel` 自体はテストがリテラルで組むため形を変えない)。
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub struct AttrExt {
33    /// `[a=v i]`(値を ASCII の大小無視で比べる)。
34    pub case_insensitive: bool,
35    /// `[a=v s]`(HTML の既定で大小無視になる属性でも大小を区別する)。
36    pub case_sensitive: bool,
37    /// `[*|a]`(どの名前空間の属性でもよい。接頭辞なし・`|a` は名前空間なしの属性だけ)。
38    pub any_ns: bool,
39}
40
41/// `:has()` の相対セレクタ 1 件。
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct RelSel {
44    /// 先頭の結合子(`:has(> a)` なら `Child`。省略時は `Descendant`)。
45    pub combinator: Combinator,
46    /// 相対セレクタ本体(`steps[0].combinator` は `None`)。
47    pub steps: Vec<SelStep>,
48    /// 先頭に「`:has()` を評価している要素」を表す段(`CompoundSel::is_has_anchor`)を置き、
49    /// `steps[0]` の結合子を `combinator` にした絶対形。照合側は、アンカー段がその要素にだけ
50    /// 一致するとして通常の複合セレクタと同じ要領で右から照合すればよい。
51    pub anchored: Vec<SelStep>,
52}
53
54/// 決して一致しない型セレクタの印(名前空間接頭辞 `ns|tag` や解析できない属性セレクタ等。
55/// 実在の要素名には NUL が入らないので、従来の照合でも一致しない)。
56pub const NEVER_MATCH_TAG: &str = "\u{0}never";
57
58#[derive(Debug, Clone, PartialEq, Eq, Default)]
59pub struct CompoundSel {
60    /// 型セレクタ(小文字化済み)。
61    pub tag: Option<String>,
62    /// 型セレクタの書かれたままの大小(HTML 以外の要素は大小を区別して比べる)。
63    pub tag_raw: Option<String>,
64    /// `|tag` / `|*`(名前空間を持たない要素だけ)。
65    pub no_namespace: bool,
66    pub id: Option<String>,
67    pub classes: Vec<String>,
68    pub attrs: Vec<AttrSel>,
69    /// `attrs` と同じ添字の付帯情報(フラグ `i`/`s`・`*|`)。
70    pub attr_ext: Vec<AttrExt>,
71    /// `:not(sel1, sel2, ...)` の中身(結合子を含まないもの)。
72    pub not: Vec<CompoundSel>,
73    /// `:not(...)` の中身のうち結合子を含むもの(`:not(table p)`)。どれかに一致したら不一致。
74    pub not_complex: Vec<Vec<SelStep>>,
75    /// `:is(sel1, sel2, ...)` / `:where(...)` の中身(結合子を含まないもの)。
76    pub is_list: Vec<CompoundSel>,
77    /// `:is(...)` / `:where(...)` の中身のうち結合子を含むもの。`is_list` と合わせたどれかに一致すればよい
78    /// (これだけのときは `is_list` に `NEVER_MATCH_TAG` の番兵を入れてあり、従来の照合では一致しない)。
79    pub is_complex: Vec<Vec<SelStep>>,
80    /// `:has(rel1, rel2, ...)`。どれかの相対セレクタに一致する要素があれば一致。
81    pub has: Vec<RelSel>,
82    /// `:has()` の相対セレクタの起点(`RelSel::anchored` の先頭段だけが持つ)。
83    pub is_has_anchor: bool,
84    /// `:first-child` / `:last-child` / `:only-child` / `:nth-child(...)`。
85    pub pos: Vec<PosPseudo>,
86    /// `:first-of-type` / `:last-of-type` / `:only-of-type` / `:nth-of-type(...)`。
87    pub pos_of_type: Vec<PosPseudo>,
88    /// `:scope`(呼び出し元の起点要素)。
89    pub is_scope: bool,
90    /// `:empty`(子要素および非空テキストを持たない要素)。
91    pub is_empty: bool,
92    /// `:root`(ドキュメントルート要素、通常 <html>)。
93    pub is_root: bool,
94    /// `:checked`(checkbox / radio の checked 属性またはプロパティ)。
95    pub is_checked: bool,
96    /// `:disabled`(disabled 属性を持つフォーム要素等)。
97    pub is_disabled: bool,
98    /// `:enabled`(disabled 属性を持たないフォーム要素等)。
99    pub is_enabled: bool,
100    /// `:valid`(制約検証を満たすフォーム要素)。
101    pub is_valid: bool,
102    /// `:invalid`(制約検証を満たさないフォーム要素)。
103    pub is_invalid: bool,
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct NthFormula {
108    pub a: i32,
109    pub b: i32,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum PosPseudo {
114    First,
115    Last,
116    Only,
117    Nth(NthFormula),
118    /// `:nth-last-child()` / `:nth-last-of-type()`。
119    NthLast(NthFormula),
120}
121
122/// `:nth-child()` 引数(`odd`/`even`/`N`/`aN+b`/`aN-b`/`-aN+b`)を CSS Syntax §6(An+B microsyntax)どおり厳密に解析する。
123/// 先頭・末尾の空白は許す。`+ n`・`- n`・`2 n`・`n- -5`・`n+ -5`・`n 5` などトークン規則に反するものは `None`。
124/// 許す形: `[+-]? digits? n`(`n` は大小無視)の後ろに、空白を挟んでもよい `[+-] digits`(符号の後ろに符号や整数でないものは不可)。
125pub fn parse_nth_formula(s: &str) -> Option<NthFormula> {
126    let s = s.trim_matches([' ', '\t', '\n', '\r', '\x0c']);
127    let lower = s.to_ascii_lowercase();
128    if lower == "odd" {
129        return Some(NthFormula { a: 2, b: 1 });
130    }
131    if lower == "even" {
132        return Some(NthFormula { a: 2, b: 0 });
133    }
134    let bytes = lower.as_bytes();
135    let mut i = 0usize;
136    let mut neg = false;
137    if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
138        neg = bytes[i] == b'-';
139        i += 1;
140    }
141    let d0 = i;
142    while i < bytes.len() && bytes[i].is_ascii_digit() {
143        i += 1;
144    }
145    let digits = lower.get(d0..i).unwrap_or("");
146    if i >= bytes.len() || bytes[i] != b'n' {
147        // 整数のみ(`+5` / `-5` / `5`)。
148        if i != bytes.len() || digits.is_empty() {
149            return None;
150        }
151        let v = digits.parse::<i32>().ok()?;
152        return Some(NthFormula { a: 0, b: if neg { -v } else { v } });
153    }
154    let mag = if digits.is_empty() { 1 } else { digits.parse::<i32>().ok()? };
155    let a = if neg { -mag } else { mag };
156    i += 1; // 'n'
157    // `n` の後ろ: 無し / 空白を挟んでよい `[+-] 空白* digits`。
158    let mut rest = lower.get(i..).unwrap_or("");
159    rest = rest.trim_start_matches([' ', '\t', '\n', '\r', '\x0c']);
160    if rest.is_empty() {
161        return Some(NthFormula { a, b: 0 });
162    }
163    let rb = rest.as_bytes();
164    let bneg = match rb[0] {
165        b'+' => false,
166        b'-' => true,
167        _ => return None,
168    };
169    let num = rest
170        .get(1..)
171        .unwrap_or("")
172        .trim_start_matches([' ', '\t', '\n', '\r', '\x0c']);
173    if num.is_empty() || !num.bytes().all(|c| c.is_ascii_digit()) {
174        return None;
175    }
176    let v = num.parse::<i32>().ok()?;
177    Some(NthFormula { a, b: if bneg { -v } else { v } })
178}
179
180/// `position`(1始まり)が `an+b` 式(`n` は 0,1,2,...)のいずれかの `n` で表せるか判定する。
181pub fn nth_formula_matches(f: NthFormula, position: usize) -> bool {
182    let p = position as i32;
183    if f.a == 0 {
184        return p == f.b;
185    }
186    let diff = p - f.b;
187    diff % f.a == 0 && diff / f.a >= 0
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub enum Combinator {
192    Descendant,
193    Child,
194    Adjacent,
195    General,
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct SelStep {
200    pub compound: CompoundSel,
201    /// 直前のステップとの結合子(先頭ステップは `None`)。
202    pub combinator: Option<Combinator>,
203}
204
205/// CSS Syntax §4.3.7 (consume an escaped code point) に従い、`chars[idx] == '\\'` から始まる
206/// エスケープ 1 件を消費し、デコードされた文字と次のインデックスを返す。
207fn consume_css_escape(chars: &[char], idx: usize) -> (char, usize) {
208    let mut i = idx + 1;
209    if i >= chars.len() {
210        // EOF でのバックスラッシュは U+FFFD
211        return ('\u{FFFD}', i);
212    }
213    if chars[i].is_ascii_hexdigit() {
214        let mut val: u32 = 0;
215        let mut count = 0;
216        while i < chars.len() && count < 6 && chars[i].is_ascii_hexdigit() {
217            let d = chars[i].to_digit(16).unwrap_or(0);
218            val = (val << 4) | d;
219            i += 1;
220            count += 1;
221        }
222        // 16進エスケープ直後の単一 ASCII 空白(\r\n は 1 つの改行として扱う)を消費する
223        if i < chars.len() {
224            match chars[i] {
225                '\r' => {
226                    i += 1;
227                    if i < chars.len() && chars[i] == '\n' {
228                        i += 1;
229                    }
230                }
231                ' ' | '\t' | '\n' | '\x0C' => {
232                    i += 1;
233                }
234                _ => {}
235            }
236        }
237        let ch = if val == 0 || (0xD800..=0xDFFF).contains(&val) || val > 0x10FFFF {
238            '\u{FFFD}'
239        } else {
240            char::from_u32(val).unwrap_or('\u{FFFD}')
241        };
242        (ch, i)
243    } else {
244        let ch = if chars[i] == '\0' { '\u{FFFD}' } else { chars[i] };
245        (ch, i + 1)
246    }
247}
248
249/// 元のエスケープ表記(`\` + 16進 + 任意単一空白、または `\` + 1文字)を
250/// そのまま文字列へコピーし、次のインデックスを返す(トークナイザ用)。
251fn copy_raw_escape(chars: &[char], idx: usize, out: &mut String) -> usize {
252    out.push(chars[idx]);
253    let mut i = idx + 1;
254    if i >= chars.len() {
255        return i;
256    }
257    if chars[i].is_ascii_hexdigit() {
258        let mut count = 0;
259        while i < chars.len() && count < 6 && chars[i].is_ascii_hexdigit() {
260            out.push(chars[i]);
261            i += 1;
262            count += 1;
263        }
264        if i < chars.len() {
265            match chars[i] {
266                '\r' => {
267                    out.push(chars[i]);
268                    i += 1;
269                    if i < chars.len() && chars[i] == '\n' {
270                        out.push(chars[i]);
271                        i += 1;
272                    }
273                }
274                ' ' | '\t' | '\n' | '\x0C' => {
275                    out.push(chars[i]);
276                    i += 1;
277                }
278                _ => {}
279            }
280        }
281        i
282    } else {
283        out.push(chars[i]);
284        i + 1
285    }
286}
287
288/// CSS の空白(CSS Syntax §4.2。U+00A0・U+2003 等の Unicode 空白は含まない。これらは識別子の文字)。
289fn is_css_ws(c: char) -> bool {
290    matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c')
291}
292
293/// 識別子の先頭に置ける文字(ASCII 英字・`_`・非 ASCII。NUL は U+FFFD になるので含める)。
294fn is_name_start(c: char) -> bool {
295    c.is_ascii_alphabetic() || c == '_' || c == '\0' || (c as u32) >= 0x80
296}
297
298/// 識別子の 2 文字目以降に置ける文字。
299fn is_name_char(c: char) -> bool {
300    is_name_start(c) || c.is_ascii_digit() || c == '-'
301}
302
303/// CSS Syntax §4.3.8 「valid escape」。
304fn is_valid_escape(a: Option<char>, b: Option<char>) -> bool {
305    a == Some('\\') && !matches!(b, Some('\n' | '\r' | '\x0c'))
306}
307
308/// CSS Syntax §4.3.9 「would start an ident sequence」。
309fn would_start_ident(c1: Option<char>, c2: Option<char>, c3: Option<char>) -> bool {
310    match c1 {
311        Some('-') => matches!(c2, Some(c) if is_name_start(c) || c == '-') || is_valid_escape(c2, c3),
312        Some('\\') => is_valid_escape(c1, c2),
313        Some(c) => is_name_start(c),
314        None => false,
315    }
316}
317
318fn skip_css_ws(chars: &[char], i: &mut usize) {
319    while *i < chars.len() && is_css_ws(chars[*i]) {
320        *i += 1;
321    }
322}
323
324/// `chars[*i]` から識別子の文字(エスケープ込み)を読めるだけ読む(先頭の数字も寛容に許す)。
325fn consume_ident_chars(chars: &[char], i: &mut usize) -> String {
326    let mut out = String::new();
327    while *i < chars.len() {
328        let ch = chars[*i];
329        if ch == '\\' {
330            if !is_valid_escape(Some(ch), chars.get(*i + 1).copied()) {
331                break;
332            }
333            let (c, next) = consume_css_escape(chars, *i);
334            out.push(c);
335            *i = next;
336        } else if is_name_char(ch) {
337            out.push(if ch == '\0' { '\u{FFFD}' } else { ch });
338            *i += 1;
339        } else {
340            break;
341        }
342    }
343    out
344}
345
346/// CSS 識別子・属性値文字列をアンエスケープする(生 NUL も U+FFFD に置換)。
347pub fn unescape_css_ident(s: &str) -> String {
348    let chars: Vec<char> = s.chars().collect();
349    let mut out = String::with_capacity(s.len());
350    let mut i = 0;
351    while i < chars.len() {
352        if chars[i] == '\\' {
353            let (ch, next_i) = consume_css_escape(&chars, i);
354            out.push(ch);
355            i = next_i;
356        } else if chars[i] == '\0' {
357            out.push('\u{FFFD}');
358            i += 1;
359        } else {
360            out.push(chars[i]);
361            i += 1;
362        }
363    }
364    out
365}
366
367/// `[attr...]` の解析結果。
368enum ParsedAttr {
369    Single(AttrSel, AttrExt),
370    /// `[a|=v]`(値が `v` か `v-` で始まる)。`AttrOp` に変種を足すと照合側の網羅 match が壊れるため、
371    /// `parse_compound` で「`[a=v]` か `[a^="v-"]`」を二重否定に組み直す(`dash_match_compound`)。
372    DashMatch(AttrSel, AttrExt),
373    /// 決して一致しない(名前空間接頭辞 `[ns|a]`・解析できない中身)。
374    Never,
375}
376
377/// `[attr...]` の中身を Selectors Level 4 §6 どおりに解析する:
378/// `ws* (*| | '|' | ns|)? 名前 ws* (演算子 ws* (識別子|文字列) ws* (i|s)? ws*)?`。
379fn parse_attr_full(inner: &str) -> ParsedAttr {
380    let chars: Vec<char> = inner.chars().collect();
381    let n = chars.len();
382    let mut i = 0usize;
383    let mut ext = AttrExt::default();
384    let mut never = false;
385    skip_css_ws(&chars, &mut i);
386    let next_is_eq = |k: usize| chars.get(k + 1) == Some(&'=');
387    if i + 1 < n && chars[i] == '*' && chars[i + 1] == '|' && !next_is_eq(i + 1) {
388        ext.any_ns = true;
389        i += 2;
390    } else if i < n && chars[i] == '|' && !next_is_eq(i) {
391        // `[|a]`(名前空間なしの属性。接頭辞なしと同じ)。
392        i += 1;
393    }
394    let mut name = consume_ident_chars(&chars, &mut i);
395    if !ext.any_ns && !name.is_empty() && i < n && chars[i] == '|' && !next_is_eq(i) {
396        // `[ns|a]`: querySelector は名前空間接頭辞を宣言できないので一致しない(構文としては SyntaxError)。
397        never = true;
398        i += 1;
399        name = consume_ident_chars(&chars, &mut i);
400    }
401    // 識別子に使えない文字(`[data-a:b]` の `:` 等)も、空白・演算子・`|` までは従来どおり名前の一部として寛容に受ける。
402    while i < n
403        && !is_css_ws(chars[i])
404        && chars[i] != '='
405        && chars[i] != '|'
406        && !(matches!(chars[i], '^' | '$' | '*' | '~') && next_is_eq(i))
407    {
408        name.push(chars[i]);
409        i += 1;
410        name.push_str(&consume_ident_chars(&chars, &mut i));
411    }
412    if name.is_empty() {
413        return ParsedAttr::Never;
414    }
415    skip_css_ws(&chars, &mut i);
416    if i >= n {
417        if never {
418            return ParsedAttr::Never;
419        }
420        return ParsedAttr::Single(AttrSel { name, op: AttrOp::Exists, value: String::new() }, ext);
421    }
422    let mut dash = false;
423    let op = match chars[i] {
424        '=' => {
425            i += 1;
426            AttrOp::Eq
427        }
428        c @ ('^' | '$' | '*' | '~' | '|') if i + 1 < n && chars[i + 1] == '=' => {
429            i += 2;
430            match c {
431                '^' => AttrOp::Prefix,
432                '$' => AttrOp::Suffix,
433                '*' => AttrOp::Contains,
434                '~' => AttrOp::Word,
435                _ => {
436                    dash = true;
437                    AttrOp::Eq
438                }
439            }
440        }
441        _ => return ParsedAttr::Never,
442    };
443    skip_css_ws(&chars, &mut i);
444    let value = if i < n && (chars[i] == '"' || chars[i] == '\'') {
445        // 文字列(CSS Syntax §4.3.5。`\` + 改行は継続行として捨てる。閉じ忘れは末尾までを値とする)。
446        let q = chars[i];
447        i += 1;
448        let mut v = String::new();
449        while i < n && chars[i] != q {
450            if chars[i] == '\\' {
451                match chars.get(i + 1) {
452                    None => i += 1,
453                    Some('\n' | '\x0c') => i += 2,
454                    Some('\r') => {
455                        i += 2;
456                        if chars.get(i) == Some(&'\n') {
457                            i += 1;
458                        }
459                    }
460                    Some(_) => {
461                        let (c, next) = consume_css_escape(&chars, i);
462                        v.push(c);
463                        i = next;
464                    }
465                }
466            } else {
467                v.push(if chars[i] == '\0' { '\u{FFFD}' } else { chars[i] });
468                i += 1;
469            }
470        }
471        if i < n {
472            i += 1; // 閉じ引用符
473        }
474        v
475    } else {
476        // 引用符なしの値は本来識別子だけだが、`[href=#top]`・`[data-x=1.5]` 等を従来どおり寛容に受け、
477        // CSS 空白までを値とする(エスケープは解く)。
478        let mut v = String::new();
479        while i < n && !is_css_ws(chars[i]) {
480            if chars[i] == '\\' {
481                let (c, next) = consume_css_escape(&chars, i);
482                v.push(c);
483                i = next;
484            } else {
485                v.push(if chars[i] == '\0' { '\u{FFFD}' } else { chars[i] });
486                i += 1;
487            }
488        }
489        if v.is_empty() {
490            return ParsedAttr::Never;
491        }
492        v
493    };
494    skip_css_ws(&chars, &mut i);
495    if i < n {
496        match chars[i] {
497            'i' | 'I' => ext.case_insensitive = true,
498            's' | 'S' => ext.case_sensitive = true,
499            _ => return ParsedAttr::Never,
500        }
501        i += 1;
502        skip_css_ws(&chars, &mut i);
503        if i < n {
504            return ParsedAttr::Never;
505        }
506    }
507    if never {
508        return ParsedAttr::Never;
509    }
510    let sel = AttrSel { name, op, value };
511    if dash {
512        ParsedAttr::DashMatch(sel, ext)
513    } else {
514        ParsedAttr::Single(sel, ext)
515    }
516}
517
518/// `[attr...]` 1件を解析する(フラグ・名前空間は捨てる。`|=` は `=` として返す。一致し得ないものは `None`)。
519pub fn parse_attr_sel(inner: &str) -> Option<AttrSel> {
520    match parse_attr_full(inner) {
521        ParsedAttr::Single(a, _) | ParsedAttr::DashMatch(a, _) => Some(a),
522        ParsedAttr::Never => None,
523    }
524}
525
526/// `[a|=v]` を `not` に入れる 1 件(`:not([a=v]):not([a^="v-"])`)に組む。外側の `not` に入るので
527/// 「どちらでもない、ではない」=「`[a=v]` か `[a^="v-"]`」になり、従来の照合のままで `|=` の意味になる。
528fn dash_match_compound(a: AttrSel, ext: AttrExt) -> CompoundSel {
529    let mut eq = CompoundSel::default();
530    eq.attrs.push(AttrSel { name: a.name.clone(), op: AttrOp::Eq, value: a.value.clone() });
531    eq.attr_ext.push(ext);
532    let mut pre = CompoundSel::default();
533    let mut v = a.value;
534    v.push('-');
535    pre.attrs.push(AttrSel { name: a.name, op: AttrOp::Prefix, value: v });
536    pre.attr_ext.push(ext);
537    CompoundSel { not: alloc::vec![eq, pre], ..CompoundSel::default() }
538}
539
540/// 先頭と、末尾の「エスケープされていない」CSS 空白を除去する(U+00A0 等の Unicode 空白は識別子の文字なので残す)。
541fn trim_selector_whitespace(s: &str) -> &str {
542    let s = s.trim_start_matches(is_css_ws);
543    let bytes = s.as_bytes();
544    let mut end = bytes.len();
545    while end > 0 && matches!(bytes[end - 1], b' ' | b'\t' | b'\n' | b'\r' | 0x0c) {
546        let mut bs = 0usize;
547        let mut idx = end - 1;
548        while idx > 0 && bytes[idx - 1] == b'\\' {
549            bs += 1;
550            idx -= 1;
551        }
552        if bs % 2 == 1 {
553            break;
554        }
555        end -= 1;
556    }
557    s.get(..end).unwrap_or(s)
558}
559
560/// 単一コンパウンドセレクタ(`div.active#foo[data-x=y]:not(...)`)を解析する。
561pub fn parse_compound(s: &str) -> Option<CompoundSel> {
562    let s = trim_selector_whitespace(s);
563    if s.is_empty() {
564        return None;
565    }
566    if s == "*" {
567        return Some(CompoundSel::default());
568    }
569    let mut c = CompoundSel::default();
570    let mut cur = String::new();
571    let mut has_token = false;
572    let mut had_escape = false;
573    let mut mode = 't'; // 't' = tag, '#' = id, '.' = class, ' ' = none
574    let chars: Vec<char> = s.chars().collect();
575    let mut i = 0;
576    // 型セレクタ(`*` を含む)を読んだか(`*|*` のように他に何も無くても一致条件として残すため)。
577    let mut saw_type = false;
578    // 名前空間接頭辞: 0 = 無し、1 = `*|`、2 = `|`(名前空間なし)、3 = `ns|`(宣言できないので一致しない)。
579    let mut ns_state = 0u8;
580    // 決して一致しない部分があった(`ns|tag`・`[ns|a]`・解析できない属性セレクタ)。
581    let mut never = false;
582    let flush = |mode: char,
583                 cur: &mut String,
584                 has_token: &mut bool,
585                 had_escape: &mut bool,
586                 saw_type: &mut bool,
587                 c: &mut CompoundSel| {
588        if !*has_token {
589            cur.clear();
590            *had_escape = false;
591            return;
592        }
593        match mode {
594            't' if *had_escape || cur.as_str() != "*" => {
595                c.tag = Some(cur.to_lowercase());
596                c.tag_raw = Some(cur.clone());
597                *saw_type = true;
598            }
599            't' => *saw_type = true,
600            '#' => c.id = Some(cur.clone()),
601            '.' => c.classes.push(cur.clone()),
602            _ => {}
603        }
604        cur.clear();
605        *has_token = false;
606        *had_escape = false;
607    };
608    while i < chars.len() {
609        let ch = chars[i];
610        match ch {
611            '|' if mode == 't' && chars.get(i + 1) != Some(&'|') => {
612                // 型・全称セレクタの名前空間接頭辞(`*|h`・`|h`・`ns|h`)。
613                ns_state = if ns_state != 0 {
614                    3
615                } else if !has_token {
616                    2
617                } else if !had_escape && cur == "*" {
618                    1
619                } else {
620                    3
621                };
622                cur.clear();
623                has_token = false;
624                had_escape = false;
625                i += 1;
626            }
627            '\\' => {
628                let (unescaped, next_i) = consume_css_escape(&chars, i);
629                cur.push(unescaped);
630                has_token = true;
631                had_escape = true;
632                i = next_i;
633            }
634            '\0' => {
635                cur.push('\u{FFFD}');
636                has_token = true;
637                i += 1;
638            }
639            '#' | '.' => {
640                flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
641                mode = ch;
642                i += 1;
643            }
644            '[' => {
645                flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
646                let start = i + 1;
647                let mut depth = 1;
648                let mut in_quote: Option<char> = None;
649                let mut j = start;
650                while j < chars.len() && depth > 0 {
651                    let cj = chars[j];
652                    if cj == '\\' {
653                        let (_, next_j) = consume_css_escape(&chars, j);
654                        j = next_j;
655                        continue;
656                    }
657                    if let Some(q) = in_quote {
658                        if cj == q {
659                            in_quote = None;
660                        }
661                        j += 1;
662                        continue;
663                    }
664                    match cj {
665                        '"' | '\'' => in_quote = Some(cj),
666                        '[' => depth += 1,
667                        ']' => depth -= 1,
668                        _ => {}
669                    }
670                    if depth > 0 {
671                        j += 1;
672                    }
673                }
674                let inner: String = chars[start..j.min(chars.len())].iter().collect();
675                match parse_attr_full(&inner) {
676                    ParsedAttr::Single(attr, ext) => {
677                        c.attrs.push(attr);
678                        c.attr_ext.push(ext);
679                    }
680                    ParsedAttr::DashMatch(attr, ext) => c.not.push(dash_match_compound(attr, ext)),
681                    ParsedAttr::Never => never = true,
682                }
683                i = if j < chars.len() { j + 1 } else { j };
684                mode = ' ';
685            }
686            ':' => {
687                flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
688                let mut j = i + 1;
689                let name_start = j;
690                while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '-') {
691                    j += 1;
692                }
693                let name: String = chars[name_start..j].iter().collect::<String>().to_lowercase();
694                if j < chars.len() && chars[j] == '(' {
695                    let paren_start = j + 1;
696                    let mut depth = 1;
697                    let mut in_quote: Option<char> = None;
698                    let mut k = paren_start;
699                    while k < chars.len() && depth > 0 {
700                        let ck = chars[k];
701                        if ck == '\\' {
702                            let (_, next_k) = consume_css_escape(&chars, k);
703                            k = next_k;
704                            continue;
705                        }
706                        if let Some(q) = in_quote {
707                            if ck == q {
708                                in_quote = None;
709                            }
710                            k += 1;
711                            continue;
712                        }
713                        match ck {
714                            '"' | '\'' => in_quote = Some(ck),
715                            '(' => depth += 1,
716                            ')' => depth -= 1,
717                            _ => {}
718                        }
719                        if depth > 0 {
720                            k += 1;
721                        }
722                    }
723                    if name == "not" {
724                        let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
725                        for part in split_top_level_commas(&inner) {
726                            let mut steps = parse_complex(&part);
727                            if steps.len() == 1 {
728                                if let Some(step) = steps.pop() {
729                                    c.not.push(step.compound);
730                                }
731                            } else if !steps.is_empty() {
732                                c.not_complex.push(steps);
733                            }
734                        }
735                    } else if name == "has" {
736                        let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
737                        for part in split_top_level_commas(&inner) {
738                            if let Some(rel) = parse_relative(&part) {
739                                c.has.push(rel);
740                            }
741                        }
742                    } else if name == "nth-child" {
743                        let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
744                        if let Some(formula) = parse_nth_formula(&inner) {
745                            c.pos.push(PosPseudo::Nth(formula));
746                        }
747                    } else if name == "nth-of-type" {
748                        let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
749                        if let Some(formula) = parse_nth_formula(&inner) {
750                            c.pos_of_type.push(PosPseudo::Nth(formula));
751                        }
752                    } else if name == "nth-last-child" {
753                        let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
754                        if let Some(formula) = parse_nth_formula(&inner) {
755                            c.pos.push(PosPseudo::NthLast(formula));
756                        }
757                    } else if name == "nth-last-of-type" {
758                        let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
759                        if let Some(formula) = parse_nth_formula(&inner) {
760                            c.pos_of_type.push(PosPseudo::NthLast(formula));
761                        }
762                    } else if name == "is" || name == "where" {
763                        let inner: String = chars[paren_start..k.min(chars.len())].iter().collect();
764                        // 寛容な(forgiving)セレクタ一覧: 解析できない部分は捨てる。
765                        for part in split_top_level_commas(&inner) {
766                            let mut steps = parse_complex(&part);
767                            if steps.len() == 1 {
768                                if let Some(step) = steps.pop() {
769                                    c.is_list.push(step.compound);
770                                }
771                            } else if !steps.is_empty() {
772                                c.is_complex.push(steps);
773                            }
774                        }
775                        if c.is_list.is_empty() && !c.is_complex.is_empty() {
776                            // 結合子を含む候補だけのとき、従来の照合(`is_list` を見るだけ)で全要素に一致しないよう番兵を置く。
777                            c.is_list.push(CompoundSel {
778                                tag: Some(String::from(NEVER_MATCH_TAG)),
779                                ..CompoundSel::default()
780                            });
781                        }
782                    }
783                    j = if k < chars.len() { k + 1 } else { k };
784                } else {
785                    match name.as_str() {
786                        "first-child" => c.pos.push(PosPseudo::First),
787                        "last-child" => c.pos.push(PosPseudo::Last),
788                        "only-child" => c.pos.push(PosPseudo::Only),
789                        "first-of-type" => c.pos_of_type.push(PosPseudo::First),
790                        "last-of-type" => c.pos_of_type.push(PosPseudo::Last),
791                        "only-of-type" => c.pos_of_type.push(PosPseudo::Only),
792                        "scope" => c.is_scope = true,
793                        "empty" => c.is_empty = true,
794                        "root" => c.is_root = true,
795                        "checked" => c.is_checked = true,
796                        "disabled" => c.is_disabled = true,
797                        "enabled" => c.is_enabled = true,
798                        "valid" => c.is_valid = true,
799                        "invalid" => c.is_invalid = true,
800                        _ => {}
801                    }
802                }
803                i = j;
804                mode = ' ';
805            }
806            _ => {
807                cur.push(ch);
808                has_token = true;
809                i += 1;
810            }
811        }
812    }
813    flush(mode, &mut cur, &mut has_token, &mut had_escape, &mut saw_type, &mut c);
814    match ns_state {
815        2 => c.no_namespace = true,
816        3 => never = true,
817        _ => {}
818    }
819    if never {
820        c.tag = Some(String::from(NEVER_MATCH_TAG));
821        c.tag_raw = Some(String::from(NEVER_MATCH_TAG));
822    }
823    if c.tag.is_none()
824        && !saw_type
825        && !c.no_namespace
826        && c.id.is_none()
827        && c.classes.is_empty()
828        && c.attrs.is_empty()
829        && c.not.is_empty()
830        && c.not_complex.is_empty()
831        && c.is_list.is_empty()
832        && c.is_complex.is_empty()
833        && c.has.is_empty()
834        && c.pos.is_empty()
835        && c.pos_of_type.is_empty()
836        && !c.is_scope
837        && !c.is_empty
838        && !c.is_root
839        && !c.is_checked
840        && !c.is_disabled
841        && !c.is_enabled
842        && !c.is_valid
843        && !c.is_invalid
844    {
845        return None;
846    }
847    Some(c)
848}
849
850/// トップレベルカンマで区切る。
851pub fn split_top_level_commas(s: &str) -> Vec<String> {
852    let chars: Vec<char> = s.chars().collect();
853    let mut parts = Vec::new();
854    let mut cur = String::new();
855    let mut depth = 0i32;
856    let mut in_quote: Option<char> = None;
857    let mut i = 0;
858    while i < chars.len() {
859        let ch = chars[i];
860        if ch == '\\' {
861            i = copy_raw_escape(&chars, i, &mut cur);
862            continue;
863        }
864        if let Some(q) = in_quote {
865            cur.push(ch);
866            if ch == q {
867                in_quote = None;
868            }
869            i += 1;
870            continue;
871        }
872        match ch {
873            '"' | '\'' => {
874                in_quote = Some(ch);
875                cur.push(ch);
876            }
877            '[' | '(' => {
878                depth += 1;
879                cur.push(ch);
880            }
881            ']' | ')' => {
882                depth -= 1;
883                cur.push(ch);
884            }
885            ',' if depth == 0 => {
886                parts.push(core::mem::take(&mut cur));
887            }
888            c if c.is_whitespace() && !is_css_ws(c) => {
889                // U+00A0・U+2003 等は CSS では識別子の文字(`#\u{A0}` は id が U+00A0)。呼び出し元が各部分を
890                // `str::trim()`(Unicode 空白を落とす)してから解析しても消えないよう、16 進エスケープに直す。
891                push_hex_escape(&mut cur, c);
892            }
893            _ => cur.push(ch),
894        }
895        i += 1;
896    }
897    parts.push(cur);
898    parts
899}
900
901/// `c` を `\XXXX `(16 進エスケープ + 終端の空白 1 つ)として書き足す。
902fn push_hex_escape(out: &mut String, c: char) {
903    const HEX: &[u8; 16] = b"0123456789abcdef";
904    out.push('\\');
905    let v = c as u32;
906    let mut started = false;
907    for shift in (0..6).rev() {
908        let d = ((v >> (shift * 4)) & 0xF) as usize;
909        if d != 0 || started || shift == 0 {
910            started = true;
911            out.push(HEX[d] as char);
912        }
913    }
914    out.push(' ');
915}
916
917/// 結合子を含むセレクタ 1 件(`:not()`/`:is()` の引数の 1 件)を段に解析する。
918fn parse_complex(part: &str) -> Vec<SelStep> {
919    build_steps(&tokenize_selector_group(trim_selector_whitespace(part)))
920}
921
922/// `:has()` の相対セレクタ 1 件(`> a b`・`+ a`・`a`)を解析する。
923fn parse_relative(part: &str) -> Option<RelSel> {
924    let tokens = tokenize_selector_group(trim_selector_whitespace(part));
925    let (combinator, rest) = match tokens.first().map(String::as_str) {
926        Some(">") => (Combinator::Child, tokens.get(1..).unwrap_or(&[])),
927        Some("+") => (Combinator::Adjacent, tokens.get(1..).unwrap_or(&[])),
928        Some("~") => (Combinator::General, tokens.get(1..).unwrap_or(&[])),
929        _ => (Combinator::Descendant, &tokens[..]),
930    };
931    let steps = build_steps(rest);
932    if steps.is_empty() {
933        return None;
934    }
935    let mut anchored = alloc::vec![SelStep {
936        compound: CompoundSel { is_has_anchor: true, ..CompoundSel::default() },
937        combinator: None,
938    }];
939    for (k, step) in steps.iter().enumerate() {
940        let mut s = step.clone();
941        if k == 0 {
942            s.combinator = Some(combinator);
943        }
944        anchored.push(s);
945    }
946    Some(RelSel { combinator, steps, anchored })
947}
948
949/// 1グループ分のセレクタ文字列をトークン分割する。
950pub fn tokenize_selector_group(s: &str) -> Vec<String> {
951    let chars: Vec<char> = s.chars().collect();
952    let mut tokens = Vec::new();
953    let mut cur = String::new();
954    let mut depth = 0i32;
955    let mut in_quote: Option<char> = None;
956    let mut i = 0;
957    while i < chars.len() {
958        let ch = chars[i];
959        if ch == '\\' {
960            i = copy_raw_escape(&chars, i, &mut cur);
961            continue;
962        }
963        if let Some(q) = in_quote {
964            cur.push(ch);
965            if ch == q {
966                in_quote = None;
967            }
968            i += 1;
969            continue;
970        }
971        match ch {
972            '"' | '\'' => {
973                in_quote = Some(ch);
974                cur.push(ch);
975            }
976            '[' | '(' => {
977                depth += 1;
978                cur.push(ch);
979            }
980            ']' | ')' => {
981                depth -= 1;
982                cur.push(ch);
983            }
984            '>' | '+' | '~' if depth == 0 => {
985                if !cur.is_empty() {
986                    tokens.push(core::mem::take(&mut cur));
987                }
988                tokens.push(ch.to_string());
989            }
990            c if is_css_ws(c) && depth == 0 => {
991                if !cur.is_empty() {
992                    tokens.push(core::mem::take(&mut cur));
993                }
994            }
995            _ => cur.push(ch),
996        }
997        i += 1;
998    }
999    if !cur.is_empty() {
1000        tokens.push(cur);
1001    }
1002    tokens
1003}
1004
1005/// トークン列から `SelStep` 列を組み立てる。
1006pub fn build_steps(tokens: &[String]) -> Vec<SelStep> {
1007    let mut steps: Vec<SelStep> = Vec::new();
1008    let mut pending: Option<Combinator> = None;
1009    for tok in tokens {
1010        match tok.as_str() {
1011            ">" => pending = Some(Combinator::Child),
1012            "+" => pending = Some(Combinator::Adjacent),
1013            "~" => pending = Some(Combinator::General),
1014            _ => {
1015                // 先頭の結合子(`> a` 等。`:has()` 以外では無効)は次の段へ持ち越さない。
1016                let p = pending.take();
1017                let combinator = if steps.is_empty() {
1018                    None
1019                } else {
1020                    Some(p.unwrap_or(Combinator::Descendant))
1021                };
1022                if let Some(compound) = parse_compound(tok) {
1023                    steps.push(SelStep { compound, combinator });
1024                }
1025            }
1026        }
1027    }
1028    steps
1029}
1030
1031// ===== 照合側(dom_bridge)が使う純粋な判定 =====
1032
1033/// HTML 文書の HTML 要素で、値を ASCII の大小無視で比べる属性(HTML Standard §4.16.2
1034/// 「Case-sensitivity of selectors」の一覧。`s` フラグがあれば大小を区別する)。
1035pub fn html_attr_value_is_case_insensitive(name: &str) -> bool {
1036    matches!(
1037        name.to_ascii_lowercase().as_str(),
1038        "accept" | "accept-charset" | "align" | "alink" | "axis" | "bgcolor" | "charset" | "checked"
1039            | "clear" | "codetype" | "color" | "compact" | "declare" | "defer" | "dir" | "direction"
1040            | "disabled" | "enctype" | "face" | "frame" | "hreflang" | "http-equiv" | "lang"
1041            | "language" | "link" | "media" | "method" | "multiple" | "nohref" | "noresize"
1042            | "noshade" | "nowrap" | "readonly" | "rel" | "rev" | "rules" | "scope" | "scrolling"
1043            | "selected" | "shape" | "target" | "text" | "type" | "valign" | "valuetype" | "vlink"
1044    )
1045}
1046
1047/// 属性セレクタの名前を、要素の属性を引く名前に直す。HTML 文書の HTML 要素は属性名が小文字で
1048/// 保存されているので小文字にし、それ以外(SVG・MathML・XML 文書)は書かれたまま大小を区別する。
1049pub fn attr_lookup_name(sel_name: &str, html_element_in_html_doc: bool) -> String {
1050    if html_element_in_html_doc {
1051        sel_name.to_ascii_lowercase()
1052    } else {
1053        String::from(sel_name)
1054    }
1055}
1056
1057/// 属性の修飾名(`xlink:href` 等)の局所名が `local` か(`[*|local]` 用。接頭辞の無い名前はそのまま比べる)。
1058pub fn attr_qname_has_local_name(qname: &str, local: &str) -> bool {
1059    match qname.split_once(':') {
1060        Some((_, l)) => l == local || qname == local,
1061        None => qname == local,
1062    }
1063}
1064
1065/// 属性値 `actual` が属性セレクタ(`op`・`sel_value`・`ext`)に一致するか(Selectors Level 4 §6.1〜6.3)。
1066/// `html_default_ci` は「HTML 文書の HTML 要素で、`html_attr_value_is_case_insensitive` の属性」のとき真。
1067/// `^=`・`$=`・`*=` は空の値なら一致しない。`~=` は空や空白を含む値なら一致しない。
1068pub fn attr_value_matches(op: AttrOp, sel_value: &str, actual: &str, ext: AttrExt, html_default_ci: bool) -> bool {
1069    let ci = !ext.case_sensitive && (ext.case_insensitive || html_default_ci);
1070    let (want, got) = if ci {
1071        (sel_value.to_ascii_lowercase(), actual.to_ascii_lowercase())
1072    } else {
1073        (String::from(sel_value), String::from(actual))
1074    };
1075    match op {
1076        AttrOp::Exists => true,
1077        AttrOp::Eq => got == want,
1078        AttrOp::Prefix => !want.is_empty() && got.starts_with(want.as_str()),
1079        AttrOp::Suffix => !want.is_empty() && got.ends_with(want.as_str()),
1080        AttrOp::Contains => !want.is_empty() && got.contains(want.as_str()),
1081        AttrOp::Word => {
1082            !want.is_empty() && !want.chars().any(is_css_ws) && got.split(is_css_ws).any(|w| w == want)
1083        }
1084    }
1085}
1086
1087/// 型セレクタが要素に一致するか(名前空間の条件は見ない。`c.no_namespace` は照合側で `namespaceURI` と比べる)。
1088/// HTML 文書の HTML 要素は ASCII の大小無視、それ以外は書かれたままの大小(`tag_raw`)で局所名と比べる。
1089pub fn type_selector_matches(c: &CompoundSel, local_name: &str, html_element_in_html_doc: bool) -> bool {
1090    let Some(tag) = &c.tag else { return true };
1091    if tag == NEVER_MATCH_TAG {
1092        return false;
1093    }
1094    if html_element_in_html_doc {
1095        local_name.eq_ignore_ascii_case(tag)
1096    } else {
1097        c.tag_raw.as_deref().unwrap_or(tag) == local_name
1098    }
1099}
1100
1101/// セレクタ文字列が構文として無効(`querySelector`・`matches`・`closest` が `SyntaxError` を投げるべき)か。
1102/// 確実に無効と言えるものだけを判定し、それ以外は従来どおり寛容に解析させる:
1103/// - `#`・`.` の後ろが識別子で始まらない(`#-123`・`.-123`・`#1`・`.` だけ)。CSS Syntax §4.3.9。
1104/// - 名前空間接頭辞の付いた型・属性(`cp|tag`・`[xml|lang]`)。`querySelector` は名前空間を宣言できない
1105///   (`*|`・`|` だけは可)。Selectors Level 4 §6.3・§16。
1106///
1107/// `:is()`/`:where()` の中は寛容な(forgiving)セレクタ一覧なので検査しない。`:nth-child()` 等の
1108/// セレクタでない引数の中も検査しない。
1109pub fn selector_syntax_error(sel: &str) -> bool {
1110    #[derive(Clone, Copy, PartialEq, Eq)]
1111    enum Ctx {
1112        /// セレクタを引数に取る(`:not()`・`:has()`)。検査する。
1113        Sel,
1114        /// 寛容なセレクタ一覧(`:is()`・`:where()`)。中は検査しない。
1115        Forgiving,
1116        /// セレクタでない引数(`:nth-child()`・`:lang()` 等)。
1117        Other,
1118    }
1119    let chars: Vec<char> = sel.chars().collect();
1120    let n = chars.len();
1121    let at = |k: usize| chars.get(k).copied();
1122    let mut stack: Vec<Ctx> = Vec::new();
1123    let mut quote: Option<char> = None;
1124    let mut in_attr = false;
1125    // 属性セレクタの名前の部分(演算子より前)にいるか。
1126    let mut attr_name_part = false;
1127    let mut i = 0usize;
1128    while i < n {
1129        let ch = chars[i];
1130        if ch == '\\' {
1131            i += 2;
1132            continue;
1133        }
1134        if let Some(q) = quote {
1135            if ch == q {
1136                quote = None;
1137            }
1138            i += 1;
1139            continue;
1140        }
1141        let checking =
1142            !stack.contains(&Ctx::Forgiving) && stack.last().is_none_or(|c| *c == Ctx::Sel);
1143        match ch {
1144            '"' | '\'' => quote = Some(ch),
1145            '[' if !in_attr => {
1146                in_attr = true;
1147                attr_name_part = true;
1148            }
1149            ']' if in_attr => in_attr = false,
1150            '=' if in_attr => attr_name_part = false,
1151            '^' | '$' | '*' | '~' if in_attr && at(i + 1) == Some('=') => attr_name_part = false,
1152            '|' => {
1153                if !in_attr && at(i + 1) == Some('|') {
1154                    // 列結合子 `||`(未対応。ここでは咎めない)。
1155                    i += 2;
1156                    continue;
1157                }
1158                if in_attr && at(i + 1) == Some('=') {
1159                    attr_name_part = false;
1160                    i += 2;
1161                    continue;
1162                }
1163                if checking && (!in_attr || attr_name_part) {
1164                    // 直前が名前の文字なら `ns|`(宣言できない接頭辞)。`*|`・`|x`(先頭・空白・`(`・`,`・`[` の後)は可。
1165                    if let Some(p) = i.checked_sub(1).and_then(at) {
1166                        if p != '*' && is_name_char(p) {
1167                            return true;
1168                        }
1169                    }
1170                }
1171            }
1172            '#' | '.' if !in_attr && checking && !would_start_ident(at(i + 1), at(i + 2), at(i + 3)) => {
1173                return true;
1174            }
1175            '(' if !in_attr => {
1176                let mut s = i;
1177                while s > 0 && is_name_char(chars[s - 1]) {
1178                    s -= 1;
1179                }
1180                let is_pseudo = s > 0 && chars[s - 1] == ':';
1181                let name: String = chars[s..i].iter().collect::<String>().to_ascii_lowercase();
1182                let ctx = if !is_pseudo {
1183                    Ctx::Other
1184                } else {
1185                    match name.as_str() {
1186                        "is" | "where" | "matches" | "any" | "-webkit-any" => Ctx::Forgiving,
1187                        "not" | "has" | "host" | "host-context" => Ctx::Sel,
1188                        _ => Ctx::Other,
1189                    }
1190                };
1191                stack.push(ctx);
1192            }
1193            ')' if !in_attr => {
1194                stack.pop();
1195            }
1196            _ => {}
1197        }
1198        i += 1;
1199    }
1200    false
1201}