xml_dom 0.2.8

A Rust crate providing a reasonably faithful implementation of the W3C DOM Core
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
use crate::level2::convert::*;
use crate::level2::dom_impl::{get_implementation, Implementation};
use crate::level2::ext::convert::as_element_namespaced_mut;
use crate::level2::ext::options::ProcessingOptions;
use crate::level2::node_impl::*;
use crate::level2::traits::*;
use crate::shared::error::*;
use crate::shared::name::Name;
use crate::shared::syntax::*;
use crate::shared::{display, text};
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::str::FromStr;
use tracing::warn;

// ------------------------------------------------------------------------------------------------
// Macros
// ------------------------------------------------------------------------------------------------

macro_rules! unwrap_extension_field {
    ($node:expr, $variant:ident, $field:ident) => {{
        let ref_self = $node.borrow();
        if let Extension::$variant { $field, .. } = &ref_self.i_extension {
            $field.clone()
        } else {
            warn!("{}", MSG_INVALID_EXTENSION);
            Default::default()
        }
    }};
    ($node:expr, $variant:ident, $field:ident, $closure_fn:expr) => {{
        let ref_self = $node.borrow();
        if let Extension::$variant { $field, .. } = &ref_self.i_extension {
            $closure_fn($field)
        } else {
            warn!("{}", MSG_INVALID_EXTENSION);
            Default::default()
        }
    }};
    ($node:expr, $variant:ident, $field:ident, $some_closure:expr) => {{
        let ref_self = $node.borrow();
        if let Extension::$variant { $field, .. } = &ref_self.i_extension {
            match $field {
                None => Default::default(),
                Some(value) => $some_closure(value),
            }
        } else {
            warn!("{}", MSG_INVALID_EXTENSION);
            Default::default()
        }
    }};
    ($node:expr, $variant:ident, $field:ident, $none_closure:expr, $some_closure:expr) => {{
        let ref_self = $node.borrow();
        if let Extension::$variant { $field, .. } = &ref_self.i_extension {
            match $field {
                None => $none_closure(),
                Some(value) => $some_closure(value),
            }
        } else {
            warn!("{}", MSG_INVALID_EXTENSION);
            Default::default()
        }
    }};
}

// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------

impl Attribute for RefNode {
    //
    // For Attribute instances:
    // On retrieval, the value of the attribute is returned as a string. Character and general
    // entity references are replaced with their values. See also the method `getAttribute` on the
    // `Element` interface.
    //
    // On setting, this creates a `Text` node with the unparsed contents of the string. I.e. any
    // characters that an XML processor would recognize as markup are instead treated as literal
    // text. See also the method `setAttribute` on the `Element` interface.
    //
    fn value(&self) -> Option<String> {
        if self.has_child_nodes() {
            let mut result = String::new();
            for child_node in self.child_nodes() {
                if child_node.node_type() == NodeType::EntityReference {
                    if let Some(value) = child_node.node_value() {
                        result.push_str(&value);
                    }
                } else if child_node.node_type() == NodeType::Text {
                    //
                    // Do not use the Text::data function as this will escape the response.
                    //
                    let ref_node = child_node.borrow();
                    if let Some(data) = &ref_node.i_value {
                        result.push_str(data);
                    }
                }
            }
            let normalized = text::normalize_attribute_value(&result, self, false);
            Some(text::escape(normalized))
        } else {
            None
        }
    }
    fn set_value(&mut self, value: &str) -> Result<()> {
        self.unset_value()?;
        let document_node = self.owner_document().unwrap();
        let document = as_document(&document_node).unwrap();
        let _safe_to_ignore = self.append_child(document.create_text_node(value))?;
        Ok(())
    }
    fn unset_value(&mut self) -> Result<()> {
        let mut mut_self = self.borrow_mut();
        mut_self.i_child_nodes.clear();
        Ok(())
    }
    fn owner_element(&self) -> Option<Self::NodeRef> {
        unwrap_extension_field!(
            self,
            Attribute,
            i_owner_element,
            |i_owner_element: &Option<WeakRefNode>| {
                match i_owner_element {
                    None => None,
                    Some(weak_ref) => match weak_ref.clone().upgrade() {
                        None => {
                            warn!("{}", MSG_WEAK_REF);
                            None
                        }
                        Some(ref_element) => Some(ref_element),
                    },
                }
            }
        )
    }
}

// ------------------------------------------------------------------------------------------------

impl CDataSection for RefNode {}

// ------------------------------------------------------------------------------------------------

impl CharacterData for RefNode {
    fn substring_data(&self, offset: usize, count: usize) -> Result<String> {
        if offset + count == offset {
            return Ok(String::new());
        }
        let ref_self = self.borrow();
        match &ref_self.i_value {
            None => {
                warn!("{}", MSG_INDEX_ERROR);
                Err(Error::IndexSize)
            }
            Some(data) => {
                if offset >= data.len() {
                    warn!("{}", MSG_INDEX_ERROR);
                    Err(Error::IndexSize)
                } else if offset + count >= data.len() {
                    Ok(data[offset..].to_string())
                } else {
                    Ok(data[offset..offset + count].to_string())
                }
            }
        }
    }

    fn append_data(&mut self, new_data: &str) -> Result<()> {
        if new_data.is_empty() {
            return Ok(());
        }
        let mut mut_self = self.borrow_mut();
        match &mut_self.i_value {
            None => mut_self.i_value = Some(new_data.to_string()),
            Some(old_data) => mut_self.i_value = Some(format!("{}{}", old_data, new_data)),
        }
        Ok(())
    }

    fn insert_data(&mut self, offset: usize, new_data: &str) -> Result<()> {
        if new_data.is_empty() {
            return Ok(());
        }
        self.replace_data(offset, 0, new_data)
    }

    fn delete_data(&mut self, offset: usize, count: usize) -> Result<()> {
        if offset + count == offset {
            return Ok(());
        }
        const NOTHING: &str = "";
        self.replace_data(offset, count, NOTHING)
    }

    fn replace_data(&mut self, offset: usize, count: usize, replace_data: &str) -> Result<()> {
        let mut mut_self = self.borrow_mut();
        match &mut_self.i_value {
            None => {
                if offset + count != 0 {
                    warn!("{}", MSG_INDEX_ERROR);
                    Err(Error::IndexSize)
                } else {
                    mut_self.i_value = Some(replace_data.to_string());
                    Ok(())
                }
            }
            Some(old_data) => {
                if offset >= old_data.len() {
                    warn!("{}", MSG_INDEX_ERROR);
                    Err(Error::IndexSize)
                } else {
                    let mut new_data = old_data.clone();
                    if offset + count >= old_data.len() {
                        new_data.replace_range(offset.., replace_data);
                    } else {
                        new_data.replace_range(offset..offset + count, replace_data);
                    }
                    mut_self.i_value = Some(new_data);
                    Ok(())
                }
            }
        }
    }
}

// ------------------------------------------------------------------------------------------------

impl Comment for RefNode {}

// ------------------------------------------------------------------------------------------------

impl Document for RefNode {
    fn doc_type(&self) -> Option<RefNode> {
        unwrap_extension_field!(self, Document, i_document_type)
    }

    fn document_element(&self) -> Option<RefNode> {
        self.child_nodes().first().cloned()
    }

    fn implementation(&self) -> &dyn DOMImplementation<NodeRef = RefNode> {
        let ref_self = self.borrow();
        if let Extension::Document {
            i_implementation, ..
        } = &ref_self.i_extension
        {
            *i_implementation
        } else {
            panic!("{}", MSG_INVALID_EXTENSION);
        }
    }

    fn create_attribute(&self, name: &str) -> Result<RefNode> {
        let name = Name::from_str(name)?;
        let node_impl = NodeImpl::new_attribute(self.clone().downgrade(), name, None);
        Ok(RefNode::new(node_impl))
    }

    fn create_attribute_with(&self, name: &str, value: &str) -> Result<RefNode> {
        let name = Name::from_str(name)?;
        let node_impl = NodeImpl::new_attribute(self.clone().downgrade(), name, Some(value));
        Ok(RefNode::new(node_impl))
    }

    fn create_attribute_ns(&self, namespace_uri: &str, qualified_name: &str) -> Result<RefNode> {
        let name = Name::new_ns(namespace_uri, qualified_name)?;
        let node_impl = NodeImpl::new_attribute(self.clone().downgrade(), name, None);
        Ok(RefNode::new(node_impl))
    }

    fn create_cdata_section(&self, data: &str) -> Result<RefNode> {
        let node_impl = NodeImpl::new_cdata(self.clone().downgrade(), data);
        Ok(RefNode::new(node_impl))
    }

    fn create_document_fragment(&self) -> Result<RefNode> {
        let node_impl = NodeImpl::new_document_fragment(self.clone().downgrade());
        Ok(RefNode::new(node_impl))
    }

    fn create_entity_reference(&self, name: &str) -> Result<RefNode> {
        let name = Name::from_str(name)?;
        let node_impl = NodeImpl::new_entity_reference(self.clone().downgrade(), name);
        Ok(RefNode::new(node_impl))
    }

    fn create_comment(&self, data: &str) -> RefNode {
        let node_impl = NodeImpl::new_comment(self.clone().downgrade(), data);
        RefNode::new(node_impl)
    }

    fn create_element(&self, tag_name: &str) -> Result<RefNode> {
        let name = Name::from_str(tag_name)?;
        let node_impl = NodeImpl::new_element(self.clone().downgrade(), name);
        Ok(RefNode::new(node_impl))
    }

    fn create_element_ns(&self, namespace_uri: &str, qualified_name: &str) -> Result<RefNode> {
        let name = Name::new_ns(namespace_uri, qualified_name)?;
        let node_impl = NodeImpl::new_element(self.clone().downgrade(), name);
        Ok(RefNode::new(node_impl))
    }

    fn create_processing_instruction(&self, target: &str, data: Option<&str>) -> Result<RefNode> {
        //
        // Ensure:
        //
        // `PITarget  ::=  Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))`
        //
        if target.to_ascii_lowercase() == XML_PI_RESERVED {
            return Err(Error::Syntax);
        }
        let target = Name::from_str(target)?;
        let node_impl =
            NodeImpl::new_processing_instruction(self.clone().downgrade(), target, data);
        Ok(RefNode::new(node_impl))
    }

    fn create_text_node(&self, data: &str) -> RefNode {
        let node_impl = NodeImpl::new_text(self.clone().downgrade(), data);
        RefNode::new(node_impl)
    }

    fn get_element_by_id(&self, id: &str) -> Option<RefNode> {
        let ref_self = self.borrow();
        if let Extension::Document { i_id_map, .. } = &ref_self.i_extension {
            match i_id_map.get(&id.to_string()) {
                None => None,
                Some(weak_ref) => match weak_ref.clone().upgrade() {
                    None => {
                        warn!("{}", MSG_WEAK_REF);
                        None
                    }
                    Some(ref_element) => Some(ref_element),
                },
            }
        } else {
            warn!("{}", MSG_INVALID_EXTENSION);
            None
        }
    }

    fn get_elements_by_tag_name(&self, tag_name: &str) -> Vec<RefNode> {
        //
        // Delegate this call to the document element
        //
        if let Some(root_element) = self.document_element() {
            Element::get_elements_by_tag_name(&root_element, tag_name)
        } else {
            Vec::default()
        }
    }

    fn get_elements_by_tag_name_ns(&self, namespace_uri: &str, local_name: &str) -> Vec<RefNode> {
        //
        // Delegate this call to the document element
        //
        if let Some(root_element) = self.document_element() {
            Element::get_elements_by_tag_name_ns(&root_element, namespace_uri, local_name)
        } else {
            Vec::default()
        }
    }
}

// ------------------------------------------------------------------------------------------------

impl DocumentFragment for RefNode {}

// ------------------------------------------------------------------------------------------------

impl DocumentType for RefNode {
    fn entities(&self) -> HashMap<Name, Self::NodeRef, RandomState> {
        unwrap_extension_field!(self, DocumentType, i_entities)
    }

    fn notations(&self) -> HashMap<Name, Self::NodeRef, RandomState> {
        unwrap_extension_field!(self, DocumentType, i_notations)
    }

    fn public_id(&self) -> Option<String> {
        unwrap_extension_field!(self, DocumentType, i_public_id)
    }

    fn system_id(&self) -> Option<String> {
        unwrap_extension_field!(self, DocumentType, i_system_id)
    }

    fn internal_subset(&self) -> Option<String> {
        unwrap_extension_field!(self, DocumentType, i_internal_subset)
    }
}

// ------------------------------------------------------------------------------------------------

impl DOMImplementation for Implementation {
    type NodeRef = RefNode;

    fn create_document(
        &self,
        namespace_uri: Option<&str>,
        qualified_name: Option<&str>,
        doc_type: Option<RefNode>,
    ) -> Result<RefNode> {
        let mut options = ProcessingOptions::new();
        options.set_add_namespaces();
        create_document_with_options(namespace_uri, qualified_name, doc_type, options)
    }

    fn create_document_type(
        &self,
        qualified_name: &str,
        public_id: Option<&str>,
        system_id: Option<&str>,
    ) -> Result<RefNode> {
        let name = Name::from_str(qualified_name)?;
        let node_impl = NodeImpl::new_document_type(None, name, public_id, system_id);
        Ok(RefNode::new(node_impl))
    }

    fn has_feature(&self, feature: &str, version: &str) -> bool {
        (feature == XML_FEATURE_CORE || feature == XML_FEATURE_XML)
            && (version == XML_FEATURE_V1 || version == XML_FEATURE_V2)
    }
}

// ------------------------------------------------------------------------------------------------

impl Element for RefNode {
    fn get_attribute(&self, name: &str) -> Option<String> {
        match self.get_attribute_node(name) {
            None => None,
            Some(attribute_node) => match as_attribute(&attribute_node) {
                Ok(attribute) => attribute.value(),
                Err(_) => {
                    warn!("{}", MSG_INVALID_NODE_TYPE);
                    None
                }
            },
        }
    }

    fn set_attribute(&mut self, name: &str, value: &str) -> Result<()> {
        let attr_name = Name::from_str(name)?;
        let attr_node = {
            let ref_self = &self.borrow_mut();
            let document = ref_self.i_owner_document.as_ref().unwrap();
            NodeImpl::new_attribute(document.clone(), attr_name, Some(value))
        };
        self.set_attribute_node(RefNode::new(attr_node)).map(|_| ())
    }

    fn remove_attribute(&mut self, name: &str) -> Result<()> {
        match self.get_attribute_node(name) {
            None => Ok(()),
            Some(attribute_node) => self.remove_attribute_node(attribute_node).map(|_| ()),
        }
    }

    fn get_attribute_node(&self, name: &str) -> Option<RefNode> {
        if is_element(self) {
            match Name::from_str(name) {
                Ok(name) => {
                    let ref_self = self.borrow();
                    if let Extension::Element { i_attributes, .. } = &ref_self.i_extension {
                        let node_name = name.to_string();
                        i_attributes
                            .iter()
                            .find(|(name, _)| name.to_string() == node_name)
                            .map(|(_, node)| node.clone())
                    } else {
                        warn!("{}", MSG_INVALID_EXTENSION);
                        None
                    }
                }
                Err(_) => {
                    warn!("{}: '{}'", MSG_INVALID_NAME, name);
                    None
                }
            }
        } else {
            warn!("{}", MSG_INVALID_NODE_TYPE);
            None
        }
    }

    fn set_attribute_node(&mut self, new_attribute: RefNode) -> Result<RefNode> {
        if is_element(self) && is_attribute(&new_attribute) {
            check_same_document(self, &new_attribute)?;

            //
            // Set the attribute's owner. This is *not* the same as parent which remains `None`.
            //
            {
                let mut mut_child = new_attribute.borrow_mut();
                if let Extension::Attribute {
                    i_owner_element, ..
                } = &mut mut_child.i_extension
                {
                    *i_owner_element = Some(self.clone().downgrade())
                } else {
                    panic!("{}", MSG_INVALID_EXTENSION);
                }
            }

            let name: Name = new_attribute.node_name();
            if name.is_namespace_attribute() {
                //
                // Add to the element's namespace mapping hash
                //
                let attribute = as_attribute(&new_attribute).unwrap();
                let namespace_uri = attribute.value().unwrap();

                let as_namespaced = as_element_namespaced_mut(self).unwrap();
                let _ignore = match &name.prefix() {
                    None => as_namespaced.insert_mapping(None, &namespace_uri),
                    Some(prefix) => as_namespaced.insert_mapping(Some(prefix), &namespace_uri),
                }?;
            }

            let mut mut_self = self.borrow_mut();
            if let Extension::Element { i_attributes, .. } = &mut mut_self.i_extension {
                let _safe_to_ignore =
                    i_attributes.insert(new_attribute.node_name(), new_attribute.clone());
                {
                    //
                    // Add to the owning document's id_map hash
                    //
                    let attribute = as_attribute(&new_attribute).unwrap();
                    let document = attribute.owner_document().unwrap();
                    let mut mut_document = document.borrow_mut();
                    let lax =
                        if let Extension::Document { i_options, .. } = &mut_document.i_extension {
                            i_options.has_assume_ids()
                        } else {
                            warn!("{}", MSG_INVALID_EXTENSION);
                            false
                        };
                    if name.is_id_attribute(lax) {
                        //
                        // Update the document ID mapping
                        //
                        if let Extension::Document { i_id_map, .. } = &mut mut_document.i_extension
                        {
                            let id_value = attribute.value().unwrap();
                            if i_id_map.contains_key(&id_value) {
                                warn!("{}", MSG_DUPLICATE_ID);
                                return Err(Error::Syntax);
                            }
                            let _safe_to_ignore =
                                i_id_map.insert(id_value, self.clone().downgrade());
                        } else {
                            warn!("{}", MSG_INVALID_EXTENSION);
                        }
                    }
                }
                Ok(new_attribute)
            } else {
                warn!("{}", MSG_INVALID_EXTENSION);
                Err(Error::Syntax)
            }
        } else {
            warn!("{}", MSG_INVALID_NODE_TYPE);
            Err(Error::InvalidState)
        }
    }

    fn remove_attribute_node(&mut self, old_attribute: RefNode) -> Result<RefNode> {
        if is_element(self) {
            let mut mut_self = self.borrow_mut();
            if let Extension::Element { i_attributes, .. } = &mut mut_self.i_extension {
                let _safe_to_ignore = i_attributes.remove(&old_attribute.node_name());
                let mut_old = old_attribute.clone();
                let mut mut_old = mut_old.borrow_mut();
                mut_old.i_parent_node = None;
                // TODO: remove from Element::namespaces
                // TODO: remove from Document::id_map
                Ok(old_attribute)
            } else {
                warn!("{}", MSG_INVALID_EXTENSION);
                Err(Error::Syntax)
            }
        } else {
            warn!("{}", MSG_INVALID_NODE_TYPE);
            Err(Error::InvalidState)
        }
    }

    fn get_elements_by_tag_name(&self, tag_name: &str) -> Vec<RefNode> {
        let mut results = Vec::default();
        if is_element(self) {
            let tag_name = tag_name.to_string();
            let ref_self = self.borrow();
            if tag_name_match(&ref_self.i_name.to_string(), &tag_name) {
                results.push(self.clone());
            }
            for child_node in &ref_self.i_child_nodes {
                match as_element(child_node) {
                    Ok(ref_child) => results.extend(ref_child.get_elements_by_tag_name(&tag_name)),
                    Err(_) => {
                        warn!("{}", MSG_INVALID_NODE_TYPE);
                    }
                }
            }
        }
        results
    }

    fn get_attribute_ns(&self, namespace_uri: &str, local_name: &str) -> Option<String> {
        match self.get_attribute_node_ns(namespace_uri, local_name) {
            None => None,
            Some(attribute_node) => match as_attribute(&attribute_node) {
                Ok(attribute) => attribute.value(),
                Err(_) => {
                    warn!("{}", MSG_INVALID_NODE_TYPE);
                    None
                }
            },
        }
    }

    fn set_attribute_ns(
        &mut self,
        namespace_uri: &str,
        qualified_name: &str,
        value: &str,
    ) -> Result<()> {
        let attr_name = Name::new_ns(namespace_uri, qualified_name)?;
        let attr_node = {
            let ref_self = &self.borrow_mut();
            let document = ref_self.i_owner_document.as_ref().unwrap();
            NodeImpl::new_attribute(document.clone(), attr_name, Some(value))
        };
        self.set_attribute_node(RefNode::new(attr_node)).map(|_| ())
    }

    fn remove_attribute_ns(&mut self, namespace_uri: &str, local_name: &str) -> Result<()> {
        match self.get_attribute_node_ns(namespace_uri, local_name) {
            None => Ok(()),
            Some(attribute_node) => self.remove_attribute_node(attribute_node).map(|_| ()),
        }
    }

    fn get_attribute_node_ns(&self, namespace_uri: &str, local_name: &str) -> Option<RefNode> {
        if is_element(self) {
            match Name::new_ns(namespace_uri, local_name) {
                Ok(_) => {
                    let ref_self = self.borrow();
                    if let Extension::Element { i_attributes, .. } = &ref_self.i_extension {
                        let namespace_uri = &Some(namespace_uri.to_string());
                        let local_name = &local_name.to_string();
                        i_attributes
                            .iter()
                            .find(|(name, _)| {
                                name.namespace_uri() == namespace_uri
                                    && name.local_name() == local_name
                            })
                            .map(|(_, node)| node.clone())
                    } else {
                        warn!("{}", MSG_INVALID_EXTENSION);
                        None
                    }
                }
                Err(_) => {
                    warn!("{}: '{}'", MSG_INVALID_NAME, local_name);
                    None
                }
            }
        } else {
            warn!("{}", MSG_INVALID_NODE_TYPE);
            None
        }
    }

    fn set_attribute_node_ns(&mut self, new_attribute: RefNode) -> Result<RefNode> {
        self.set_attribute_node(new_attribute)
    }

    fn get_elements_by_tag_name_ns(&self, namespace_uri: &str, local_name: &str) -> Vec<RefNode> {
        let mut results = Vec::default();
        if is_element(self) {
            let namespace_uri = namespace_uri.to_string();
            let local_name = local_name.to_string();
            let ref_self = self.borrow();
            if namespaced_name_match(
                match ref_self.i_name.namespace_uri() {
                    None => None,
                    Some(s) => Some(s.as_str()),
                },
                ref_self.i_name.local_name(),
                &namespace_uri,
                &local_name,
            ) {
                results.push(self.clone());
            }
            for child_node in &ref_self.i_child_nodes {
                match as_element(child_node) {
                    Ok(ref_child) => results
                        .extend(ref_child.get_elements_by_tag_name_ns(&namespace_uri, &local_name)),
                    Err(_) => {
                        warn!("{}", MSG_INVALID_NODE_TYPE);
                    }
                }
            }
        }
        results
    }

    fn has_attribute(&self, name: &str) -> bool {
        if is_element(self) {
            match Name::from_str(name) {
                Ok(name) => {
                    let ref_self = self.borrow();
                    if let Extension::Element { i_attributes, .. } = &ref_self.i_extension {
                        i_attributes
                            .keys()
                            .any(|n| n.to_string() == name.to_string())
                    } else {
                        warn!("{}", MSG_INVALID_EXTENSION);
                        false
                    }
                }
                Err(_) => {
                    warn!("{}: '{}'", MSG_INVALID_NAME, name);
                    false
                }
            }
        } else {
            warn!("{}", MSG_INVALID_NODE_TYPE);
            false
        }
    }

    fn has_attribute_ns(&self, namespace_uri: &str, local_name: &str) -> bool {
        if is_element(self) {
            match Name::new_ns(namespace_uri, local_name) {
                Ok(name) => {
                    let ref_self = self.borrow();
                    if let Extension::Element { i_attributes, .. } = &ref_self.i_extension {
                        i_attributes.keys().any(|n| {
                            n.namespace_uri() == name.namespace_uri()
                                && n.local_name() == name.local_name()
                        })
                    } else {
                        warn!("{}", MSG_INVALID_EXTENSION);
                        false
                    }
                }
                Err(_) => {
                    warn!("{}: '{}'", MSG_INVALID_NAME, local_name);
                    false
                }
            }
        } else {
            warn!("{}", MSG_INVALID_NODE_TYPE);
            false
        }
    }
}

// ------------------------------------------------------------------------------------------------

impl Entity for RefNode {
    fn public_id(&self) -> Option<String> {
        unwrap_extension_field!(self, Entity, i_public_id)
    }

    fn system_id(&self) -> Option<String> {
        unwrap_extension_field!(self, Entity, i_system_id)
    }

    fn notation_name(&self) -> Option<String> {
        unwrap_extension_field!(self, Entity, i_notation_name)
    }
}

// ------------------------------------------------------------------------------------------------

impl EntityReference for RefNode {}

// ------------------------------------------------------------------------------------------------

impl Node for RefNode {
    type NodeRef = RefNode;

    fn node_name(&self) -> Name {
        let ref_self = self.borrow();
        ref_self.i_name.clone()
    }

    fn node_value(&self) -> Option<String> {
        let ref_self = self.borrow();
        ref_self.i_value.clone()
    }

    fn set_node_value(&mut self, value: &str) -> Result<()> {
        let mut mut_self = self.borrow_mut();
        mut_self.i_value = Some(value.to_string());
        Ok(())
    }

    fn unset_node_value(&mut self) -> Result<()> {
        let mut mut_self = self.borrow_mut();
        mut_self.i_value = None;
        Ok(())
    }

    fn node_type(&self) -> NodeType {
        let ref_self = self.borrow();
        ref_self.i_node_type.clone()
    }

    fn parent_node(&self) -> Option<RefNode> {
        if is_attribute(self) {
            return None;
        }
        let ref_self = self.borrow();
        match &ref_self.i_parent_node {
            None => None,
            Some(node) => node.clone().upgrade(),
        }
    }

    fn child_nodes(&self) -> Vec<RefNode> {
        let ref_self = self.borrow();
        ref_self.i_child_nodes.clone()
    }

    fn first_child(&self) -> Option<RefNode> {
        let ref_self = self.borrow();
        ref_self.i_child_nodes.first().cloned()
    }

    fn last_child(&self) -> Option<RefNode> {
        let ref_self = self.borrow();
        ref_self.i_child_nodes.last().cloned()
    }

    fn previous_sibling(&self) -> Option<RefNode> {
        if is_attribute(self) {
            return None;
        }
        let ref_self = self.borrow();
        match &ref_self.i_parent_node {
            None => {
                warn!("{}", MSG_NO_PARENT_NODE);
                None
            }
            Some(parent_node) => {
                let parent_node = parent_node.clone();
                let parent_node = parent_node.upgrade()?;
                let ref_parent = parent_node.borrow();
                match ref_parent
                    .i_child_nodes
                    .iter()
                    .position(|child| child == self)
                {
                    None => None,
                    Some(index) => {
                        if index == 0 {
                            None
                        } else {
                            let sibling = ref_parent.i_child_nodes.get(index - 1);
                            sibling.cloned()
                        }
                    }
                }
            }
        }
    }

    fn next_sibling(&self) -> Option<RefNode> {
        if is_attribute(self) {
            return None;
        }
        let ref_self = self.borrow();
        match &ref_self.i_parent_node {
            None => {
                warn!("{}", MSG_NO_PARENT_NODE);
                None
            }
            Some(parent_node) => {
                let parent_node = parent_node.clone();
                let parent_node = parent_node.upgrade()?;
                let ref_parent = parent_node.borrow();
                match ref_parent
                    .i_child_nodes
                    .iter()
                    .position(|child| child == self)
                {
                    None => None,
                    Some(index) => {
                        let sibling = ref_parent.i_child_nodes.get(index + 1);
                        sibling.cloned()
                    }
                }
            }
        }
    }

    fn attributes(&self) -> HashMap<Name, RefNode, RandomState> {
        if is_element(self) {
            unwrap_extension_field!(self, Element, i_attributes)
        } else {
            warn!("{}", MSG_INVALID_NODE_TYPE);
            HashMap::default()
        }
    }

    fn owner_document(&self) -> Option<RefNode> {
        let ref_self = self.borrow();
        match &ref_self.i_owner_document {
            None => None,
            Some(node) => node.clone().upgrade(),
        }
    }

    fn insert_before(&mut self, new_child: RefNode, ref_child: Option<RefNode>) -> Result<RefNode> {
        fn insert_or_append(
            parent_node: &mut RefNode,
            new_child: &RefNode,
            insert_position: Option<usize>,
        ) {
            let mut mut_parent = parent_node.borrow_mut();
            let new_child = new_child.clone();
            match insert_position {
                None => mut_parent.i_child_nodes.push(new_child),
                Some(position) => mut_parent.i_child_nodes.insert(position, new_child),
            }
        }

        if !is_child_allowed(self, &new_child) {
            warn!("The child you tried to add is not valid for this parent.");
            return Err(Error::HierarchyRequest);
        }

        //
        // Special case for Document only.
        //
        if is_document(self)
            && is_element(&new_child)
            && self
                .child_nodes()
                .iter()
                .any(|n| n.node_type() == NodeType::Element)
        {
            warn!("cannot add more than one element to a document");
            return Error::HierarchyRequest.into();
        }

        //
        // Find the index in `child_nodes` of the `ref_child`.
        //
        let insert_position = match ref_child {
            None => None,
            Some(ref_child) => match self
                .borrow()
                .i_child_nodes
                .iter()
                .position(|child| child == &ref_child)
            {
                None => {
                    warn!("insert_before: ref_child not found in `child_nodes`");
                    return Error::NotFound.into();
                }
                position => position,
            },
        };

        check_same_document(self, &new_child)?;

        //
        // Remove from it's current parent
        //
        match new_child.parent_node() {
            None => (),
            Some(mut parent_node) => {
                let _safe_to_ignore = parent_node.remove_child(new_child.clone())?;
            }
        }

        //
        // update new child with references from self
        //
        {
            let ref_self = self.borrow();
            let mut mut_child = new_child.borrow_mut();
            mut_child.i_parent_node = Some(self.to_owned().downgrade());
            if is_document(self) {
                mut_child.i_owner_document = Some(self.clone().downgrade());
            } else {
                mut_child
                    .i_owner_document
                    .clone_from(&ref_self.i_owner_document);
            }
        }

        //
        // Special case
        //
        if is_document_fragment(&new_child) {
            for (index, child) in new_child.child_nodes().iter().enumerate() {
                match insert_position {
                    None => insert_or_append(self, child, None),
                    Some(position) => insert_or_append(self, child, Some(position + index)),
                }
            }
        } else {
            insert_or_append(self, &new_child, insert_position)
        }

        Ok(new_child)
    }

    fn replace_child(&mut self, new_child: RefNode, old_child: RefNode) -> Result<RefNode> {
        if !is_child_allowed(self, &new_child) {
            return Err(Error::HierarchyRequest);
        }
        let exists = {
            let ref_self = self.borrow();
            ref_self.i_child_nodes.contains(&old_child.clone())
        };
        if exists {
            let next_node = old_child.next_sibling();
            let removed = self.remove_child(old_child)?;
            let _safe_to_ignore = self.insert_before(new_child, next_node)?;
            Ok(removed)
        } else {
            warn!("replace_child: old_child not found in `child_nodes`");
            Err(Error::NotFound)
        }
    }

    fn remove_child(&mut self, old_child: Self::NodeRef) -> Result<Self::NodeRef> {
        let position = {
            let ref_self = self.borrow();
            ref_self
                .i_child_nodes
                .iter()
                .position(|child| child == &old_child)
        };
        match position {
            None => {
                warn!("remove_child: old_child not found in `child_nodes`");
                Err(Error::NotFound)
            }
            Some(position) => {
                let removed = {
                    let mut mut_self = self.borrow_mut();
                    mut_self.i_child_nodes.remove(position)
                };
                let mut mut_removed = removed.borrow_mut();
                mut_removed.i_parent_node = None;
                Ok(removed.clone())
            }
        }
    }

    fn append_child(&mut self, new_child: RefNode) -> Result<RefNode> {
        self.insert_before(new_child, None)
    }

    fn has_child_nodes(&self) -> bool {
        !self.child_nodes().is_empty()
    }

    fn clone_node(&self, deep: bool) -> Option<RefNode> {
        let ref_self = self.borrow();
        let new_node = ref_self.clone_node(deep);
        Some(RefNode::new(new_node))
    }

    fn normalize(&mut self) {
        for child_node in self.child_nodes() {
            if is_text(&child_node) {
                if CharacterData::length(&child_node) == 0 {
                    if self.remove_child(child_node).is_err() {
                        panic!("Could not remove unnecessary text node");
                    }
                } else if let Some(last_child_node) = child_node.previous_sibling() {
                    let last_child_node = &mut last_child_node.clone();
                    if is_text(last_child_node) {
                        if last_child_node
                            .append_data(&child_node.node_value().unwrap())
                            .is_err()
                        {
                            panic!("Could not merge text nodes");
                        }
                        if self.remove_child(child_node).is_err() {
                            panic!("Could not remove unnecessary text node");
                        }
                    }
                }
            }
        }
    }

    fn is_supported(&self, feature: &str, version: &str) -> bool {
        get_implementation().has_feature(feature, version)
    }

    fn has_attributes(&self) -> bool {
        !self.attributes().is_empty()
    }
}

// ------------------------------------------------------------------------------------------------

impl Notation for RefNode {
    fn public_id(&self) -> Option<String> {
        unwrap_extension_field!(self, Notation, i_public_id)
    }

    fn system_id(&self) -> Option<String> {
        unwrap_extension_field!(self, Notation, i_system_id)
    }
}

// ------------------------------------------------------------------------------------------------

impl ProcessingInstruction for RefNode {}

// ------------------------------------------------------------------------------------------------

impl Text for RefNode {
    fn split(&mut self, offset: usize) -> Result<RefNode> {
        let new_data = {
            let text = as_character_data_mut(self)?;
            let length = text.length();
            if offset >= length {
                String::new()
            } else {
                let count = length - offset;
                let new_data = text.substring_data(offset, count)?;
                text.delete_data(offset, count)?;
                new_data
            }
        };

        let new_node = {
            //
            // Create a new node and adjust contents
            //
            let mut_self = self.borrow_mut();
            match mut_self.i_node_type {
                NodeType::Text => {
                    let document = mut_self.i_owner_document.as_ref().unwrap();
                    Ok(NodeImpl::new_text(document.clone(), &new_data))
                }
                NodeType::CData => {
                    let document = mut_self.i_owner_document.as_ref().unwrap();
                    Ok(NodeImpl::new_cdata(document.clone(), &new_data))
                }
                _ => {
                    warn!("{}", MSG_INVALID_NODE_TYPE);
                    Err(Error::Syntax)
                }
            }?
        };

        let new_node = RefNode::new(new_node);
        if let Some(mut parent) = self.parent_node() {
            let _safe_to_ignore = parent.insert_before(new_node.clone(), self.next_sibling())?;
        }
        Ok(new_node)
    }
}

// ------------------------------------------------------------------------------------------------

impl Display for RefNode {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        display::fmt_node(self, f)
    }
}

// ------------------------------------------------------------------------------------------------
// Private Functions
// ------------------------------------------------------------------------------------------------

const WILD_CARD: &str = "*";

fn tag_name_match(test: &str, against: &str) -> bool {
    (test == against) || test == WILD_CARD || against == WILD_CARD
}

fn namespaced_name_match(
    test_ns: Option<&str>,
    test_local: &str,
    against_ns: &str,
    against_local: &str,
) -> bool {
    match test_ns {
        None => {
            against_ns == WILD_CARD
                && ((test_local == against_local)
                    || test_local == WILD_CARD
                    || against_local == WILD_CARD)
        }
        Some(test_ns) => {
            ((test_ns == against_ns) || test_ns == WILD_CARD || against_ns == WILD_CARD)
                && ((test_local == against_local)
                    || test_local == WILD_CARD
                    || against_local == WILD_CARD)
        }
    }
}

//
// CHECK: Raise `Error::WrongDocument` if `newChild` was created from a different
// document than the one that created this node.
//
fn check_same_document(self_node: &RefNode, new_child: &RefNode) -> Result<()> {
    {
        if self_node.node_type() == NodeType::Document {
            let child_document = &new_child.borrow().i_owner_document;
            if !match child_document {
                None => true,
                Some(child_document) => {
                    let child_document = child_document.clone().upgrade().unwrap();
                    self_node == &child_document
                }
            } {
                warn!("Error::WrongDocument: child could not be added to the document node.");
                return Err(Error::WrongDocument);
            }
        } else {
            let self_document = &self_node.borrow().i_owner_document;
            let child_document = &new_child.borrow().i_owner_document;
            if !match (self_document, child_document) {
                (None, None) => true,
                (Some(_), None) => true,
                (None, Some(_)) => false,
                (Some(self_document), Some(child_document)) => {
                    let self_document = self_document.clone().upgrade().unwrap();
                    let child_document = child_document.clone().upgrade().unwrap();
                    self_document == child_document
                }
            } {
                warn!("Error::WrongDocument: child could not be added to the current node.");
                return Err(Error::WrongDocument);
            }
        }
    }
    Ok(())
}
//
// From [https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1590626202]
//
// The DOM presents documents as a hierarchy of Node objects that also implement other, more
// specialized interfaces. Some types of nodes may have child nodes of various types, and others
// are leaf nodes that cannot have anything below them in the document structure. For XML and HTML,
// the node types, and which node types they may have as children, are as follows:
//
// * Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType (maximum of one)
// * DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
// * DocumentType -- no children
// * EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
// * Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
// * Attr -- Text, EntityReference
// * ProcessingInstruction -- no children
// * Comment -- no children
// * Text -- no children
// * CDATASection -- no children
// * Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
// * Notation -- no children
//
fn is_child_allowed(parent: &RefNode, child: &RefNode) -> bool {
    let self_node_type = { &parent.borrow().i_node_type };
    let child_node_type = { &child.borrow().i_node_type };
    match self_node_type {
        NodeType::Element => matches!(
            child_node_type,
            NodeType::Element
                | NodeType::Text
                | NodeType::Comment
                | NodeType::ProcessingInstruction
                | NodeType::CData
                | NodeType::EntityReference
        ),
        NodeType::Attribute => {
            matches!(child_node_type, NodeType::Text | NodeType::EntityReference)
        }
        NodeType::Text => false,
        NodeType::CData => false,
        NodeType::EntityReference => matches!(
            child_node_type,
            NodeType::Element
                | NodeType::Text
                | NodeType::Comment
                | NodeType::ProcessingInstruction
                | NodeType::CData
                | NodeType::EntityReference
        ),
        NodeType::Entity => matches!(
            child_node_type,
            NodeType::Element
                | NodeType::Text
                | NodeType::Comment
                | NodeType::ProcessingInstruction
                | NodeType::CData
                | NodeType::EntityReference
        ),
        NodeType::ProcessingInstruction => false,
        NodeType::Comment => false,
        NodeType::Document => matches!(
            child_node_type,
            NodeType::Element | NodeType::Comment | NodeType::ProcessingInstruction
        ),
        NodeType::DocumentType => false,
        NodeType::DocumentFragment => matches!(
            child_node_type,
            NodeType::Element
                | NodeType::Text
                | NodeType::Comment
                | NodeType::ProcessingInstruction
                | NodeType::CData
                | NodeType::EntityReference
        ),
        NodeType::Notation => false,
    }
}

pub(crate) fn create_document_with_options(
    namespace_uri: Option<&str>,
    qualified_name: Option<&str>,
    doc_type: Option<RefNode>,
    options: ProcessingOptions,
) -> Result<RefNode> {
    let node_impl = NodeImpl::new_document(doc_type, options);
    let mut document_node = RefNode::new(node_impl);

    //
    // If specified, create a new root element
    //
    let element: Option<RefNode> = {
        let ref_document = as_document(&document_node)?;
        match (namespace_uri, qualified_name) {
            (Some(namespace_uri), Some(qualified_name)) => {
                Some(ref_document.create_element_ns(namespace_uri, qualified_name)?)
            }
            (None, Some(qualified_name)) => Some(ref_document.create_element(qualified_name)?),
            (Some(_), None) => return Error::Namespace.into(),
            (None, None) => None,
        }
    };

    //
    // If successfully created, append root element. This can only be done once.
    //
    if let Some(element_node) = element {
        let document = as_document_mut(&mut document_node)?;
        let _safe_to_ignore = document.append_child(element_node)?;
    }

    Ok(document_node)
}