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
pub mod attlist_decl;
pub mod attribute;
pub mod cdata_section;
pub mod comment;
pub mod convert;
pub mod document;
pub mod document_fragment;
pub mod document_type;
pub mod element;
pub mod element_decl;
pub mod entity_decl;
pub mod entity_reference;
pub mod namespace;
pub mod node;
pub mod notation_decl;
pub mod processing_instruction;
pub mod text;

use std::sync::Arc;

use anyxml_uri::uri::URIStr;
pub use attlist_decl::AttlistDecl;
pub use attribute::Attribute;
pub use cdata_section::CDATASection;
pub use comment::Comment;
pub use document::Document;
pub use document_fragment::DocumentFragment;
pub use document_type::DocumentType;
pub use element::Element;
pub use element_decl::ElementDecl;
pub use entity_decl::EntityDecl;
pub use entity_reference::EntityReference;
pub use node::Node;
pub use notation_decl::NotationDecl;
pub use processing_instruction::ProcessingInstruction;
pub use text::Text;

use crate::{
    error::XMLError,
    sax::{
        AttributeType, DefaultDecl, Locator,
        attributes::Attributes,
        contentspec::ContentSpec,
        error::SAXParseError,
        handler::{DefaultSAXHandler, EntityResolver, ErrorHandler, SAXHandler},
        source::InputSource,
    },
    tree::{convert::NodeKind, node::InternalNodeSpec},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeType {
    Element = 1,
    Attribute = 2,
    Text = 3,
    CDATASection = 4,
    EntityReference = 5,
    EntityDecl = 6,
    ProcessingInstruction = 7,
    Comment = 8,
    Document = 9,
    DocumentType = 10,
    DocumentFragment = 11,
    NotationDecl = 12,

    ElementDecl = 128,
    AttlistDecl = 129,
    Namespace = 130,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XMLTreeError {
    EmptyPrefix,
    UnacceptablePrefix,
    UnresolvablePrefix,
    AlreadyBoundPrefix,
    UnacceptableNamespaceBinding,
    UnacceptableNamespaceName,
    MultipleDocumentElement,
    DuplicateAttribute,
    UnspecifiedAttribute,
    MultipleDocumentType,
    DuplicateElementDecl,
    DuplicateNotationDecl,
    CyclicReference,
    UnacceptableHierarchy,
    UnacceptableHorizontality,
    BaseURINotAbsolute,
    Unsupported,
}

pub struct TreeBuildHandler<H: SAXHandler = DefaultSAXHandler> {
    node: Node<dyn InternalNodeSpec>,
    pub document: Document,
    pub handler: H,
    pub fatal_error: bool,
    in_cdata: bool,
}

impl<H: SAXHandler> TreeBuildHandler<H> {
    pub fn with_handler(handler: H) -> Self {
        let document = Document::new();
        Self {
            node: document.clone().into(),
            document,
            handler,
            fatal_error: false,
            in_cdata: false,
        }
    }
}

impl Default for TreeBuildHandler {
    fn default() -> Self {
        let document = Document::new();
        Self {
            node: document.clone().into(),
            document,
            handler: DefaultSAXHandler,
            fatal_error: false,
            in_cdata: false,
        }
    }
}

impl<H: SAXHandler> EntityResolver for TreeBuildHandler<H> {
    fn get_external_subset(
        &mut self,
        name: &str,
        base_uri: Option<&URIStr>,
    ) -> Result<InputSource<'static>, XMLError> {
        self.handler.get_external_subset(name, base_uri)
    }

    fn resolve_entity(
        &mut self,
        name: &str,
        public_id: Option<&str>,
        base_uri: &URIStr,
        system_id: &URIStr,
    ) -> Result<InputSource<'static>, XMLError> {
        self.handler
            .resolve_entity(name, public_id, base_uri, system_id)
    }
}

impl<H: SAXHandler> ErrorHandler for TreeBuildHandler<H> {
    fn error(&mut self, error: SAXParseError) {
        self.handler.error(error);
    }

    fn fatal_error(&mut self, error: SAXParseError) {
        self.fatal_error = true;
        self.handler.fatal_error(error);
    }

    fn warning(&mut self, error: SAXParseError) {
        self.handler.warning(error);
    }
}

impl<H: SAXHandler> SAXHandler for TreeBuildHandler<H> {
    fn attribute_decl(
        &mut self,
        element_name: &str,
        attribute_name: &str,
        attribute_type: &AttributeType,
        default_decl: &DefaultDecl,
    ) {
        self.node
            .append_child(self.document.create_attlist_decl(
                element_name,
                attribute_name,
                attribute_type.clone(),
                default_decl.clone(),
            ))
            .unwrap();
        self.handler
            .attribute_decl(element_name, attribute_name, attribute_type, default_decl);
    }

    fn characters(&mut self, data: &str) {
        match self.node.last_child().map(|ch| ch.downcast()) {
            Some(NodeKind::CDATASection(mut cdata)) => {
                if self.in_cdata {
                    cdata.push_str(data);
                } else {
                    self.node
                        .append_child(self.document.create_text(data))
                        .unwrap();
                }
            }
            Some(NodeKind::Text(mut text)) => text.push_str(data),
            _ => self
                .node
                .append_child(self.document.create_text(data))
                .unwrap(),
        }
        self.handler.characters(data);
    }

    fn comment(&mut self, data: &str) {
        self.node
            .append_child(self.document.create_comment(data))
            .unwrap();
        self.handler.comment(data);
    }

    fn declaration(&mut self, version: &str, encoding: Option<&str>, standalone: Option<bool>) {
        self.document.set_version(Some(version));
        self.document.set_encoding(encoding);
        self.document.set_standalone(standalone);
        self.handler.declaration(version, encoding, standalone);
    }

    fn element_decl(&mut self, name: &str, contentspec: &ContentSpec) {
        self.node
            .append_child(self.document.create_element_decl(name, contentspec.clone()))
            .unwrap();
        self.handler.element_decl(name, contentspec);
    }

    fn external_entity_decl(&mut self, name: &str, public_id: Option<&str>, system_id: &URIStr) {
        self.node
            .append_child(self.document.create_external_entity_decl(
                name,
                system_id,
                public_id.map(|id| id.into()),
            ))
            .unwrap();
        self.handler
            .external_entity_decl(name, public_id, system_id);
    }

    fn ignorable_whitespace(&mut self, data: &str) {
        match self.node.last_child().map(|ch| ch.downcast()) {
            Some(NodeKind::CDATASection(mut cdata)) => {
                if self.in_cdata {
                    cdata.push_str(data);
                } else {
                    self.node
                        .append_child(self.document.create_text(data))
                        .unwrap();
                }
            }
            Some(NodeKind::Text(mut text)) => text.push_str(data),
            _ => self
                .node
                .append_child(self.document.create_text(data))
                .unwrap(),
        }
        self.handler.ignorable_whitespace(data);
    }

    fn internal_entity_decl(&mut self, name: &str, value: &str) {
        self.node
            .append_child(self.document.create_internal_entity_decl(name, value))
            .unwrap();
        self.handler.internal_entity_decl(name, value);
    }

    fn notation_decl(&mut self, name: &str, public_id: Option<&str>, system_id: Option<&URIStr>) {
        self.node
            .append_child(self.document.create_notation_decl(
                name,
                system_id.map(|id| id.into()),
                public_id.map(|id| id.into()),
            ))
            .unwrap();
        self.handler.notation_decl(name, public_id, system_id);
    }

    fn processing_instruction(&mut self, target: &str, data: Option<&str>) {
        self.node
            .append_child(
                self.document
                    .create_processing_instruction(target, data.map(|data| data.into())),
            )
            .unwrap();
        self.handler.processing_instruction(target, data);
    }

    fn set_document_locator(&mut self, locator: Arc<Locator>) {
        self.document
            .set_base_uri(locator.system_id().as_ref().into())
            .ok();
        self.handler.set_document_locator(locator);
    }

    fn skipped_entity(&mut self, name: &str) {
        if name != "[dtd]" {
            // we should create an empty entity reference,
            // so we should use `EntityReference::new`, not but `self.document.create_entity_reference`.
            self.node
                .append_child(EntityReference::new(name.into(), self.document.clone()))
                .unwrap();
        }
        self.handler.skipped_entity(name);
    }

    fn start_cdata(&mut self) {
        self.in_cdata = true;
        self.node
            .append_child(self.document.create_cdata_section(""))
            .unwrap();
        self.handler.start_cdata();
    }
    fn end_cdata(&mut self) {
        self.in_cdata = false;
        self.handler.end_cdata();
    }

    fn start_document(&mut self) {
        self.handler.start_document();
    }
    fn end_document(&mut self) {
        self.handler.end_document();
    }

    fn start_dtd(&mut self, name: &str, public_id: Option<&str>, system_id: Option<&URIStr>) {
        let doctype = self.document.create_document_type(
            name,
            system_id.map(|id| id.into()),
            public_id.map(|id| id.into()),
        );
        self.node.append_child(doctype.clone()).unwrap();
        self.node = doctype.into();
        self.handler.start_dtd(name, public_id, system_id);
    }
    fn end_dtd(&mut self) {
        if let Some(parent) = self.node.parent_node() {
            self.node = parent;
        }
        self.handler.end_dtd();
    }

    fn start_element(
        &mut self,
        uri: Option<&str>,
        local_name: Option<&str>,
        qname: &str,
        atts: &Attributes,
    ) {
        if let Ok(mut elem) = self
            .document
            .create_element(qname, uri.map(|uri| uri.into()))
        {
            for att in atts {
                if att.is_nsdecl() {
                    if att.qname.as_ref() == "xmlns" {
                        elem.declare_namespace(None, &att.value).ok();
                    } else {
                        elem.declare_namespace(att.local_name.as_deref(), &att.value)
                            .ok();
                    }
                } else {
                    elem.set_attribute(&att.qname, att.uri.as_deref(), Some(&att.value))
                        .ok();
                }
            }
            self.node.append_child(elem.clone()).unwrap();
            self.node = elem.into();
        }
        self.handler.start_element(uri, local_name, qname, atts);
    }
    fn end_element(&mut self, uri: Option<&str>, local_name: Option<&str>, qname: &str) {
        if let Some(parent) = self.node.parent_node() {
            self.node = parent;
        }
        self.handler.end_element(uri, local_name, qname);
    }

    fn start_entity(&mut self, name: &str) {
        if name != "[dtd]" {
            // we should create an empty entity reference,
            // so we should use `EntityReference::new`, not but `self.document.create_entity_reference`.
            let ent = EntityReference::new(name.into(), self.document.clone());
            self.node.append_child(ent.clone()).unwrap();
            self.node = ent.into();
        }
        self.handler.start_entity(name);
    }
    fn end_entity(&mut self) {
        if matches!(self.node.node_type(), NodeType::EntityReference)
            && let Some(parent) = self.node.parent_node()
        {
            self.node = parent;
        }
        self.handler.end_entity();
    }

    fn start_prefix_mapping(&mut self, prefix: Option<&str>, uri: &str) {
        self.handler.start_prefix_mapping(prefix, uri);
    }
    fn end_prefix_mapping(&mut self, prefix: Option<&str>) {
        self.handler.end_prefix_mapping(prefix);
    }

    fn unparsed_entity_decl(
        &mut self,
        name: &str,
        public_id: Option<&str>,
        system_id: &URIStr,
        notation_name: &str,
    ) {
        self.node
            .append_child(self.document.create_unparsed_entity_decl(
                name,
                system_id,
                public_id.map(|id| id.into()),
                notation_name,
            ))
            .unwrap();
        self.handler
            .unparsed_entity_decl(name, public_id, system_id, notation_name);
    }
}