rdom-core 0.5.0

Arena-backed DOM for Rust — pure tree + events, no renderer. Can be used headlessly or paired with rdom-tui for terminal rendering.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! CSS selector grammar — tokenizer + parser + AST.
//!
//! Supports a practical subset of CSS Level 3:
//!
//! - Simple selectors: `*`, `tag`, `#id`, `.class`, `[attr]`, `[attr=v]`,
//!   `[attr="v"]`, `[attr^=v]`, `[attr$=v]`, `[attr*=v]`, `[attr~=v]`, `[attr|=v]`
//! - Compound: `tag.foo#bar[attr=x]`
//! - Combinators: descendant (space), child `>`, adjacent `+`, general `~`
//! - Pseudo-classes: `:not(selector)`, `:where(selector-list)`,
//!   `:first-child`, `:last-child`, `:only-child`, `:empty`, `:root`,
//!   plus the interaction pseudos (`:hover`, `:focus`, `:focus-within`, …)
//!   and the form-state pseudos (`:checked`, `:disabled`, `:enabled`,
//!   `:valid`, `:invalid`, `:required`, `:optional`, …)
//! - Selector list: `a, b, c`
//!
//! Attribute values match case-sensitively, except the attributes HTML
//! §4.16.2 lists as ASCII case-insensitive on HTML elements (`type`,
//! `method`, `enctype`, `lang`, `checked`, …), so the UA sheet's
//! `input[type=checkbox]` matches `<input type="CheckBox">`.
//!
//! `:where()` matches like `:is()` (any item in its list) but contributes
//! **zero specificity** (Selectors L4) — the mechanism a component library
//! uses to ship default styles that any author rule overrides freely.
//!
//! Not supported yet (reserved for later phases):
//! - `:nth-child(an+b)`, `:has(...)`, `:is(...)`, namespaces, attribute
//!   case flags (`[attr="v" i]`), pseudo-elements (`::before`, `::after`).

use std::fmt;

// ─── AST ─────────────────────────────────────────────────────────────

/// A full selector expression — one or more comma-separated compound
/// selector chains connected by combinators.
#[derive(Debug, Clone, PartialEq)]
pub struct SelectorList(pub Vec<ComplexSelector>);

/// A chain of compound selectors joined by combinators, read left→right.
/// `a > b c` parses as `[Compound(a), Combinator(Child), Compound(b),
/// Combinator(Descendant), Compound(c)]` — stored as a root compound plus
/// a list of `(combinator, compound)` pairs for easier right-to-left
/// matching.
#[derive(Debug, Clone, PartialEq)]
pub struct ComplexSelector {
    /// The right-most compound (what we match against the candidate node).
    pub subject: CompoundSelector,
    /// Parents of the subject, each prefaced by the combinator connecting
    /// it to the *next* compound on the right. Ordered right-to-left
    /// for efficient matching (e.g. `a > b c` → [(Descendant, b), (Child, a)]).
    pub ancestors: Vec<(Combinator, CompoundSelector)>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Combinator {
    /// `a b` — b descends from a.
    Descendant,
    /// `a > b` — b is a direct child of a.
    Child,
    /// `a + b` — b is the immediately-following sibling of a.
    AdjacentSibling,
    /// `a ~ b` — b is a following sibling of a.
    GeneralSibling,
}

/// A compound selector: one or more simple selectors that must *all* match.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CompoundSelector {
    pub simples: Vec<SimpleSelector>,
}

impl ComplexSelector {
    /// The selector's specificity `(A, B, C)` per
    /// [Selectors 4 §17](https://www.w3.org/TR/selectors-4/#specificity):
    /// `A` counts ID selectors; `B` class selectors, attribute selectors
    /// and pseudo-classes; `C` type selectors (pseudo-elements live
    /// outside this AST, so the caller adds them). `*` counts nothing,
    /// `:not(X)` counts as its most specific argument and `:where(X)` as
    /// zero. The match over the selector vocabulary lives here, next to
    /// the (`#[non_exhaustive]`) AST, so a new simple selector is counted
    /// where it is defined.
    pub fn specificity(&self) -> (u16, u16, u16) {
        let mut abc = (0, 0, 0);
        add_compound_specificity(&mut abc, &self.subject);
        for (_, compound) in &self.ancestors {
            add_compound_specificity(&mut abc, compound);
        }
        abc
    }
}

impl SelectorList {
    /// The largest [`ComplexSelector::specificity`] of the list's
    /// selectors — how `:not()` and `:is()` count their argument
    /// (Selectors 4 §17). `(0, 0, 0)` for an empty list.
    pub fn max_specificity(&self) -> (u16, u16, u16) {
        self.0
            .iter()
            .map(ComplexSelector::specificity)
            .max()
            .unwrap_or((0, 0, 0))
    }
}

fn add_compound_specificity(abc: &mut (u16, u16, u16), compound: &CompoundSelector) {
    for simple in &compound.simples {
        match simple {
            SimpleSelector::Universal | SimpleSelector::Where(_) => {}
            SimpleSelector::Type(_) => abc.2 += 1,
            SimpleSelector::Id(_) => abc.0 += 1,
            SimpleSelector::Class(_)
            | SimpleSelector::Attribute { .. }
            | SimpleSelector::Pseudo(_) => abc.1 += 1,
            SimpleSelector::Not(inner) => {
                let (a, b, c) = inner.max_specificity();
                abc.0 += a;
                abc.1 += b;
                abc.2 += c;
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SimpleSelector {
    /// `*`.
    Universal,
    /// `tag`.
    Type(String),
    /// `#id` → equivalent to `[id=...]` but stored separately for index support.
    Id(String),
    /// `.class`.
    Class(String),
    /// `[attr]` / `[attr op value]`.
    Attribute {
        name: String,
        op: Option<AttrOp>,
        value: Option<String>,
    },
    /// `:not(...)` — the negated selector list.
    Not(Box<SelectorList>),
    /// `:where(...)` — matches like `:is()` (any complex selector in the
    /// list matches the element), but contributes **zero specificity**
    /// (Selectors Level 4). Lets a library ship default styles that any
    /// real author selector overrides without a specificity fight.
    Where(Box<SelectorList>),
    /// Structural pseudo-classes.
    Pseudo(PseudoClass),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttrOp {
    /// `[attr=value]` — exact match.
    Exact,
    /// `[attr~=value]` — one of a whitespace-separated list.
    Includes,
    /// `[attr|=value]` — exact or starts with `value-`.
    DashMatch,
    /// `[attr^=value]` — prefix.
    Prefix,
    /// `[attr$=value]` — suffix.
    Suffix,
    /// `[attr*=value]` — substring.
    Substring,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PseudoClass {
    FirstChild,
    LastChild,
    OnlyChild,
    Empty,
    Root,
    /// `:hover` — matches the Dom's currently-hovered node (tracked via
    /// `Dom::set_hovered`) and every ancestor of it (Selectors 4 §9.2).
    Hover,
    /// `:active` — matches the element being activated (tracked via
    /// `Dom::set_active`) and every ancestor of it (Selectors 4 §9.4).
    Active,
    /// `:focus` — matches when the node is the Dom's currently-focused
    /// node (tracked via `Dom::set_focused`).
    Focus,
    /// `:focus-within` — matches when the node OR any of its
    /// descendants is the Dom's currently-focused node. Mirrors
    /// CSS Selectors L4 §10.1.4 — lets authors style an entire
    /// container (form row, label, dialog) based on whether
    /// focus is somewhere inside it. The substrate walks from
    /// the focused node upward through parents; every ancestor
    /// in the chain matches, plus the focused node itself.
    FocusWithin,
    /// `:focus-visible` — Selectors 4 §13.2: the focused node while
    /// the UA judges its focus should be evident
    /// ([`Dom::focus_visible`](crate::Dom::focus_visible), driven by
    /// the backend's keyboard / pointer heuristics).
    FocusVisible,
    /// `:checked` — matches when the element has a `checked`
    /// attribute (any value, presence-only). The user-toggle
    /// builtins flip this attribute on click / Space, so this
    /// selector reflects current state without needing a separate
    /// IDL property.
    Checked,
    /// `:placeholder-shown` — matches form controls that have a
    /// non-empty `placeholder` attribute AND whose current text
    /// content is empty. Used by UA rules to render the
    /// placeholder via `::before { content: attr(placeholder) }`.
    PlaceholderShown,
    /// `:indeterminate` — matches elements in an indeterminate
    /// state. In this v1 that means `<progress>` without a `value`
    /// attribute; browsers also match indeterminate checkboxes
    /// and orphan radio buttons, which we defer to polish (neither
    /// has a concrete state model in rdom yet).
    Indeterminate,
    /// `:open` — matches elements with the `open` attribute
    /// present. Covers `<details open>` and `<dialog open>` /
    /// `<dialog data-rdom-open>`. Authors use it to style the
    /// expanded state of disclosure widgets via CSS without having
    /// to write attribute selectors themselves.
    Open,
    /// `:disabled` — matches elements that are *actually disabled*
    /// (HTML §4.16.3): a form control with `disabled` or inside a
    /// `<fieldset disabled>` (outside its first `<legend>`), a disabled
    /// `<fieldset>` / `<optgroup>`, a disabled `<option>`. See
    /// [`Dom::is_actually_disabled`](crate::Dom::is_actually_disabled).
    Disabled,
    /// `:enabled` — matches the elements that can be disabled
    /// (`<button>`, `<input>`, `<select>`, `<textarea>`, `<fieldset>`,
    /// `<optgroup>`, `<option>`) when they are not actually disabled.
    Enabled,
    /// `:valid` — HTML §4.16.3: a candidate for constraint validation
    /// that satisfies its constraints, a `<form>` owning no invalid
    /// candidate, a `<fieldset>` with no invalid descendant candidate.
    /// The verdict per candidate comes from the backend's validity hook
    /// ([`Dom::set_validity_hook`](crate::Dom::set_validity_hook)); without
    /// one every candidate is valid, so a backend matching this installs
    /// its hook — see
    /// [`Dom::constraint_validity`](crate::Dom::constraint_validity).
    Valid,
    /// `:invalid` — the complement of `:valid` among the same elements:
    /// an invalid candidate, a form or fieldset with one.
    Invalid,
    /// `:required` — an `<input>` (in a state `required` applies to),
    /// `<select>` or `<textarea>` with the `required` attribute.
    Required,
    /// `:optional` — an `<input>`, `<select>` or `<textarea>` that is
    /// not `:required`.
    Optional,
}

// ─── Error ───────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseError {
    pub msg: String,
    pub pos: usize,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "selector parse error at {}: {}", self.pos, self.msg)
    }
}

impl std::error::Error for ParseError {}

// ─── Parser ──────────────────────────────────────────────────────────

/// Parse `input` into a selector list. Returns `ParseError` on malformed
/// input. Whitespace-tolerant; comments are not supported.
pub fn parse(input: &str) -> Result<SelectorList, ParseError> {
    let mut p = Parser::new(input);
    let list = p.parse_selector_list()?;
    p.skip_ws();
    if !p.eof() {
        return Err(p.err(format!("unexpected trailing input: `{}`", &p.src[p.pos..])));
    }
    Ok(list)
}

struct Parser<'a> {
    src: &'a str,
    bytes: &'a [u8],
    pos: usize,
}

impl<'a> Parser<'a> {
    fn new(src: &'a str) -> Self {
        Self {
            src,
            bytes: src.as_bytes(),
            pos: 0,
        }
    }

    fn eof(&self) -> bool {
        self.pos >= self.bytes.len()
    }

    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.pos).copied()
    }

    fn skip_ws(&mut self) {
        while let Some(b) = self.peek() {
            if b.is_ascii_whitespace() {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    fn err(&self, msg: String) -> ParseError {
        ParseError { msg, pos: self.pos }
    }

    fn expect(&mut self, want: u8, ctx: &str) -> Result<(), ParseError> {
        match self.peek() {
            Some(b) if b == want => {
                self.pos += 1;
                Ok(())
            }
            Some(b) => Err(self.err(format!(
                "expected `{}` in {ctx}, got `{}`",
                want as char, b as char
            ))),
            None => Err(self.err(format!("expected `{}` in {ctx}, got EOF", want as char))),
        }
    }

    fn parse_selector_list(&mut self) -> Result<SelectorList, ParseError> {
        let mut items = Vec::new();
        loop {
            self.skip_ws();
            if self.eof() {
                break;
            }
            let sel = self.parse_complex_selector()?;
            items.push(sel);
            self.skip_ws();
            if self.peek() == Some(b',') {
                self.pos += 1;
                continue;
            }
            break;
        }
        if items.is_empty() {
            return Err(self.err("empty selector".to_string()));
        }
        Ok(SelectorList(items))
    }

    fn parse_complex_selector(&mut self) -> Result<ComplexSelector, ParseError> {
        // Parse left-to-right into (compound, combinator_to_next) pairs,
        // then rotate into subject + ancestors (subject = rightmost).
        let first = self.parse_compound()?;
        let mut chain: Vec<(CompoundSelector, Combinator)> = Vec::new();
        let mut pending = first;

        loop {
            let had_ws = self.skip_ws_noting();
            let Some(b) = self.peek() else {
                // End of input — finalize with pending compound.
                return Ok(self.finalize(pending, chain));
            };
            let combinator = match b {
                b',' | b')' => {
                    return Ok(self.finalize(pending, chain));
                }
                b'>' => {
                    self.pos += 1;
                    self.skip_ws();
                    Combinator::Child
                }
                b'+' => {
                    self.pos += 1;
                    self.skip_ws();
                    Combinator::AdjacentSibling
                }
                b'~' => {
                    self.pos += 1;
                    self.skip_ws();
                    Combinator::GeneralSibling
                }
                _ if had_ws => Combinator::Descendant,
                _ => {
                    return Ok(self.finalize(pending, chain));
                }
            };
            let next = self.parse_compound()?;
            chain.push((pending, combinator));
            pending = next;
        }
    }

    /// Assemble subject + right-to-left ancestor list.
    fn finalize(
        &self,
        subject: CompoundSelector,
        chain: Vec<(CompoundSelector, Combinator)>,
    ) -> ComplexSelector {
        // chain is [(c0, comb0_to_c1), (c1, comb1_to_c2), …, (c_{n-1}, comb_to_subject)]
        // We want ancestors ordered from closest-to-subject → outward,
        // each tagged with the combinator that connects it to the *next*
        // compound on the right.
        let mut ancestors: Vec<(Combinator, CompoundSelector)> =
            chain.into_iter().map(|(c, comb)| (comb, c)).collect();
        ancestors.reverse();
        ComplexSelector { subject, ancestors }
    }

    /// Skip whitespace and return true if any was consumed. Used to
    /// distinguish descendant combinators from compound boundaries.
    fn skip_ws_noting(&mut self) -> bool {
        let start = self.pos;
        self.skip_ws();
        self.pos > start
    }

    fn parse_compound(&mut self) -> Result<CompoundSelector, ParseError> {
        let mut simples = Vec::new();
        // Optional type / universal at the head.
        match self.peek() {
            Some(b'*') => {
                self.pos += 1;
                simples.push(SimpleSelector::Universal);
            }
            Some(b) if is_ident_start(b) => {
                let name = self.parse_ident();
                simples.push(SimpleSelector::Type(name));
            }
            _ => {}
        }
        loop {
            match self.peek() {
                Some(b'#') => {
                    self.pos += 1;
                    let id = self.parse_ident();
                    if id.is_empty() {
                        return Err(self.err("empty id selector".to_string()));
                    }
                    simples.push(SimpleSelector::Id(id));
                }
                Some(b'.') => {
                    self.pos += 1;
                    let cls = self.parse_ident();
                    if cls.is_empty() {
                        return Err(self.err("empty class selector".to_string()));
                    }
                    simples.push(SimpleSelector::Class(cls));
                }
                Some(b'[') => {
                    simples.push(self.parse_attribute()?);
                }
                Some(b':') => {
                    simples.push(self.parse_pseudo()?);
                }
                _ => break,
            }
        }
        if simples.is_empty() {
            return Err(self.err("expected selector".to_string()));
        }
        Ok(CompoundSelector { simples })
    }

    fn parse_attribute(&mut self) -> Result<SimpleSelector, ParseError> {
        self.expect(b'[', "attribute selector")?;
        self.skip_ws();
        let name = self.parse_ident();
        if name.is_empty() {
            return Err(self.err("expected attribute name".to_string()));
        }
        self.skip_ws();

        let op = match self.peek() {
            Some(b']') => None,
            Some(b'=') => {
                self.pos += 1;
                Some(AttrOp::Exact)
            }
            Some(b'~') if self.bytes.get(self.pos + 1) == Some(&b'=') => {
                self.pos += 2;
                Some(AttrOp::Includes)
            }
            Some(b'|') if self.bytes.get(self.pos + 1) == Some(&b'=') => {
                self.pos += 2;
                Some(AttrOp::DashMatch)
            }
            Some(b'^') if self.bytes.get(self.pos + 1) == Some(&b'=') => {
                self.pos += 2;
                Some(AttrOp::Prefix)
            }
            Some(b'$') if self.bytes.get(self.pos + 1) == Some(&b'=') => {
                self.pos += 2;
                Some(AttrOp::Suffix)
            }
            Some(b'*') if self.bytes.get(self.pos + 1) == Some(&b'=') => {
                self.pos += 2;
                Some(AttrOp::Substring)
            }
            Some(b) => {
                return Err(self.err(format!("unexpected `{}` in attribute selector", b as char)));
            }
            None => return Err(self.err("unexpected EOF in attribute selector".to_string())),
        };

        let value = if op.is_some() {
            self.skip_ws();
            Some(self.parse_attr_value()?)
        } else {
            None
        };
        self.skip_ws();
        self.expect(b']', "attribute selector")?;
        Ok(SimpleSelector::Attribute { name, op, value })
    }

    fn parse_attr_value(&mut self) -> Result<String, ParseError> {
        match self.peek() {
            Some(b'"') => {
                self.pos += 1;
                let start = self.pos;
                while let Some(b) = self.peek() {
                    if b == b'"' {
                        break;
                    }
                    self.pos += 1;
                }
                let s = self.src[start..self.pos].to_string();
                self.expect(b'"', "quoted attribute value")?;
                Ok(s)
            }
            Some(b'\'') => {
                self.pos += 1;
                let start = self.pos;
                while let Some(b) = self.peek() {
                    if b == b'\'' {
                        break;
                    }
                    self.pos += 1;
                }
                let s = self.src[start..self.pos].to_string();
                self.expect(b'\'', "quoted attribute value")?;
                Ok(s)
            }
            _ => {
                let id = self.parse_ident();
                if id.is_empty() {
                    return Err(self.err("expected attribute value".to_string()));
                }
                Ok(id)
            }
        }
    }

    fn parse_pseudo(&mut self) -> Result<SimpleSelector, ParseError> {
        self.expect(b':', "pseudo-class")?;
        // Reject pseudo-elements (`::before` etc.) — reserved.
        if self.peek() == Some(b':') {
            return Err(self.err("pseudo-elements are not supported yet".to_string()));
        }
        let name = self.parse_ident();
        if name.is_empty() {
            return Err(self.err("expected pseudo-class name".to_string()));
        }
        match name.as_str() {
            "not" => {
                self.expect(b'(', ":not")?;
                self.skip_ws();
                let inner = self.parse_selector_list()?;
                self.skip_ws();
                self.expect(b')', ":not")?;
                Ok(SimpleSelector::Not(Box::new(inner)))
            }
            "where" => {
                self.expect(b'(', ":where")?;
                self.skip_ws();
                let inner = self.parse_selector_list()?;
                self.skip_ws();
                self.expect(b')', ":where")?;
                Ok(SimpleSelector::Where(Box::new(inner)))
            }
            "first-child" => Ok(SimpleSelector::Pseudo(PseudoClass::FirstChild)),
            "last-child" => Ok(SimpleSelector::Pseudo(PseudoClass::LastChild)),
            "only-child" => Ok(SimpleSelector::Pseudo(PseudoClass::OnlyChild)),
            "empty" => Ok(SimpleSelector::Pseudo(PseudoClass::Empty)),
            "root" => Ok(SimpleSelector::Pseudo(PseudoClass::Root)),
            "hover" => Ok(SimpleSelector::Pseudo(PseudoClass::Hover)),
            "active" => Ok(SimpleSelector::Pseudo(PseudoClass::Active)),
            "focus" => Ok(SimpleSelector::Pseudo(PseudoClass::Focus)),
            "focus-within" => Ok(SimpleSelector::Pseudo(PseudoClass::FocusWithin)),
            "focus-visible" => Ok(SimpleSelector::Pseudo(PseudoClass::FocusVisible)),
            "checked" => Ok(SimpleSelector::Pseudo(PseudoClass::Checked)),
            "placeholder-shown" => Ok(SimpleSelector::Pseudo(PseudoClass::PlaceholderShown)),
            "indeterminate" => Ok(SimpleSelector::Pseudo(PseudoClass::Indeterminate)),
            "open" => Ok(SimpleSelector::Pseudo(PseudoClass::Open)),
            "disabled" => Ok(SimpleSelector::Pseudo(PseudoClass::Disabled)),
            "enabled" => Ok(SimpleSelector::Pseudo(PseudoClass::Enabled)),
            "valid" => Ok(SimpleSelector::Pseudo(PseudoClass::Valid)),
            "invalid" => Ok(SimpleSelector::Pseudo(PseudoClass::Invalid)),
            "required" => Ok(SimpleSelector::Pseudo(PseudoClass::Required)),
            "optional" => Ok(SimpleSelector::Pseudo(PseudoClass::Optional)),
            other => Err(self.err(format!("unsupported pseudo-class `:{other}`"))),
        }
    }

    fn parse_ident(&mut self) -> String {
        let start = self.pos;
        while let Some(b) = self.peek() {
            if is_ident_continue(b) {
                self.pos += 1;
            } else {
                break;
            }
        }
        self.src[start..self.pos].to_string()
    }
}

/// CSS Syntax 3 §4.2 ident-start code point, byte-wise: a letter, `_`,
/// or any non-ASCII code point (every byte of a multi-byte UTF-8
/// sequence is ≥ 0x80, so a byte scan stays on `char` boundaries). `-`
/// is accepted too, for `-foo` / custom idents.
fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_' || b == b'-' || !b.is_ascii()
}

/// CSS Syntax 3 §4.2 ident code point, byte-wise: an ident-start code
/// point, a digit or `-`.
fn is_ident_continue(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || !b.is_ascii()
}

// ─── Tests ───────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn s(v: &str) -> SimpleSelector {
        SimpleSelector::Type(v.to_string())
    }

    #[test]
    fn parse_type_selector() {
        let sl = parse("div").unwrap();
        assert_eq!(sl.0.len(), 1);
        assert_eq!(sl.0[0].subject.simples, vec![s("div")]);
        assert!(sl.0[0].ancestors.is_empty());
    }

    #[test]
    fn parse_universal() {
        let sl = parse("*").unwrap();
        assert_eq!(sl.0[0].subject.simples, vec![SimpleSelector::Universal]);
    }

    #[test]
    fn parse_id() {
        let sl = parse("#main").unwrap();
        assert_eq!(
            sl.0[0].subject.simples,
            vec![SimpleSelector::Id("main".into())]
        );
    }

    #[test]
    fn parse_class() {
        let sl = parse(".foo").unwrap();
        assert_eq!(
            sl.0[0].subject.simples,
            vec![SimpleSelector::Class("foo".into())]
        );
    }

    /// CSS Syntax 3 §4.2 (`P7G-CORE-SMALL-1`): a code point at or above
    /// U+0080 is an ident code point, start included.
    #[test]
    fn non_ascii_idents_parse() {
        match &parse("[lang|=én]").unwrap().0[0].subject.simples[0] {
            SimpleSelector::Attribute { value, .. } => assert_eq!(value.as_deref(), Some("én")),
            other => panic!("expected an attribute selector, got {other:?}"),
        }
        assert_eq!(
            parse(".café#naïve").unwrap().0[0].subject.simples,
            vec![
                SimpleSelector::Class("café".into()),
                SimpleSelector::Id("naïve".into()),
            ]
        );
        assert_eq!(
            parse("élément").unwrap().0[0].subject.simples,
            vec![s("élément")]
        );
        assert_eq!(
            parse(".日本").unwrap().0[0].subject.simples,
            vec![SimpleSelector::Class("日本".into())]
        );
    }

    #[test]
    fn parse_compound() {
        let sl = parse("div.foo#bar.baz").unwrap();
        assert_eq!(
            sl.0[0].subject.simples,
            vec![
                s("div"),
                SimpleSelector::Class("foo".into()),
                SimpleSelector::Id("bar".into()),
                SimpleSelector::Class("baz".into()),
            ]
        );
    }

    #[test]
    fn parse_attribute_presence() {
        let sl = parse("[disabled]").unwrap();
        assert_eq!(
            sl.0[0].subject.simples,
            vec![SimpleSelector::Attribute {
                name: "disabled".into(),
                op: None,
                value: None,
            }]
        );
    }

    #[test]
    fn parse_attribute_exact_unquoted() {
        let sl = parse("[role=banner]").unwrap();
        match &sl.0[0].subject.simples[0] {
            SimpleSelector::Attribute { name, op, value } => {
                assert_eq!(name, "role");
                assert_eq!(*op, Some(AttrOp::Exact));
                assert_eq!(value.as_deref(), Some("banner"));
            }
            _ => panic!("expected attribute"),
        }
    }

    #[test]
    fn parse_attribute_exact_quoted() {
        let sl = parse(r#"[title="hello world"]"#).unwrap();
        match &sl.0[0].subject.simples[0] {
            SimpleSelector::Attribute { value, .. } => {
                assert_eq!(value.as_deref(), Some("hello world"));
            }
            _ => panic!(),
        }
    }

    #[test]
    fn parse_attribute_operators() {
        for (src, op) in [
            ("[a~=b]", AttrOp::Includes),
            ("[a|=b]", AttrOp::DashMatch),
            ("[a^=b]", AttrOp::Prefix),
            ("[a$=b]", AttrOp::Suffix),
            ("[a*=b]", AttrOp::Substring),
        ] {
            let sl = parse(src).unwrap();
            match &sl.0[0].subject.simples[0] {
                SimpleSelector::Attribute { op: got, .. } => assert_eq!(*got, Some(op)),
                _ => panic!("{src}"),
            }
        }
    }

    #[test]
    fn parse_descendant() {
        let sl = parse("a b").unwrap();
        let complex = &sl.0[0];
        assert_eq!(complex.subject.simples, vec![s("b")]);
        assert_eq!(complex.ancestors.len(), 1);
        assert_eq!(complex.ancestors[0].0, Combinator::Descendant);
        assert_eq!(complex.ancestors[0].1.simples, vec![s("a")]);
    }

    #[test]
    fn parse_child_combinator() {
        let sl = parse("a > b").unwrap();
        let c = &sl.0[0];
        assert_eq!(c.ancestors[0].0, Combinator::Child);
    }

    #[test]
    fn parse_adjacent_and_general_sibling() {
        let sl = parse("a + b").unwrap();
        assert_eq!(sl.0[0].ancestors[0].0, Combinator::AdjacentSibling);
        let sl = parse("a ~ b").unwrap();
        assert_eq!(sl.0[0].ancestors[0].0, Combinator::GeneralSibling);
    }

    #[test]
    fn parse_chain_right_to_left() {
        let sl = parse("a > b c").unwrap();
        let c = &sl.0[0];
        // Subject = c, ancestors (closest→outer) = [(Descendant, b), (Child, a)]
        assert_eq!(c.subject.simples, vec![s("c")]);
        assert_eq!(c.ancestors.len(), 2);
        assert_eq!(c.ancestors[0].0, Combinator::Descendant);
        assert_eq!(c.ancestors[0].1.simples, vec![s("b")]);
        assert_eq!(c.ancestors[1].0, Combinator::Child);
        assert_eq!(c.ancestors[1].1.simples, vec![s("a")]);
    }

    #[test]
    fn parse_selector_list() {
        let sl = parse("a, b, c.foo").unwrap();
        assert_eq!(sl.0.len(), 3);
    }

    #[test]
    fn parse_not_pseudo() {
        let sl = parse("div:not(.foo)").unwrap();
        match &sl.0[0].subject.simples[1] {
            SimpleSelector::Not(inner) => {
                assert_eq!(inner.0.len(), 1);
                assert_eq!(
                    inner.0[0].subject.simples,
                    vec![SimpleSelector::Class("foo".into())]
                );
            }
            _ => panic!(),
        }
    }

    #[test]
    fn parse_where_pseudo() {
        let sl = parse("div:where(.foo, #bar)").unwrap();
        match &sl.0[0].subject.simples[1] {
            SimpleSelector::Where(inner) => assert_eq!(inner.0.len(), 2),
            other => panic!("expected Where, got {other:?}"),
        }
        // Combinators are allowed inside the argument.
        let sl = parse(":where(table:focus td)").unwrap();
        assert!(matches!(
            sl.0[0].subject.simples[0],
            SimpleSelector::Where(_)
        ));
    }

    #[test]
    fn parse_structural_pseudos() {
        for (src, p) in [
            (":first-child", PseudoClass::FirstChild),
            (":last-child", PseudoClass::LastChild),
            (":only-child", PseudoClass::OnlyChild),
            (":empty", PseudoClass::Empty),
            (":root", PseudoClass::Root),
        ] {
            let sl = parse(src).unwrap();
            assert_eq!(sl.0[0].subject.simples, vec![SimpleSelector::Pseudo(p)]);
        }
    }

    #[test]
    fn parse_whitespace_tolerance() {
        parse("  a  ,  b  ").unwrap();
        parse("a   >   b").unwrap();
        parse("[ role = \"x\" ]").unwrap();
    }

    #[test]
    fn parse_errors_on_empty_input() {
        assert!(parse("").is_err());
        assert!(parse("   ").is_err());
    }

    #[test]
    fn parse_errors_on_trailing_garbage() {
        assert!(parse("div ))").is_err());
    }

    #[test]
    fn parse_errors_on_unknown_pseudo() {
        assert!(parse(":banana").is_err());
    }

    #[test]
    fn parse_errors_on_unterminated_attr() {
        assert!(parse("[foo=").is_err());
        assert!(parse("[foo=bar").is_err());
    }

    #[test]
    fn parse_errors_on_pseudo_element() {
        assert!(parse("::before").is_err());
    }
}