anyxml 0.9.1

A fully spec-conformant XML library
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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
use std::{
    cell::RefCell,
    rc::{Rc, Weak},
};

use crate::{
    XML_XML_NAMESPACE,
    tree::{
        Element, NodeType, XMLTreeError, compare_document_order,
        convert::NodeKind,
        document::{Document, DocumentSpec},
        document_fragment::DocumentFragmentSpec,
    },
    uri::URIString,
};

/// Common traits for node types.
///
/// This trait is not intended to be implemented by library users and should not be implemented.
pub trait NodeSpec: std::any::Any {
    /// Return the node type.
    ///
    /// For abstract node types, this method guarantees that conversion
    /// to the specified node type will always succeed.
    fn node_type(&self) -> NodeType;
    fn first_child(&self) -> Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>>;
    fn last_child(&self) -> Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>>;
}

/// Common traits of internal nodes (i.e., nodes that are not leaf nodes).
///
/// This trait is not intended to be implemented by library users and should not be implemented.
pub trait InternalNodeSpec: NodeSpec {
    fn set_first_child(&mut self, new: Rc<RefCell<NodeCore<dyn NodeSpec>>>);
    fn unset_first_child(&mut self);

    fn set_last_child(&mut self, new: Rc<RefCell<NodeCore<dyn NodeSpec>>>);
    fn unset_last_child(&mut self);

    fn pre_child_removal(&mut self, removed_child: Node<dyn NodeSpec>) -> Result<(), XMLTreeError> {
        let _ = removed_child;
        Ok(())
    }

    /// Perform preprocessing when `inserted_child` is inserted following `preceding_node`.
    ///
    /// If there is no preceding node (i.e., `inserted_child` is inserted as the first child),
    /// `preceding_node` is `None`.
    ///
    /// Only perform precondition checks; do not cause side effects.
    fn pre_child_insertion(
        &self,
        inserted_child: Node<dyn NodeSpec>,
        preceding_node: Option<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        let _ = (inserted_child, preceding_node);
        Ok(())
    }

    /// Perform postprocessing when `inserted_child` is inserted following `preceding_node`.
    ///
    /// If there is no preceding node (i.e., `inserted_child` is inserted as the first child),
    /// `preceding_node` is `None`.
    ///
    /// Assume all prerequisites are satisfied; errors must not occur.
    fn post_child_insertion(&mut self, inserted_child: Node<dyn NodeSpec>) {
        let _ = inserted_child;
    }
}

pub struct NodeCore<Spec: ?Sized> {
    pub(super) parent_node: Weak<RefCell<NodeCore<dyn InternalNodeSpec>>>,
    pub(super) previous_sibling: Weak<RefCell<NodeCore<dyn NodeSpec>>>,
    pub(super) next_sibling: Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>>,
    pub(super) spec: Spec,
}

/// Pointer to a node.
///
/// Internally, it is a pair consisting of a reference counter for the node's data
/// and a reference counter for the document node that owns it.
///
/// `Node<dyn NodeSpec>` and `Node<dyn InternalNodeSpec>` are abstract node types.  \
/// They enable common operations on concrete node types that implement their respective traits,
/// as well as conversion to a specific concrete node type.
pub struct Node<Spec: ?Sized> {
    pub(super) core: Rc<RefCell<NodeCore<Spec>>>,
    pub(super) owner_document: Rc<RefCell<NodeCore<DocumentSpec>>>,
}

impl<Spec: NodeSpec + ?Sized> Node<Spec> {
    /// Return the node type.
    ///
    /// For abstract node types, this method guarantees that conversion
    /// to the specified node type will always succeed.
    pub fn node_type(&self) -> NodeType {
        self.core.borrow().spec.node_type()
    }

    /// Get the parent node of `self` if exsits.
    ///
    /// # Note
    /// [`Attribute`](crate::tree::Attribute) and [`Namespace`](crate::tree::Namespace) each return
    /// the same result as [`Attribute::owner_element`](crate::tree::Attribute::owner_element)
    /// and [`Namespace::owner_element`](crate::tree::Namespace::owner_element),
    /// but neither is a child of [`Element`](crate::tree::Element).
    pub fn parent_node(&self) -> Option<Node<dyn InternalNodeSpec>> {
        self.core.borrow().parent_node.upgrade().map(|core| Node {
            core,
            owner_document: self.owner_document.clone(),
        })
    }
    /// Get the previous sibling node of `self` if exsits.
    ///
    /// # Note
    /// [`Attribute`](crate::tree::Attribute) and [`Namespace`](crate::tree::Namespace)
    /// always return [`None`].
    pub fn previous_sibling(&self) -> Option<Node<dyn NodeSpec>> {
        self.core
            .borrow()
            .previous_sibling
            .upgrade()
            .map(|core| Node {
                core: core as _,
                owner_document: self.owner_document.clone(),
            })
    }
    /// Get the previous sibling whose node type is [`Element`](NodeType::Element).
    pub fn previous_element_sibling(&self) -> Option<Element> {
        let mut previous = self.previous_sibling();
        while let Some(now) = previous {
            if let Some(element) = now.as_element() {
                return Some(element);
            }

            if matches!(now.node_type(), NodeType::EntityReference)
                && let Some(last) = now.last_child()
            {
                previous = Some(last);
            } else if let Some(prev) = now.previous_sibling() {
                previous = Some(prev);
            } else {
                previous = None;

                let mut parent = now.parent_node();
                while let Some(par) =
                    parent.filter(|par| matches!(par.node_type(), NodeType::EntityReference))
                {
                    if let Some(prev) = par.previous_sibling() {
                        previous = Some(prev);
                        break;
                    }
                    parent = par.parent_node();
                }
            }
        }
        None
    }
    /// Get the next sibling node of `self` if exsits.
    ///
    /// # Note
    /// [`Attribute`](crate::tree::Attribute) and [`Namespace`](crate::tree::Namespace)
    /// always return [`None`].
    pub fn next_sibling(&self) -> Option<Node<dyn NodeSpec>> {
        self.core.borrow().next_sibling.clone().map(|core| Node {
            core: core as _,
            owner_document: self.owner_document.clone(),
        })
    }
    /// Get the next sibling whose node type is [`Element`](NodeType::Element).
    pub fn next_element_sibling(&self) -> Option<Element> {
        let mut next = self.next_sibling();
        while let Some(now) = next {
            if let Some(element) = now.as_element() {
                return Some(element);
            }

            if matches!(now.node_type(), NodeType::EntityReference)
                && let Some(first) = now.first_child()
            {
                next = Some(first);
            } else if let Some(nt) = now.next_sibling() {
                next = Some(nt);
            } else {
                next = None;

                let mut parent = now.parent_node();
                while let Some(par) =
                    parent.filter(|par| matches!(par.node_type(), NodeType::EntityReference))
                {
                    if let Some(nt) = par.next_sibling() {
                        next = Some(nt);
                        break;
                    }
                    parent = par.parent_node();
                }
            }
        }
        None
    }
    /// Get the first child node of `self` if exsits.
    pub fn first_child(&self) -> Option<Node<dyn NodeSpec>> {
        self.core.borrow().spec.first_child().map(|core| Node {
            core,
            owner_document: self.owner_document.clone(),
        })
    }
    /// Get the first child whose node type is [`Element`](NodeType::Element).
    pub fn first_element_child(&self) -> Option<Element> {
        let mut children = self.first_child();
        while let Some(child) = children {
            if let Some(element) = child.as_element() {
                return Some(element);
            }

            if matches!(child.node_type(), NodeType::EntityReference)
                && let Some(first) = child.first_child()
            {
                children = Some(first);
            } else if let Some(next) = child.next_sibling() {
                children = Some(next);
            } else {
                children = None;

                let mut parent = child.parent_node();
                while let Some(par) =
                    parent.filter(|par| matches!(par.node_type(), NodeType::EntityReference))
                {
                    if let Some(next) = par.next_sibling() {
                        children = Some(next);
                        break;
                    }
                    parent = par.parent_node();
                }
            }
        }
        None
    }
    /// Get the last child node of `self` if exsits.
    pub fn last_child(&self) -> Option<Node<dyn NodeSpec>> {
        self.core.borrow().spec.last_child().map(|core| Node {
            core,
            owner_document: self.owner_document.clone(),
        })
    }
    /// Get the first child whose node type is [`Element`](NodeType::Element).
    pub fn last_element_child(&self) -> Option<Element> {
        let mut children = self.last_child();
        while let Some(child) = children {
            if let Some(element) = child.as_element() {
                return Some(element);
            }

            if matches!(child.node_type(), NodeType::EntityReference)
                && let Some(first) = child.last_child()
            {
                children = Some(first);
            } else if let Some(next) = child.previous_sibling() {
                children = Some(next);
            } else {
                children = None;

                let mut parent = child.parent_node();
                while let Some(par) =
                    parent.filter(|par| matches!(par.node_type(), NodeType::EntityReference))
                {
                    if let Some(next) = par.previous_sibling() {
                        children = Some(next);
                        break;
                    }
                    parent = par.parent_node();
                }
            }
        }
        None
    }

    /// Get the [`Document`] node that represents the owner document of `self`.
    pub fn owner_document(&self) -> Document {
        Document {
            core: self.owner_document.clone(),
            owner_document: self.owner_document.clone(),
        }
    }

    fn set_paretn_node(&mut self, new: Node<dyn InternalNodeSpec>) {
        self.core.borrow_mut().parent_node = Rc::downgrade(&new.core) as _;
    }
    fn unset_parent_node(&mut self) {
        // Since the type size must be known at compile time,
        // create a weak reference to an arbitrary node as a dummy and upcast it.
        let weak: Weak<RefCell<NodeCore<DocumentFragmentSpec>>> = Weak::new();
        self.core.borrow_mut().parent_node = weak as _;
    }

    fn set_previous_sibling(&mut self, new: Node<dyn NodeSpec>) {
        self.core.borrow_mut().previous_sibling = Rc::downgrade(&new.core);
    }
    fn unset_previous_sibling(&mut self) {
        // Since the type size must be known at compile time,
        // create a weak reference to an arbitrary node as a dummy and upcast it.
        let weak: Weak<RefCell<NodeCore<DocumentFragmentSpec>>> = Weak::new();
        self.core.borrow_mut().previous_sibling = weak as _;
    }

    fn set_next_sibling(&mut self, new: Node<dyn NodeSpec>) {
        self.core.borrow_mut().next_sibling = Some(new.core.clone());
    }
    fn unset_next_sibling(&mut self) {
        self.core.borrow_mut().next_sibling = None;
    }

    pub(super) fn is_same_owner_document<Other: NodeSpec + ?Sized>(
        &self,
        other: &Node<Other>,
    ) -> bool {
        Rc::ptr_eq(&self.owner_document, &other.owner_document)
    }
}

impl Node<dyn NodeSpec> {
    /// Detach the link between parent and self, and remove self from the sibling list.
    ///
    /// For attribute nodes, execute [`remove_attribute_node`](crate::tree::Element::remove_attribute_node) on the parent element for itself.  \
    /// For namespace nodes, execute [`undeclare_namespace`](crate::tree::Element::undeclare_namespace) on the parent element for itself.
    pub fn detach(&mut self) -> Result<(), XMLTreeError> {
        let mut parent_node = self.parent_node();
        if let Some(parent_node) = parent_node.as_mut() {
            match self.downcast() {
                NodeKind::Attribute(attribute) => {
                    if let Some(mut element) = attribute.owner_element() {
                        element.remove_attribute_node(attribute).ok();
                    }
                    return Ok(());
                }
                NodeKind::Namespace(namespace) => {
                    if let Some(mut element) = namespace.owner_element() {
                        element.undeclare_namespace(namespace.prefix().as_deref());
                    }
                    return Ok(());
                }
                _ => {
                    parent_node.pre_child_removal(self.clone())?;
                }
            }
        }
        self.unset_parent_node();
        let previous_sibling = self.previous_sibling();
        self.unset_previous_sibling();
        let next_sibling = self.next_sibling();
        self.unset_next_sibling();

        match (parent_node, previous_sibling, next_sibling) {
            (_, Some(mut previous_sibling), Some(mut next_sibling)) => {
                previous_sibling.set_next_sibling(next_sibling.clone());
                next_sibling.set_previous_sibling(previous_sibling.clone());
            }
            (Some(mut parent_node), Some(mut previous_sibling), None) => {
                previous_sibling.unset_next_sibling();
                parent_node.set_last_child(previous_sibling);
            }
            (Some(mut parent_node), None, Some(mut next_sibling)) => {
                next_sibling.unset_previous_sibling();
                parent_node.set_first_child(next_sibling);
            }
            (Some(mut parent_node), None, None) => {
                parent_node.unset_first_child();
                parent_node.unset_last_child();
            }
            (None, Some(mut previous_sibling), None) => {
                previous_sibling.unset_next_sibling();
            }
            (None, None, Some(mut next_sibling)) => {
                next_sibling.unset_previous_sibling();
            }
            (None, None, None) => {}
        }
        Ok(())
    }

    fn cyclic_reference_check(
        &self,
        reference_node: &Node<dyn NodeSpec>,
    ) -> Result<(), XMLTreeError> {
        let mut parent_node = Some(self.clone());
        while let Some(now) = parent_node {
            parent_node = now.parent_node().map(From::from);
            if Rc::ptr_eq(&reference_node.core, &now.core) {
                return Err(XMLTreeError::CyclicReference);
            }
        }
        Ok(())
    }

    fn pre_insertion_common_check(
        &self,
        new_sibling: &Node<dyn NodeSpec>,
    ) -> Result<(), XMLTreeError> {
        if matches!(
            new_sibling.node_type(),
            NodeType::Document
                | NodeType::DocumentFragment
                | NodeType::Attribute
                | NodeType::Namespace
        ) {
            return Err(XMLTreeError::UnacceptableHierarchy);
        }

        self.cyclic_reference_check(new_sibling)?;
        Ok(())
    }

    fn do_insert_previous_sibling(
        &mut self,
        mut new_sibling: Node<dyn NodeSpec>,
    ) -> Result<(), XMLTreeError> {
        if self.parent_node().is_none() {
            return Err(XMLTreeError::UnacceptableHierarchy);
        }
        if let Some(frag) = new_sibling.as_document_fragment() {
            let mut succeed = 0;
            while let Some(mut child) = frag.first_child() {
                let ret = self.insert_previous_sibling(child.clone());
                if ret.is_err() {
                    // rollback
                    for _ in 0..succeed {
                        if let Some(mut previous) = self.previous_sibling() {
                            previous.detach()?;
                            child.insert_previous_sibling(previous.clone())?;
                            child = previous;
                        }
                    }
                    return ret;
                }
                succeed += 1;
            }
            return Ok(());
        }
        self.pre_insertion_common_check(&new_sibling)?;
        if let Some(parent_node) = self.parent_node() {
            parent_node.pre_child_insertion(new_sibling.clone(), self.previous_sibling())?;
        }
        new_sibling.detach()?;
        new_sibling.set_next_sibling(self.clone());
        if let Some(mut previous_sibling) = self.previous_sibling() {
            previous_sibling.set_next_sibling(new_sibling.clone());
            new_sibling.set_previous_sibling(previous_sibling);
            if let Some(parent_node) = self.parent_node() {
                new_sibling.set_paretn_node(parent_node);
            }
        } else if let Some(mut parent_node) = self.parent_node() {
            parent_node.set_first_child(new_sibling.clone());
            new_sibling.set_paretn_node(parent_node);
        }
        self.set_previous_sibling(new_sibling.clone());
        if let Some(mut parent_node) = self.parent_node() {
            parent_node.post_child_insertion(new_sibling);
        }
        Ok(())
    }

    /// Insert `new_sibling` as a sibling preceding itself.
    ///
    /// Insertions that violate tree constraints (such as those that create cyclic references
    /// or insert siblings at the root node) are errors.  \
    /// Additionally, operations that generate expressions impossible in well-formed XML documents
    /// (such as placing Text outside document elements or inserting declarations into element
    /// content) are also errors.
    ///
    /// # Example
    /// ```rust
    /// use anyxml::tree::Document;
    ///
    /// let mut document = Document::new();
    /// let mut root = document.create_element("root", None).unwrap();
    /// let mut comment = document.create_comment("comment");
    /// // cyclic reference
    /// assert!(root.insert_previous_sibling(root.clone()).is_err());
    /// // multiple root
    /// assert!(root.insert_previous_sibling(comment.clone()).is_err());
    /// document.append_child(root.clone()).unwrap();
    /// root.insert_previous_sibling(comment).unwrap();
    /// assert!(root
    ///     .previous_sibling()
    ///     .and_then(|sib| sib.as_comment())
    ///     .is_some_and(|comment| &*comment.data() == "comment")
    /// );
    /// ```
    pub fn insert_previous_sibling(
        &mut self,
        new_sibling: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        self.do_insert_previous_sibling(new_sibling.into())
    }

    fn do_insert_next_sibling(
        &mut self,
        mut new_sibling: Node<dyn NodeSpec>,
    ) -> Result<(), XMLTreeError> {
        if self.parent_node().is_none() {
            return Err(XMLTreeError::UnacceptableHierarchy);
        }
        if let Some(mut frag) = new_sibling.as_document_fragment() {
            let mut succeed = 0;
            while let Some(child) = frag.last_child() {
                let ret = self.insert_next_sibling(child);
                if ret.is_err() {
                    // rollback
                    for _ in 0..succeed {
                        if let Some(mut next) = self.next_sibling() {
                            next.detach()?;
                            frag.append_child(next)?;
                        }
                    }
                    return ret;
                }
                succeed += 1;
            }
            return Ok(());
        }
        self.pre_insertion_common_check(&new_sibling)?;
        if let Some(parent_node) = self.parent_node() {
            parent_node.pre_child_insertion(new_sibling.clone(), Some(self.clone()))?;
        }
        new_sibling.detach()?;
        new_sibling.set_previous_sibling(self.clone());
        if let Some(mut next_sibling) = self.next_sibling() {
            next_sibling.set_previous_sibling(new_sibling.clone());
            new_sibling.set_next_sibling(next_sibling);
            if let Some(parent_node) = self.parent_node() {
                new_sibling.set_paretn_node(parent_node);
            }
        } else if let Some(mut parent_node) = self.parent_node() {
            parent_node.set_last_child(new_sibling.clone());
            new_sibling.set_paretn_node(parent_node);
        }
        self.set_next_sibling(new_sibling.clone());
        if let Some(mut parent_node) = self.parent_node() {
            parent_node.post_child_insertion(new_sibling);
        }
        Ok(())
    }

    /// Insert `new_sibling` as a sibling following itself.
    ///
    /// Insertions that violate tree constraints (such as those that create cyclic references
    /// or insert siblings at the root node) are errors.  \
    /// Additionally, operations that generate expressions impossible in well-formed XML documents
    /// (such as placing Text outside document elements or inserting declarations into element
    /// content) are also errors.
    ///
    /// # Example
    /// ```rust
    /// use anyxml::tree::Document;
    ///
    /// let mut document = Document::new();
    /// let mut root = document.create_element("root", None).unwrap();
    /// let mut comment = document.create_comment("comment");
    /// // cyclic reference
    /// assert!(root.insert_next_sibling(root.clone()).is_err());
    /// // multiple root
    /// assert!(root.insert_next_sibling(comment.clone()).is_err());
    /// document.append_child(root.clone()).unwrap();
    /// root.insert_next_sibling(comment).unwrap();
    /// assert!(root
    ///     .next_sibling()
    ///     .and_then(|sib| sib.as_comment())
    ///     .is_some_and(|comment| &*comment.data() == "comment")
    /// );
    /// ```
    pub fn insert_next_sibling(
        &mut self,
        new_sibling: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        self.do_insert_next_sibling(new_sibling.into())
    }

    /// Replace the subtree rooted at `self` with the subtree rooted at `src`.
    ///
    /// If `self` has no parent, nothing happens.  \
    /// If `self` has a parent, the following occurs:
    /// - [`src.detach()`](Node::detach) is executed,
    /// - `src` is inserted as an adjacent sibling to `self`,
    /// - and finally [`self.detach()`](Node::detach) is executed.
    ///
    /// # Note
    /// `self` is never inserted into the position where `src` was.  \
    /// `self` simply becomes a subtree without a parent.
    pub fn replace_subtree(
        &mut self,
        src: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        let Some(parent) = self.parent_node() else {
            return Ok(());
        };

        if let Some(mut document) = parent.as_document() {
            if let Some(mut prev) = self.previous_sibling() {
                self.detach()?;
                if let Err(err) = prev.insert_next_sibling(src) {
                    prev.insert_next_sibling(self)?;
                    return Err(err);
                }
            } else if let Some(mut next) = self.next_sibling() {
                self.detach()?;
                if let Err(err) = next.insert_previous_sibling(src) {
                    next.insert_previous_sibling(self)?;
                    return Err(err);
                }
            } else {
                self.detach()?;
                if let Err(err) = document.append_child(src) {
                    document.append_child(self)?;
                    return Err(err);
                }
            }
        } else {
            self.insert_previous_sibling(src)?;
            self.detach()?;
        }
        Ok(())
    }

    /// Check whether `self` and `other` are the same node.
    ///
    /// # Note
    /// This method does not perform equality comparison.  \
    /// For example, `is_same_node` will always return `false` for two [`Text`](crate::tree::Text)
    /// nodes containing exactly the same string generated from the same [`Document`],
    /// unless one is a clone of the other.
    ///
    /// # Example
    /// ```rust
    /// use anyxml::tree::Document;
    ///
    /// let document = Document::new();
    /// let text1 = document.create_text("Hello");
    /// let text2 = document.create_text("Hello");
    ///
    /// assert!(text1.is_same_node(text1.clone()));
    /// // These have the same character data, but are not the same node.
    /// assert!(!text1.is_same_node(text2.clone()));
    /// ```
    pub fn is_same_node(&self, other: impl Into<Self>) -> bool {
        let other: Self = other.into();
        Rc::ptr_eq(&self.core, &other.core)
    }

    /// Compare the positions of `self` and `other` in the document order.
    ///
    /// If `self` appears first, return `Less`;  \
    /// if it appears later, return `Greater`;  \
    /// if they are the same node, return `Equal`.
    ///
    /// If `self` and `other` do not belong to the same document tree
    /// (i.e., they have no common ancestor), return `None`.
    ///
    /// # Reference
    /// [5 Data Model in XPath 1.0](https://www.w3.org/TR/1999/REC-xpath-19991116/#dt-document-order)
    pub fn compare_document_order(
        &self,
        other: impl Into<Node<dyn NodeSpec>>,
    ) -> Option<std::cmp::Ordering> {
        compare_document_order(self.clone(), other.into())
    }

    /// Retrieve the base URI according to the [XML Base](https://www.w3.org/TR/xmlbase/).
    ///
    /// If the node is embedded as a descendant of a [`Document`] node, always return `Some`.  \
    /// If there are insufficient ancestor nodes to resolve the base URI, return `None`.
    pub fn base_uri(&self) -> Option<URIString> {
        let mut node = Some(self.clone());
        let mut uris: Vec<URIString> = vec![];
        let mut ret = None;
        while let Some(now) = node {
            if let Some(base) = now
                .as_element()
                .and_then(|elem| elem.get_attribute("base", Some(XML_XML_NAMESPACE)))
                .and_then(|base| URIString::parse(base).ok())
            {
                if base.scheme().is_some() {
                    ret = Some(
                        uris.into_iter()
                            .rev()
                            .fold(base, |base, rel| base.resolve(&rel)),
                    );
                    break;
                }
                uris.push(base);
            } else if let Some(document) = now.as_document() {
                let base = document.document_base_uri().as_ref().to_owned();
                ret = Some(
                    uris.into_iter()
                        .rev()
                        .fold(base, |base, rel| base.resolve(&rel)),
                );
                break;
            } else if let Some(entity) = now.as_entity_reference() {
                let name = entity.name();
                if let Some(base) = self
                    .owner_document()
                    .document_type()
                    .and_then(|doctype| doctype.get_entity_decl(&name))
                    .and_then(|decl| decl.system_id())
                {
                    let base = base.as_ref().to_owned();
                    ret = Some(
                        uris.into_iter()
                            .rev()
                            .fold(base, |base, rel| base.resolve(&rel)),
                    );
                    break;
                }
            }
            node = now.parent_node().map(From::from);
        }
        ret.map(|uri| {
            // The URI returned as the base URI must be an absolute URI.
            // However, at this point, only relative references have been resolved,
            // and a fragment may be included.
            // The URI returned as the base URI must be an absolute URI.
            // Therefore, resolving the relative reference without the fragment removes the fragment.
            //
            // Reference:
            // [Testing XML Base Conformance](https://www.w3.org/XML/2006/12/xmlbase-testing.html)
            // section 4. in "Discussion of few key example"
            uri.resolve(&URIString::parse("").unwrap())
        })
    }

    /// If `self` and its descendants contain character data, concatenate all of it
    /// and return the result.  \
    /// If they do not contain character data, return an empty string.
    ///
    /// # Note
    /// If descendants contain [`Comment`](crate::tree::Comment)
    /// or [`ProcessingInstruction`](crate::tree::ProcessingInstruction), these are also
    /// included in the result.  \
    /// For [`ProcessingInstruction`](crate::tree::ProcessingInstruction),
    /// the result is the data following the target.
    ///
    /// Additionally, the result for [`Document`] is an empty string.
    pub fn text_content(&self) -> String {
        let mut buf = String::new();
        fn collect_text_content(node: Node<dyn NodeSpec>, buf: &mut String) {
            match node.downcast() {
                NodeKind::Element(_)
                | NodeKind::Attribute(_)
                | NodeKind::EntityDecl(_)
                | NodeKind::EntityReference(_)
                | NodeKind::DocumentFragment(_) => {
                    let mut children = node.first_child();
                    while let Some(child) = children {
                        children = child.next_sibling();
                        collect_text_content(child, buf);
                    }
                }
                NodeKind::Text(text) => {
                    buf.push_str(&text.data());
                }
                NodeKind::CDATASection(cdata) => {
                    buf.push_str(&cdata.data());
                }
                NodeKind::Comment(comment) => {
                    buf.push_str(&comment.data());
                }
                NodeKind::ProcessingInstruction(pi) => {
                    buf.push_str(pi.data().as_deref().unwrap_or_default());
                }
                _ => {}
            }
        }
        collect_text_content(self.clone(), &mut buf);
        buf
    }

    /// Create new node and copy internal data to the new node other than pointers to neighbor nodes.
    ///
    /// Attribute nodes and namespace nodes are cloned.
    ///
    /// While [`Clone::clone`] merely copies the pointer, this method copies the internal data
    /// to new memory, creating a completely different node. Comparing the source node and
    /// the new node using [`Node::is_same_node`] will always return `false`.
    pub fn deep_copy(&self) -> Result<Node<dyn NodeSpec>, XMLTreeError> {
        match self.downcast() {
            NodeKind::AttlistDecl(node) => Ok(node.deep_copy().into()),
            NodeKind::Attribute(_) => Err(XMLTreeError::Unsupported),
            NodeKind::CDATASection(node) => Ok(node.deep_copy().into()),
            NodeKind::Comment(node) => Ok(node.deep_copy().into()),
            NodeKind::Document(node) => Ok(node.deep_copy().into()),
            NodeKind::DocumentFragment(node) => Ok(node.deep_copy().into()),
            NodeKind::DocumentType(node) => Ok(node.deep_copy().into()),
            NodeKind::Element(node) => Ok(node.deep_copy()?.into()),
            NodeKind::ElementDecl(node) => Ok(node.deep_copy().into()),
            NodeKind::EntityDecl(node) => Ok(node.deep_copy().into()),
            NodeKind::EntityReference(node) => Ok(node.deep_copy().into()),
            NodeKind::Namespace(_) => Err(XMLTreeError::Unsupported),
            NodeKind::NotationDecl(node) => Ok(node.deep_copy().into()),
            NodeKind::ProcessingInstruction(node) => Ok(node.deep_copy().into()),
            NodeKind::Text(node) => Ok(node.deep_copy().into()),
        }
    }

    /// Perform a deep copy on all descendant nodes and construct a tree with the same structure.
    ///
    /// The link to the parent is not preserved.
    pub fn deep_copy_subtree(&self) -> Result<Node<dyn NodeSpec>, XMLTreeError> {
        match self.downcast() {
            NodeKind::AttlistDecl(node) => Ok(node.deep_copy().into()),
            NodeKind::Attribute(_) => Err(XMLTreeError::Unsupported),
            NodeKind::CDATASection(node) => Ok(node.deep_copy().into()),
            NodeKind::Comment(node) => Ok(node.deep_copy().into()),
            NodeKind::Document(node) => Ok(node.deep_copy_subtree()?.into()),
            NodeKind::DocumentFragment(node) => Ok(node.deep_copy_subtree()?.into()),
            NodeKind::DocumentType(node) => Ok(node.deep_copy_subtree()?.into()),
            NodeKind::Element(node) => Ok(node.deep_copy_subtree()?.into()),
            NodeKind::ElementDecl(node) => Ok(node.deep_copy().into()),
            NodeKind::EntityDecl(node) => Ok(node.deep_copy_subtree()?.into()),
            NodeKind::EntityReference(node) => Ok(node.deep_copy_subtree()?.into()),
            NodeKind::Namespace(_) => Err(XMLTreeError::Unsupported),
            NodeKind::NotationDecl(node) => Ok(node.deep_copy().into()),
            NodeKind::ProcessingInstruction(node) => Ok(node.deep_copy().into()),
            NodeKind::Text(node) => Ok(node.deep_copy().into()),
        }
    }
}

impl Node<dyn InternalNodeSpec> {
    /// See [Node::detach].
    pub fn detach(&mut self) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self.clone()).detach()
    }

    /// See [Node::insert_previous_sibling].
    pub fn insert_previous_sibling(
        &mut self,
        new_sibling: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self.clone()).insert_previous_sibling(new_sibling)
    }

    /// See [Node::insert_next_sibling].
    pub fn insert_next_sibling(
        &mut self,
        new_sibling: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self.clone()).insert_next_sibling(new_sibling)
    }

    /// See [Node::replace_subtree].
    pub fn replace_subtree(
        &mut self,
        src: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self).replace_subtree(src)
    }

    fn do_append_child(&mut self, mut new_child: Node<dyn NodeSpec>) -> Result<(), XMLTreeError> {
        if let Some(mut last_child) = self.last_child() {
            last_child.insert_next_sibling(new_child)?;
        } else {
            if let Some(mut frag) = new_child.as_document_fragment() {
                let Some(mut child) = frag.first_child() else {
                    return Ok(());
                };

                self.append_child(child.clone())?;
                return match self.append_child(frag.clone()) {
                    Ok(()) => Ok(()),
                    Err(err) => {
                        child.detach()?;
                        if let Some(mut first) = frag.first_child() {
                            first.insert_previous_sibling(child)?;
                        } else {
                            frag.append_child(child)?;
                        }
                        return Err(err);
                    }
                };
            }
            Node::<dyn NodeSpec>::from(self.clone()).pre_insertion_common_check(&new_child)?;
            self.pre_child_insertion(new_child.clone(), None)?;
            new_child.detach()?;
            new_child.set_paretn_node(self.clone());
            self.set_first_child(new_child.clone());
            self.set_last_child(new_child.clone());
            self.post_child_insertion(new_child);
        }
        Ok(())
    }

    /// Insert `new_child` as a last child of `self`.
    ///
    /// Insertions that violate tree constraints (such as those that create cyclic references)
    /// are errors.  \
    /// Additionally, operations that generate expressions impossible in well-formed XML documents
    /// (such as placing Text outside document elements or inserting declarations into element
    /// content) are also errors.
    pub fn append_child(
        &mut self,
        new_child: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        self.do_append_child(new_child.into())
    }

    fn pre_child_removal(&mut self, removed_child: Node<dyn NodeSpec>) -> Result<(), XMLTreeError> {
        self.core.borrow_mut().spec.pre_child_removal(removed_child)
    }

    fn pre_child_insertion(
        &self,
        inserted_child: Node<dyn NodeSpec>,
        preceding_node: Option<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        self.core
            .borrow()
            .spec
            .pre_child_insertion(inserted_child, preceding_node)
    }

    fn post_child_insertion(&mut self, inserted_child: Node<dyn NodeSpec>) {
        self.core
            .borrow_mut()
            .spec
            .post_child_insertion(inserted_child);
    }

    /// Check whether `self` and `other` are the same node.
    ///
    /// For more details, please refer [`Node::is_same_node`] of [`Node<dyn NodeSpec>`]
    pub fn is_same_node(&self, other: impl Into<Node<dyn NodeSpec>>) -> bool {
        let left = Node::<dyn NodeSpec>::from(self);
        let right: Node<dyn NodeSpec> = other.into();
        Rc::ptr_eq(&left.core, &right.core)
    }

    /// Compare the positions of `self` and `other` in the document order.
    ///
    /// For more details, please refer [`Node::compare_document_order`] of [`Node<dyn NodeSpec>`].
    pub fn compare_document_order(
        &self,
        other: impl Into<Node<dyn NodeSpec>>,
    ) -> Option<std::cmp::Ordering> {
        compare_document_order(self.into(), other.into())
    }

    /// Retrieve the base URI according to the [XML Base](https://www.w3.org/TR/xmlbase/).
    ///
    /// For more details, please refer to [Node::base_uri].
    pub fn base_uri(&self) -> Option<URIString> {
        Node::<dyn NodeSpec>::from(self).base_uri()
    }

    /// Please see [Node::text_content].
    pub fn text_content(&self) -> String {
        Node::<dyn NodeSpec>::from(self).text_content()
    }

    /// Please see [Node::deep_copy].
    pub fn deep_copy(&self) -> Result<Node<dyn NodeSpec>, XMLTreeError> {
        Node::<dyn NodeSpec>::from(self).deep_copy()
    }

    /// Please see [Node::deep_copy_subtree].
    pub fn deep_copy_subtree(&self) -> Result<Node<dyn NodeSpec>, XMLTreeError> {
        Node::<dyn NodeSpec>::from(self).deep_copy_subtree()
    }
}

impl<Spec: NodeSpec + 'static> Node<Spec> {
    pub(crate) fn create_node(spec: Spec, owner_document: Document) -> Self {
        let weak: Weak<RefCell<NodeCore<DocumentFragmentSpec>>> = Weak::new();
        Node {
            core: Rc::new(RefCell::new(NodeCore {
                parent_node: weak.clone(),
                previous_sibling: weak,
                next_sibling: None,
                spec,
            })),
            owner_document: owner_document.owner_document.clone(),
        }
    }

    /// See [Node::detach].
    pub fn detach(&mut self) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self).detach()
    }

    /// See [Node::insert_previous_sibling].
    pub fn insert_previous_sibling(
        &mut self,
        new_sibling: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self).insert_previous_sibling(new_sibling)
    }

    /// See [Node::insert_next_sibling].
    pub fn insert_next_sibling(
        &mut self,
        new_sibling: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self).insert_next_sibling(new_sibling)
    }

    /// See [Node::replace_subtree].
    pub fn replace_subtree(
        &mut self,
        src: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        Node::<dyn NodeSpec>::from(self).replace_subtree(src)
    }

    /// Check whether `self` and `other` are the same node.
    ///
    /// For more details, please refer [`Node::is_same_node`] of [`Node<dyn NodeSpec>`]
    pub fn is_same_node(&self, other: impl Into<Node<dyn NodeSpec>>) -> bool {
        let left = Node::<dyn NodeSpec>::from(self);
        let right: Node<dyn NodeSpec> = other.into();
        Rc::ptr_eq(&left.core, &right.core)
    }

    /// Compare the positions of `self` and `other` in the document order.
    ///
    /// For more details, please refer [`Node::compare_document_order`] of [`Node<dyn NodeSpec>`].
    pub fn compare_document_order(
        &self,
        other: impl Into<Node<dyn NodeSpec>>,
    ) -> Option<std::cmp::Ordering> {
        compare_document_order(self.into(), other.into())
    }

    /// Retrieve the base URI according to the [XML Base](https://www.w3.org/TR/xmlbase/).
    ///
    /// For more details, please refer to [Node::base_uri].
    pub fn base_uri(&self) -> Option<URIString> {
        Node::<dyn NodeSpec>::from(self).base_uri()
    }

    /// Please see [Node::text_content].
    pub fn text_content(&self) -> String {
        Node::<dyn NodeSpec>::from(self).text_content()
    }
}

impl<Spec: InternalNodeSpec + ?Sized> Node<Spec> {
    fn set_first_child(&mut self, new: Node<dyn NodeSpec>) {
        self.core
            .borrow_mut()
            .spec
            .set_first_child(new.core.clone());
    }
    fn unset_first_child(&mut self) {
        self.core.borrow_mut().spec.unset_first_child();
    }

    fn set_last_child(&mut self, new: Node<dyn NodeSpec>) {
        self.core.borrow_mut().spec.set_last_child(new.core.clone());
    }
    fn unset_last_child(&mut self) {
        self.core.borrow_mut().spec.unset_last_child();
    }
}

impl<Spec: InternalNodeSpec + 'static> Node<Spec> {
    /// See [Node::append_child].
    pub fn append_child(
        &mut self,
        new_child: impl Into<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        Node::<dyn InternalNodeSpec>::from(self.clone()).append_child(new_child)
    }
}

impl<Spec: ?Sized> Clone for Node<Spec> {
    fn clone(&self) -> Self {
        Self {
            core: self.core.clone(),
            owner_document: self.owner_document.clone(),
        }
    }
}

impl From<&Node<dyn NodeSpec>> for Node<dyn NodeSpec> {
    fn from(value: &Node<dyn NodeSpec>) -> Self {
        value.clone()
    }
}

impl From<&mut Node<dyn NodeSpec>> for Node<dyn NodeSpec> {
    fn from(value: &mut Node<dyn NodeSpec>) -> Self {
        value.clone()
    }
}

impl<Spec: NodeSpec + 'static> From<Node<Spec>> for Node<dyn NodeSpec> {
    fn from(value: Node<Spec>) -> Self {
        Node {
            core: value.core,
            owner_document: value.owner_document,
        }
    }
}

impl<Spec: NodeSpec + 'static> From<&Node<Spec>> for Node<dyn NodeSpec> {
    fn from(value: &Node<Spec>) -> Self {
        value.clone().into()
    }
}

impl<Spec: NodeSpec + 'static> From<&mut Node<Spec>> for Node<dyn NodeSpec> {
    fn from(value: &mut Node<Spec>) -> Self {
        value.clone().into()
    }
}

impl From<Node<dyn InternalNodeSpec>> for Node<dyn NodeSpec> {
    fn from(value: Node<dyn InternalNodeSpec>) -> Self {
        Node {
            core: value.core,
            owner_document: value.owner_document,
        }
    }
}

impl From<&Node<dyn InternalNodeSpec>> for Node<dyn NodeSpec> {
    fn from(value: &Node<dyn InternalNodeSpec>) -> Self {
        value.clone().into()
    }
}

impl From<&mut Node<dyn InternalNodeSpec>> for Node<dyn NodeSpec> {
    fn from(value: &mut Node<dyn InternalNodeSpec>) -> Self {
        value.clone().into()
    }
}

impl<Spec: InternalNodeSpec + 'static> From<Node<Spec>> for Node<dyn InternalNodeSpec> {
    fn from(value: Node<Spec>) -> Self {
        Node {
            core: value.core,
            owner_document: value.owner_document,
        }
    }
}

impl<Spec: InternalNodeSpec + 'static> From<&Node<Spec>> for Node<dyn InternalNodeSpec> {
    fn from(value: &Node<Spec>) -> Self {
        value.clone().into()
    }
}

impl<Spec: InternalNodeSpec + 'static> From<&mut Node<Spec>> for Node<dyn InternalNodeSpec> {
    fn from(value: &mut Node<Spec>) -> Self {
        value.clone().into()
    }
}

impl std::fmt::Display for Node<dyn NodeSpec> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.downcast() {
            NodeKind::AttlistDecl(attlist) => write!(f, "{}", attlist),
            NodeKind::Attribute(attribute) => write!(f, "{}", attribute),
            NodeKind::CDATASection(cdata) => write!(f, "{}", cdata),
            NodeKind::Comment(comment) => write!(f, "{}", comment),
            NodeKind::Document(document) => write!(f, "{}", document),
            NodeKind::DocumentFragment(frag) => write!(f, "{}", frag),
            NodeKind::DocumentType(doctype) => write!(f, "{}", doctype),
            NodeKind::Element(element) => write!(f, "{}", element),
            NodeKind::ElementDecl(element) => write!(f, "{}", element),
            NodeKind::EntityDecl(entity) => write!(f, "{}", entity),
            NodeKind::EntityReference(entref) => write!(f, "{}", entref),
            NodeKind::Namespace(namespace) => write!(f, "{}", namespace),
            NodeKind::NotationDecl(notation) => write!(f, "{}", notation),
            NodeKind::ProcessingInstruction(pi) => write!(f, "{}", pi),
            NodeKind::Text(text) => write!(f, "{}", text),
        }
    }
}

impl std::fmt::Display for Node<dyn InternalNodeSpec> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", Node::<dyn NodeSpec>::from(self.clone()))
    }
}

#[cfg(test)]
mod tests {
    use crate::{sax::parser::XMLReaderBuilder, tree::TreeBuildHandler};

    use super::*;

    #[test]
    fn cyclic_reference_tests() {
        let mut document = Document::new();
        let mut elem = document.create_element("elem", None).unwrap();
        let mut elem2 = document.create_element("elem2", None).unwrap();
        elem.append_child(elem2.clone()).unwrap();
        document.append_child(elem.clone()).unwrap();

        assert!(
            elem2
                .append_child(elem.clone())
                .is_err_and(|err| matches!(err, XMLTreeError::CyclicReference))
        );
        assert!(
            elem.insert_previous_sibling(elem.clone())
                .is_err_and(|err| matches!(err, XMLTreeError::CyclicReference))
        );
        assert!(
            elem.append_child(elem.clone())
                .is_err_and(|err| matches!(err, XMLTreeError::CyclicReference))
        );
        assert!(
            elem.insert_next_sibling(elem.clone())
                .is_err_and(|err| matches!(err, XMLTreeError::CyclicReference))
        );
        assert!(
            elem2
                .append_child(elem2.clone())
                .is_err_and(|err| matches!(err, XMLTreeError::CyclicReference))
        );
        assert!(
            elem2
                .insert_previous_sibling(elem2.clone())
                .is_err_and(|err| matches!(err, XMLTreeError::CyclicReference))
        );
        assert!(
            elem2
                .insert_next_sibling(elem2.clone())
                .is_err_and(|err| matches!(err, XMLTreeError::CyclicReference))
        );
    }

    #[test]
    fn document_order_comparison_tests() {
        let mut parser = XMLReaderBuilder::new()
            .set_handler(TreeBuildHandler::default())
            .build();

        const CASE: &str = r#"<?xml version="1.0"?>
        <!DOCTYPE root [
            <!ELEMENT root   ANY>
            <!ATTLIST root   foo   CDATA #IMPLIED>
            <!ELEMENT child  ANY>
            <!ATTLIST child  bar   CDATA #IMPLIED
                             xmlns CDATA #FIXED "http://example.com/pre"
                             hoge  CDATA #IMPLIED>
            <!ELEMENT child2 ANY>
            <!ATTLIST child2 xmlns CDATA #FIXED "">
            <!ELEMENT child3 ANY>
            <!ENTITY  ent "in entity reference">
        ]>
        <!-- before document element -->
        <?pi before document element?>
        <root foo="foo">
            child of 'foo'
            <?pi in document element1?>
            <!-- in document element1 -->
            <child bar="bar" xmlns="http://example.com/pre" hoge="hoge">
                child of 'child'
                <child2 xmlns=""/>
                <![CDATA[child of 'child2']]>
                &ent;
                <?pi in document element2?>
                <!-- in document element2 -->
                <child3 xml:lang="ch" />
            </child>
        </root>
        <?pi after document element?>
        <!-- after document element -->"#;

        parser.parse_str(CASE, None).unwrap();
        assert!(!parser.handler.fatal_error);
        let document = parser.handler.document;
        let mut children = Some(Node::<dyn NodeSpec>::from(document.clone()));
        while let Some(now) = children {
            let mut others = Some(Node::<dyn NodeSpec>::from(document.clone()));
            let mut pre = true;
            while let Some(other) = others {
                if now.is_same_node(other.clone()) {
                    assert!(now.compare_document_order(other.clone()).unwrap().is_eq());
                    pre = false;
                    if let Some(element) = now.as_element() {
                        for att in element.attributes() {
                            assert!(att.compare_document_order(other.clone()).unwrap().is_gt());
                            assert!(now.compare_document_order(att).unwrap().is_lt());
                        }
                    }
                } else {
                    assert_eq!(
                        pre,
                        now.compare_document_order(other.clone()).unwrap().is_gt()
                    );
                    if let Some(element) = now.as_element() {
                        for att in element.attributes() {
                            assert_eq!(
                                pre,
                                att.compare_document_order(other.clone()).unwrap().is_gt()
                            );
                        }
                    }
                    if let Some(element) = other.as_element() {
                        for att in element.attributes() {
                            assert_eq!(pre, now.compare_document_order(att).unwrap().is_gt());
                        }
                    }
                }

                if let Some(first) = other.first_child() {
                    others = Some(first);
                } else if let Some(next) = other.next_sibling() {
                    others = Some(next);
                } else {
                    others = None;
                    let mut parent = other.parent_node();
                    while let Some(now) = parent {
                        if let Some(next) = now.next_sibling() {
                            others = Some(next);
                            break;
                        }
                        parent = now.parent_node();
                    }
                }
            }

            if let Some(first) = now.first_child() {
                children = Some(first);
            } else if let Some(next) = now.next_sibling() {
                children = Some(next);
            } else {
                children = None;
                let mut parent = now.parent_node();
                while let Some(now) = parent {
                    if let Some(next) = now.next_sibling() {
                        children = Some(next);
                        break;
                    }
                    parent = now.parent_node();
                }
            }
        }
    }

    #[test]
    fn base_uri_tests() {
        // Testing XML Base Conformance
        // https://www.w3.org/XML/2006/12/xmlbase-testing.html

        const CASES: &[&str] = &[
            r#"<elt xml:base="http://www.example.org/~Dürst/"/>"#,
            r#"<outer xml:base="http://www.example.org/one/two"> <inner xml:base=""/> </outer>"#,
            r#"<elt xml:base="http://www.example.org/one/two#frag"/>"#,
            r##"<outer xml:base="http://www.example.org/one/two"> <inner xml:base="#frag"/> </outer>"##,
        ];
        const TARGETS: &[&str] = &["elt", "inner", "elt", "inner"];
        const EXPECTED: &[&str] = &[
            "http://www.example.org/~Dürst/",
            "http://www.example.org/one/two",
            "http://www.example.org/one/two",
            "http://www.example.org/one/two",
        ];

        let mut parser = XMLReaderBuilder::new()
            .set_handler(TreeBuildHandler::default())
            .build();
        for (i, &case) in CASES.iter().enumerate() {
            parser.parse_str(case, None).unwrap();
            let document = parser.handler.document.clone();
            for elem in document.get_elements_by_qname(TARGETS[i]) {
                assert_eq!(
                    elem.base_uri().unwrap().as_unescaped_str().unwrap(),
                    EXPECTED[i]
                );
            }
        }
    }
}