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

use crate::tree::{
    Document, NodeType, XMLTreeError,
    convert::NodeKind,
    node::{InternalNodeSpec, Node, NodeCore, NodeSpec},
};

#[derive(Debug, Clone, Copy)]
enum State {
    // cannot be determined
    None,
    // has only one element, but it is unclear whether content or document element
    HasAnElement,
    // has a document type
    HasDocumentType,
    // has document type and document element
    AsDocument,
    // has character data and zero or one element
    AsContent { elem: usize, text: usize },
    // has declarations
    AsDocumentType { decl: usize },
}

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

    state: State,
}

impl NodeSpec for DocumentFragmentSpec {
    fn node_type(&self) -> NodeType {
        NodeType::DocumentFragment
    }

    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 DocumentFragmentSpec {
    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::AttlistDecl
            | NodeType::ElementDecl
            | NodeType::EntityDecl
            | NodeType::NotationDecl => match &mut self.state {
                State::AsDocumentType { decl } => {
                    *decl -= 1;
                    if *decl == 0 {
                        self.state = State::None;
                    }
                }
                _ => unreachable!(),
            },
            NodeType::DocumentType => match self.state {
                State::AsDocument => self.state = State::HasAnElement,
                State::HasDocumentType => self.state = State::None,
                _ => unreachable!(),
            },
            NodeType::Element => match &mut self.state {
                State::AsContent { elem, text } => {
                    *elem -= 1;
                    if *elem == 0 && *text == 0 {
                        self.state = State::None;
                    }
                }
                State::AsDocument => self.state = State::HasDocumentType,
                State::HasAnElement => self.state = State::None,
                _ => unreachable!(),
            },
            NodeType::CDATASection | NodeType::Text => match &mut self.state {
                State::AsContent { elem, text } => {
                    *text -= 1;
                    if *elem == 0 && *text == 0 {
                        self.state = State::None;
                    }
                }
                _ => unreachable!(),
            },
            NodeType::EntityReference => match &mut self.state {
                State::AsContent { elem, text } => {
                    *text -= 1;
                    if *elem == 0 && *text == 0 {
                        self.state = State::None;
                    }
                }
                State::AsDocumentType { decl } => {
                    *decl -= 1;
                    if *decl == 0 {
                        self.state = State::None;
                    }
                }
                _ => unreachable!(),
            },
            NodeType::Comment | NodeType::ProcessingInstruction => {}
            _ => {}
        }
        Ok(())
    }

    fn pre_child_insertion(
        &self,
        inserted_child: Node<dyn NodeSpec>,
        mut preceding_node: Option<Node<dyn NodeSpec>>,
    ) -> Result<(), super::XMLTreeError> {
        match inserted_child.downcast() {
            NodeKind::AttlistDecl(_)
            | NodeKind::ElementDecl(_)
            | NodeKind::EntityDecl(_)
            | NodeKind::NotationDecl(_) => {
                if !matches!(self.state, State::None | State::AsDocumentType { .. }) {
                    return Err(XMLTreeError::UnacceptableHierarchy);
                }
            }
            NodeKind::DocumentType(_) => match self.state {
                State::AsContent { .. }
                | State::AsDocument
                | State::AsDocumentType { .. }
                | State::HasDocumentType => {
                    return Err(XMLTreeError::UnacceptableHierarchy);
                }
                State::HasAnElement => {
                    while let Some(prev) = preceding_node {
                        preceding_node = prev.previous_sibling();
                        if matches!(prev.node_type(), NodeType::Element) {
                            return Err(XMLTreeError::UnacceptableHorizontality);
                        }
                    }
                }
                State::None => {}
            },
            NodeKind::Element(_) => match self.state {
                State::HasDocumentType => {
                    while let Some(prev) = preceding_node.as_ref() {
                        if matches!(prev.node_type(), NodeType::DocumentType) {
                            break;
                        }
                        preceding_node = prev.previous_sibling();
                    }

                    if preceding_node.is_none() {
                        return Err(XMLTreeError::UnacceptableHorizontality);
                    }
                }
                State::AsDocument | State::AsDocumentType { .. } => {
                    return Err(XMLTreeError::UnacceptableHierarchy);
                }
                State::AsContent { .. } | State::HasAnElement | State::None => {}
            },
            NodeKind::CDATASection(_) | NodeKind::Text(_) => {
                if !matches!(
                    self.state,
                    State::AsContent { .. } | State::HasAnElement | State::None
                ) {
                    return Err(XMLTreeError::UnacceptableHierarchy);
                }
            }
            NodeKind::EntityReference(entity) => {
                // TODO: support parameter entities
                #[allow(clippy::if_same_then_else)]
                if entity.name().starts_with('%') {
                    return Err(XMLTreeError::Unsupported);
                } else if !matches!(
                    self.state,
                    State::AsContent { .. } | State::HasAnElement | State::None
                ) {
                    return Err(XMLTreeError::UnacceptableHierarchy);
                }
            }
            NodeKind::Comment(_) | NodeKind::ProcessingInstruction(_) => {}
            _ => return Err(XMLTreeError::UnacceptableHierarchy),
        }
        Ok(())
    }

    fn post_child_insertion(&mut self, inserted_child: Node<dyn NodeSpec>) {
        match inserted_child.downcast() {
            NodeKind::AttlistDecl(_)
            | NodeKind::ElementDecl(_)
            | NodeKind::EntityDecl(_)
            | NodeKind::NotationDecl(_) => match &mut self.state {
                State::AsDocumentType { decl } => *decl += 1,
                _ => self.state = State::AsDocumentType { decl: 1 },
            },
            NodeKind::DocumentType(_) => {
                if matches!(self.state, State::None) {
                    self.state = State::HasDocumentType;
                } else {
                    self.state = State::AsDocument;
                }
            }
            NodeKind::Element(_) => match &mut self.state {
                State::HasAnElement => self.state = State::AsContent { elem: 2, text: 0 },
                State::AsContent { elem, .. } => *elem += 1,
                State::None => self.state = State::HasAnElement,
                State::HasDocumentType => self.state = State::AsDocument,
                State::AsDocument | State::AsDocumentType { .. } => unreachable!(),
            },
            NodeKind::CDATASection(_) | NodeKind::Text(_) => match &mut self.state {
                State::AsContent { text, .. } => *text += 1,
                State::HasAnElement => self.state = State::AsContent { elem: 1, text: 1 },
                State::None => self.state = State::AsContent { elem: 0, text: 1 },
                _ => unreachable!(),
            },
            NodeKind::EntityReference(entity) => {
                if entity.name().starts_with('%') {
                    match &mut self.state {
                        State::AsDocumentType { decl } => *decl += 1,
                        State::None => self.state = State::AsDocumentType { decl: 1 },
                        _ => unreachable!(),
                    }
                } else {
                    match &mut self.state {
                        State::AsContent { text, .. } => *text += 1,
                        State::HasAnElement => self.state = State::AsContent { elem: 1, text: 1 },
                        State::None => self.state = State::AsContent { elem: 0, text: 1 },
                        _ => unreachable!(),
                    }
                }
            }
            NodeKind::Comment(_) | NodeKind::ProcessingInstruction(_) => {}
            _ => {}
        }
    }
}

pub type DocumentFragment = Node<DocumentFragmentSpec>;

impl DocumentFragment {
    pub(crate) fn new(owner_document: Document) -> Self {
        Self {
            core: Rc::new(RefCell::new(NodeCore {
                parent_node: owner_document.core.borrow().parent_node.clone(),
                previous_sibling: owner_document.core.borrow().previous_sibling.clone(),
                next_sibling: None,
                spec: DocumentFragmentSpec {
                    first_child: None,
                    last_child: None,
                    state: State::None,
                },
            })),
            owner_document: owner_document.core.clone(),
        }
    }

    /// Create new node and copy internal data to the new node other than pointers to neighbor nodes.
    ///
    /// 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) -> Self {
        Node::create_node(
            DocumentFragmentSpec {
                first_child: None,
                last_child: None,
                state: self.core.borrow().spec.state,
            },
            self.owner_document(),
        )
    }

    /// 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<Self, XMLTreeError> {
        let mut ret = self.deep_copy();
        let mut children = self.first_child();
        while let Some(child) = children {
            children = child.next_sibling();
            ret.append_child(child.deep_copy_subtree()?)?;
        }
        Ok(ret)
    }
}

impl std::fmt::Display for DocumentFragment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut children = self.first_child();
        while let Some(child) = children {
            children = child.next_sibling();

            write!(f, "{}", child)?;
        }
        Ok(())
    }
}

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

    #[test]
    fn document_fragment_doctype_insertion_test() {
        let document = Document::new();

        let mut doctype = document.create_document_type("root", None, None);
        let mut elem1 = document.create_element("elem1", None).unwrap();
        let elem2 = document.create_element("elem2", None).unwrap();
        let mut frag = document.create_document_fragment();

        //       frag
        //      /    \
        // doctype  elem1
        frag.append_child(doctype.clone()).unwrap();
        frag.append_child(elem1.clone()).unwrap();
        assert!(frag.append_child(elem2.clone()).is_err());
        assert!(
            frag.first_child()
                .and_then(|ch| ch.as_document_type())
                .is_some()
        );
        assert!(
            frag.last_child()
                .and_then(|ch| ch.as_element())
                .is_some_and(|elem| elem.name().as_ref() == "elem1")
        );

        //   frag
        //     |
        //  doctype
        elem1.detach().unwrap();
        assert!(
            frag.first_child()
                .and_then(|ch| ch.as_document_type())
                .is_some()
        );
        assert!(
            frag.last_child()
                .and_then(|ch| ch.as_document_type())
                .is_some()
        );

        assert!(doctype.insert_previous_sibling(elem1.clone()).is_err());
        assert!(
            frag.first_child()
                .and_then(|ch| ch.as_document_type())
                .is_some()
        );
        assert!(
            frag.last_child()
                .and_then(|ch| ch.as_document_type())
                .is_some()
        );

        doctype.detach().unwrap();
        assert!(frag.first_child().is_none());
        assert!(frag.last_child().is_none());

        frag.append_child(elem1.clone()).unwrap();
        assert!(
            frag.first_child()
                .and_then(|ch| ch.as_element())
                .is_some_and(|elem| elem.name().as_ref() == "elem1")
        );
        assert!(
            frag.last_child()
                .and_then(|ch| ch.as_element())
                .is_some_and(|elem| elem.name().as_ref() == "elem1")
        );
        elem1.insert_previous_sibling(doctype.clone()).unwrap();

        doctype.detach().unwrap();

        assert!(frag.append_child(doctype.clone()).is_err());

        frag.append_child(elem2).unwrap();
        assert!(
            frag.first_child()
                .and_then(|ch| ch.as_element())
                .is_some_and(|elem| elem.name().as_ref() == "elem1")
        );
        assert!(
            frag.last_child()
                .and_then(|ch| ch.as_element())
                .is_some_and(|elem| elem.name().as_ref() == "elem2")
        );
        assert!(elem1.insert_previous_sibling(doctype).is_err());
    }

    #[test]
    fn document_fragment_insertion_to_other_test() {
        let document = Document::new();

        let mut elem = document.create_element("root", None).unwrap();
        let mut frag = document.create_document_fragment();

        frag.append_child(document.create_element("child1", None).unwrap())
            .unwrap();
        frag.append_child(document.create_text("text1")).unwrap();
        frag.append_child(document.create_element("child2", None).unwrap())
            .unwrap();

        elem.append_child(frag.clone()).unwrap();

        let mut children = elem.first_child();
        for expect in ["child1", "text1", "child2"] {
            match children.as_ref().unwrap().downcast() {
                NodeKind::Element(elem) => {
                    assert_eq!(elem.name().as_ref(), expect);
                }
                NodeKind::Text(text) => {
                    assert_eq!(&*text.data(), expect);
                }
                _ => unreachable!(),
            }
            children = children.unwrap().next_sibling();
        }
        assert!(children.is_none());
        assert!(frag.first_child().is_none());
        assert!(frag.last_child().is_none());
    }

    #[test]
    fn document_fragment_wrong_insertion_to_other_test() {
        let mut document = Document::new();

        let mut frag = document.create_document_fragment();
        frag.append_child(document.create_comment("comment1"))
            .unwrap();
        frag.append_child(document.create_comment("comment2"))
            .unwrap();
        frag.append_child(document.create_text("text1")).unwrap();
        frag.append_child(document.create_text("text2")).unwrap();
        frag.append_child(document.create_comment("comment3"))
            .unwrap();

        assert!(document.append_child(frag.clone()).is_err());
        assert!(document.first_child().is_none());
        assert!(document.last_child().is_none());

        let mut children = frag.first_child();
        for expect in ["comment1", "comment2", "text1", "text2", "comment3"] {
            match children.as_ref().expect(expect).downcast() {
                NodeKind::Comment(comment) => {
                    assert_eq!(&*comment.data(), expect);
                }
                NodeKind::Text(text) => {
                    assert_eq!(&*text.data(), expect);
                }
                _ => unreachable!(),
            }
            children = children.unwrap().next_sibling();
        }
        assert!(children.is_none());
    }
}