1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(clippy::pedantic, clippy::nursery, clippy::too_many_lines)]
5
mod autotest_generated {
6
    use azul_css::{
7
        css::{CssNthChildPattern, CssScopeRange, NodeTypeTag},
8
        OptionString,
9
    };
10

            
11
    use super::*;
12
    use crate::{
13
        dom::{AttributeNameValue, AttributeType, NodeType},
14
        id::Node,
15
    };
16

            
17
    // ---------------------------------------------------------------------
18
    // helpers
19
    // ---------------------------------------------------------------------
20

            
21
    fn node(
22
        parent: Option<usize>,
23
        prev: Option<usize>,
24
        next: Option<usize>,
25
        last_child: Option<usize>,
26
    ) -> Node {
27
        Node {
28
            parent: parent.map(NodeId::new),
29
            previous_sibling: prev.map(NodeId::new),
30
            next_sibling: next.map(NodeId::new),
31
            last_child: last_child.map(NodeId::new),
32
        }
33
    }
34

            
35
    fn items(nodes: &[Node]) -> Vec<NodeHierarchyItem> {
36
        nodes.iter().map(|n| NodeHierarchyItem::from(*n)).collect()
37
    }
38

            
39
    fn div_with(id: Option<&str>, class: Option<&str>) -> NodeData {
40
        let mut nd = NodeData::create_div();
41
        if let Some(i) = id {
42
            nd.add_id(i.into());
43
        }
44
        if let Some(c) = class {
45
            nd.add_class(c.into());
46
        }
47
        nd
48
    }
49

            
50
    fn node_with_attrs(attrs: Vec<AttributeType>) -> NodeData {
51
        let mut nd = NodeData::create_div();
52
        nd.set_attributes(attrs.into());
53
        nd
54
    }
55

            
56
    fn custom(name: &str, value: &str) -> AttributeType {
57
        AttributeType::Custom(AttributeNameValue {
58
            attr_name: name.into(),
59
            value: value.into(),
60
        })
61
    }
62

            
63
    fn attr_sel(name: &str, op: AttributeMatchOp, value: Option<&str>) -> CssAttributeSelector {
64
        CssAttributeSelector {
65
            name: name.into(),
66
            op,
67
            value: value.map_or(OptionString::None, |v| OptionString::Some(v.into())),
68
        }
69
    }
70

            
71
    fn info(index_in_parent: u32, is_last_child: bool) -> CascadeInfo {
72
        CascadeInfo {
73
            index_in_parent,
74
            is_last_child,
75
        }
76
    }
77

            
78
    /// The shared fixture DOM. Note node 2 is a **text node** sitting between
79
    /// two element siblings — the whole point is to exercise the "text nodes
80
    /// are not counted as element siblings" rule (CSS Selectors L4 §13).
81
    ///
82
    /// ```text
83
    /// 0 body
84
    /// ├── 1 div#first.a
85
    /// ├── 2 "hello"          (text)
86
    /// ├── 3 div.b
87
    /// │   └── 4 p.inner
88
    /// └── 5 div.c
89
    /// ```
90
    fn sample_hierarchy() -> Vec<Node> {
91
        vec![
92
            node(None, None, None, Some(5)),
93
            node(Some(0), None, Some(2), None),
94
            node(Some(0), Some(1), Some(3), None),
95
            node(Some(0), Some(2), Some(5), Some(4)),
96
            node(Some(3), None, None, None),
97
            node(Some(0), Some(3), None, None),
98
        ]
99
    }
100

            
101
    fn sample_node_data() -> Vec<NodeData> {
102
        let mut p = NodeData::create_node(NodeType::P);
103
        p.add_class("inner".into());
104
        vec![
105
            NodeData::create_body(),
106
            div_with(Some("first"), Some("a")),
107
            NodeData::create_text_do_not_use_without_block_level_wrapper("hello"),
108
            div_with(None, Some("b")),
109
            p,
110
            div_with(None, Some("c")),
111
        ]
112
    }
113

            
114
    /// Runs `matches_html_element` against the sample fixture.
115
    fn matches(
116
        selectors: Vec<CssPathSelector>,
117
        node_index: usize,
118
        expected_path_ending: Option<CssPathPseudoSelector>,
119
    ) -> bool {
120
        let hierarchy = sample_hierarchy();
121
        let hier_items = items(&hierarchy);
122
        let data = sample_node_data();
123

            
124
        let hierarchy_ref = NodeHierarchyRef::from_slice(&hierarchy);
125
        let data_ref = NodeDataContainerRef::from_slice(&data);
126
        let depths = hierarchy_ref.get_parents_sorted_by_depth();
127
        let cascade = construct_html_cascade_tree(&hierarchy_ref, &depths, &data_ref);
128

            
129
        matches_html_element(
130
            &CssPath::new(selectors),
131
            NodeId::new(node_index),
132
            &NodeDataContainerRef::from_slice(&hier_items),
133
            &data_ref,
134
            &cascade.as_ref(),
135
            expected_path_ending,
136
        )
137
    }
138

            
139
    // ---------------------------------------------------------------------
140
    // CascadeInfoVec::as_container  (getter)
141
    // ---------------------------------------------------------------------
142

            
143
    #[test]
144
    fn cascade_info_vec_as_container_preserves_every_entry() {
145
        let v: CascadeInfoVec = vec![info(0, false), info(1, false), info(2, true)].into();
146
        let c = v.as_container();
147

            
148
        assert_eq!(c.len(), 3);
149
        assert!(!c.is_empty());
150
        assert_eq!(c[NodeId::new(0)], info(0, false));
151
        assert_eq!(c[NodeId::new(2)], info(2, true));
152
        // Out-of-range access must be a `None`, not a panic.
153
        assert_eq!(c.get(NodeId::new(3)), None);
154
        assert_eq!(c.get(NodeId::new(usize::MAX)), None);
155
    }
156

            
157
    #[test]
158
    fn cascade_info_vec_as_container_on_empty_vec_does_not_panic() {
159
        let v: CascadeInfoVec = Vec::new().into();
160
        let c = v.as_container();
161
        assert_eq!(c.len(), 0);
162
        assert!(c.is_empty());
163
        assert_eq!(c.get(NodeId::new(0)), None);
164
    }
165

            
166
    #[test]
167
    fn cascade_info_vec_as_container_survives_extreme_field_values() {
168
        let v: CascadeInfoVec = vec![info(u32::MAX, true)].into();
169
        let c = v.as_container();
170
        assert_eq!(c[NodeId::new(0)].index_in_parent, u32::MAX);
171
        assert!(c[NodeId::new(0)].is_last_child);
172
    }
173

            
174
    // ---------------------------------------------------------------------
175
    // CssGroupIterator
176
    // ---------------------------------------------------------------------
177

            
178
    #[test]
179
    fn css_group_iterator_new_records_the_path_and_yields_nothing_when_empty() {
180
        let empty: [CssPathSelector; 0] = [];
181
        let it = CssGroupIterator::new(&empty);
182
        assert!(it.css_path.is_empty());
183
        assert_eq!(CssGroupIterator::new(&empty).count(), 0);
184
    }
185

            
186
    #[test]
187
    fn css_group_iterator_new_keeps_the_slice_it_was_given() {
188
        let path = vec![
189
            CssPathSelector::Global,
190
            CssPathSelector::Children,
191
            CssPathSelector::Class("x".into()),
192
        ];
193
        let it = CssGroupIterator::new(&path);
194
        assert_eq!(it.css_path.len(), 3);
195
        assert_eq!(it.css_path, path.as_slice());
196
    }
197

            
198
    #[test]
199
    fn css_group_iterator_splits_right_to_left_with_the_left_hand_combinator() {
200
        // `body > .foo.main .baz`
201
        let path = vec![
202
            CssPathSelector::Type(NodeTypeTag::Body),
203
            CssPathSelector::DirectChildren,
204
            CssPathSelector::Class("foo".into()),
205
            CssPathSelector::Class("main".into()),
206
            CssPathSelector::Children,
207
            CssPathSelector::Class("baz".into()),
208
        ];
209

            
210
        let groups: Vec<_> = CssGroupIterator::new(&path).collect();
211
        assert_eq!(groups.len(), 3);
212

            
213
        // Group 0 is the RIGHTMOST group (the subject of the selector).
214
        assert_eq!(groups[0].0, vec![&path[5]]);
215
        assert_eq!(groups[0].1, CssGroupSplitReason::Children);
216

            
217
        assert_eq!(groups[1].0, vec![&path[2], &path[3]]);
218
        assert_eq!(groups[1].1, CssGroupSplitReason::DirectChildren);
219

            
220
        assert_eq!(groups[2].0, vec![&path[0]]);
221
        // NOTE: the leftmost group's `reason` is a carry-over from the previous
222
        // split (there is no combinator to its left). `matches_html_element`
223
        // never reads it — it uses `groups[i - 1].1` as the combinator for
224
        // group `i` — so we deliberately do not assert on it here.
225
    }
226

            
227
    #[test]
228
    fn css_group_iterator_yields_an_empty_group_for_a_trailing_combinator() {
229
        // Malformed path `.foo >` (a combinator with nothing to its right).
230
        let path = vec![
231
            CssPathSelector::Class("foo".into()),
232
            CssPathSelector::DirectChildren,
233
        ];
234
        let groups: Vec<_> = CssGroupIterator::new(&path).collect();
235

            
236
        assert_eq!(groups.len(), 2);
237
        assert!(
238
            groups[0].0.is_empty(),
239
            "the group to the right of the dangling combinator is empty"
240
        );
241
        assert_eq!(groups[0].1, CssGroupSplitReason::DirectChildren);
242
        assert_eq!(groups[1].0, vec![&path[0]]);
243
    }
244

            
245
    #[test]
246
    fn css_group_iterator_terminates_on_consecutive_combinators() {
247
        // `.a > ~ .b` — two combinators in a row (parser should never emit this,
248
        // but the iterator must not loop forever or drop selectors).
249
        let path = vec![
250
            CssPathSelector::Class("a".into()),
251
            CssPathSelector::Children,
252
            CssPathSelector::DirectChildren,
253
            CssPathSelector::Class("b".into()),
254
        ];
255
        let groups: Vec<_> = CssGroupIterator::new(&path).collect();
256

            
257
        assert_eq!(groups.len(), 3);
258
        assert_eq!(groups[0].0, vec![&path[3]]);
259
        assert!(
260
            groups[1].0.is_empty(),
261
            "the group between the two combinators is empty"
262
        );
263
        assert_eq!(groups[2].0, vec![&path[0]]);
264
    }
265

            
266
    #[test]
267
    fn css_group_iterator_only_combinators_yields_only_empty_groups() {
268
        let path = vec![
269
            CssPathSelector::Children,
270
            CssPathSelector::DirectChildren,
271
            CssPathSelector::AdjacentSibling,
272
            CssPathSelector::GeneralSibling,
273
        ];
274
        let groups: Vec<_> = CssGroupIterator::new(&path).collect();
275

            
276
        // Four combinators, four splits, and the final `new_idx == 0 &&
277
        // current_path.is_empty()` branch ends the iteration.
278
        assert_eq!(groups.len(), 4);
279
        assert!(groups.iter().all(|(g, _)| g.is_empty()));
280
    }
281

            
282
    #[test]
283
    fn css_group_iterator_conserves_every_non_combinator_selector_on_a_huge_path() {
284
        // 10_000 selectors: `.c0 .c1 .c2 ...` — must terminate and must not
285
        // lose or duplicate a single selector.
286
        let mut path = Vec::new();
287
        for i in 0..5_000u32 {
288
            if i != 0 {
289
                path.push(CssPathSelector::Children);
290
            }
291
            path.push(CssPathSelector::Class(alloc::format!(".c{i}").into()));
292
        }
293

            
294
        let groups: Vec<_> = CssGroupIterator::new(&path).collect();
295
        assert_eq!(groups.len(), 5_000);
296
        let total: usize = groups.iter().map(|(g, _)| g.len()).sum();
297
        assert_eq!(
298
            total, 5_000,
299
            "every non-combinator selector must appear in exactly one group"
300
        );
301
        assert!(groups
302
            .iter()
303
            .all(|(_, r)| *r == CssGroupSplitReason::Children));
304
    }
305

            
306
    // ---------------------------------------------------------------------
307
    // rule_ends_with
308
    // ---------------------------------------------------------------------
309

            
310
    #[test]
311
    fn rule_ends_with_empty_path_is_always_false() {
312
        let empty = CssPath::new(Vec::new());
313
        assert!(!rule_ends_with(&empty, None));
314
        assert!(!rule_ends_with(&empty, Some(CssPathPseudoSelector::Hover)));
315
        assert!(!rule_ends_with(
316
            &empty,
317
            Some(CssPathPseudoSelector::NthChild(CssNthChildSelector::Even))
318
        ));
319
    }
320

            
321
    #[test]
322
    fn rule_ends_with_none_rejects_interactive_pseudos_but_keeps_structural_ones() {
323
        let ends_with = |s: CssPathSelector| {
324
            rule_ends_with(
325
                &CssPath::new(vec![CssPathSelector::Class("a".into()), s]),
326
                None,
327
            )
328
        };
329

            
330
        // Interactive => rejected for the "normal" (non-pseudo) pass.
331
        for p in [
332
            CssPathPseudoSelector::Hover,
333
            CssPathPseudoSelector::Active,
334
            CssPathPseudoSelector::Focus,
335
            CssPathPseudoSelector::Backdrop,
336
            CssPathPseudoSelector::Dragging,
337
            CssPathPseudoSelector::DragOver,
338
        ] {
339
            assert!(
340
                !ends_with(CssPathSelector::PseudoSelector(p.clone())),
341
                "interactive pseudo {p:?} must not end a `None` rule"
342
            );
343
        }
344

            
345
        // Structural => kept.
346
        assert!(ends_with(CssPathSelector::PseudoSelector(
347
            CssPathPseudoSelector::First
348
        )));
349
        assert!(ends_with(CssPathSelector::PseudoSelector(
350
            CssPathPseudoSelector::Last
351
        )));
352
        assert!(ends_with(CssPathSelector::PseudoSelector(
353
            CssPathPseudoSelector::NthChild(CssNthChildSelector::Odd)
354
        )));
355
        // Non-pseudo endings are always kept.
356
        assert!(ends_with(CssPathSelector::Global));
357
        assert!(ends_with(CssPathSelector::Class("b".into())));
358
        assert!(ends_with(CssPathSelector::Type(NodeTypeTag::Div)));
359
        assert!(ends_with(CssPathSelector::DirectChildren));
360
    }
361

            
362
    #[test]
363
    fn rule_ends_with_some_target_requires_an_exact_match_on_the_last_selector() {
364
        let hover = CssPath::new(vec![
365
            CssPathSelector::Class("a".into()),
366
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::Hover),
367
        ]);
368
        assert!(rule_ends_with(&hover, Some(CssPathPseudoSelector::Hover)));
369
        assert!(!rule_ends_with(&hover, Some(CssPathPseudoSelector::Active)));
370
        assert!(!rule_ends_with(&hover, Some(CssPathPseudoSelector::Focus)));
371

            
372
        // A non-pseudo ending never matches a pseudo target.
373
        let plain = CssPath::new(vec![CssPathSelector::Class("a".into())]);
374
        assert!(!rule_ends_with(&plain, Some(CssPathPseudoSelector::Hover)));
375

            
376
        // Documented limitation: only the VERY LAST selector is inspected, so
377
        // `.a:hover:first` does not count as ending with `:hover`.
378
        let compound = CssPath::new(vec![
379
            CssPathSelector::Class("a".into()),
380
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::Hover),
381
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::First),
382
        ]);
383
        assert!(!rule_ends_with(
384
            &compound,
385
            Some(CssPathPseudoSelector::Hover)
386
        ));
387
        assert!(rule_ends_with(
388
            &compound,
389
            Some(CssPathPseudoSelector::First)
390
        ));
391
    }
392

            
393
    #[test]
394
    fn rule_ends_with_compares_nth_child_and_lang_payloads() {
395
        let nth = |s| {
396
            CssPath::new(vec![CssPathSelector::PseudoSelector(
397
                CssPathPseudoSelector::NthChild(s),
398
            )])
399
        };
400
        assert!(rule_ends_with(
401
            &nth(CssNthChildSelector::Number(3)),
402
            Some(CssPathPseudoSelector::NthChild(
403
                CssNthChildSelector::Number(3)
404
            ))
405
        ));
406
        assert!(!rule_ends_with(
407
            &nth(CssNthChildSelector::Number(3)),
408
            Some(CssPathPseudoSelector::NthChild(
409
                CssNthChildSelector::Number(4)
410
            ))
411
        ));
412
        assert!(!rule_ends_with(
413
            &nth(CssNthChildSelector::Even),
414
            Some(CssPathPseudoSelector::NthChild(CssNthChildSelector::Odd))
415
        ));
416

            
417
        // Unicode / boundary language tags must compare by value, not by prefix.
418
        let lang = |s: &str| {
419
            CssPath::new(vec![CssPathSelector::PseudoSelector(
420
                CssPathPseudoSelector::Lang(s.into()),
421
            )])
422
        };
423
        assert!(rule_ends_with(
424
            &lang("zh-Hant-🎉"),
425
            Some(CssPathPseudoSelector::Lang("zh-Hant-🎉".into()))
426
        ));
427
        assert!(!rule_ends_with(
428
            &lang("zh-Hant-🎉"),
429
            Some(CssPathPseudoSelector::Lang("zh".into()))
430
        ));
431
        assert!(!rule_ends_with(
432
            &lang(""),
433
            Some(CssPathPseudoSelector::Lang("de".into()))
434
        ));
435
    }
436

            
437
    // ---------------------------------------------------------------------
438
    // match_first_child / match_last_child
439
    // ---------------------------------------------------------------------
440

            
441
    #[test]
442
    fn match_first_and_last_child_read_only_their_own_field() {
443
        assert!(match_first_child(info(0, false)));
444
        assert!(!match_first_child(info(1, true)));
445
        assert!(!match_first_child(info(u32::MAX, true)));
446

            
447
        assert!(match_last_child(info(0, true)));
448
        assert!(!match_last_child(info(0, false)));
449
        assert!(match_last_child(info(u32::MAX, true)));
450
    }
451

            
452
    // ---------------------------------------------------------------------
453
    // match_nth_child  (numeric: 1-indexing, saturation, div-by-zero, overflow)
454
    // ---------------------------------------------------------------------
455

            
456
    #[test]
457
    fn match_nth_child_is_one_indexed() {
458
        // index_in_parent 0 == :nth-child(1) == odd
459
        assert!(match_nth_child(
460
            info(0, false),
461
            &CssNthChildSelector::Number(1)
462
        ));
463
        assert!(!match_nth_child(
464
            info(0, false),
465
            &CssNthChildSelector::Number(0)
466
        ));
467
        assert!(match_nth_child(info(0, false), &CssNthChildSelector::Odd));
468
        assert!(!match_nth_child(info(0, false), &CssNthChildSelector::Even));
469

            
470
        assert!(match_nth_child(
471
            info(1, false),
472
            &CssNthChildSelector::Number(2)
473
        ));
474
        assert!(match_nth_child(info(1, false), &CssNthChildSelector::Even));
475
        assert!(!match_nth_child(info(1, false), &CssNthChildSelector::Odd));
476
    }
477

            
478
    #[test]
479
    fn match_nth_child_number_matches_exactly_one_index() {
480
        for n in 1..64u32 {
481
            for idx in 0..64u32 {
482
                let matched = match_nth_child(info(idx, false), &CssNthChildSelector::Number(n));
483
                assert_eq!(matched, idx + 1 == n, "nth-child({n}) vs index {idx}");
484
            }
485
        }
486
        // `:nth-child(0)` can never match: the index is 1-based.
487
        for idx in 0..64u32 {
488
            assert!(!match_nth_child(
489
                info(idx, false),
490
                &CssNthChildSelector::Number(0)
491
            ));
492
        }
493
    }
494

            
495
    #[test]
496
    fn match_nth_child_even_and_odd_partition_every_index() {
497
        for idx in 0..1_000u32 {
498
            let even = match_nth_child(info(idx, false), &CssNthChildSelector::Even);
499
            let odd = match_nth_child(info(idx, false), &CssNthChildSelector::Odd);
500
            assert_ne!(even, odd, "index {idx} must be exactly one of even/odd");
501
        }
502
    }
503

            
504
    #[test]
505
    fn match_nth_child_pattern_agrees_with_the_even_and_odd_shorthands() {
506
        // CSS: `even` == `2n`, `odd` == `2n+1`.
507
        for idx in 0..256u32 {
508
            let even_pat = CssNthChildSelector::Pattern(CssNthChildPattern {
509
                pattern_repeat: 2,
510
                offset: 0,
511
            });
512
            let odd_pat = CssNthChildSelector::Pattern(CssNthChildPattern {
513
                pattern_repeat: 2,
514
                offset: 1,
515
            });
516
            assert_eq!(
517
                match_nth_child(info(idx, false), &even_pat),
518
                match_nth_child(info(idx, false), &CssNthChildSelector::Even),
519
                "2n disagrees with `even` at index {idx}"
520
            );
521
            assert_eq!(
522
                match_nth_child(info(idx, false), &odd_pat),
523
                match_nth_child(info(idx, false), &CssNthChildSelector::Odd),
524
                "2n+1 disagrees with `odd` at index {idx}"
525
            );
526
        }
527
    }
528

            
529
    #[test]
530
    fn match_nth_child_zero_repeat_never_divides_by_zero() {
531
        // `0n+3` matches only the 3rd child; `0n+0` matches nothing (1-based).
532
        let only_third = CssNthChildSelector::Pattern(CssNthChildPattern {
533
            pattern_repeat: 0,
534
            offset: 3,
535
        });
536
        let never = CssNthChildSelector::Pattern(CssNthChildPattern {
537
            pattern_repeat: 0,
538
            offset: 0,
539
        });
540

            
541
        for idx in 0..32u32 {
542
            assert_eq!(match_nth_child(info(idx, false), &only_third), idx == 2);
543
            assert!(
544
                !match_nth_child(info(idx, false), &never),
545
                "0n+0 must never match (index is 1-based)"
546
            );
547
        }
548
    }
549

            
550
    #[test]
551
    fn match_nth_child_pattern_below_the_offset_does_not_underflow() {
552
        // `2n+5`: nothing below the 5th child may match, and the `index - offset`
553
        // subtraction must never be reached for those.
554
        let pat = CssNthChildSelector::Pattern(CssNthChildPattern {
555
            pattern_repeat: 2,
556
            offset: 5,
557
        });
558
        for idx in 0..4u32 {
559
            assert!(
560
                !match_nth_child(info(idx, false), &pat),
561
                "index {idx} < offset"
562
            );
563
        }
564
        assert!(match_nth_child(info(4, false), &pat)); // 5th child
565
        assert!(!match_nth_child(info(5, false), &pat)); // 6th
566
        assert!(match_nth_child(info(6, false), &pat)); // 7th
567
    }
568

            
569
    #[test]
570
    fn match_nth_child_with_a_u32_max_offset_does_not_underflow() {
571
        let pat = CssNthChildSelector::Pattern(CssNthChildPattern {
572
            pattern_repeat: 1,
573
            offset: u32::MAX,
574
        });
575
        assert!(!match_nth_child(info(0, false), &pat));
576
        assert!(!match_nth_child(info(1_000, false), &pat));
577
        // index == u32::MAX (index_in_parent == u32::MAX - 1) is the largest
578
        // index that can be formed without overflowing the `+ 1`.
579
        assert!(match_nth_child(info(u32::MAX - 1, false), &pat));
580
    }
581

            
582
    /// BOUNDARY: `match_nth_child` computes `index_in_parent + 1` unchecked.
583
    /// `index_in_parent == u32::MAX` is reachable — `construct_html_cascade_tree`
584
    /// itself saturates to `u32::MAX` (`unwrap_or(u32::MAX)`), and `CascadeInfo`
585
    /// is a `#[repr(C)]` struct with public fields. Debug builds therefore panic
586
    /// on overflow, release builds wrap the index to 0. Assert that the wrap can
587
    /// never silently produce the *wrong* answer for even/odd/number.
588
    #[cfg(feature = "std")]
589
    #[test]
590
    fn match_nth_child_at_u32_max_index_never_answers_wrongly() {
591
        // The true 1-based index here is 2^32, which is even.
592
        let even = std::panic::catch_unwind(|| {
593
            match_nth_child(info(u32::MAX, false), &CssNthChildSelector::Even)
594
        });
595
        let odd = std::panic::catch_unwind(|| {
596
            match_nth_child(info(u32::MAX, false), &CssNthChildSelector::Odd)
597
        });
598
        let one = std::panic::catch_unwind(|| {
599
            match_nth_child(info(u32::MAX, false), &CssNthChildSelector::Number(1))
600
        });
601

            
602
        // debug: the overflow check fires — loud failure, acceptable.
603
        // release: the index wraps to 0, which must still not flip an answer.
604
        if let Ok(v) = even {
605
            assert!(v, "2^32 is even");
606
        }
607
        if let Ok(v) = odd {
608
            assert!(!v, "2^32 is not odd");
609
        }
610
        if let Ok(v) = one {
611
            assert!(!v, "the 2^32-th child is not the 1st child");
612
        }
613
    }
614

            
615
    // ---------------------------------------------------------------------
616
    // match_interactive_pseudo / match_pseudo_selector
617
    // ---------------------------------------------------------------------
618

            
619
    #[test]
620
    fn match_interactive_pseudo_needs_both_the_last_group_and_the_expected_ending() {
621
        let hover = CssPathPseudoSelector::Hover;
622
        let active = CssPathPseudoSelector::Active;
623

            
624
        assert!(match_interactive_pseudo(&hover, Some(&hover), true));
625
        assert!(!match_interactive_pseudo(&hover, Some(&hover), false));
626
        assert!(!match_interactive_pseudo(&hover, Some(&active), true));
627
        assert!(!match_interactive_pseudo(&hover, None, true));
628
        assert!(!match_interactive_pseudo(&hover, None, false));
629
    }
630

            
631
    #[test]
632
    fn match_pseudo_selector_routes_every_interactive_pseudo_through_the_gate() {
633
        for p in [
634
            CssPathPseudoSelector::Hover,
635
            CssPathPseudoSelector::Active,
636
            CssPathPseudoSelector::Focus,
637
            CssPathPseudoSelector::Backdrop,
638
            CssPathPseudoSelector::Dragging,
639
            CssPathPseudoSelector::DragOver,
640
        ] {
641
            assert!(
642
                match_pseudo_selector(&p, info(0, false), Some(&p), true),
643
                "{p:?} must match when it is the expected ending of the last group"
644
            );
645
            assert!(
646
                !match_pseudo_selector(&p, info(0, false), Some(&p), false),
647
                "{p:?} must not match outside the last content group"
648
            );
649
            assert!(
650
                !match_pseudo_selector(&p, info(0, false), None, true),
651
                "{p:?} must not match when no pseudo state is expected"
652
            );
653
        }
654
    }
655

            
656
    #[test]
657
    fn match_pseudo_selector_structural_pseudos_ignore_the_expected_ending() {
658
        let hover = CssPathPseudoSelector::Hover;
659

            
660
        // :first / :last / :nth-child depend only on the CascadeInfo.
661
        for (expected, is_last) in [(None, true), (Some(&hover), false), (Some(&hover), true)] {
662
            assert!(match_pseudo_selector(
663
                &CssPathPseudoSelector::First,
664
                info(0, false),
665
                expected,
666
                is_last
667
            ));
668
            assert!(!match_pseudo_selector(
669
                &CssPathPseudoSelector::First,
670
                info(1, false),
671
                expected,
672
                is_last
673
            ));
674
            assert!(match_pseudo_selector(
675
                &CssPathPseudoSelector::Last,
676
                info(9, true),
677
                expected,
678
                is_last
679
            ));
680
            assert!(match_pseudo_selector(
681
                &CssPathPseudoSelector::NthChild(CssNthChildSelector::Number(10)),
682
                info(9, true),
683
                expected,
684
                is_last
685
            ));
686
        }
687
    }
688

            
689
    #[test]
690
    fn match_pseudo_selector_lang_only_matches_the_expected_lang() {
691
        let de = CssPathPseudoSelector::Lang("de".into());
692
        let en = CssPathPseudoSelector::Lang("en".into());
693

            
694
        assert!(match_pseudo_selector(&de, info(0, false), Some(&de), true));
695
        assert!(!match_pseudo_selector(&de, info(0, false), Some(&en), true));
696
        assert!(!match_pseudo_selector(&de, info(0, false), None, true));
697
        assert!(!match_pseudo_selector(
698
            &de,
699
            info(0, false),
700
            Some(&CssPathPseudoSelector::Hover),
701
            true
702
        ));
703

            
704
        // Unicode + empty language tags must not panic and must compare by value.
705
        let emoji = CssPathPseudoSelector::Lang("de-🎉".into());
706
        assert!(match_pseudo_selector(
707
            &emoji,
708
            info(0, false),
709
            Some(&emoji),
710
            true
711
        ));
712
        assert!(!match_pseudo_selector(
713
            &emoji,
714
            info(0, false),
715
            Some(&de),
716
            true
717
        ));
718
        let empty = CssPathPseudoSelector::Lang("".into());
719
        assert!(match_pseudo_selector(
720
            &empty,
721
            info(0, false),
722
            Some(&empty),
723
            true
724
        ));
725
    }
726

            
727
    // ---------------------------------------------------------------------
728
    // match_attribute_selector
729
    // ---------------------------------------------------------------------
730

            
731
    #[test]
732
    fn match_attribute_selector_on_a_node_without_attributes_is_always_false() {
733
        let nd = NodeData::create_div();
734
        for op in [
735
            AttributeMatchOp::Exists,
736
            AttributeMatchOp::Eq,
737
            AttributeMatchOp::Includes,
738
            AttributeMatchOp::DashMatch,
739
            AttributeMatchOp::Prefix,
740
            AttributeMatchOp::Suffix,
741
            AttributeMatchOp::Substring,
742
        ] {
743
            assert!(!match_attribute_selector(
744
                &attr_sel("data-x", op, Some("v")),
745
                &nd
746
            ));
747
            assert!(!match_attribute_selector(&attr_sel("", op, None), &nd));
748
        }
749
    }
750

            
751
    #[test]
752
    fn match_attribute_selector_exists_matches_any_value_including_the_empty_one() {
753
        let nd = node_with_attrs(vec![custom("data-x", "")]);
754
        assert!(match_attribute_selector(
755
            &attr_sel("data-x", AttributeMatchOp::Exists, None),
756
            &nd
757
        ));
758
        // Exists ignores the value entirely, even if one is (wrongly) supplied.
759
        assert!(match_attribute_selector(
760
            &attr_sel("data-x", AttributeMatchOp::Exists, Some("nonsense")),
761
            &nd
762
        ));
763
        assert!(!match_attribute_selector(
764
            &attr_sel("data-y", AttributeMatchOp::Exists, None),
765
            &nd
766
        ));
767
    }
768

            
769
    #[test]
770
    fn match_attribute_selector_operator_without_a_value_never_matches() {
771
        let nd = node_with_attrs(vec![custom("data-x", "value")]);
772
        for op in [
773
            AttributeMatchOp::Eq,
774
            AttributeMatchOp::Includes,
775
            AttributeMatchOp::DashMatch,
776
            AttributeMatchOp::Prefix,
777
            AttributeMatchOp::Suffix,
778
            AttributeMatchOp::Substring,
779
        ] {
780
            assert!(
781
                !match_attribute_selector(&attr_sel("data-x", op, None), &nd),
782
                "{op:?} with a missing target value must be rejected, not matched"
783
            );
784
        }
785
    }
786

            
787
    #[test]
788
    fn match_attribute_selector_empty_target_never_matches_the_substring_family() {
789
        // `[x^=""]` / `[x$=""]` / `[x*=""]` / `[x~=""]` would otherwise match
790
        // every node (every string starts with / contains the empty string).
791
        let nd = node_with_attrs(vec![custom("data-x", "abc")]);
792
        for op in [
793
            AttributeMatchOp::Prefix,
794
            AttributeMatchOp::Suffix,
795
            AttributeMatchOp::Substring,
796
            AttributeMatchOp::Includes,
797
        ] {
798
            assert!(
799
                !match_attribute_selector(&attr_sel("data-x", op, Some("")), &nd),
800
                "{op:?} with an empty target must not match"
801
            );
802
        }
803
        // Eq is the exception: `[x=""]` legitimately means "the empty value".
804
        assert!(!match_attribute_selector(
805
            &attr_sel("data-x", AttributeMatchOp::Eq, Some("")),
806
            &nd
807
        ));
808
        let empty = node_with_attrs(vec![custom("data-x", "")]);
809
        assert!(match_attribute_selector(
810
            &attr_sel("data-x", AttributeMatchOp::Eq, Some("")),
811
            &empty
812
        ));
813
    }
814

            
815
    #[test]
816
    fn match_attribute_selector_includes_matches_one_of_several_class_entries() {
817
        // Classes are stored as separate `AttributeType::Class` entries, so the
818
        // matcher has to be "any value satisfies the op" (see the fn doc).
819
        let mut nd = NodeData::create_div();
820
        nd.add_class("foo".into());
821
        nd.add_class("primary".into());
822
        nd.add_class("bar".into());
823

            
824
        assert!(match_attribute_selector(
825
            &attr_sel("class", AttributeMatchOp::Includes, Some("primary")),
826
            &nd
827
        ));
828
        assert!(!match_attribute_selector(
829
            &attr_sel("class", AttributeMatchOp::Includes, Some("prim")),
830
            &nd
831
        ));
832
        // A target containing whitespace is invalid for `~=` and must not match.
833
        assert!(!match_attribute_selector(
834
            &attr_sel("class", AttributeMatchOp::Includes, Some("foo bar")),
835
            &nd
836
        ));
837
        assert!(!match_attribute_selector(
838
            &attr_sel("class", AttributeMatchOp::Includes, Some("\t")),
839
            &nd
840
        ));
841
    }
842

            
843
    #[test]
844
    fn match_attribute_selector_dash_match_requires_a_dash_boundary() {
845
        let nd = node_with_attrs(vec![AttributeType::Lang("en-US".into())]);
846

            
847
        assert!(match_attribute_selector(
848
            &attr_sel("lang", AttributeMatchOp::DashMatch, Some("en")),
849
            &nd
850
        ));
851
        assert!(match_attribute_selector(
852
            &attr_sel("lang", AttributeMatchOp::DashMatch, Some("en-US")),
853
            &nd
854
        ));
855
        // A prefix that does not end on the `-` boundary must not match.
856
        assert!(!match_attribute_selector(
857
            &attr_sel("lang", AttributeMatchOp::DashMatch, Some("en-U")),
858
            &nd
859
        ));
860
        assert!(!match_attribute_selector(
861
            &attr_sel("lang", AttributeMatchOp::DashMatch, Some("e")),
862
            &nd
863
        ));
864

            
865
        // `en` must not match the value `english` (no dash boundary).
866
        let english = node_with_attrs(vec![AttributeType::Lang("english".into())]);
867
        assert!(!match_attribute_selector(
868
            &attr_sel("lang", AttributeMatchOp::DashMatch, Some("en")),
869
            &english
870
        ));
871
    }
872

            
873
    #[test]
874
    fn match_attribute_selector_name_matching_is_exact_and_case_sensitive() {
875
        let nd = node_with_attrs(vec![custom("data-foo", "v")]);
876
        assert!(match_attribute_selector(
877
            &attr_sel("data-foo", AttributeMatchOp::Eq, Some("v")),
878
            &nd
879
        ));
880
        assert!(!match_attribute_selector(
881
            &attr_sel("data-fo", AttributeMatchOp::Eq, Some("v")),
882
            &nd
883
        ));
884
        assert!(!match_attribute_selector(
885
            &attr_sel("data-foo2", AttributeMatchOp::Eq, Some("v")),
886
            &nd
887
        ));
888
        assert!(!match_attribute_selector(
889
            &attr_sel("DATA-FOO", AttributeMatchOp::Eq, Some("v")),
890
            &nd
891
        ));
892
        assert!(!match_attribute_selector(
893
            &attr_sel("", AttributeMatchOp::Exists, None),
894
            &nd
895
        ));
896
    }
897

            
898
    #[test]
899
    fn match_attribute_selector_handles_unicode_values_on_char_boundaries() {
900
        // "héllo-🎉-世界" has no ASCII 'e' and no ASCII-splittable emoji.
901
        let nd = node_with_attrs(vec![custom("data-x", "héllo-🎉-世界")]);
902

            
903
        assert!(match_attribute_selector(
904
            &attr_sel("data-x", AttributeMatchOp::Prefix, Some("hé")),
905
            &nd
906
        ));
907
        assert!(match_attribute_selector(
908
            &attr_sel("data-x", AttributeMatchOp::Suffix, Some("世界")),
909
            &nd
910
        ));
911
        assert!(match_attribute_selector(
912
            &attr_sel("data-x", AttributeMatchOp::Substring, Some("🎉")),
913
            &nd
914
        ));
915
        assert!(match_attribute_selector(
916
            &attr_sel("data-x", AttributeMatchOp::Eq, Some("héllo-🎉-世界")),
917
            &nd
918
        ));
919
        // No false positive from the ASCII byte inside a multi-byte codepoint.
920
        assert!(!match_attribute_selector(
921
            &attr_sel("data-x", AttributeMatchOp::Substring, Some("e")),
922
            &nd
923
        ));
924
        // DashMatch on a unicode segment.
925
        assert!(match_attribute_selector(
926
            &attr_sel("data-x", AttributeMatchOp::DashMatch, Some("héllo")),
927
            &nd
928
        ));
929
    }
930

            
931
    #[test]
932
    fn match_attribute_selector_handles_huge_values() {
933
        let huge = "ä".repeat(100_000);
934
        let value = alloc::format!("{huge}-tail");
935
        let nd = node_with_attrs(vec![custom("data-big", &value)]);
936

            
937
        assert!(match_attribute_selector(
938
            &attr_sel("data-big", AttributeMatchOp::Suffix, Some("-tail")),
939
            &nd
940
        ));
941
        assert!(match_attribute_selector(
942
            &attr_sel("data-big", AttributeMatchOp::Prefix, Some("ää")),
943
            &nd
944
        ));
945
        assert!(match_attribute_selector(
946
            &attr_sel("data-big", AttributeMatchOp::DashMatch, Some(huge.as_str())),
947
            &nd
948
        ));
949
        assert!(!match_attribute_selector(
950
            &attr_sel("data-big", AttributeMatchOp::Eq, Some(huge.as_str())),
951
            &nd
952
        ));
953
    }
954

            
955
    // ---------------------------------------------------------------------
956
    // match_single_selector / selector_group_matches
957
    // ---------------------------------------------------------------------
958

            
959
    #[test]
960
    fn match_single_selector_global_matches_elements_but_never_text_nodes() {
961
        let div = NodeData::create_div();
962
        let text = NodeData::create_text_do_not_use_without_block_level_wrapper("hello");
963
        assert!(match_single_selector(
964
            &CssPathSelector::Global,
965
            info(0, false),
966
            &div,
967
            NodeId::new(0),
968
            None,
969
            true,
970
            false
971
        ));
972
        // Per CSS, `*` matches ELEMENTS only. Text nodes take styling by
973
        // inheritance; a universal rule hitting them directly overwrote
974
        // freshly inherited values (`* { color }` vs `p { color }`).
975
        assert!(!match_single_selector(
976
            &CssPathSelector::Global,
977
            info(u32::MAX, true),
978
            &text,
979
            NodeId::new(usize::MAX),
980
            None,
981
            false,
982
            false
983
        ));
984
    }
985

            
986
    #[test]
987
    fn global_matches_a_text_node_only_when_the_rule_is_scoped_to_exactly_it() {
988
        // Inline-style semantics (miniword ENGINE-ISSUE 4):
989
        // `create_text_do_not_use_without_block_level_wrapper("x").with_css("color: white")`
990
        // produces `[Root(n..=n), Global]` — the author addressed THIS node, so the
991
        // universal selector must match despite it being a text node.
992
        let text = NodeData::create_text_do_not_use_without_block_level_wrapper("hello");
993
        let nid = NodeId::new(7);
994
        let self_scope = CssPathSelector::Root(CssScopeRange { start: 7, end: 7 });
995
        let global = CssPathSelector::Global;
996

            
997
        let group: Vec<&CssPathSelector> = vec![&self_scope, &global];
998
        assert!(
999
            selector_group_matches(&group, info(0, true), &text, nid, None, true),
            "a node-only-scoped bare-decl rule must style its own text node"
        );
        // Negative control 1: the SAME group on a DIFFERENT text node (the
        // scope range excludes it) must not match.
        assert!(
            !selector_group_matches(&group, info(0, true), &text, NodeId::new(8), None, true),
            "node-only scope must not leak to other text nodes"
        );
        // Negative control 2: a SUBTREE-scoped `* { }` (stylesheet semantics,
        // start != end) keeps refusing text nodes — the historical
        // `* { color: #666 }` inheritance-overwrite bug must stay fixed.
        let subtree_scope = CssPathSelector::Root(CssScopeRange { start: 0, end: 20 });
        let group2: Vec<&CssPathSelector> = vec![&subtree_scope, &global];
        assert!(
            !selector_group_matches(&group2, info(0, true), &text, nid, None, true),
            "subtree-scoped universal selectors must never match text nodes"
        );
        // Negative control 3: an UNSCOPED bare `*` refuses text nodes too.
        let group3: Vec<&CssPathSelector> = vec![&global];
        assert!(!selector_group_matches(
            &group3,
            info(0, true),
            &text,
            nid,
            None,
            true
        ));
    }
    #[test]
    fn match_single_selector_never_matches_a_combinator() {
        // Combinators must be split out by the group iterator; if one ever
        // reaches the matcher it must fail closed, not match everything.
        let div = NodeData::create_div();
        for c in [
            CssPathSelector::DirectChildren,
            CssPathSelector::Children,
            CssPathSelector::AdjacentSibling,
            CssPathSelector::GeneralSibling,
        ] {
            assert!(!match_single_selector(
                &c,
                info(0, true),
                &div,
                NodeId::new(0),
                None,
                true,
                false
            ));
        }
    }
    #[test]
    fn match_single_selector_root_scope_range_is_inclusive_on_both_ends() {
        let div = NodeData::create_div();
        let sel = CssPathSelector::Root(CssScopeRange { start: 2, end: 4 });
        for id in [2usize, 3, 4] {
            assert!(match_single_selector(
                &sel,
                info(0, false),
                &div,
                NodeId::new(id),
                None,
                true,
                false
            ));
        }
        for id in [0usize, 1, 5, usize::MAX] {
            assert!(!match_single_selector(
                &sel,
                info(0, false),
                &div,
                NodeId::new(id),
                None,
                true,
                false
            ));
        }
    }
    #[test]
    fn match_single_selector_root_scope_with_an_inverted_or_full_range() {
        let div = NodeData::create_div();
        // Inverted range (start > end) matches nothing, and must not panic.
        let inverted = CssPathSelector::Root(CssScopeRange { start: 9, end: 2 });
        for id in [0usize, 2, 9, usize::MAX] {
            assert!(!match_single_selector(
                &inverted,
                info(0, false),
                &div,
                NodeId::new(id),
                None,
                true,
                false
            ));
        }
        // Full range matches every node id, including usize::MAX.
        let full = CssPathSelector::Root(CssScopeRange {
            start: 0,
            end: usize::MAX,
        });
        for id in [0usize, 1, usize::MAX] {
            assert!(match_single_selector(
                &full,
                info(0, false),
                &div,
                NodeId::new(id),
                None,
                true,
                false
            ));
        }
    }
    #[test]
    fn match_single_selector_type_class_and_id() {
        let mut nd = div_with(Some("first"), Some("a"));
        nd.add_class("日本語-🎉".into());
        let hit = |s: &CssPathSelector| {
            match_single_selector(s, info(0, false), &nd, NodeId::new(0), None, true, false)
        };
        assert!(hit(&CssPathSelector::Type(NodeTypeTag::Div)));
        assert!(!hit(&CssPathSelector::Type(NodeTypeTag::P)));
        assert!(hit(&CssPathSelector::Class("a".into())));
        assert!(hit(&CssPathSelector::Class("日本語-🎉".into())));
        assert!(
            !hit(&CssPathSelector::Class("日本語".into())),
            "no prefix matching"
        );
        assert!(!hit(&CssPathSelector::Class("".into())));
        assert!(hit(&CssPathSelector::Id("first".into())));
        assert!(!hit(&CssPathSelector::Id("firs".into())));
        // Ids and classes must not cross over.
        assert!(!hit(&CssPathSelector::Class("first".into())));
        assert!(!hit(&CssPathSelector::Id("a".into())));
    }
    #[test]
    fn selector_group_matches_requires_every_selector_in_the_group() {
        let nd = div_with(Some("first"), Some("a"));
        let div = CssPathSelector::Type(NodeTypeTag::Div);
        let class_a = CssPathSelector::Class("a".into());
        let class_z = CssPathSelector::Class("zzz".into());
        let group: Vec<&CssPathSelector> = vec![&div, &class_a];
        assert!(selector_group_matches(
            &group,
            info(0, false),
            &nd,
            NodeId::new(0),
            None,
            true
        ));
        let group: Vec<&CssPathSelector> = vec![&div, &class_a, &class_z];
        assert!(!selector_group_matches(
            &group,
            info(0, false),
            &nd,
            NodeId::new(0),
            None,
            true
        ));
    }
    #[test]
    fn selector_group_matches_empty_group_matches_vacuously() {
        // This is what a dangling combinator (`.foo >`) produces — see
        // `css_group_iterator_yields_an_empty_group_for_a_trailing_combinator`.
        // `all()` over an empty group is `true`, so such a group matches ANY node.
        let empty: Vec<&CssPathSelector> = Vec::new();
        assert!(selector_group_matches(
            &empty,
            info(0, false),
            &NodeData::create_div(),
            NodeId::new(0),
            None,
            true
        ));
    }
    // ---------------------------------------------------------------------
    // find_non_anonymous_parent / find_non_anonymous_prev_sibling
    // ---------------------------------------------------------------------
    /// ```text
    /// 0 body
    /// ├── 1 <anonymous>
    /// │   └── 2 <anonymous>
    /// │       └── 3 div        <- parent chain must skip 1 and 2
    /// ├── 4 <anonymous>
    /// └── 5 div                <- prev-sibling chain must skip 4 and 1
    /// ```
    fn anonymous_fixture() -> (Vec<Node>, Vec<NodeData>) {
        let hierarchy = vec![
            node(None, None, None, Some(5)),
            node(Some(0), None, Some(4), Some(2)),
            node(Some(1), None, None, Some(3)),
            node(Some(2), None, None, None),
            node(Some(0), Some(1), Some(5), None),
            node(Some(0), Some(4), None, None),
        ];
        let mut anon1 = NodeData::create_div();
        anon1.set_anonymous(true);
        let mut anon2 = NodeData::create_div();
        anon2.set_anonymous(true);
        let mut anon4 = NodeData::create_div();
        anon4.set_anonymous(true);
        let data = vec![
            NodeData::create_body(),
            anon1,
            anon2,
            div_with(None, Some("deep")),
            anon4,
            div_with(None, Some("c")),
        ];
        (hierarchy, data)
    }
    #[test]
    fn find_non_anonymous_parent_skips_a_chain_of_anonymous_boxes() {
        let (hierarchy, data) = anonymous_fixture();
        let hier_items = items(&hierarchy);
        let h = NodeDataContainerRef::from_slice(&hier_items);
        let d = NodeDataContainerRef::from_slice(&data);
        // node 3's real parent is the body (0), not the anonymous 2 / 1.
        assert_eq!(
            find_non_anonymous_parent(NodeId::new(3), &h, &d),
            Some(NodeId::new(0))
        );
        // node 5's parent is the body directly.
        assert_eq!(
            find_non_anonymous_parent(NodeId::new(5), &h, &d),
            Some(NodeId::new(0))
        );
        // the root has no parent at all.
        assert_eq!(find_non_anonymous_parent(NodeId::new(0), &h, &d), None);
    }
    #[test]
    fn find_non_anonymous_parent_returns_none_when_every_ancestor_is_anonymous() {
        // 0 <anonymous root> -> 1 div
        let hierarchy = vec![
            node(None, None, None, Some(1)),
            node(Some(0), None, None, None),
        ];
        let mut anon_root = NodeData::create_div();
        anon_root.set_anonymous(true);
        let data = vec![anon_root, NodeData::create_div()];
        let hier_items = items(&hierarchy);
        let h = NodeDataContainerRef::from_slice(&hier_items);
        let d = NodeDataContainerRef::from_slice(&data);
        assert_eq!(find_non_anonymous_parent(NodeId::new(1), &h, &d), None);
    }
    #[test]
    fn find_non_anonymous_prev_sibling_skips_anonymous_siblings() {
        let (hierarchy, data) = anonymous_fixture();
        let hier_items = items(&hierarchy);
        let h = NodeDataContainerRef::from_slice(&hier_items);
        let d = NodeDataContainerRef::from_slice(&data);
        // node 5's previous siblings are 4 (anonymous) and 1 (anonymous), so
        // there is no non-anonymous previous sibling.
        assert_eq!(
            find_non_anonymous_prev_sibling(NodeId::new(5), &h, &d),
            None
        );
        // a first child has no previous sibling.
        assert_eq!(
            find_non_anonymous_prev_sibling(NodeId::new(1), &h, &d),
            None
        );
        assert_eq!(
            find_non_anonymous_prev_sibling(NodeId::new(0), &h, &d),
            None
        );
    }
    #[test]
    fn find_non_anonymous_prev_sibling_returns_the_nearest_real_sibling() {
        let hierarchy = sample_hierarchy();
        let data = sample_node_data();
        let hier_items = items(&hierarchy);
        let h = NodeDataContainerRef::from_slice(&hier_items);
        let d = NodeDataContainerRef::from_slice(&data);
        // The text node (2) between div.a (1) and div.b (3) is SKIPPED — sibling
        // combinators target elements only — so the previous element sibling of node 3
        // is div.a (1), not the text node. See
        // `matches_html_element_adjacent_sibling_skips_text_nodes`.
        assert_eq!(
            find_non_anonymous_prev_sibling(NodeId::new(3), &h, &d),
            Some(NodeId::new(1))
        );
        assert_eq!(
            find_non_anonymous_prev_sibling(NodeId::new(5), &h, &d),
            Some(NodeId::new(3))
        );
    }
    // ---------------------------------------------------------------------
    // construct_html_cascade_tree
    // ---------------------------------------------------------------------
    #[test]
    fn construct_html_cascade_tree_on_an_empty_hierarchy_is_empty() {
        let hierarchy: Vec<Node> = Vec::new();
        let data: Vec<NodeData> = Vec::new();
        let out = construct_html_cascade_tree(
            &NodeHierarchyRef::from_slice(&hierarchy),
            &[],
            &NodeDataContainerRef::from_slice(&data),
        );
        assert_eq!(out.len(), 0);
        assert!(out.is_empty());
    }
    #[test]
    fn construct_html_cascade_tree_with_no_parents_defaults_every_node() {
        // A single childless root is a LEAF, so `get_parents_sorted_by_depth`
        // returns nothing and every entry keeps the zeroed default.
        let hierarchy = vec![node(None, None, None, None)];
        let data = vec![NodeData::create_body()];
        let hierarchy_ref = NodeHierarchyRef::from_slice(&hierarchy);
        let depths = hierarchy_ref.get_parents_sorted_by_depth();
        assert!(depths.is_empty());
        let out = construct_html_cascade_tree(
            &hierarchy_ref,
            &depths,
            &NodeDataContainerRef::from_slice(&data),
        );
        assert_eq!(out.len(), 1);
        assert_eq!(out.internal[0], CascadeInfo::default());
    }
    #[test]
    fn construct_html_cascade_tree_does_not_count_text_nodes_as_element_siblings() {
        let hierarchy = sample_hierarchy();
        let data = sample_node_data();
        let hierarchy_ref = NodeHierarchyRef::from_slice(&hierarchy);
        let data_ref = NodeDataContainerRef::from_slice(&data);
        let depths = hierarchy_ref.get_parents_sorted_by_depth();
        let out = construct_html_cascade_tree(&hierarchy_ref, &depths, &data_ref);
        assert_eq!(out.len(), hierarchy.len(), "one CascadeInfo per node");
        assert_eq!(out.internal[0], info(0, true), "root");
        assert_eq!(
            out.internal[1],
            info(0, false),
            "div#first.a — 1st element child"
        );
        assert_eq!(
            out.internal[3],
            info(1, false),
            "div.b — 2nd element child (text skipped)"
        );
        assert_eq!(
            out.internal[4],
            info(0, true),
            "p.inner — only child of div.b"
        );
        assert_eq!(
            out.internal[5],
            info(2, true),
            "div.c — 3rd element child and the last one"
        );
        // The text node itself is never the last child and is not an element.
        assert!(!out.internal[2].is_last_child);
    }
    #[test]
    fn construct_html_cascade_tree_ignores_trailing_text_nodes_for_is_last_child() {
        // 0 body -> [1 div, 2 "text", 3 "text"]  => div is still the LAST element child.
        let hierarchy = vec![
            node(None, None, None, Some(3)),
            node(Some(0), None, Some(2), None),
            node(Some(0), Some(1), Some(3), None),
            node(Some(0), Some(2), None, None),
        ];
        let data = vec![
            NodeData::create_body(),
            NodeData::create_div(),
            NodeData::create_text_do_not_use_without_block_level_wrapper("a"),
            NodeData::create_text_do_not_use_without_block_level_wrapper("b"),
        ];
        let hierarchy_ref = NodeHierarchyRef::from_slice(&hierarchy);
        let data_ref = NodeDataContainerRef::from_slice(&data);
        let depths = hierarchy_ref.get_parents_sorted_by_depth();
        let out = construct_html_cascade_tree(&hierarchy_ref, &depths, &data_ref);
        assert_eq!(
            out.internal[1],
            info(0, true),
            "trailing text must not un-last the div"
        );
    }
    #[test]
    fn construct_html_cascade_tree_handles_a_wide_tree() {
        const CHILDREN: usize = 2_000;
        let mut hierarchy = vec![node(None, None, None, Some(CHILDREN))];
        let mut data = vec![NodeData::create_body()];
        for i in 1..=CHILDREN {
            hierarchy.push(node(
                Some(0),
                if i == 1 { None } else { Some(i - 1) },
                if i == CHILDREN { None } else { Some(i + 1) },
                None,
            ));
            data.push(NodeData::create_div());
        }
        let hierarchy_ref = NodeHierarchyRef::from_slice(&hierarchy);
        let data_ref = NodeDataContainerRef::from_slice(&data);
        let depths = hierarchy_ref.get_parents_sorted_by_depth();
        let out = construct_html_cascade_tree(&hierarchy_ref, &depths, &data_ref);
        assert_eq!(out.len(), CHILDREN + 1);
        for i in 1..=CHILDREN {
            let expected = info(u32::try_from(i - 1).unwrap(), i == CHILDREN);
            assert_eq!(out.internal[i], expected, "child {i}");
        }
    }
    #[test]
    fn construct_html_cascade_tree_handles_a_deep_chain() {
        const DEPTH: usize = 1_000;
        let mut hierarchy = Vec::with_capacity(DEPTH);
        let mut data = Vec::with_capacity(DEPTH);
        for i in 0..DEPTH {
            hierarchy.push(node(
                if i == 0 { None } else { Some(i - 1) },
                None,
                None,
                if i + 1 == DEPTH { None } else { Some(i + 1) },
            ));
            data.push(NodeData::create_div());
        }
        let hierarchy_ref = NodeHierarchyRef::from_slice(&hierarchy);
        let data_ref = NodeDataContainerRef::from_slice(&data);
        let depths = hierarchy_ref.get_parents_sorted_by_depth();
        let out = construct_html_cascade_tree(&hierarchy_ref, &depths, &data_ref);
        assert_eq!(out.len(), DEPTH);
        for i in 0..DEPTH {
            assert_eq!(
                out.internal[i],
                info(0, true),
                "every node in a chain is an only child"
            );
        }
    }
    // ---------------------------------------------------------------------
    // matches_html_element
    // ---------------------------------------------------------------------
    #[test]
    fn matches_html_element_empty_path_never_matches() {
        assert!(!matches(Vec::new(), 1, None));
        assert!(!matches(Vec::new(), 0, Some(CssPathPseudoSelector::Hover)));
    }
    #[test]
    fn matches_html_element_matches_type_class_and_id_on_the_subject() {
        assert!(matches(vec![CssPathSelector::Global], 1, None));
        assert!(matches(vec![CssPathSelector::Class("a".into())], 1, None));
        assert!(!matches(vec![CssPathSelector::Class("a".into())], 3, None));
        assert!(matches(vec![CssPathSelector::Id("first".into())], 1, None));
        assert!(matches(
            vec![CssPathSelector::Type(NodeTypeTag::Div)],
            1,
            None
        ));
        assert!(!matches(
            vec![CssPathSelector::Type(NodeTypeTag::Div)],
            0,
            None
        ));
        assert!(matches(
            vec![CssPathSelector::Type(NodeTypeTag::Body)],
            0,
            None
        ));
        // Compound group: `div.a` matches node 1 but not node 3 (`div.b`).
        let div_a = vec![
            CssPathSelector::Type(NodeTypeTag::Div),
            CssPathSelector::Class("a".into()),
        ];
        assert!(matches(div_a.clone(), 1, None));
        assert!(!matches(div_a, 3, None));
    }
    #[test]
    fn matches_html_element_never_matches_an_anonymous_node() {
        let (hierarchy, data) = anonymous_fixture();
        let hier_items = items(&hierarchy);
        let hierarchy_ref = NodeHierarchyRef::from_slice(&hierarchy);
        let data_ref = NodeDataContainerRef::from_slice(&data);
        let depths = hierarchy_ref.get_parents_sorted_by_depth();
        let cascade = construct_html_cascade_tree(&hierarchy_ref, &depths, &data_ref);
        // `*` matches everything EXCEPT the anonymous boxes (1, 2, 4).
        for id in [1usize, 2, 4] {
            assert!(
                !matches_html_element(
                    &CssPath::new(vec![CssPathSelector::Global]),
                    NodeId::new(id),
                    &NodeDataContainerRef::from_slice(&hier_items),
                    &data_ref,
                    &cascade.as_ref(),
                    None,
                ),
                "anonymous node {id} must not be styled"
            );
        }
        for id in [0usize, 3, 5] {
            assert!(matches_html_element(
                &CssPath::new(vec![CssPathSelector::Global]),
                NodeId::new(id),
                &NodeDataContainerRef::from_slice(&hier_items),
                &data_ref,
                &cascade.as_ref(),
                None,
            ));
        }
    }
    #[test]
    fn matches_html_element_child_combinator_is_stricter_than_the_descendant_one() {
        // `body > p` must NOT match p.inner (its parent is div.b) ...
        let child = vec![
            CssPathSelector::Type(NodeTypeTag::Body),
            CssPathSelector::DirectChildren,
            CssPathSelector::Type(NodeTypeTag::P),
        ];
        assert!(!matches(child, 4, None));
        // ... but `body p` must.
        let descendant = vec![
            CssPathSelector::Type(NodeTypeTag::Body),
            CssPathSelector::Children,
            CssPathSelector::Type(NodeTypeTag::P),
        ];
        assert!(matches(descendant, 4, None));
        // `body > div.b` is a direct child.
        let direct = vec![
            CssPathSelector::Type(NodeTypeTag::Body),
            CssPathSelector::DirectChildren,
            CssPathSelector::Type(NodeTypeTag::Div),
            CssPathSelector::Class("b".into()),
        ];
        assert!(matches(direct, 3, None));
    }
    #[test]
    fn matches_html_element_descendant_combinator_walks_the_whole_ancestor_chain() {
        // `div.b p.inner` (direct) and `body p.inner` (two levels up).
        let close = vec![
            CssPathSelector::Class("b".into()),
            CssPathSelector::Children,
            CssPathSelector::Class("inner".into()),
        ];
        assert!(matches(close, 4, None));
        // A non-ancestor class must not match, even though it exists in the DOM.
        let unrelated = vec![
            CssPathSelector::Class("c".into()),
            CssPathSelector::Children,
            CssPathSelector::Class("inner".into()),
        ];
        assert!(!matches(unrelated, 4, None));
    }
    #[test]
    fn matches_html_element_general_sibling_scans_all_previous_siblings() {
        // `div.a ~ div.c`: div.c (5) is preceded by div.b (3) and a text node (2),
        // and the scan must keep walking until it reaches div.a (1).
        let general = vec![
            CssPathSelector::Class("a".into()),
            CssPathSelector::GeneralSibling,
            CssPathSelector::Class("c".into()),
        ];
        assert!(matches(general, 5, None));
        // The subject must come AFTER the sibling: `div.c ~ div.a` must not match.
        let backwards = vec![
            CssPathSelector::Class("c".into()),
            CssPathSelector::GeneralSibling,
            CssPathSelector::Class("a".into()),
        ];
        assert!(!matches(backwards, 1, None));
    }
    #[test]
    fn matches_html_element_adjacent_sibling_matches_the_immediate_element_sibling() {
        // `div.b + div.c`: node 5's immediately preceding sibling IS div.b.
        let adjacent = vec![
            CssPathSelector::Class("b".into()),
            CssPathSelector::AdjacentSibling,
            CssPathSelector::Class("c".into()),
        ];
        assert!(matches(adjacent, 5, None));
        // `div.a + div.c` must not match (div.b sits between them).
        let not_adjacent = vec![
            CssPathSelector::Class("a".into()),
            CssPathSelector::AdjacentSibling,
            CssPathSelector::Class("c".into()),
        ];
        assert!(!matches(not_adjacent, 5, None));
    }
    /// EXPECTED-RED (genuine bug, see report): `find_non_anonymous_prev_sibling`
    /// only skips *anonymous* nodes, not *non-element* (text) nodes. CSS
    /// Selectors L4 §15.2 defines `E + F` over element siblings only — and
    /// `construct_html_cascade_tree` already excludes text nodes from sibling
    /// indexing (L4 §13) — so `div.a + div.b` must still match across the
    /// intervening text node. Today it returns `false`.
    #[test]
    fn matches_html_element_adjacent_sibling_skips_text_nodes() {
        // `div.a + div.b`, with the text node 2 sitting between them.
        let adjacent = vec![
            CssPathSelector::Class("a".into()),
            CssPathSelector::AdjacentSibling,
            CssPathSelector::Class("b".into()),
        ];
        assert!(
            matches(adjacent, 3, None),
            "the `+` combinator must ignore non-element (text) siblings"
        );
    }
    #[test]
    fn matches_html_element_hover_on_a_single_group_path_needs_the_expected_ending() {
        let hover = vec![
            CssPathSelector::Class("a".into()),
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::Hover),
        ];
        assert!(matches(
            hover.clone(),
            1,
            Some(CssPathPseudoSelector::Hover)
        ));
        // Without the expected pseudo state the rule must not apply...
        assert!(!matches(hover.clone(), 1, None));
        // ... and neither must a different state.
        assert!(!matches(
            hover.clone(),
            1,
            Some(CssPathPseudoSelector::Focus)
        ));
        // ... and it still has to match the rest of the selector.
        assert!(!matches(hover, 3, Some(CssPathPseudoSelector::Hover)));
    }
    /// EXPECTED-RED (genuine bug, see report): `matches_html_element` passes
    /// `is_last_content_group = groups.len() == 1` for the SUBJECT group (the
    /// rightmost one, which the iterator yields first), so an interactive pseudo
    /// on the subject of any multi-group selector — `.container .btn:hover`,
    /// `body > .btn:hover`, … — can never match. `prop_cache` reaches
    /// `matches_html_element` with exactly this shape (`rule_ends_with(path,
    /// Some(Hover))` → `matches_html_element(..., Some(Hover))`), so every
    /// descendant/child `:hover` / `:active` / `:focus` rule is silently dropped.
    #[test]
    fn matches_html_element_hover_on_a_descendant_path_still_matches() {
        // `body .a:hover` — the hover applies to the SUBJECT (node 1).
        let hover_descendant = vec![
            CssPathSelector::Type(NodeTypeTag::Body),
            CssPathSelector::Children,
            CssPathSelector::Class("a".into()),
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::Hover),
        ];
        assert!(
            matches(hover_descendant, 1, Some(CssPathPseudoSelector::Hover)),
            ":hover on the subject of a multi-group selector must still match"
        );
    }
    #[test]
    fn matches_html_element_structural_pseudos_work_on_the_subject() {
        // div#first.a is the first element child; div.c is the last one.
        let first = vec![
            CssPathSelector::Class("a".into()),
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::First),
        ];
        assert!(matches(first, 1, None));
        let last = vec![
            CssPathSelector::Class("c".into()),
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::Last),
        ];
        assert!(matches(last, 5, None));
        // div.b is the 2nd element child — the text node must not shift the index.
        let nth = vec![
            CssPathSelector::Class("b".into()),
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::NthChild(
                CssNthChildSelector::Number(2),
            )),
        ];
        assert!(matches(nth, 3, None));
        let wrong_nth = vec![
            CssPathSelector::Class("b".into()),
            CssPathSelector::PseudoSelector(CssPathPseudoSelector::NthChild(
                CssNthChildSelector::Number(3),
            )),
        ];
        assert!(!matches(wrong_nth, 3, None));
    }
    #[test]
    fn matches_html_element_root_scope_confines_a_rule_to_its_subtree() {
        // `[Root(3..=4), *]` — the #47 scope marker: only div.b and its child.
        let scoped = vec![
            CssPathSelector::Root(CssScopeRange { start: 3, end: 4 }),
            CssPathSelector::Global,
        ];
        assert!(matches(scoped.clone(), 3, None));
        assert!(matches(scoped.clone(), 4, None));
        assert!(
            !matches(scoped.clone(), 1, None),
            "must not leak to a sibling"
        );
        assert!(
            !matches(scoped.clone(), 5, None),
            "must not leak to a sibling"
        );
        assert!(!matches(scoped, 0, None), "must not leak to the parent");
        // Node-only scope (`[start, start]`) = inline-style semantics.
        let node_only = vec![
            CssPathSelector::Root(CssScopeRange { start: 3, end: 3 }),
            CssPathSelector::Global,
        ];
        assert!(matches(node_only.clone(), 3, None));
        assert!(
            !matches(node_only, 4, None),
            "a node-only scope must not reach children"
        );
    }
    #[test]
    fn matches_html_element_with_a_dangling_combinator_does_not_panic() {
        // `.a >` — the iterator yields an empty subject group, which matches
        // vacuously, and then requires an `.a` parent. Node 4's parent is div.b,
        // so this must be false; no panic either way.
        let dangling = vec![
            CssPathSelector::Class("a".into()),
            CssPathSelector::DirectChildren,
        ];
        assert!(!matches(dangling.clone(), 4, None));
        // ... but div.a IS the parent of nothing, so no node matches it.
        for id in 0..6 {
            let _ = matches(dangling.clone(), id, None);
        }
    }
    #[test]
    fn matches_html_element_on_a_very_long_selector_chain_terminates() {
        // 500 `body ...` descendant groups: the ancestor scan must fail fast
        // (there are only 3 levels in the DOM) instead of looping.
        let mut path = Vec::new();
        for _ in 0..500 {
            path.push(CssPathSelector::Type(NodeTypeTag::Body));
            path.push(CssPathSelector::Children);
        }
        path.push(CssPathSelector::Class("inner".into()));
        assert!(!matches(path, 4, None));
    }
}