anyxml 0.4.0

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
use std::{
    cell::{Ref, RefCell},
    rc::{Rc, Weak},
};

use anyxml_uri::uri::{URIStr, URIString};

use crate::{
    sax::{AttributeType, DefaultDecl, contentspec::ContentSpec},
    tree::{
        AttlistDecl, CDATASection, Comment, DocumentFragment, DocumentType, Element, ElementDecl,
        EntityDecl, EntityReference, NodeType, NotationDecl, ProcessingInstruction, Text,
        XMLTreeError,
        convert::NodeKind,
        document_fragment::DocumentFragmentSpec,
        document_type::DocumentTypeSpec,
        element::ElementSpec,
        node::{InternalNodeSpec, Node, NodeCore, NodeSpec},
    },
};

pub struct DocumentSpec {
    first_child: Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>>,
    last_child: Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>>,

    document_element: Option<Rc<RefCell<NodeCore<ElementSpec>>>>,
    document_type: Option<Rc<RefCell<NodeCore<DocumentTypeSpec>>>>,

    version: Option<Box<str>>,
    encoding: Option<Box<str>>,
    standalone: Option<bool>,
    base_uri: Box<URIStr>,
}

impl NodeSpec for DocumentSpec {
    fn node_type(&self) -> NodeType {
        NodeType::Document
    }

    fn first_child(&self) -> Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>> {
        self.first_child.clone()
    }

    fn last_child(&self) -> Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>> {
        self.last_child.clone()
    }
}

impl InternalNodeSpec for DocumentSpec {
    fn set_first_child(&mut self, new: Rc<RefCell<NodeCore<dyn NodeSpec>>>) {
        self.first_child = Some(new);
    }
    fn unset_first_child(&mut self) {
        self.first_child = None;
    }

    fn set_last_child(&mut self, new: Rc<RefCell<NodeCore<dyn NodeSpec>>>) {
        self.last_child = Some(new);
    }
    fn unset_last_child(&mut self) {
        self.last_child = None;
    }

    fn pre_child_removal(&mut self, removed_child: Node<dyn NodeSpec>) -> Result<(), XMLTreeError> {
        match removed_child.node_type() {
            NodeType::Element => {
                self.document_element = None;
            }
            NodeType::DocumentType => {
                self.document_type = None;
            }
            _ => {}
        }
        Ok(())
    }

    fn pre_child_insertion(
        &self,
        inserted_child: Node<dyn NodeSpec>,
        mut preceding_node: Option<Node<dyn NodeSpec>>,
    ) -> Result<(), XMLTreeError> {
        match inserted_child.node_type() {
            NodeType::DocumentType => {
                if self.document_type.is_some() {
                    return Err(XMLTreeError::MultipleDocumentType);
                }
                if self.document_element.is_some() {
                    while let Some(now) = preceding_node {
                        if matches!(now.node_type(), NodeType::Element) {
                            return Err(XMLTreeError::UnacceptableHorizontality);
                        }
                        preceding_node = now.previous_sibling();
                    }
                }
            }
            NodeType::Element => {
                if self.document_element.is_some() {
                    return Err(XMLTreeError::MultipleDocumentElement);
                }
                if self.document_type.is_some() {
                    while let Some(now) = preceding_node.as_ref() {
                        if matches!(now.node_type(), NodeType::DocumentType) {
                            break;
                        }
                        preceding_node = now.previous_sibling();
                    }

                    if preceding_node.is_none() {
                        return Err(XMLTreeError::UnacceptableHorizontality);
                    }
                }
            }
            NodeType::Comment | NodeType::ProcessingInstruction => {}
            _ => return Err(XMLTreeError::UnacceptableHierarchy),
        }
        Ok(())
    }

    fn post_child_insertion(&mut self, inserted_child: Node<dyn NodeSpec>) {
        match inserted_child.downcast() {
            NodeKind::DocumentType(doctype) => {
                self.document_type = Some(doctype.core);
            }
            NodeKind::Element(element) => {
                self.document_element = Some(element.core);
            }
            _ => {}
        }
    }
}

pub type Document = Node<DocumentSpec>;

impl Document {
    pub fn new() -> Self {
        let weak: Weak<RefCell<NodeCore<DocumentFragmentSpec>>> = Weak::new();
        let rc = Rc::new(RefCell::new(NodeCore {
            parent_node: weak.clone(),
            previous_sibling: weak.clone(),
            next_sibling: None,
            spec: DocumentSpec {
                first_child: None,
                last_child: None,
                document_element: None,
                document_type: None,
                version: None,
                encoding: None,
                standalone: None,
                base_uri: URIString::parse_file_path(std::env::current_dir().unwrap_or_default())
                    .unwrap_or_else(|_| URIString::parse("file:///").unwrap())
                    .resolve(&URIString::parse("document.xml").unwrap())
                    .into(),
            },
        }));

        Self {
            core: rc.clone(),
            owner_document: rc.clone(),
        }
    }

    pub fn create_document_type(
        &self,
        name: impl Into<Rc<str>>,
        system_id: Option<Rc<URIStr>>,
        public_id: Option<Rc<str>>,
    ) -> DocumentType {
        DocumentType::new(name.into(), system_id, public_id, self.clone())
    }

    pub fn create_element(
        &self,
        qname: impl Into<Rc<str>>,
        namespace_name: Option<Rc<str>>,
    ) -> Result<Element, XMLTreeError> {
        Element::new(qname.into(), namespace_name, self.clone())
    }

    pub fn create_text(&self, data: impl Into<String>) -> Text {
        Text::new(data.into(), self.clone())
    }

    pub fn create_cdata_section(&self, data: impl Into<String>) -> CDATASection {
        CDATASection::new(data.into(), self.clone())
    }

    pub fn create_comment(&self, data: impl Into<String>) -> Comment {
        Comment::new(data.into(), self.clone())
    }

    pub fn create_processing_instruction(
        &self,
        target: impl Into<Rc<str>>,
        data: Option<Rc<str>>,
    ) -> ProcessingInstruction {
        ProcessingInstruction::new(target.into(), data, self.clone())
    }

    pub fn create_entity_reference(&self, name: impl Into<Rc<str>>) -> EntityReference {
        // TODO: try to expand contents
        EntityReference::new(name.into(), self.clone())
    }

    pub fn create_document_fragment(&self) -> DocumentFragment {
        DocumentFragment::new(self.clone())
    }

    pub fn create_attlist_decl(
        &self,
        elem_name: impl Into<Rc<str>>,
        attr_name: impl Into<Rc<str>>,
        attr_type: AttributeType,
        default_decl: DefaultDecl,
    ) -> AttlistDecl {
        AttlistDecl::new(
            elem_name.into(),
            attr_name.into(),
            attr_type,
            default_decl,
            self.clone(),
        )
    }

    pub fn create_element_decl(
        &self,
        name: impl Into<Rc<str>>,
        content_spec: ContentSpec,
    ) -> ElementDecl {
        ElementDecl::new(name.into(), content_spec, self.clone())
    }

    pub fn create_internal_entity_decl(
        &self,
        name: impl Into<Rc<str>>,
        value: impl Into<Rc<str>>,
    ) -> EntityDecl {
        EntityDecl::new_internal_entity_decl(name.into(), value.into(), self.clone())
    }

    pub fn create_external_entity_decl(
        &self,
        name: impl Into<Rc<str>>,
        system_id: impl Into<Rc<URIStr>>,
        public_id: Option<Rc<str>>,
    ) -> EntityDecl {
        EntityDecl::new_external_entity_decl(name.into(), system_id.into(), public_id, self.clone())
    }

    pub fn create_unparsed_entity_decl(
        &self,
        name: impl Into<Rc<str>>,
        system_id: impl Into<Rc<URIStr>>,
        public_id: Option<Rc<str>>,
        notation_name: impl Into<Rc<str>>,
    ) -> EntityDecl {
        EntityDecl::new_unparsed_entity_decl(
            name.into(),
            system_id.into(),
            public_id,
            notation_name.into(),
            self.clone(),
        )
    }

    pub fn create_notation_decl(
        &self,
        name: impl Into<Rc<str>>,
        system_id: Option<Rc<URIStr>>,
        public_id: Option<Rc<str>>,
    ) -> NotationDecl {
        NotationDecl::new(name.into(), system_id, public_id, self.clone())
    }

    pub fn document_element(&self) -> Option<Element> {
        self.core
            .borrow()
            .spec
            .document_element
            .clone()
            .map(|core| Element {
                core,
                owner_document: self.owner_document.clone(),
            })
    }

    pub fn document_type(&self) -> Option<DocumentType> {
        self.core
            .borrow()
            .spec
            .document_type
            .clone()
            .map(|core| DocumentType {
                core,
                owner_document: self.owner_document.clone(),
            })
    }

    /// If XML declaration is present, return the version specified in the declaration.  \
    /// Otherwise, return `None`.
    pub fn version(&self) -> Option<Ref<'_, str>> {
        Ref::filter_map(self.core.borrow(), |core| core.spec.version.as_deref()).ok()
    }

    pub fn set_version(&mut self, version: Option<&str>) {
        self.core.borrow_mut().spec.version = version.map(|version| version.into());
    }

    /// If XML declaration is present and it has the encoding declaration,
    /// return the encoding specified in the declaration.  \
    /// Otherwise, return `None`.
    pub fn encoding(&self) -> Option<Ref<'_, str>> {
        Ref::filter_map(self.core.borrow(), |core| core.spec.encoding.as_deref()).ok()
    }

    pub fn set_encoding(&mut self, encoding: Option<&str>) {
        self.core.borrow_mut().spec.encoding = encoding.map(|encoding| encoding.into());
    }

    /// If XML declaration is present and it has the standalone declaration,
    /// return the boolean value specified in the declaration.  \
    /// Otherwise, return `None`.
    pub fn standalone(&self) -> Option<bool> {
        self.core.borrow().spec.standalone
    }

    pub fn set_standalone(&mut self, standalone: Option<bool>) {
        self.core.borrow_mut().spec.standalone = standalone;
    }

    pub fn base_uri(&self) -> Ref<'_, URIStr> {
        Ref::map(self.core.borrow(), |core| core.spec.base_uri.as_ref())
    }

    pub fn set_base_uri(&mut self, base_uri: Box<URIStr>) -> Result<(), XMLTreeError> {
        if !base_uri.is_absolute() {
            return Err(XMLTreeError::BaseURINotAbsolute);
        }

        self.core.borrow_mut().spec.base_uri = base_uri;
        Ok(())
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn document_element_insertion_test() {
        let mut document = Document::new();
        assert!(document.document_element().is_none());
        assert!(document.first_child().is_none());
        assert!(document.last_child().is_none());
        let mut elem = document.create_element("root", None).unwrap();
        document.append_child(elem.clone()).unwrap();
        assert!(document.document_element().is_some());
        assert!(document.document_element().is_some());
        assert!(document.document_element().is_some());

        let elem2 = document.create_element("root2", None).unwrap();
        assert!(document.append_child(elem2.clone()).is_err());
        assert!(
            document
                .document_element()
                .is_some_and(|elem| elem.name().as_ref() == "root")
        );
        assert!(
            document
                .first_child()
                .is_some_and(|elem| elem.as_element().unwrap().name().as_ref() == "root")
        );
        assert!(
            document
                .last_child()
                .is_some_and(|elem| elem.as_element().unwrap().name().as_ref() == "root")
        );
        assert!(
            elem.parent_node()
                .is_some_and(|doc| matches!(doc.node_type(), NodeType::Document))
        );
        assert!(elem2.parent_node().is_none());

        elem.detach().unwrap();

        assert!(document.document_element().is_none());
        assert!(document.first_child().is_none());
        assert!(document.last_child().is_none());
        assert!(elem.parent_node().is_none());
    }

    #[test]
    fn document_type_insertion_test() {
        let mut document = Document::new();
        let mut doctype = document.create_document_type("root", None, None);
        document.append_child(doctype.clone()).unwrap();
        assert!(document.document_type().is_some());
        assert!(
            document.first_child().is_some_and(|doctype| &*doctype
                .as_document_type()
                .unwrap()
                .name()
                == "root")
        );
        assert!(
            document.last_child().is_some_and(|doctype| &*doctype
                .as_document_type()
                .unwrap()
                .name()
                == "root")
        );

        let doctype2 = document.create_document_type("root2", None, None);
        assert!(document.append_child(doctype2).is_err());
        assert!(
            document
                .document_type()
                .is_some_and(|doctype| &*doctype.name() == "root")
        );
        assert!(
            document.first_child().is_some_and(|doctype| &*doctype
                .as_document_type()
                .unwrap()
                .name()
                == "root")
        );
        assert!(
            document.last_child().is_some_and(|doctype| &*doctype
                .as_document_type()
                .unwrap()
                .name()
                == "root")
        );

        doctype.detach().unwrap();
        assert!(document.document_type().is_none());
        assert!(document.first_child().is_none());
        assert!(document.last_child().is_none());
        assert!(doctype.parent_node().is_none());
    }

    #[test]
    fn document_element_insertion_before_document_type_test() {
        let mut document = Document::new();
        let mut doctype = document.create_document_type("root", None, None);
        let root = document.create_element("root", None).unwrap();
        document.append_child(doctype.clone()).unwrap();
        assert!(doctype.insert_previous_sibling(root.clone()).is_err());

        assert!(document.document_type().is_some());
        assert!(document.document_element().is_none());
        assert!(
            document
                .first_child()
                .is_some_and(|doctype| matches!(doctype.node_type(), NodeType::DocumentType))
        );
        assert!(
            document
                .last_child()
                .is_some_and(|doctype| matches!(doctype.node_type(), NodeType::DocumentType))
        );
        assert!(doctype.parent_node().is_some());
        assert!(doctype.previous_sibling().is_none());
        assert!(root.parent_node().is_none());
        assert!(root.next_sibling().is_none());
    }

    #[test]
    fn document_type_insertion_after_document_element_test() {
        let mut document = Document::new();
        let doctype = document.create_document_type("root", None, None);
        let mut root = document.create_element("root", None).unwrap();
        document.append_child(root.clone()).unwrap();
        assert!(root.insert_next_sibling(doctype.clone()).is_err());

        assert!(document.document_type().is_none());
        assert!(document.document_element().is_some());
        assert!(
            document
                .first_child()
                .is_some_and(|root| matches!(root.node_type(), NodeType::Element))
        );
        assert!(
            document
                .last_child()
                .is_some_and(|root| matches!(root.node_type(), NodeType::Element))
        );
        assert!(doctype.parent_node().is_none());
        assert!(doctype.previous_sibling().is_none());
        assert!(root.parent_node().is_some());
        assert!(root.next_sibling().is_none());
    }
}