asciidoc-parser 0.19.0

Parser for AsciiDoc format
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
//! CSS-like query support for Virtual DOM nodes.
//!
//! This module provides a minimal CSS query engine for testing purposes.
//! It supports a subset of CSS syntax used in test assertions.

use crate::tests::assert_dom::virtual_dom::VirtualNode;

/// Queries a virtual DOM tree using an CSS-like selector.
///
/// Supports the following patterns:
/// - `tag` - Find all elements with the given tag anywhere in the tree
/// - `tag child` - Find child elements as direct children of tag elements
/// - `tag > child` - Find direct children only
/// - `tag:first-of-type` - Find first occurrence of tag among siblings
/// - `tag:not(selector)` - Find elements that do NOT match the inner selector
/// - `tag:nth-child(N)` - Find the element that is the Nth child of its parent
/// - `tag:empty` - Find elements with no children and no text
/// - Pseudo-classes may be chained, e.g. `td:nth-child(3):empty`
///
/// # Example
///
/// ```ignore
/// let doc = Parser::default().parse("* item 1\n* item 2");
/// let vdom = doc.to_virtual_dom();
/// let items = query_css(&vdom, "ul li");
/// assert_eq!(items.len(), 2);
/// ```
pub(crate) fn query_css<'a>(root: &'a VirtualNode, selector: &str) -> Vec<&'a VirtualNode> {
    let selector = selector.trim();

    // A descendant selector can reach the same node through more than one
    // matching ancestor (e.g. `.tableblock h1` where both the `<table>` and the
    // `<td>` carry the `tableblock` class). De-duplicate so each node is counted
    // once, matching a real CSS engine.
    let mut seen: Vec<*const VirtualNode> = Vec::new();
    query_descendant_or_self(root, selector)
        .into_iter()
        .filter(|node| {
            let ptr = *node as *const VirtualNode;
            if seen.contains(&ptr) {
                false
            } else {
                seen.push(ptr);
                true
            }
        })
        .collect()
}

/// Finds the position of the first space that acts as a descendant combinator,
/// scanning the whole pattern. Returns `None` if there are none.
///
/// A space is a descendant combinator only when it is not merely whitespace
/// padding a `>` or `+` combinator. This distinguishes between:
/// - `div p` - space is a descendant combinator
/// - `div > p` - spaces are just whitespace around `>`
/// - `div + p` - spaces are just whitespace around `+`
/// - `a > b c` - the space before `c` is a descendant combinator even though it
///   follows a `>` combinator earlier in the pattern
fn find_descendant_combinator_space(pattern: &str) -> Option<usize> {
    for (i, ch) in pattern.char_indices() {
        if ch != ' ' {
            continue;
        }

        // Whitespace immediately before a `>`/`+` combinator is not a descendant
        // combinator (e.g. the space in `div >`).
        let rest = pattern[i..].trim_start();
        if rest.starts_with('>') || rest.starts_with('+') {
            continue;
        }

        // Whitespace immediately after a `>`/`+` combinator (or leading the
        // pattern) is not a descendant combinator either (e.g. the space in
        // `div > p`).
        let prev = pattern[..i].trim_end();
        if prev.is_empty() || prev.ends_with('>') || prev.ends_with('+') {
            continue;
        }

        // A simple selector on both sides: this is a descendant combinator.
        return Some(i);
    }

    None
}

/// Queries for descendants or self matching the pattern.
fn query_descendant_or_self<'a>(node: &'a VirtualNode, pattern: &str) -> Vec<&'a VirtualNode> {
    // Check which combinator appears first to process them in correct order.
    // Space (descendant) has lower precedence and should be processed first.
    // However, we need to distinguish between a space as a descendant combinator
    // and a space that's just whitespace around `>` or `+` combinators.
    let space_pos = find_descendant_combinator_space(pattern);
    let gt_pos = pattern.find('>');

    // Process space combinator first if it appears before `>`.
    if let Some(space) = space_pos
        && (gt_pos.is_none() || space < gt_pos.unwrap())
    {
        // Split on first ` ` to handle paths like `ul li`.
        let (first, rest) = pattern.split_at(space);
        let first = first.trim();
        let rest = rest.trim();

        // Find all nodes matching first part.
        let mut results = Vec::new();
        collect_descendants_matching(node, first, &mut results);

        // For each matching node, search its descendants (not including itself) for
        // the rest of the pattern. The descendant combinator (space) means "any
        // descendant", which by definition excludes the element itself.
        let mut final_results = Vec::new();
        for matched_node in results {
            // Search only children (descendants), not the matched node itself
            for child in &matched_node.children {
                let descendants = query_descendant_or_self(child, rest);
                final_results.extend(descendants);
            }
        }
        return final_results;
    }

    // Handle direct child combinator: "tag > child".
    if let Some((first, rest)) = pattern.split_once('>') {
        let first = first.trim();
        let rest = rest.trim();

        // Find all nodes matching first part.
        // NOTE: We still search all descendants for the first part, because the
        // initial query can match elements anywhere in the tree. The `>` only
        // constrains the relationship between matched elements and what follows.
        let mut results = Vec::new();
        collect_descendants_matching(node, first, &mut results);

        // For each matching node, use the direct-child-only query helper to process
        // rest.
        let mut final_results = Vec::new();
        for matched_node in results {
            let children_matches = query_with_direct_child_constraint(matched_node, rest);
            final_results.extend(children_matches);
        }
        return final_results;
    }

    // Handle adjacent sibling combinator: "tag + sibling".
    if let Some((first, rest)) = pattern.split_once('+') {
        let first = first.trim();
        let rest = rest.trim();

        // Find all nodes matching first part.
        let mut results = Vec::new();
        collect_descendants_matching_with_siblings(node, first, &mut results);

        // For each matching node, find its next sibling and check if it matches rest.
        let mut final_results = Vec::new();
        for (_matched_node, parent, child_index) in results {
            if let Some(next_sibling) = parent.children.get(child_index + 1) {
                // If rest has more combinators, recursively process.
                if rest.contains('>') || rest.contains('+') {
                    let further = query_descendant_or_self(next_sibling, rest);
                    final_results.extend(further);
                } else {
                    // Simple selector - just check next sibling directly.
                    if matches_selector_with_context(next_sibling, rest, Some(parent)) {
                        final_results.push(next_sibling);
                    }
                }
            }
        }
        return final_results;
    }

    // Simple tag match: Find all descendants (or self) matching this selector.
    let mut results = Vec::new();
    collect_descendants_matching(node, pattern.trim(), &mut results);
    results
}

/// Recursively collects all descendants (including self) that match the
/// selector.
fn collect_descendants_matching<'a>(
    node: &'a VirtualNode,
    selector: &str,
    results: &mut Vec<&'a VirtualNode>,
) {
    collect_descendants_matching_with_parent(node, selector, None, results);
}

/// Recursively collects all descendants (including self) that match the
/// selector, with parent context for pseudo-selectors.
fn collect_descendants_matching_with_parent<'a>(
    node: &'a VirtualNode,
    selector: &str,
    parent: Option<&'a VirtualNode>,
    results: &mut Vec<&'a VirtualNode>,
) {
    if matches_selector_with_context(node, selector, parent) {
        results.push(node);
    }

    for child in &node.children {
        collect_descendants_matching_with_parent(child, selector, Some(node), results);
    }
}

/// Recursively collects all descendants (including self) that match the
/// selector, along with their parent and child index for sibling lookups.
fn collect_descendants_matching_with_siblings<'a>(
    node: &'a VirtualNode,
    selector: &str,
    results: &mut Vec<(&'a VirtualNode, &'a VirtualNode, usize)>,
) {
    for (index, child) in node.children.iter().enumerate() {
        if matches_selector_with_context(child, selector, Some(node)) {
            results.push((child, node, index));
        }
        collect_descendants_matching_with_siblings(child, selector, results);
    }
}

/// Helper to query with `>` and `+` combinator chains, only looking at direct
/// children/siblings.
fn query_with_direct_child_constraint<'a>(
    node: &'a VirtualNode,
    pattern: &str,
) -> Vec<&'a VirtualNode> {
    // Find which combinator appears first to process them in order.
    let plus_pos = pattern.find('+');
    let gt_pos = pattern.find('>');
    let space_pos = find_descendant_combinator_space(pattern);

    // Process a descendant combinator first if it is the leftmost combinator
    // (e.g. the ` ` in `td .paragraph`, reached after stripping the preceding
    // `>` steps of `table > tbody > tr > td .paragraph`). The constrained child
    // matches a direct child; the rest is an unconstrained descendant search.
    if let Some(space) = space_pos
        && gt_pos.is_none_or(|gt| space < gt)
        && plus_pos.is_none_or(|plus| space < plus)
    {
        let (first, rest) = pattern.split_at(space);
        let first = first.trim();
        let rest = rest.trim();

        let mut results = Vec::new();
        for child in &node.children {
            if matches_selector_with_context(child, first, Some(node)) {
                // The descendant combinator excludes the matched child itself, so
                // search its subtrees rather than the child node.
                for grandchild in &child.children {
                    results.extend(query_descendant_or_self(grandchild, rest));
                }
            }
        }
        return results;
    }

    // Process `>` first if it appears before `+`.
    if let Some(gt) = gt_pos
        && (plus_pos.is_none() || gt < plus_pos.unwrap())
    {
        // `>` comes first or there's no `+`.
        let (first, rest) = pattern.split_at(gt);
        let first = first.trim();
        let rest = rest[1..].trim(); // Skip the `>` character.

        let mut results = Vec::new();
        for child in &node.children {
            if matches_selector_with_context(child, first, Some(node)) {
                // This child matches, recursively process rest with this child.
                let further_matches = query_with_direct_child_constraint(child, rest);
                results.extend(further_matches);
            }
        }
        return results;
    }

    // Process `+` if it appears first or there's no `>`.
    if let Some((first, rest)) = pattern.split_once('+') {
        let first = first.trim();
        let rest = rest.trim();

        let mut results = Vec::new();
        for child in &node.children {
            if matches_selector_with_context(child, first, Some(node)) {
                // Find next sibling.
                let child_index = node
                    .children
                    .iter()
                    .position(|c| std::ptr::eq(c as *const _, child as *const _));

                if let Some(idx) = child_index
                    && let Some(next_sibling) = node.children.get(idx + 1)
                {
                    // Check if next sibling matches rest.
                    // If rest has combinators, we need to continue processing from
                    // next_sibling.
                    if rest.contains('>') || rest.contains('+') {
                        // Parse the first part of rest to check against next_sibling.
                        let (next_part, remaining) = if let Some(pos) = rest.find('>') {
                            (rest[..pos].trim(), Some(rest[pos + 1..].trim()))
                        } else if let Some(pos) = rest.find('+') {
                            (rest[..pos].trim(), Some(rest[pos + 1..].trim()))
                        } else {
                            (rest, None)
                        };

                        // Check if next_sibling matches next_part.
                        if matches_selector_with_context(next_sibling, next_part, Some(node)) {
                            if let Some(remaining) = remaining {
                                // Continue processing from next_sibling with remaining
                                // selector.
                                let further =
                                    query_with_direct_child_constraint(next_sibling, remaining);
                                results.extend(further);
                            } else {
                                // No more selector parts, next_sibling is a match.
                                results.push(next_sibling);
                            }
                        }
                    } else {
                        // Simple selector - just check next sibling directly.
                        if matches_selector_with_context(next_sibling, rest, Some(node)) {
                            results.push(next_sibling);
                        }
                    }
                }
            }
        }
        results
    } else {
        // No more `>` combinators - just match direct children.
        let mut results = Vec::new();
        for child in &node.children {
            if matches_selector_with_context(child, pattern, Some(node)) {
                results.push(child);
            }
        }
        results
    }
}

/// Checks if a node matches the given selector with parent context.
///
/// Supports:
/// - Tag name: `div`, `ul`, `li`
/// - Wildcard: `*` (matches any element)
/// - Class selector: `[@class="ulist"]` or `.ulist`
/// - ID selector: `[@id="foo"]` or `#foo`
/// - Text content: `[text()="value"]`
/// - Index: `[1]`, `[2]`, etc. (handled by `apply_numeric_predicate`)
/// - Pseudo-selectors: `:first-of-type`, `:not(...)`, `:nth-child(N)`, `:empty`
///   (and chains thereof, e.g. `:nth-child(3):empty`)
fn matches_selector_with_context(
    node: &VirtualNode,
    selector: &str,
    parent: Option<&VirtualNode>,
) -> bool {
    let selector = selector.trim();

    // Handle pseudo-selectors like :first-of-type.
    let (selector_without_pseudo, pseudo_selector) = if let Some(colon_pos) = selector.find(':') {
        (&selector[..colon_pos], Some(&selector[colon_pos + 1..]))
    } else {
        (selector, None)
    };

    // Handle index predicates [N] by stripping them off.
    // (Caller should handle filtering by index.)
    let (base_selector, predicate) = if let Some(bracket_pos) = selector_without_pseudo.find('[') {
        (
            &selector_without_pseudo[..bracket_pos],
            Some(&selector_without_pseudo[bracket_pos..]),
        )
    } else {
        (selector_without_pseudo, None)
    };

    // Split tag from class selectors for patterns like `ul.disc` or
    // `div.ulist.disc`. After this split:
    // - `tag_part` will be the tag name (or empty if selector starts with `.`)
    // - `class_selectors` will be the class portion (e.g., `.disc` or
    //   `.ulist.disc`)
    let (tag_part, class_selectors) = if let Some(dot_pos) = base_selector.find('.') {
        (&base_selector[..dot_pos], Some(&base_selector[dot_pos..]))
    } else {
        (base_selector, None)
    };

    // Split an `#id` suffix off the tag part so that a combined selector like
    // `a#taoup` (tag plus id) is honored, not just a standalone `#taoup`.
    let (tag_part, id_selector) = if let Some(hash_pos) = tag_part.find('#') {
        (&tag_part[..hash_pos], Some(&tag_part[hash_pos + 1..]))
    } else {
        (tag_part, None)
    };

    // Wildcard selector: matches any element.
    if tag_part == "*" {
        if let Some(predicate) = predicate
            && !matches_predicate(node, predicate)
        {
            return false;
        }
        // Fall through to check id and class selectors if present.
    } else if !tag_part.is_empty() {
        // Tag name must match.
        if node.tag != tag_part {
            return false;
        }
    }

    // CSS-style ID selector (`#id`, possibly combined with a tag as in `a#id`).
    if let Some(id) = id_selector
        && node.id.as_deref() != Some(id)
    {
        return false;
    }

    // Check class selectors if present.
    if let Some(classes) = class_selectors {
        // Handle multiple class selectors like `.disc` or `.ulist.disc`.
        let class_names: Vec<&str> = classes[1..].split('.').filter(|s| !s.is_empty()).collect();

        // All specified classes must be present.
        if !class_names
            .iter()
            .all(|class_name| node.classes.iter().any(|c| c == class_name))
        {
            return false;
        }
    }

    // Handle predicates if present.
    if let Some(predicate) = predicate
        && !matches_predicate(node, predicate)
    {
        return false;
    }

    // Handle pseudo-selectors if present.
    if let Some(pseudo) = pseudo_selector
        && !matches_pseudo_selector(node, pseudo, parent)
    {
        return false;
    }

    true
}

/// Checks if a node matches a pseudo-selector, which may be a chain of several
/// pseudo-classes (e.g. `nth-child(3):empty`). Every pseudo-class in the chain
/// must match.
fn matches_pseudo_selector(node: &VirtualNode, pseudo: &str, parent: Option<&VirtualNode>) -> bool {
    split_pseudo_chain(pseudo.trim())
        .iter()
        .all(|part| matches_single_pseudo(node, part, parent))
}

/// Splits a pseudo-selector chain on top-level `:` separators, leaving colons
/// inside parentheses (e.g. a nested `:not(...)`) untouched.
/// `nth-child(3):empty` becomes `["nth-child(3)", "empty"]`.
fn split_pseudo_chain(pseudo: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut start = 0;
    for (i, ch) in pseudo.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            ':' if depth == 0 => {
                parts.push(&pseudo[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    parts.push(&pseudo[start..]);
    parts.into_iter().filter(|p| !p.is_empty()).collect()
}

/// Checks if a node matches a single pseudo-class.
fn matches_single_pseudo(node: &VirtualNode, pseudo: &str, parent: Option<&VirtualNode>) -> bool {
    let pseudo = pseudo.trim();

    // Handle :not() pseudo-class.
    if let Some(inner) = pseudo.strip_prefix("not(") {
        if let Some(inner) = inner.strip_suffix(')') {
            // The inner selector should NOT match.
            return !matches_inner_not_selector(node, inner.trim());
        }
        return false; // Malformed :not().
    }

    // Handle :nth-child(N) pseudo-class (1-indexed position among siblings).
    if let Some(arg) = pseudo.strip_prefix("nth-child(") {
        if let Some(arg) = arg.strip_suffix(')')
            && let Ok(n) = arg.trim().parse::<usize>()
            && let Some(parent) = parent
        {
            return parent
                .children
                .get(n.wrapping_sub(1))
                .is_some_and(|child| std::ptr::eq(child as *const _, node as *const _));
        }
        return false; // Malformed or unsupported :nth-child() argument.
    }

    match pseudo {
        "first-of-type" => {
            // Check if this is the first child with the same tag among its siblings.
            if let Some(parent) = parent {
                // Find the first child with the same tag.
                for child in &parent.children {
                    if child.tag == node.tag {
                        // This is the first occurrence.
                        return std::ptr::eq(child as *const _, node as *const _);
                    }
                }
            }
            // If no parent or no matching siblings, consider it first-of-type.
            true
        }

        "empty" => {
            // Check if this element has no children and no text content.
            node.children.is_empty()
                && (node.text.is_none() || node.text.as_ref().is_some_and(|t| t.is_empty()))
        }

        _ => false, // Unknown pseudo-selector.
    }
}

/// Checks if a node matches the inner selector of a :not() pseudo-class.
/// This handles the subset of selectors that can appear inside :not().
fn matches_inner_not_selector(node: &VirtualNode, selector: &str) -> bool {
    let selector = selector.trim();

    // Handle attribute selector: [attr] or [attr="value"].
    if selector.starts_with('[') && selector.ends_with(']') {
        let inner = &selector[1..selector.len() - 1];
        return matches_single_predicate(node, inner);
    }

    // Handle class selector: .classname.
    if let Some(class_name) = selector.strip_prefix('.') {
        return node.classes.iter().any(|c| c == class_name);
    }

    // Handle ID selector: #id.
    if let Some(id) = selector.strip_prefix('#') {
        return node.id.as_deref() == Some(id);
    }

    // Handle tag selector.
    if !selector.is_empty() && !selector.contains('[') {
        return node.tag == selector;
    }

    false
}

/// Checks if a node matches a predicate like `[@class="value"]` or
/// `[text()="value"]`.
/// Can handle multiple predicates like `[@class="value"][text()="text"]`.
fn matches_predicate(node: &VirtualNode, predicate: &str) -> bool {
    let mut predicate = predicate.trim();

    // Handle multiple predicates by checking each one.
    while !predicate.is_empty() {
        // Find the next closing bracket.
        if let Some(bracket_start) = predicate.find('[') {
            if let Some(bracket_end) = predicate[bracket_start..].find(']') {
                let bracket_end = bracket_start + bracket_end;
                let single_pred = &predicate[bracket_start + 1..bracket_end];

                // Check this single predicate.
                if !matches_single_predicate(node, single_pred) {
                    return false;
                }

                // Move to the next predicate.
                predicate = predicate[bracket_end + 1..].trim();
            } else {
                // Malformed predicate.
                return false;
            }
        } else {
            // No more predicates.
            break;
        }
    }

    true
}

/// Checks if a node matches a single predicate.
fn matches_single_predicate(node: &VirtualNode, predicate: &str) -> bool {
    let predicate = predicate.trim();

    // Check for `text()` predicate.
    if let Some(rest) = predicate.strip_prefix("text()") {
        let rest = rest.trim();

        // Handle text() = 'value' (single quotes).
        if let Some(value_part) = rest.strip_prefix('=').map(|s| s.trim()) {
            // Try single-quoted string first.
            if let Some(value) = value_part.strip_prefix('\'') {
                if let Some(value) = value.strip_suffix('\'') {
                    let unescaped = unescape_css_string(value);
                    return node.text.as_deref() == Some(&unescaped);
                }
            }
            // Try double-quoted string.
            else if let Some(value) = value_part.strip_prefix('"')
                && let Some(value) = value.strip_suffix('"')
            {
                let unescaped = unescape_css_string(value);
                return node.text.as_deref() == Some(&unescaped);
            }
        }

        return false;
    }

    // Check for attribute predicates `[@attr="value"]` or `[@attr]`.
    if let Some(attr_part) = predicate.strip_prefix('@') {
        if let Some((attr_name, value_part)) = attr_part.split_once('=') {
            // Attribute with value: [@attr="value"].
            let attr_name = attr_name.trim();
            let value = value_part
                .trim()
                .strip_prefix('"')
                .and_then(|s| s.strip_suffix('"'))
                .unwrap_or(value_part.trim());

            match attr_name {
                "class" => return node.classes.iter().any(|c| c == value),
                "id" => return node.id.as_deref() == Some(value),
                _ => {
                    // Check arbitrary attributes.
                    return node.attributes.get(attr_name).map(|v| v.as_str()) == Some(value);
                }
            }
        } else {
            // Attribute existence: [@attr].
            let attr_name = attr_part.trim();
            match attr_name {
                "class" => return !node.classes.is_empty(),
                "id" => return node.id.is_some(),
                _ => return node.attributes.contains_key(attr_name),
            }
        }
    }

    // Check for CSS-style attribute existence selector: [attr] (without @).
    if !predicate.contains('=') && !predicate.contains('(') {
        // This is a simple attribute existence check.
        let attr_name = predicate.trim();
        match attr_name {
            "class" => return !node.classes.is_empty(),
            "id" => return node.id.is_some(),
            _ => return node.attributes.contains_key(attr_name),
        }
    }

    // CSS-style attribute substring selector: [attr*="value"]. As with the
    // exact-match form below, `class` and `id` live on their own node fields
    // rather than in `attributes`; `class` is matched against the rendered
    // (space-joined) class list so the substring may span class boundaries.
    if let Some((attr_name, value_part)) = predicate.split_once("*=") {
        let attr_name = attr_name.trim();
        let value = unquote_attr_value(value_part);
        return match attr_name {
            "class" => node.classes.join(" ").contains(value.as_str()),
            "id" => node
                .id
                .as_deref()
                .is_some_and(|id| id.contains(value.as_str())),
            _ => node
                .attributes
                .get(attr_name)
                .is_some_and(|v| v.contains(&value)),
        };
    }

    // CSS-style attribute value selector without the `@` prefix:
    // [attr="value"]. (The `@`-prefixed form is handled above.)
    if let Some((attr_name, value_part)) = predicate.split_once('=') {
        let attr_name = attr_name.trim();
        let value = unquote_attr_value(value_part);
        match attr_name {
            "class" => {
                return value
                    .split_whitespace()
                    .all(|c| node.classes.iter().any(|nc| nc == c));
            }
            "id" => return node.id.as_deref() == Some(value.as_str()),
            _ => return node.attributes.get(attr_name).map(|v| v.as_str()) == Some(value.as_str()),
        }
    }

    // Numeric predicate [N]: Would need to be handled by caller with context.
    // For now, just return `true` to pass through.
    true
}

/// Strips surrounding single or double quotes (and whitespace) from a CSS
/// attribute selector value.
fn unquote_attr_value(value_part: &str) -> String {
    let trimmed = value_part.trim();
    let unquoted = trimmed
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| {
            trimmed
                .strip_prefix('\'')
                .and_then(|s| s.strip_suffix('\''))
        })
        .unwrap_or(trimmed);
    unescape_css_string(unquoted)
}

/// Unescapes CSS string literals.
/// Handles escape sequences like `\n` (newline), `\'` (single quote), `\\`
/// (backslash).
fn unescape_css_string(s: &str) -> String {
    let mut result = String::new();
    let mut chars = s.chars();

    while let Some(ch) = chars.next() {
        if ch == '\\' {
            // Handle escape sequence.
            if let Some(next) = chars.next() {
                match next {
                    'n' => result.push('\n'),
                    't' => result.push('\t'),
                    'r' => result.push('\r'),
                    '\\' => result.push('\\'),
                    '\'' => result.push('\''),
                    '"' => result.push('"'),
                    _ => {
                        // Unknown escape - keep as is.
                        result.push('\\');
                        result.push(next);
                    }
                }
            } else {
                result.push('\\');
            }
        } else {
            result.push(ch);
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::{assert_dom::virtual_dom::ToVirtualDom, prelude::*};

    #[test]
    fn query_all_paragraphs() {
        let doc = Parser::default().parse("Para 1\n\nPara 2\n\nPara 3");
        let vdom = doc.to_virtual_dom();
        let paras = query_css(&vdom, "p");
        assert_eq!(paras.len(), 3);
    }

    #[test]
    fn query_list_items() {
        let doc = Parser::default().parse("* item 1\n* item 2\n* item 3");
        let vdom = doc.to_virtual_dom();

        // Find all `ul` elements.
        let uls = query_css(&vdom, "ul");
        assert_eq!(uls.len(), 1);

        // Find all `li` elements.
        let lis = query_css(&vdom, "li");
        assert_eq!(lis.len(), 3);

        // Find `li` as children of `ul`.
        let ul_lis = query_css(&vdom, "ul li");
        assert_eq!(ul_lis.len(), 3);
    }

    #[test]
    fn query_first_of_type() {
        let doc = Parser::default().parse("* item 1\n* item 2\n* item 3");
        let vdom = doc.to_virtual_dom();

        // Find first li element.
        let first_li = query_css(&vdom, "li:first-of-type");
        assert_eq!(first_li.len(), 1);

        // Verify it's the correct element by checking its content.
        assert_eq!(first_li[0].children.len(), 1); // Should have one child (p tag).
        assert_eq!(first_li[0].children[0].tag, "p");
        assert_eq!(first_li[0].children[0].text.as_deref(), Some("item 1"));
    }

    #[test]
    fn query_direct_children() {
        let doc = Parser::default().parse("* item 1\n\n  para\n* item 2");
        let vdom = doc.to_virtual_dom();

        // Find direct children of first li using > combinator.
        let children = query_css(&vdom, "li:first-of-type > *");
        assert!(!children.is_empty()); // Should have at least the initial paragraph.
    }

    #[test]
    fn query_first_of_type_with_direct_child() {
        let doc = Parser::default().parse("* item 1\n\n  para\n* item 2");
        let vdom = doc.to_virtual_dom();

        // Combine :first-of-type with > combinator to find paragraphs that are
        // direct children of the first li.
        let paras = query_css(&vdom, "li:first-of-type > p");
        assert!(!paras.is_empty());
    }

    #[test]
    fn query_plus_with_direct_child() {
        let doc = Parser::default().parse("* bullet 1\n. numbered 1.1");
        let vdom = doc.to_virtual_dom();

        // Test: li > p + .olist
        let matches = query_css(&vdom, "li > p + .olist");
        assert_eq!(
            matches.len(),
            1,
            "Should find 1 .olist that is adjacent sibling of p inside li"
        );
    }

    #[test]
    fn query_nth_child_and_pseudo_chain() {
        // A two-row, three-column table whose middle row has an empty trailing
        // cell. Exercises `:nth-child(N)` and a pseudo chain (`:nth-child(3):empty`).
        let doc = Parser::default().parse("[format=csv]\n|===\na,b,c\n1,2,\n|===");
        let vdom = doc.to_virtual_dom();

        assert_eq!(query_css(&vdom, "tbody > tr").len(), 2);
        assert_eq!(query_css(&vdom, "tbody > tr:nth-child(1) > td").len(), 3);
        assert_eq!(query_css(&vdom, "tbody > tr:nth-child(2) > td").len(), 3);

        // Only the second row's third cell is empty.
        assert_eq!(
            query_css(&vdom, "tbody > tr:nth-child(2) > td:nth-child(3):empty").len(),
            1
        );
        assert_eq!(
            query_css(&vdom, "tbody > tr:nth-child(1) > td:nth-child(3):empty").len(),
            0
        );

        // A position that no sibling occupies matches nothing.
        assert_eq!(query_css(&vdom, "tbody > tr:nth-child(3)").len(), 0);
    }

    #[test]
    fn query_child_chain_then_descendant() {
        // A chain of `>` child combinators followed by a trailing descendant
        // combinator (`a > b > c d`). The descendant step is reached only after
        // the preceding `>` steps are stripped, so it must be handled inside the
        // direct-child traversal, not just at the top level.
        let doc = Parser::default().parse("[cols=\"1a\"]\n|===\n|AsciiDoc content\n|===");
        let vdom = doc.to_virtual_dom();

        // The paragraph sits at td > div.content > div.paragraph, i.e. it is a
        // descendant (not a direct child) of the `td`.
        assert_eq!(query_css(&vdom, "table > tbody > tr > td").len(), 1);
        assert_eq!(
            query_css(&vdom, "table > tbody > tr > td .paragraph").len(),
            1
        );

        // A descendant step that itself precedes a further child combinator
        // (`td .content > .paragraph`) is also handled.
        assert_eq!(query_css(&vdom, "td .content > .paragraph").len(), 1);
    }

    #[test]
    fn query_full_ulist_selector() {
        let doc = Parser::default().parse("* bullet 1\n. numbered 1.1");
        let vdom = doc.to_virtual_dom();

        // Test: .ulist > ul > li > p + .olist
        let matches = query_css(&vdom, ".ulist > ul > li > p + .olist");
        assert_eq!(matches.len(), 1, "Should find 1 .olist with full selector");
    }

    #[test]
    fn query_with_arbitrary_attribute() {
        // Test querying for elements with arbitrary attributes.
        let doc = Parser::default().parse("* Foo\n[start=2]\n. Boo\n* Blech\n");
        let vdom = doc.to_virtual_dom();

        // Find all ol elements with start attribute using CSS-style attribute selector.
        let result = query_css(&vdom, "ol[@start=\"2\"]");
        assert_eq!(result.len(), 1, "Should find one ol with start=2");

        // Verify the attribute value.
        assert_eq!(result[0].attributes.get("start"), Some(&"2".to_string()));
    }

    #[test]
    fn query_attribute_substring_selector() {
        // The `[attr*="value"]` substring selector must consult the dedicated
        // `class` and `id` node fields, not just `attributes`.
        let node = VirtualNode::new("table")
            .with_classes(["tableblock", "fit-content"])
            .with_id("results")
            .with_attribute("style", "width: 50%;");

        // `class` matches against the space-joined class list.
        assert_eq!(query_css(&node, "table[class*=\"fit\"]").len(), 1);
        assert_eq!(query_css(&node, "table[class*=\"block\"]").len(), 1);
        assert_eq!(query_css(&node, "table[class*=\"nope\"]").len(), 0);

        // `id` matches against the id field.
        assert_eq!(query_css(&node, "table[id*=\"sult\"]").len(), 1);
        assert_eq!(query_css(&node, "table[id*=\"nope\"]").len(), 0);

        // An ordinary attribute matches against its value.
        assert_eq!(query_css(&node, "table[style*=\"width\"]").len(), 1);
        assert_eq!(query_css(&node, "table[style*=\"height\"]").len(), 0);
    }

    #[test]
    fn query_attribute_existence() {
        // Test attribute existence selectors (without value comparison).
        let doc = Parser::default().parse("* Foo\n[start=2]\n. Boo\n. Blech\n");
        let vdom = doc.to_virtual_dom();

        // Find all ol elements with start attribute (CSS-style: [start]).
        let with_start = query_css(&vdom, "ol[start]");
        assert_eq!(
            with_start.len(),
            1,
            "Should find one ol with start attribute"
        );

        // Find all ol elements (should be 1 total).
        let all_ol = query_css(&vdom, "ol");
        assert_eq!(all_ol.len(), 1, "Should find one ol element total");

        // Test XPath-style attribute existence: [@start].
        let with_start_xpath = query_css(&vdom, "ol[@start]");
        assert_eq!(
            with_start_xpath.len(),
            1,
            "Should find one ol with start attribute (XPath-style)"
        );
    }

    #[test]
    fn query_not_selector() {
        // Test :not() pseudo-class with attribute selector.
        let doc = Parser::default().parse("[glossary]\nterm 1:: def 1\nterm 2:: def 2\n");
        let vdom = doc.to_virtual_dom();

        // Find dt elements that don't have a class attribute.
        let dt_no_class = query_css(&vdom, "dt:not([class])");
        assert_eq!(
            dt_no_class.len(),
            2,
            "Should find 2 dt elements without class"
        );

        // All dt elements should match since none have class attributes.
        let all_dt = query_css(&vdom, "dt");
        assert_eq!(all_dt.len(), 2, "Should find 2 dt elements total");
    }

    #[test]
    fn query_not_selector_with_class() {
        // Test :not() pseudo-class with class selector.
        let doc = Parser::default().parse("* item");
        let vdom = doc.to_virtual_dom();

        // The ulist div should match .ulist.
        let ulist_divs = query_css(&vdom, "div.ulist");
        assert_eq!(ulist_divs.len(), 1, "Should find 1 .ulist div");

        // Find divs that have the .ulist class - :not(.ulist) should exclude them.
        let ulist_with_not = query_css(&vdom, ".ulist:not(.olist)");
        assert_eq!(
            ulist_with_not.len(),
            1,
            "Should find 1 .ulist that is not .olist"
        );

        // Test that :not() properly excludes matching elements.
        let excluded = query_css(&vdom, "div:not(.nonexistent)");
        assert!(
            !excluded.is_empty(),
            "Should find divs that don't have .nonexistent class"
        );
    }
}