html5-parser 0.1.0

A pure-Rust WHATWG HTML5 tokenizer and tree-construction implementation
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
// Tree/node model produced by tree_builder — element/text/comment/
// processing-instruction/doctype nodes with expanded names and per-node
// source positions.
//
// Shaped as a classic arena tree (`NonZeroU32` node ids, doubly-linked
// sibling lists), structurally close enough to the tree API
// `html-conform`'s existing `src/infoset.rs::normalize()` already adapts
// (currently written against its current HTML5-parsing dependency's tree
// shape) that switching `normalize()` over to this crate should need only
// modest changes. See plan/03-tree-construction.md, "Zieldatenmodell".

use std::num::NonZeroU32;

use crate::tokenizer::{Attribute as TokenAttribute, Position};

/// Identifies a node within a [`Document`]'s arena. `NonZeroU32` so that
/// `Option<NodeId>` is the same size as `NodeId` — index 0 is never
/// issued.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeId(NonZeroU32);

impl NodeId {
    fn from_index(index: usize) -> Self {
        Self(
            NonZeroU32::new(u32::try_from(index).expect("node arena index overflowed u32"))
                .expect("node arena index must be nonzero"),
        )
    }

    fn index(self) -> usize {
        self.0.get() as usize
    }
}

/// An HTML attribute, resolved to its (possibly foreign-content-adjusted)
/// namespace during tree construction — see plan/03-tree-construction.md's
/// Foreign-Content-Dispatch step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attribute {
    pub name: String,
    pub value: String,
    pub namespace: Option<String>,
}

impl From<TokenAttribute> for Attribute {
    /// Attributes arrive off the tokenizer with no namespace at all
    /// (`namespace: None`) — HTML tag/attribute parsing itself is
    /// namespace-unaware, per §13.2.5. Namespace resolution (XHTML
    /// default, or the foreign-content adjustment tables for SVG/MathML
    /// attributes like `xlink:href`) is tree-construction's job, applied
    /// on top of this conversion, not part of it.
    fn from(attribute: TokenAttribute) -> Self {
        Attribute {
            name: attribute.name,
            value: attribute.value,
            namespace: None,
        }
    }
}

/// The kind of a document node and its associated data. Mostly covers
/// what the HTML5 tokenizer can actually produce a token for (§13.2.5's
/// token kinds) — no `CData`/`EntityRef` variants, since the HTML5
/// tokenizer never emits those (character references and CDATA content
/// both resolve straight to character tokens, see
/// `tokenizer::TokenKind`'s doc comment). [`DocumentFragment`](Self::DocumentFragment)
/// is the one exception: not tokenizer-token-shaped at all, synthesized
/// directly by tree construction (§13.2.6.1's "create an element for a
/// token" step, for `template` elements specifically).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeKind {
    /// The document node — there is exactly one per [`Document`].
    Document,
    /// An element node, e.g. `<div class="x">`.
    Element {
        name: String,
        namespace: Option<String>,
        attributes: Vec<Attribute>,
    },
    /// A text node.
    Text { content: String },
    /// A comment node.
    Comment { content: String },
    /// A processing instruction node, e.g. `<?target data?>`. Every
    /// insertion mode's token dispatch has an explicit "processing
    /// instruction token" branch (verified against the raw spec text,
    /// not assumed) that inserts one of these — `html-conform`'s
    /// `normalize()` drops it afterwards, but tree-construction still
    /// puts it in the tree, so the node kind exists here too.
    ProcessingInstruction { target: String, data: String },
    /// A DOCUMENT TYPE node, e.g. `<!DOCTYPE html>`. Also dropped by
    /// `html-conform::normalize()`, but inserted into the tree by the
    /// "initial" insertion mode per spec, same reasoning as above.
    Doctype {
        name: Option<String>,
        public_identifier: Option<String>,
        system_identifier: Option<String>,
    },
    /// A `template` element's "template contents" — an inert fragment
    /// root that real content inserted "inside" a `template` element
    /// actually lands in, per §13.2.6.1's "appropriate place for
    /// inserting a node". Modeled here as the template element's sole
    /// real tree child (created alongside it, see
    /// `tree_builder.rs::create_element_for_token`), since `Document`
    /// has no separate out-of-tree fragment concept — matching how
    /// html5lib-tests' own `#document` dump format represents it (a
    /// synthetic `content` line, with the real children nested one
    /// level below that).
    DocumentFragment,
}

/// A single node in a [`Document`]'s arena: its kind/payload, its source
/// position (`None` for the document node itself and for any node a
/// tree-construction algorithm synthesizes rather than parses — e.g. an
/// implied `<html>`/`<head>`/`<body>` — `Some` for everything else), and
/// its tree-navigation links.
#[derive(Debug, Clone)]
pub struct Node {
    pub kind: NodeKind,
    /// The node's position in the original input, or `None` for
    /// synthesized nodes (see the struct-level doc comment above).
    pub position: Option<Position>,
    parent: Option<NodeId>,
    first_child: Option<NodeId>,
    last_child: Option<NodeId>,
    next_sibling: Option<NodeId>,
    prev_sibling: Option<NodeId>,
}

impl Node {
    fn new(kind: NodeKind, position: Option<Position>) -> Self {
        Node {
            kind,
            position,
            parent: None,
            first_child: None,
            last_child: None,
            next_sibling: None,
            prev_sibling: None,
        }
    }
}

/// An HTML document tree, produced by [`crate::parse`].
///
/// Read access (`root`/`node`/`parent`/`children`) is the public surface:
/// enough to walk the tree and read each node's kind and source position.
/// Mutation (`new_node`/`append_child`/...) stays crate-internal — it's
/// `tree_builder`'s job to build the tree in the first place, following
/// the spec-level insertion algorithms ("insert a comment", "insert an
/// HTML element", table foster parenting, ...), see
/// plan/03-tree-construction.md's "gemeinsame
/// Tree-Construction-Infrastruktur" step.
#[derive(Debug)]
pub struct Document {
    nodes: Vec<Node>,
    root: NodeId,
}

impl Document {
    /// Creates a new document containing only its own [`Document`] node
    /// (index 1 — index 0 is an unused placeholder, so `NodeId`'s
    /// `NonZeroU32` never has to represent zero).
    pub(crate) fn new() -> Self {
        let placeholder = Node::new(NodeKind::Document, None);
        let root_node = Node::new(NodeKind::Document, None);
        Document {
            nodes: vec![placeholder, root_node],
            root: NodeId::from_index(1),
        }
    }

    /// Returns the id of the document's own root node (the [`NodeKind::Document`] node).
    pub fn root(&self) -> NodeId {
        self.root
    }

    /// Returns the node identified by `id`: its kind, source position, and
    /// tree-navigation links (via [`Document::parent`]/[`Document::children`]).
    pub fn node(&self, id: NodeId) -> &Node {
        &self.nodes[id.index()]
    }

    /// Mutable access to a node — used by `tree_builder` to append to an
    /// existing text node's content ("insert a character", §13.2.6.1)
    /// rather than always creating a new one.
    pub(crate) fn node_mut(&mut self, id: NodeId) -> &mut Node {
        &mut self.nodes[id.index()]
    }

    /// Returns `id`'s parent node, or `None` if `id` is the document's
    /// own root node.
    pub fn parent(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).parent
    }

    pub(crate) fn last_child(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).last_child
    }

    pub(crate) fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).prev_sibling
    }

    /// Creates a new, detached node and returns its id. Callers attach it
    /// into the tree via [`append_child`](Self::append_child).
    pub(crate) fn new_node(&mut self, kind: NodeKind, position: Option<Position>) -> NodeId {
        self.nodes.push(Node::new(kind, position));
        NodeId::from_index(self.nodes.len() - 1)
    }

    /// "Clone a node", with `subtree` implicitly always `true` (the only
    /// case this crate needs — `<selectedcontent>`'s option-content
    /// mirroring, see `tree_builder.rs::maybe_clone_option_into_selectedcontent`).
    /// Returns a new, detached node with the same kind as `source` (and,
    /// recursively, the same for its descendants) — a full, independent
    /// copy, not sharing any state with the original. No source
    /// position (a clone has no position of its own, same convention as
    /// any other synthesized node). Simplified from the DOM Standard's
    /// "clone" algorithm: no custom-element callbacks, no
    /// registered-observer copying, no `Document`/shadow-root special
    /// cases — none apply without a live, scripted DOM.
    pub(crate) fn clone_subtree(&mut self, source: NodeId) -> NodeId {
        let kind = self.node(source).kind.clone();
        let clone = self.new_node(kind, None);
        let children: Vec<_> = self.children(source).collect();
        for child in children {
            let child_clone = self.clone_subtree(child);
            self.append_child(clone, child_clone);
        }
        clone
    }

    /// Detaches `node` from its current parent and siblings, if any — a
    /// no-op if it has none. The node itself stays in the arena (nothing
    /// is ever freed); it can be reinserted elsewhere afterward via
    /// [`insert_before`](Self::insert_before)/[`append_child`](Self::append_child).
    ///
    /// This is the DOM Standard's "remove" primitive
    /// (<https://dom.spec.whatwg.org/#concept-node-remove>), simplified
    /// to the tree-shape bookkeeping this crate tracks (no live
    /// ranges/mutation records/shadow DOM). Needed once tree-construction
    /// actually relocates already-inserted nodes — first by the adoption
    /// agency algorithm (§13.2.6.4.7) — rather than only ever inserting
    /// freshly created ones.
    pub(crate) fn remove(&mut self, node: NodeId) {
        let Some(parent) = self.node(node).parent else {
            return;
        };
        let previous_sibling = self.node(node).prev_sibling;
        let next_sibling = self.node(node).next_sibling;
        match previous_sibling {
            Some(previous_sibling) => {
                self.nodes[previous_sibling.index()].next_sibling = next_sibling;
            }
            None => self.nodes[parent.index()].first_child = next_sibling,
        }
        match next_sibling {
            Some(next_sibling) => {
                self.nodes[next_sibling.index()].prev_sibling = previous_sibling;
            }
            None => self.nodes[parent.index()].last_child = previous_sibling,
        }
        let node = &mut self.nodes[node.index()];
        node.parent = None;
        node.prev_sibling = None;
        node.next_sibling = None;
    }

    /// True if `ancestor` is `node` itself or one of its ancestors —
    /// the DOM Standard's "(inclusive) ancestor" relation
    /// (<https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor>),
    /// minus the "host-including" shadow-DOM extension (this crate has
    /// no shadow DOM). Used by the adoption agency algorithm's insertion
    /// guard (§13.2.6.4.7) to avoid creating a cycle.
    pub(crate) fn is_inclusive_ancestor(&self, ancestor: NodeId, node: NodeId) -> bool {
        let mut current = Some(node);
        while let Some(current_node) = current {
            if current_node == ancestor {
                return true;
            }
            current = self.node(current_node).parent;
        }
        false
    }

    /// Inserts `new_node` as a child of `parent`, immediately before
    /// `reference` — or, if `reference` is `None`, as the last child.
    /// If `new_node` is already attached elsewhere, it is
    /// [`remove`](Self::remove)d first — matching the DOM Standard's
    /// "insert" algorithm, whose per-node "adopt" step does the same
    /// (<https://dom.spec.whatwg.org/#concept-node-insert>: "Adopt node
    /// into parent's node document", and adopt: "If node's parent is
    /// non-null, then remove node."). `reference`, if given, must
    /// already be a child of `parent`.
    ///
    /// This is the one primitive tree-construction's insertion algorithms
    /// build on, both for the common "append as the last child of the
    /// current node" path (`reference: None`) and the less common
    /// mid-list cases (e.g. table foster parenting inserting before the
    /// table itself, or the adoption agency algorithm relocating
    /// already-inserted nodes).
    pub(crate) fn insert_before(
        &mut self,
        parent: NodeId,
        reference: Option<NodeId>,
        new_node: NodeId,
    ) {
        self.remove(new_node);
        match reference {
            None => {
                let previous_last_child = self.node(parent).last_child;
                self.nodes[new_node.index()].parent = Some(parent);
                self.nodes[new_node.index()].prev_sibling = previous_last_child;
                if let Some(previous_last_child) = previous_last_child {
                    self.nodes[previous_last_child.index()].next_sibling = Some(new_node);
                } else {
                    self.nodes[parent.index()].first_child = Some(new_node);
                }
                self.nodes[parent.index()].last_child = Some(new_node);
            }
            Some(reference) => {
                debug_assert_eq!(
                    self.node(reference).parent,
                    Some(parent),
                    "insert_before's reference node must already be a child of parent"
                );
                let previous_sibling = self.node(reference).prev_sibling;
                self.nodes[new_node.index()].parent = Some(parent);
                self.nodes[new_node.index()].next_sibling = Some(reference);
                self.nodes[new_node.index()].prev_sibling = previous_sibling;
                self.nodes[reference.index()].prev_sibling = Some(new_node);
                if let Some(previous_sibling) = previous_sibling {
                    self.nodes[previous_sibling.index()].next_sibling = Some(new_node);
                } else {
                    self.nodes[parent.index()].first_child = Some(new_node);
                }
            }
        }
    }

    /// Appends `child` as the last child of `parent`. Shorthand for
    /// [`insert_before`](Self::insert_before) with `reference: None`.
    pub(crate) fn append_child(&mut self, parent: NodeId, child: NodeId) {
        self.insert_before(parent, None, child);
    }

    /// Returns an iterator over the direct children of `id`, in document
    /// order.
    pub fn children(&self, id: NodeId) -> Children<'_> {
        Children {
            document: self,
            next: self.node(id).first_child,
        }
    }
}

impl Default for Document {
    fn default() -> Self {
        Self::new()
    }
}

/// Iterator over a node's direct children, in document order. Created by
/// [`Document::children`].
pub struct Children<'a> {
    document: &'a Document,
    next: Option<NodeId>,
}

impl Iterator for Children<'_> {
    type Item = NodeId;

    fn next(&mut self) -> Option<NodeId> {
        let current = self.next?;
        self.next = self.document.node(current).next_sibling;
        Some(current)
    }
}

#[cfg(test)]
mod tests {
    use super::{Document, NodeKind, Position};

    fn pos(line: u32, column: u32, byte_offset: usize) -> Position {
        Position {
            line,
            column,
            byte_offset,
        }
    }

    #[test]
    fn new_document_has_only_its_own_document_node() {
        let document = Document::new();
        assert_eq!(document.node(document.root()).kind, NodeKind::Document);
        assert_eq!(document.children(document.root()).count(), 0);
        assert_eq!(document.node(document.root()).position, None);
    }

    #[test]
    fn append_child_attaches_a_detached_node_as_the_last_child() {
        let mut document = Document::new();
        let root = document.root();
        let p = document.new_node(
            NodeKind::Element {
                name: "p".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            Some(pos(1, 1, 0)),
        );
        document.append_child(root, p);

        let children: Vec<_> = document.children(root).collect();
        assert_eq!(children, vec![p]);
        assert_eq!(document.parent(p), Some(root));
    }

    #[test]
    fn multiple_children_are_yielded_in_document_order() {
        let mut document = Document::new();
        let root = document.root();
        let first = document.new_node(
            NodeKind::Text {
                content: "a".to_owned(),
            },
            None,
        );
        let second = document.new_node(
            NodeKind::Text {
                content: "b".to_owned(),
            },
            None,
        );
        let third = document.new_node(
            NodeKind::Text {
                content: "c".to_owned(),
            },
            None,
        );
        document.append_child(root, first);
        document.append_child(root, second);
        document.append_child(root, third);

        let children: Vec<_> = document.children(root).collect();
        assert_eq!(children, vec![first, second, third]);
    }

    #[test]
    fn insert_before_a_reference_places_the_new_node_in_the_middle() {
        let mut document = Document::new();
        let root = document.root();
        let first = document.new_node(
            NodeKind::Text {
                content: "a".to_owned(),
            },
            None,
        );
        let third = document.new_node(
            NodeKind::Text {
                content: "c".to_owned(),
            },
            None,
        );
        document.append_child(root, first);
        document.append_child(root, third);
        let second = document.new_node(
            NodeKind::Text {
                content: "b".to_owned(),
            },
            None,
        );
        document.insert_before(root, Some(third), second);

        let children: Vec<_> = document.children(root).collect();
        assert_eq!(children, vec![first, second, third]);
    }

    #[test]
    fn insert_before_at_the_start_updates_first_child() {
        let mut document = Document::new();
        let root = document.root();
        let second = document.new_node(
            NodeKind::Text {
                content: "b".to_owned(),
            },
            None,
        );
        document.append_child(root, second);
        let first = document.new_node(
            NodeKind::Text {
                content: "a".to_owned(),
            },
            None,
        );
        document.insert_before(root, Some(second), first);

        let children: Vec<_> = document.children(root).collect();
        assert_eq!(children, vec![first, second]);
    }

    #[test]
    fn nested_children_are_independent_of_their_parents_siblings() {
        let mut document = Document::new();
        let root = document.root();
        let div = document.new_node(
            NodeKind::Element {
                name: "div".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            Some(pos(1, 1, 0)),
        );
        document.append_child(root, div);
        let text = document.new_node(
            NodeKind::Text {
                content: "hi".to_owned(),
            },
            Some(pos(1, 6, 5)),
        );
        document.append_child(div, text);

        assert_eq!(document.children(root).collect::<Vec<_>>(), vec![div]);
        assert_eq!(document.children(div).collect::<Vec<_>>(), vec![text]);
        assert_eq!(document.parent(text), Some(div));
    }

    #[test]
    fn synthesized_nodes_carry_no_position_while_parsed_nodes_do() {
        let mut document = Document::new();
        let root = document.root();
        let implied_html = document.new_node(
            NodeKind::Element {
                name: "html".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            None,
        );
        document.append_child(root, implied_html);
        let parsed_p = document.new_node(
            NodeKind::Element {
                name: "p".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            Some(pos(1, 1, 0)),
        );
        document.append_child(implied_html, parsed_p);

        assert_eq!(document.node(implied_html).position, None);
        assert_eq!(document.node(parsed_p).position, Some(pos(1, 1, 0)));
    }

    #[test]
    fn remove_detaches_a_node_and_relinks_its_siblings() {
        let mut document = Document::new();
        let root = document.root();
        let first = document.new_node(
            NodeKind::Text {
                content: "a".to_owned(),
            },
            None,
        );
        let second = document.new_node(
            NodeKind::Text {
                content: "b".to_owned(),
            },
            None,
        );
        let third = document.new_node(
            NodeKind::Text {
                content: "c".to_owned(),
            },
            None,
        );
        document.append_child(root, first);
        document.append_child(root, second);
        document.append_child(root, third);

        document.remove(second);

        assert_eq!(
            document.children(root).collect::<Vec<_>>(),
            vec![first, third]
        );
        assert_eq!(document.parent(second), None);
    }

    #[test]
    fn remove_on_a_node_with_no_parent_is_a_no_op() {
        let mut document = Document::new();
        let detached = document.new_node(
            NodeKind::Text {
                content: "a".to_owned(),
            },
            None,
        );
        document.remove(detached);
        assert_eq!(document.parent(detached), None);
    }

    #[test]
    fn insert_before_an_already_attached_node_moves_it() {
        // Matches the DOM Standard's "insert" algorithm, whose "adopt"
        // step removes a node from its old parent before placing it in
        // the new location — exercised for the first time by the
        // adoption agency algorithm (§13.2.6.4.7), which relocates
        // already-inserted nodes rather than only ever inserting fresh
        // ones.
        let mut document = Document::new();
        let root = document.root();
        let old_parent = document.new_node(
            NodeKind::Element {
                name: "div".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            None,
        );
        let new_parent = document.new_node(
            NodeKind::Element {
                name: "span".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            None,
        );
        document.append_child(root, old_parent);
        document.append_child(root, new_parent);
        let child = document.new_node(
            NodeKind::Text {
                content: "hi".to_owned(),
            },
            None,
        );
        document.append_child(old_parent, child);

        document.append_child(new_parent, child);

        assert_eq!(document.children(old_parent).count(), 0);
        assert_eq!(
            document.children(new_parent).collect::<Vec<_>>(),
            vec![child]
        );
        assert_eq!(document.parent(child), Some(new_parent));
    }

    #[test]
    fn is_inclusive_ancestor_covers_self_and_real_ancestors_but_not_others() {
        let mut document = Document::new();
        let root = document.root();
        let div = document.new_node(
            NodeKind::Element {
                name: "div".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            None,
        );
        document.append_child(root, div);
        let span = document.new_node(
            NodeKind::Element {
                name: "span".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            None,
        );
        document.append_child(div, span);
        let unrelated = document.new_node(
            NodeKind::Text {
                content: "x".to_owned(),
            },
            None,
        );
        document.append_child(root, unrelated);

        assert!(document.is_inclusive_ancestor(span, span));
        assert!(document.is_inclusive_ancestor(div, span));
        assert!(document.is_inclusive_ancestor(root, span));
        assert!(!document.is_inclusive_ancestor(unrelated, span));
        assert!(!document.is_inclusive_ancestor(span, div));
    }

    #[test]
    fn clone_subtree_deep_copies_kind_and_structure_into_new_nodes() {
        let mut document = Document::new();
        let root = document.root();
        let original = document.new_node(
            NodeKind::Element {
                name: "b".to_owned(),
                namespace: Some("http://www.w3.org/1999/xhtml".to_owned()),
                attributes: vec![],
            },
            Some(pos(1, 1, 0)),
        );
        document.append_child(root, original);
        let text = document.new_node(
            NodeKind::Text {
                content: "hi".to_owned(),
            },
            Some(pos(1, 4, 3)),
        );
        document.append_child(original, text);

        let clone = document.clone_subtree(original);

        assert_ne!(clone, original);
        assert_eq!(document.node(clone).kind, document.node(original).kind);
        // The clone is detached — the caller decides where it goes.
        assert_eq!(document.parent(clone), None);
        let clone_children: Vec<_> = document.children(clone).collect();
        assert_eq!(clone_children.len(), 1);
        assert_ne!(clone_children[0], text);
        assert_eq!(
            document.node(clone_children[0]).kind,
            NodeKind::Text {
                content: "hi".to_owned()
            }
        );
        // A clone carries no position of its own.
        assert_eq!(document.node(clone).position, None);
        // The original is untouched.
        assert_eq!(document.children(original).collect::<Vec<_>>(), vec![text]);
    }
}