parsec-html-core 0.1.0

The core of parsec-html: an HTML parser that follows the WHATWG spec, with CSS selectors and a mutable DOM. Depend on parsec-html.
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 James Conway

//! Changing a parsed document: new nodes, moves, removals and attributes.
//! A removed node stays in the document's arena, detached, and can be
//! inserted again.
//!
//! A shadow root is edited as a template's contents are: nodes go in and
//! out of it like any parent, but it's never anyone's child
//! ([`EditError::NotInsertable`]), and a host can't go into its own shadow
//! tree ([`EditError::Cycle`]). A host keeps its shadow root when it's
//! removed, moved or renamed, as an element keeps it in the DOM; a root
//! is made with [`Document::attach_shadow`] and never taken away.

use crate::dom::{Attr, AttrNs, Data, Document, Element, NONE, Name, NodeId, Ns, Span};
use crate::tags::Tag;

/// Why an edit was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditError {
    /// The node would end up inside itself.
    Cycle,
    /// The parent can't have children: text, a comment, a doctype or a
    /// processing instruction.
    NotAParent,
    /// `before` isn't a child of the parent.
    NotAChild,
    /// The node is a document, a fragment or a shadow root, such as the
    /// root or a template's contents, which is never anyone's child.
    NotInsertable,
    /// A node was taken out with [`Document::remove`], so it can't be used
    /// again. [`Document::detach`] takes one out to move it.
    Removed,
    /// The element can't have a shadow root: it already has one, or it
    /// isn't an HTML element that may (`div`, `span`, `section`, a
    /// custom element...).
    NotAShadowHost,
}

impl std::fmt::Display for EditError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            EditError::Cycle => "a node can't be inserted into itself or its descendants",
            EditError::NotAParent => "only an element, a document or a fragment can have children",
            EditError::NotAChild => "the node to insert before isn't a child of the parent",
            EditError::NotInsertable => {
                "a document, fragment or shadow root can't be inserted, only its children"
            }
            EditError::Removed => {
                "the node was removed from its document, so it can't be used again"
            }
            EditError::NotAShadowHost => "the element can't have a shadow root, or has one",
        })
    }
}

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

impl Document {
    /// A new element, not yet in the tree. HTML names are lowercased, as
    /// `createElement` does.
    pub fn create_element(&mut self, ns: Ns, name: &str) -> NodeId {
        let (tag, name) = self.name_element(ns, name);
        let at = self.attrs.len() as u32;
        let contents = if ns == Ns::Html && tag == Tag::Template {
            self.add(Data::Fragment)
        } else {
            NONE
        };
        let id = self.add(Data::Element(Element {
            ns,
            tag,
            name,
            attrs: Span { start: at, end: at },
            contents,
            html_integration: false,
        }));
        if contents != NONE
            && let Some(hosts) = &mut self.hosts
        {
            hosts.insert(contents, id);
        }
        id
    }

    pub fn create_text(&mut self, text: &str) -> NodeId {
        let span = self.push_stable(text);
        self.add(Data::Text(span))
    }

    pub fn create_cdata(&mut self, text: &str) -> NodeId {
        let span = self.push_stable(text);
        self.add(Data::Cdata(span))
    }

    pub fn create_comment(&mut self, text: &str) -> NodeId {
        let span = self.push_stable(text);
        self.add(Data::Comment(span))
    }

    pub fn create_processing_instruction(&mut self, target: &str, data: &str) -> NodeId {
        let target = self.push_stable(target);
        let data = self.push_stable(data);
        self.add(Data::ProcessingInstruction { target, data })
    }

    pub fn create_doctype(&mut self, name: &str, public_id: &str, system_id: &str) -> NodeId {
        let name = self.push_stable(name);
        let public_id = self.push_stable(public_id);
        let system_id = self.push_stable(system_id);
        self.add(Data::Doctype {
            name,
            public_id,
            system_id,
        })
    }

    /// Moves `child` to be the last child of `parent`.
    pub fn append(&mut self, parent: NodeId, child: NodeId) -> Result<(), EditError> {
        self.insert_before(parent, child, None)
    }

    /// Moves `child` into `parent`, before `before`, or last for `None`.
    pub fn insert_before(
        &mut self,
        parent: NodeId,
        child: NodeId,
        before: Option<NodeId>,
    ) -> Result<(), EditError> {
        if self.is_removed(parent)
            || self.is_removed(child)
            || before.is_some_and(|b| self.is_removed(b))
        {
            return Err(EditError::Removed);
        }
        if !matches!(
            self.nodes[parent as usize].data,
            Data::Element(_) | Data::Document | Data::Fragment | Data::ShadowRoot { .. }
        ) {
            return Err(EditError::NotAParent);
        }
        // As the DOM's pre-insertion check: the root, or a template's
        // contents, would otherwise end up under a detached element.
        if matches!(
            self.nodes[child as usize].data,
            Data::Document | Data::Fragment | Data::ShadowRoot { .. }
        ) {
            return Err(EditError::NotInsertable);
        }
        if let Some(b) = before
            && self.parent(b) != Some(parent)
        {
            return Err(EditError::NotAChild);
        }
        // Up through the parents, and out of a template's contents to the
        // template and out of a shadow root to its host: serializing goes
        // down into both, so a template put in its own contents, or a host
        // in its own shadow tree, would never end.
        let mut at = Some(parent);
        while let Some(a) = at {
            if a == child {
                return Err(EditError::Cycle);
            }
            at = self.parent(a).or_else(|| self.host(a));
        }
        if before == Some(child) {
            return Ok(());
        }
        self.detach(child);
        self.insert(parent, child, before.unwrap_or(NONE));
        Ok(())
    }

    /// The template whose contents `fragment` is, if it's any's. The map
    /// is built once, then kept as edits add and rename templates, so a
    /// run of inserts into contents stays linear.
    fn host(&mut self, fragment: NodeId) -> Option<NodeId> {
        if let Data::ShadowRoot { host, .. } = self.nodes[fragment as usize].data {
            return Some(host);
        }
        if !matches!(self.nodes[fragment as usize].data, Data::Fragment) {
            return None;
        }
        let nodes = &self.nodes;
        self.hosts
            .get_or_insert_with(|| {
                (0..nodes.len() as NodeId)
                    .filter_map(|id| match nodes[id as usize].data {
                        Data::Element(e) if e.contents != NONE => Some((e.contents, id)),
                        _ => None,
                    })
                    .collect()
            })
            .get(&fragment)
            .copied()
            .inspect(|&t| {
                debug_assert!(
                    self.element(t).is_some_and(|e| e.contents == fragment),
                    "the hosts map says {t} holds {fragment}, which it doesn't"
                )
            })
    }

    /// Moves every template's contents in under the template element
    /// itself, as lxml and Beautiful Soup show them and scrapers expect:
    /// selectors and walks then see them. The contents are left empty.
    pub fn adopt_template_contents(&mut self) {
        for id in 0..self.nodes.len() as NodeId {
            let Data::Element(e) = self.nodes[id as usize].data else {
                continue;
            };
            if e.ns != Ns::Html || e.tag != Tag::Template || e.contents == NONE {
                continue;
            }
            if self.is_removed(id) {
                continue;
            }
            while let Some(child) = self.first_child(e.contents) {
                self.detach(child);
                self.insert(id, child, NONE);
            }
        }
    }

    /// Takes `id`, and everything in it, out of the document for good. From
    /// then on each of their ids reads as nothing (see
    /// [`Document::is_removed`]), editing one does nothing, and inserting
    /// one, or anything into one, is [`EditError::Removed`]. A template's
    /// contents go with it, and so does a shadow host's shadow tree. To move
    /// a node, take it out with [`Document::detach`] and insert it again.
    /// The root, a template's contents or a shadow root on its own can't be
    /// removed: they're never anyone's child.
    pub fn remove(&mut self, id: NodeId) {
        if matches!(
            self.nodes[id as usize].data,
            Data::Document | Data::Fragment | Data::ShadowRoot { .. }
        ) || self.is_removed(id)
        {
            return;
        }
        self.detach(id);
        // By the links themselves: the readers say nothing of a node once
        // it's marked.
        let mut stack = vec![id];
        while let Some(n) = stack.pop() {
            self.mark_removed(n);
            let node = &self.nodes[n as usize];
            if let Data::Element(e) = &node.data
                && e.contents != NONE
            {
                stack.push(e.contents);
            }
            // A shadow host's shadow tree goes with it, by the map: the
            // reader says nothing once the host is marked.
            if let Some(&shadow) = self.shadow_roots.get(&n) {
                stack.push(shadow);
            }
            let mut c = node.first_child;
            while c != NONE {
                stack.push(c);
                c = self.nodes[c as usize].next;
            }
        }
    }

    /// Sets an attribute, replacing the first one of the same qualified name
    /// in any namespace (`xlink:href`), as `setAttribute` does. HTML
    /// elements' attribute names are lowercased; SVG's and MathML's keep the
    /// case they're given.
    /// A node taken out with [`Document::remove`] is left alone.
    pub fn set_attr(&mut self, id: NodeId, name: &str, value: &str) {
        if self.is_removed(id) {
            return;
        }
        let Some(e) = self.element(id) else { return };
        let ns = e.ns;
        let given = name;
        let name = stored_attr_name(ns, given);
        let value = self.push_stable(value);
        let name_span = self.push_stable(&name);
        self.rewrite_attrs(id, |doc, attrs| {
            // By qualified name in any namespace, as setAttribute does, so
            // xlink:href finds a parsed xlink:href and keeps its namespace;
            // on a foreign element by the name as written too, so viewBox
            // finds a parsed viewBox and no two are ever written alike.
            match attrs.iter_mut().find(|a| doc.is_attr(ns, a, &name, given)) {
                Some(a) => a.value = value,
                None => attrs.push(Attr {
                    ns: AttrNs::None,
                    name: name_span,
                    value,
                }),
            }
            true
        });
    }

    /// Adds an attribute as given, after the others, without replacing one
    /// of the same name: for building XML, where the caller has already
    /// checked names.
    /// A node taken out with [`Document::remove`] is left alone.
    pub fn add_attr(&mut self, id: NodeId, ns: AttrNs, name: &str, value: &str) {
        if self.is_removed(id) {
            return;
        }
        let name = self.push_stable(name);
        let value = self.push_stable(value);
        let attr = Attr { ns, name, value };
        let len = self.attrs.len() as u32;
        // An element whose attributes are the last in the list, as while
        // it's being built, grows in place: a clone sharing the range keeps
        // its own end, so it's unchanged. Anything else goes through a copy.
        if let Data::Element(e) = &mut self.nodes[id as usize].data
            && e.attrs.end == len
        {
            e.attrs.end += 1;
            self.attrs.push(attr);
            return;
        }
        self.rewrite_attrs(id, |_, attrs| {
            attrs.push(attr);
            true
        });
    }

    /// Replaces all of the element's attributes at once.
    /// A node taken out with [`Document::remove`] is left alone.
    pub fn set_attrs(&mut self, id: NodeId, attrs: &[(AttrNs, &str, &str)]) {
        if self.is_removed(id) {
            return;
        }
        if self.element(id).is_none() {
            return;
        }
        let start = self.attrs.len() as u32;
        for &(ns, name, value) in attrs {
            let name = self.push_stable(name);
            let value = self.push_stable(value);
            self.attrs.push(Attr { ns, name, value });
        }
        let end = self.attrs.len() as u32;
        if let Data::Element(e) = &mut self.nodes[id as usize].data {
            e.attrs = Span { start, end };
        }
    }

    /// Renames the element: lowercased for HTML, as given for the rest.
    /// An element renamed to `template` gets empty contents, as a new one
    /// does. A template renamed to anything else gives its contents up as
    /// ordinary children, ahead of any it has, so its markup stays the same
    /// and nothing in them is lost.
    /// A node taken out with [`Document::remove`] is left alone.
    pub fn rename(&mut self, id: NodeId, name: &str) {
        if self.is_removed(id) {
            return;
        }
        let Some(e) = self.element(id).copied() else {
            return;
        };
        let (tag, new) = self.name_element(e.ns, name);
        let template = e.ns == Ns::Html && tag == Tag::Template;
        let contents = if template && e.contents == NONE {
            let contents = self.add(Data::Fragment);
            if let Some(hosts) = &mut self.hosts {
                hosts.insert(contents, id);
            }
            contents
        } else if !template && e.contents != NONE {
            let first = self.first_child(id).unwrap_or(NONE);
            while let Some(child) = self.first_child(e.contents) {
                self.detach(child);
                self.insert(id, child, first);
            }
            if let Some(hosts) = &mut self.hosts {
                hosts.remove(&e.contents);
            }
            NONE
        } else {
            e.contents
        };
        if let Data::Element(e) = &mut self.nodes[id as usize].data {
            e.tag = tag;
            e.name = new;
            e.contents = contents;
        }
    }

    /// The tag and stored name of an element called `name` in `ns`. HTML
    /// names are lowercased; foreign ones keep their case.
    fn name_element(&mut self, ns: Ns, name: &str) -> (Tag, Name) {
        let lower = name.to_ascii_lowercase();
        match ns {
            Ns::Html => {
                let tag = Tag::from_name(&lower);
                let name = if tag == Tag::Other {
                    Name::Span(self.push_stable(&lower))
                } else {
                    Name::Tag
                };
                (tag, name)
            }
            // An XML element is never an HTML one, whatever its name.
            Ns::Xml => (Tag::Other, Name::Span(self.push_stable(name))),
            _ => {
                let tag = Tag::from_name(&lower);
                // SVG's mixed-case names, written as the spec writes them, are
                // stored as the parser stores them, so lower_name and the
                // markup agree with a parsed element's.
                if ns == Ns::Svg
                    && let Some(i) = crate::tree::svg_tag_name(&lower)
                    && crate::tree::SVG_TAG_NAMES[i as usize].1 == name
                {
                    return (tag, Name::Svg(i));
                }
                let name = if tag != Tag::Other && tag.name() == name {
                    Name::Tag
                } else {
                    Name::Span(self.push_stable(name))
                };
                (tag, name)
            }
        }
    }

    /// Renames the element's `index`th attribute, and sets its namespace.
    /// A node taken out with [`Document::remove`] is left alone.
    pub fn rename_attr(&mut self, id: NodeId, index: usize, ns: AttrNs, name: &str) {
        if self.is_removed(id) {
            return;
        }
        let name = self.push_stable(name);
        self.rewrite_attrs(id, |_, attrs| match attrs.get_mut(index) {
            Some(a) => {
                a.ns = ns;
                a.name = name;
                true
            }
            None => false,
        });
    }

    /// Removes the element's `index`th attribute; false if there's none.
    /// A node taken out with [`Document::remove`] is left alone, and gives
    /// false.
    pub fn remove_attr_at(&mut self, id: NodeId, index: usize) -> bool {
        if self.is_removed(id) {
            return false;
        }
        self.rewrite_attrs(id, |_, attrs| {
            if index < attrs.len() {
                attrs.remove(index);
                true
            } else {
                false
            }
        })
    }

    /// Removes an attribute by name; false if there wasn't one.
    /// A node taken out with [`Document::remove`] is left alone, and gives
    /// false.
    pub fn remove_attr(&mut self, id: NodeId, name: &str) -> bool {
        if self.is_removed(id) {
            return false;
        }
        let Some(e) = self.element(id) else {
            return false;
        };
        let (ns, given) = (e.ns, name);
        let name = stored_attr_name(ns, given);
        self.rewrite_attrs(id, |doc, attrs| {
            let before = attrs.len();
            attrs.retain(|a| !doc.is_attr(ns, a, &name, given));
            attrs.len() != before
        })
    }

    /// Whether `a`, on an element in `ns`, is the attribute code calls
    /// `given`, stored as `stored`: by the name as stored when it has no
    /// namespace (a namespaced one stores its local name), or on a foreign
    /// element by the name as written, so viewBox finds a parsed viewBox
    /// and no two attributes are ever written alike.
    fn is_attr(&self, ns: Ns, a: &Attr, stored: &str, given: &str) -> bool {
        (a.ns == AttrNs::None && self.str(a.name) == stored)
            || (ns != Ns::Html && self.written_name(ns, a) == given)
    }

    /// Changes an element's attributes through a copy at the end of the
    /// list, never in place: the parser's clones of a formatting element
    /// share their original's attributes.
    fn rewrite_attrs(
        &mut self,
        id: NodeId,
        change: impl FnOnce(&Document, &mut Vec<Attr>) -> bool,
    ) -> bool {
        let Some(e) = self.element(id) else {
            return false;
        };
        let mut attrs = self.attrs[e.attrs.start as usize..e.attrs.end as usize].to_vec();
        if !change(self, &mut attrs) {
            return false;
        }
        let start = self.attrs.len() as u32;
        self.attrs.extend(attrs);
        let end = self.attrs.len() as u32;
        if let Data::Element(e) = &mut self.nodes[id as usize].data {
            e.attrs = Span { start, end };
        }
        true
    }
}

/// An attribute name set from code, as the parser would store it: on an
/// HTML element lowercased, as `setAttribute` does. On SVG and MathML a
/// name whose case the writer puts back (viewBox, definitionURL) is
/// lowercased too, and any other keeps the case it's given, as does an XML
/// one.
fn stored_attr_name(ns: Ns, given: &str) -> String {
    let lower = given.to_ascii_lowercase();
    let restored = match ns {
        Ns::Html => true,
        Ns::Svg => crate::tree::svg_attr_name(&lower) == Some(given),
        Ns::MathMl => lower == "definitionurl" && given == "definitionURL",
        Ns::Xml => false,
    };
    if restored { lower } else { given.to_string() }
}

#[cfg(test)]
mod tests {
    use super::EditError;
    use crate::{NodeId, Ns, parse, parse_fragment};

    #[test]
    fn nodes_can_be_made_moved_and_removed() {
        let mut doc = parse_fragment("<p>a</p><p>b</p>", Ns::Html, "div", false);
        let (first, second) = {
            let mut c = doc.children(0);
            (c.next().unwrap(), c.next().unwrap())
        };
        let em = doc.create_element(Ns::Html, "EM");
        let t = doc.create_text("x & y");
        doc.append(em, t).unwrap();
        doc.insert_before(first, em, doc.first_child(first))
            .unwrap();
        assert_eq!(doc.inner_html(0), "<p><em>x &amp; y</em>a</p><p>b</p>");
        doc.append(second, em).unwrap();
        assert_eq!(doc.inner_html(0), "<p>a</p><p>b<em>x &amp; y</em></p>");
        doc.detach(second);
        assert_eq!(doc.inner_html(0), "<p>a</p>");
        doc.append(0, second).unwrap();
        assert_eq!(doc.inner_html(0), "<p>a</p><p>b<em>x &amp; y</em></p>");
    }

    /// Moves, removals, renames and new templates in a pseudo-random
    /// order, the whole tree checked after each.
    #[cfg(debug_assertions)]
    #[test]
    fn edits_keep_every_invariant() {
        let mut doc = parse(
            "<div><p>a<b>b</b></p><template><i>c</i></template><ul><li>d</ul></div>",
            false,
        );
        let mut seed: u32 = 0x2545_f491;
        let mut next = move |n: usize| {
            seed ^= seed << 13;
            seed ^= seed >> 17;
            seed ^= seed << 5;
            seed as usize % n
        };
        for i in 0..2000 {
            let n = doc.len();
            let (a, b) = (next(n) as NodeId, next(n) as NodeId);
            match next(6) {
                0 => {
                    let _ = doc.append(a, b);
                }
                1 => {
                    let before = doc.first_child(a);
                    let _ = doc.insert_before(a, b, before);
                }
                2 if i % 2 == 0 => doc.remove(b),
                2 => doc.detach(b),
                3 => doc.rename(a, if i % 2 == 0 { "template" } else { "span" }),
                4 => {
                    let t = doc.create_element(Ns::Html, "template");
                    let _ = doc.append(a, t);
                }
                _ => {
                    let t = doc.create_text("t");
                    let _ = doc.append(a, t);
                }
            }
            doc.check_tree();
        }
    }

    #[test]
    fn a_created_svg_element_is_named_as_a_parsed_one() {
        let parsed = parse_fragment("<svg><linearGradient/></svg>", Ns::Html, "div", false);
        let svg = parsed.children(parsed.root()).next().unwrap();
        let parsed_gradient = parsed.children(svg).next().unwrap();
        let mut doc = parse_fragment("", Ns::Html, "div", false);
        let made = doc.create_element(Ns::Svg, "linearGradient");
        assert_eq!(doc.lower_name(made), Some("lineargradient"));
        assert_eq!(doc.lower_name(made), parsed.lower_name(parsed_gradient));
        assert_eq!(doc.outer_html(made), parsed.outer_html(parsed_gradient));
        // Another case is another element, kept as written.
        let shouting = doc.create_element(Ns::Svg, "LINEARGRADIENT");
        assert_eq!(
            doc.outer_html(shouting),
            "<LINEARGRADIENT></LINEARGRADIENT>"
        );
    }

    #[test]
    fn a_document_or_fragment_is_never_inserted() {
        let mut doc = parse("<template><b>x</b></template><p>y</p>", false);
        let root = doc.root();
        let contents = (0..doc.len() as NodeId)
            .find_map(|n| doc.template_contents(n))
            .unwrap();
        let loose = doc.create_element(Ns::Html, "div");
        let before = doc.inner_html(root);
        assert_eq!(doc.append(loose, root), Err(EditError::NotInsertable));
        assert_eq!(doc.append(loose, contents), Err(EditError::NotInsertable));
        assert_eq!(
            doc.insert_before(loose, root, None),
            Err(EditError::NotInsertable)
        );
        assert_eq!(doc.inner_html(root), before);
        assert_eq!(doc.inner_html(loose), "");
        // Their children still go anywhere.
        let b = doc.first_child(contents).unwrap();
        assert_eq!(doc.append(loose, b), Ok(()));
        assert_eq!(doc.inner_html(loose), "<b>x</b>");
    }

    #[test]
    fn set_attr_replaces_a_namespaced_attribute_of_the_same_name() {
        let mut doc = parse_fragment(
            "<svg><use xlink:href=\"#a\"></use></svg>",
            Ns::Html,
            "div",
            false,
        );
        let svg = doc.children(doc.root()).next().unwrap();
        let used = doc.children(svg).next().unwrap();
        doc.set_attr(used, "xlink:href", "#b");
        assert_eq!(doc.outer_html(used), "<use xlink:href=\"#b\"></use>");
        let attrs: Vec<_> = doc.attrs(used).collect();
        assert_eq!(attrs, [(crate::AttrNs::XLink, "href", "#b")]);
        // A plain href is another attribute: its qualified name isn't xlink:href.
        assert!(!doc.remove_attr(used, "href"));
        doc.set_attr(used, "href", "#c");
        let attrs: Vec<_> = doc.attrs(used).collect();
        assert_eq!(
            attrs,
            [
                (crate::AttrNs::XLink, "href", "#b"),
                (crate::AttrNs::None, "href", "#c")
            ]
        );
        assert!(doc.remove_attr(used, "href"));
        let attrs: Vec<_> = doc.attrs(used).collect();
        assert_eq!(attrs, [(crate::AttrNs::XLink, "href", "#b")]);
    }

    #[test]
    fn set_attr_keeps_the_case_of_foreign_names() {
        let mut doc = parse_fragment(
            "<svg viewBox=\"0 0 1 1\"></svg><math definitionURL=\"a\"></math><p></p>",
            Ns::Html,
            "div",
            false,
        );
        let kids: Vec<_> = doc.children(doc.root()).collect();
        let (svg, math, p) = (kids[0], kids[1], kids[2]);
        doc.set_attr(svg, "dataFoo", "x");
        doc.set_attr(svg, "viewBox", "0 0 2 2");
        doc.set_attr(math, "mathVariant", "bold");
        doc.set_attr(math, "definitionURL", "b");
        doc.set_attr(p, "DATA-X", "y");
        assert_eq!(
            doc.outer_html(svg),
            "<svg viewBox=\"0 0 2 2\" dataFoo=\"x\"></svg>"
        );
        assert_eq!(
            doc.outer_html(math),
            "<math definitionURL=\"b\" mathVariant=\"bold\"></math>"
        );
        assert_eq!(doc.outer_html(p), "<p data-x=\"y\"></p>");
        // A lowercase viewbox finds the same attribute: never two written alike.
        doc.set_attr(svg, "viewbox", "0 0 3 3");
        assert_eq!(
            doc.outer_html(svg),
            "<svg viewBox=\"0 0 3 3\" dataFoo=\"x\"></svg>"
        );
        // And it's set again, not added, when the case matches what was given.
        doc.set_attr(svg, "dataFoo", "z");
        assert_eq!(
            doc.outer_html(svg),
            "<svg viewBox=\"0 0 3 3\" dataFoo=\"z\"></svg>"
        );
        // What set_attr sets, remove_attr finds by the same name.
        assert!(doc.remove_attr(svg, "dataFoo"));
        assert!(doc.remove_attr(svg, "viewBox"));
        assert!(doc.remove_attr(math, "mathVariant"));
        assert!(!doc.remove_attr(svg, "dataFoo"));
        assert_eq!(doc.outer_html(svg), "<svg></svg>");
        assert_eq!(doc.outer_html(math), "<math definitionURL=\"b\"></math>");
    }

    #[test]
    fn renaming_to_or_from_template_adds_or_gives_up_its_contents() {
        let mut doc = parse_fragment("<template><b>x</b>y</template>", Ns::Html, "div", false);
        let t = doc.first_child(doc.root()).unwrap();
        doc.rename(t, "div");
        assert_eq!(doc.template_contents(t), None);
        assert_eq!(doc.outer_html(t), "<div><b>x</b>y</div>");
        doc.rename(t, "template");
        let contents = doc.template_contents(t).expect("new contents");
        assert_eq!(doc.first_child(contents), None);
        assert_eq!(doc.outer_html(t), "<template><b>x</b>y</template>");
        // Contents go ahead of children a template already has, as written.
        let p = doc.create_element(Ns::Html, "p");
        doc.append(contents, p).unwrap();
        doc.rename(t, "section");
        assert_eq!(doc.outer_html(t), "<section><p></p><b>x</b>y</section>");
        // Renaming a template to template leaves its contents be.
        let u = doc.create_element(Ns::Html, "template");
        let kept = doc.template_contents(u);
        doc.rename(u, "TEMPLATE");
        assert_eq!(doc.template_contents(u), kept);
    }

    #[test]
    fn a_renamed_foreign_element_takes_its_new_names_tag() {
        let mut doc = parse_fragment("", Ns::Html, "div", false);
        let svg_title = doc.create_element(Ns::Svg, "title");
        let title_tag = doc.known_tag(svg_title);
        assert!(title_tag.is_some());
        let n = doc.create_element(Ns::Svg, "rect");
        doc.rename(n, "title");
        assert_eq!(doc.known_tag(n), title_tag);
        doc.rename(n, "rect");
        assert_eq!(doc.known_tag(n), None);
    }

    #[test]
    fn template_contents_can_become_children() {
        let mut doc = parse_fragment("<template><b>x</b></template>", Ns::Html, "div", false);
        let t = doc.first_child(0).unwrap();
        assert_eq!(doc.first_child(t), None);
        doc.adopt_template_contents();
        let b = doc.first_child(t).unwrap();
        assert_eq!(doc.outer_html(b), "<b>x</b>");
        // Written the same before and after.
        assert_eq!(doc.inner_html(0), "<template><b>x</b></template>");
    }

    /// Netweir reads strings through a shared borrow while an edit may
    /// run under its own lock, so a string an edit didn't touch must stay
    /// exactly where it was.
    #[test]
    fn edits_never_move_strings_already_read() {
        // Values with references: the parser copies those into its buffer,
        // the one place that could move.
        let mut doc = parse_fragment("<a href='x&amp;y'>t&amp;u</a>", Ns::Html, "div", false);
        let a = doc.first_child(0).unwrap();
        let text = doc.first_child(a).unwrap();
        let href = doc.attrs(a).next().unwrap().2.as_ptr();
        let data = match doc.kind(text) {
            crate::Kind::Text(t) => t.as_ptr(),
            _ => unreachable!(),
        };
        for i in 0..10_000 {
            let n = doc.create_element(Ns::Html, &format!("custom-{i}"));
            doc.set_attr(n, "data-long", &"y".repeat(100));
            let t = doc.create_text(&"z".repeat(100));
            doc.append(n, t).unwrap();
            doc.append(0, n).unwrap();
        }
        doc.set_attr(a, "title", "new");
        assert_eq!(doc.attrs(a).next().unwrap().2.as_ptr(), href);
        assert!(matches!(doc.kind(text), crate::Kind::Text(t) if t.as_ptr() == data));
    }

    #[test]
    fn xml_is_built_as_written_and_matched_as_netweir_did() {
        use crate::css::SelectorList;
        use crate::{AttrNs, Document};
        let mut doc = Document::empty();
        let feed = doc.create_element(Ns::Xml, "Feed");
        doc.append(0, feed).unwrap();
        let entry = doc.create_element(Ns::Xml, "dc:Creator");
        doc.add_attr(entry, AttrNs::None, "ID", "up");
        doc.add_attr(entry, AttrNs::None, "id", "lo");
        doc.add_attr(entry, AttrNs::Host(3), "x:href", "/p");
        doc.append(feed, entry).unwrap();
        let cdata = doc.create_cdata("<raw>");
        doc.append(entry, cdata).unwrap();
        let found = |css: &str| SelectorList::parse(css).unwrap().select(&doc, 0).len();
        assert_eq!(found("feed creator"), 1);
        assert_eq!(found("[id=lo]"), 1);
        assert_eq!(found("[id=up]"), 0);
        assert_eq!(found("#lo"), 1);
        assert_eq!(found("#up"), 0);
        assert_eq!(found("[href^='/']"), 1);
        assert_eq!(
            doc.outer_html(entry),
            "<dc:Creator ID=\"up\" id=\"lo\" x:href=\"/p\"><![CDATA[<raw>]]></dc:Creator>"
        );
        doc.rename(entry, "Creator");
        doc.rename_attr(entry, 2, AttrNs::None, "href");
        assert!(doc.remove_attr_at(entry, 0));
        assert_eq!(
            doc.outer_html(entry),
            "<Creator id=\"lo\" href=\"/p\"><![CDATA[<raw>]]></Creator>"
        );
    }

    #[test]
    fn a_node_cant_go_inside_itself() {
        let mut doc = parse_fragment("<div><span></span></div>", Ns::Html, "body", false);
        let div = doc.first_child(0).unwrap();
        let span = doc.first_child(div).unwrap();
        assert_eq!(doc.append(span, div), Err(EditError::Cycle));
        assert_eq!(doc.append(div, div), Err(EditError::Cycle));
        let text = doc.create_text("t");
        assert_eq!(doc.append(text, span), Err(EditError::NotAParent));
        assert_eq!(
            doc.insert_before(span, text, Some(div)),
            Err(EditError::NotAChild)
        );
    }

    #[test]
    fn a_template_cant_go_inside_its_own_contents() {
        let mut doc = parse_fragment(
            "<div><template><p></p></template></div>",
            Ns::Html,
            "body",
            false,
        );
        let div = doc.first_child(0).unwrap();
        let template = doc.first_child(div).unwrap();
        let contents = doc.template_contents(template).unwrap();
        let p = doc.first_child(contents).unwrap();
        assert_eq!(doc.append(contents, template), Err(EditError::Cycle));
        assert_eq!(doc.append(contents, div), Err(EditError::Cycle));
        assert_eq!(doc.insert_before(p, div, None), Err(EditError::Cycle));
        // Through a template made after the first check, two deep.
        let made = doc.create_element(Ns::Html, "template");
        doc.append(p, made).unwrap();
        let made_contents = doc.template_contents(made).unwrap();
        assert_eq!(doc.append(made_contents, div), Err(EditError::Cycle));
        // And one renamed into a template.
        let span = doc.create_element(Ns::Html, "span");
        doc.append(made_contents, span).unwrap();
        doc.rename(span, "template");
        let span_contents = doc.template_contents(span).unwrap();
        assert_eq!(doc.append(span_contents, template), Err(EditError::Cycle));
        // A template renamed away leaves contents nothing reaches.
        doc.rename(span, "section");
        doc.append(span_contents, template).unwrap();
        assert_eq!(doc.inner_html(0), "<div></div>");
        doc.append(div, template).unwrap();
        assert_eq!(
            doc.inner_html(0),
            "<div><template><p><template><section></section></template></p></template></div>"
        );
    }

    #[test]
    fn attributes_can_be_set_replaced_and_removed() {
        let mut doc = parse_fragment("<a href=x>a</a><a href=x>b</a>", Ns::Html, "div", false);
        let a = doc.first_child(0).unwrap();
        doc.set_attr(a, "HREF", "y");
        doc.set_attr(a, "title", "t");
        assert_eq!(doc.outer_html(a), "<a href=\"y\" title=\"t\">a</a>");
        assert!(doc.remove_attr(a, "href"));
        assert!(!doc.remove_attr(a, "href"));
        assert_eq!(doc.outer_html(a), "<a title=\"t\">a</a>");
        let b = doc.next_sibling(a).unwrap();
        assert_eq!(doc.outer_html(b), "<a href=\"x\">b</a>");
    }

    /// The parser's clones of a formatting element share its attributes
    /// until one of them is changed.
    #[test]
    fn changing_a_reconstructed_clone_leaves_the_original_alone() {
        let mut doc = parse_fragment("<p><b class=x>a</p>t", Ns::Html, "body", false);
        let p = doc.first_child(0).unwrap();
        let original = doc.first_child(p).unwrap();
        let clone = doc.next_sibling(p).unwrap();
        assert_eq!(doc.outer_html(clone), "<b class=\"x\">t</b>");
        doc.set_attr(clone, "class", "y");
        assert_eq!(doc.outer_html(original), "<b class=\"x\">a</b>");
        assert_eq!(doc.outer_html(clone), "<b class=\"y\">t</b>");
    }

    #[test]
    fn foreign_names_keep_their_case() {
        let mut doc = parse_fragment("<svg></svg>", Ns::Svg, "svg", false);
        let g = doc.create_element(Ns::Svg, "linearGradient");
        doc.set_attr(g, "gradientUnits", "u");
        doc.append(0, g).unwrap();
        assert!(
            doc.inner_html(0)
                .contains("<linearGradient gradientUnits=\"u\"></linearGradient>")
        );
    }

    /// The `<p id=a>` in `<div><p id=a>one <b>two</b></p><p id=b>three</p></div>`,
    /// its `<b>` and the `<b>`'s text.
    fn removable() -> (crate::Document, NodeId, NodeId, NodeId) {
        let doc = parse(
            "<div><p id=a>one <b>two</b></p><p id=b>three</p></div>",
            false,
        );
        let id = |name: &str| {
            (0..doc.len() as NodeId)
                .find(|&n| doc.lower_name(n) == Some(name))
                .unwrap()
        };
        let (p, b) = (id("p"), id("b"));
        let text = doc.first_child(b).unwrap();
        (doc, p, b, text)
    }

    #[test]
    fn a_removed_node_reads_as_nothing() {
        let (mut doc, p, _, _) = removable();
        let div = doc.parent(p).unwrap();
        doc.remove(p);
        assert!(doc.is_removed(p));
        assert_eq!(doc.outer_html(div), "<div><p id=\"b\">three</p></div>");
        assert_eq!(doc.parent(p), None);
        assert_eq!(doc.first_child(p), None);
        assert_eq!(doc.children(p).count(), 0);
        assert_eq!(doc.attrs(p).count(), 0);
        assert_eq!(doc.attrs_written(p).count(), 0);
        assert_eq!(doc.lower_name(p), None);
        assert_eq!(doc.known_tag(p), None);
        assert_eq!(doc.outer_html(p), "");
        assert_eq!(doc.inner_html(p), "");
        assert_eq!(doc.html_alone(p), "");
        assert_eq!(doc.text(p), "");
        // Its kind stays, an element's name with it.
        assert!(matches!(
            doc.kind(p),
            crate::Kind::Element { name: "p", .. }
        ));
        // Removing it again, or the root, does nothing.
        doc.remove(p);
        doc.remove(doc.root());
        assert!(!doc.is_removed(doc.root()));
    }

    #[test]
    fn a_removed_node_cant_be_edited_or_inserted() {
        let (mut doc, p, _, _) = removable();
        let div = doc.parent(p).unwrap();
        let other = doc.next_sibling(p).unwrap();
        doc.remove(p);
        assert_eq!(doc.append(div, p), Err(EditError::Removed));
        let fresh = doc.create_element(Ns::Html, "span");
        assert_eq!(doc.append(p, fresh), Err(EditError::Removed));
        assert_eq!(
            doc.insert_before(div, fresh, Some(p)),
            Err(EditError::Removed)
        );
        // The setters, which return nothing to fail with, do nothing.
        doc.set_attr(p, "class", "x");
        doc.rename(p, "section");
        assert!(!doc.remove_attr(p, "id"));
        assert_eq!(doc.attrs(p).count(), 0);
        assert!(matches!(
            doc.kind(p),
            crate::Kind::Element { name: "p", .. }
        ));
        // Nothing else was touched.
        doc.append(div, fresh).unwrap();
        assert_eq!(
            doc.outer_html(div),
            "<div><p id=\"b\">three</p><span></span></div>"
        );
        assert_eq!(doc.text(other), "three");
    }

    #[test]
    fn removing_a_parent_removes_what_it_holds() {
        let (mut doc, p, b, text) = removable();
        doc.remove(p);
        for n in [b, text] {
            assert!(doc.is_removed(n), "node {n}");
            assert_eq!(doc.parent(n), None);
            assert_eq!(doc.outer_html(n), "");
        }
        assert!(matches!(doc.kind(text), crate::Kind::Text("")));
        assert_eq!(doc.append(doc.root(), b), Err(EditError::Removed));
    }

    #[test]
    fn a_detached_node_can_be_inserted_again() {
        let (mut doc, p, b, _) = removable();
        let div = doc.parent(p).unwrap();
        doc.detach(p);
        assert!(!doc.is_removed(p));
        assert_eq!(doc.outer_html(div), "<div><p id=\"b\">three</p></div>");
        assert_eq!(doc.outer_html(p), "<p id=\"a\">one <b>two</b></p>");
        assert_eq!(doc.parent(b), Some(p));
        doc.append(div, p).unwrap();
        assert_eq!(
            doc.outer_html(div),
            "<div><p id=\"b\">three</p><p id=\"a\">one <b>two</b></p></div>"
        );
    }

    #[test]
    fn a_removed_templates_contents_go_with_it() {
        let mut doc = parse("<template><i>x</i></template>", false);
        let template = (0..doc.len() as NodeId)
            .find(|&n| doc.lower_name(n) == Some("template"))
            .unwrap();
        let contents = doc.template_contents(template).unwrap();
        let i = doc.first_child(contents).unwrap();
        doc.remove(template);
        assert!(doc.is_removed(contents) && doc.is_removed(i));
        assert_eq!(doc.template_contents(template), None);
        #[cfg(debug_assertions)]
        doc.check_tree();
    }

    #[test]
    fn a_removed_node_matches_no_selector() {
        let (mut doc, p, b, _) = removable();
        let list = crate::css::SelectorList::parse("p, b, #a").unwrap();
        assert!(list.matches(&doc, p, None));
        doc.remove(p);
        assert!(!list.matches(&doc, p, None));
        assert!(!list.matches(&doc, b, None));
        assert_eq!(list.select(&doc, p), Vec::<NodeId>::new());
        // From the root, only the paragraph that wasn't removed is left.
        let left = list.select(&doc, doc.root());
        assert_eq!(left.len(), 1);
        assert_eq!(doc.outer_html(left[0]), "<p id=\"b\">three</p>");
    }

    #[test]
    fn a_removed_hosts_shadow_tree_goes_with_it() {
        let mut doc = parse("<div id=host><span>light</span></div>", false);
        let host = (0..doc.len() as NodeId)
            .find(|&n| doc.lower_name(n) == Some("div"))
            .unwrap();
        let light = doc.first_child(host).unwrap();
        let shadow = doc.attach_shadow(host, crate::ShadowRoot::open()).unwrap();
        let slot = doc.create_element(Ns::Html, "slot");
        doc.append(shadow, slot).unwrap();
        assert_eq!(doc.assigned_nodes(slot), [light]);
        doc.remove(host);
        for n in [shadow, slot, light] {
            assert!(doc.is_removed(n), "node {n}");
        }
        assert_eq!(doc.shadow_root(host), None);
        assert_eq!(doc.shadow_host(shadow), None);
        assert_eq!(doc.assigned_nodes(slot), Vec::<NodeId>::new());
        assert_eq!(doc.flat_tree(host).count(), 0);
        assert_eq!(
            doc.attach_shadow(host, crate::ShadowRoot::open()),
            Err(EditError::Removed)
        );
        // A shadow root on its own isn't removed, like a template's contents.
        let mut doc = parse("<div></div>", false);
        let host = (0..doc.len() as NodeId)
            .find(|&n| doc.lower_name(n) == Some("div"))
            .unwrap();
        let shadow = doc.attach_shadow(host, crate::ShadowRoot::open()).unwrap();
        doc.remove(shadow);
        assert!(!doc.is_removed(shadow));
        assert_eq!(doc.shadow_root(host), Some(shadow));
        #[cfg(debug_assertions)]
        doc.check_tree();
    }
}