crossfoot-xml 0.1.0

Namespace-aware XML 1.0 parser with an immutable arena DOM (Crossfoot XBRL platform)
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
//! crossfoot-xml: a namespace-aware XML 1.0 parser producing an immutable arena DOM.
//!
//! The DOM is `Send + Sync`, keeps byte offsets for every node (line/column on demand),
//! resolves `xml:base`, `xml:lang` and QName-valued content, and indexes `id` attributes.
//! It is the one XML representation every Crossfoot component reads.

mod parse;

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

pub use parse::{parse, parse_str, ParseOptions};

/// Interned-ish string. Plain `Arc<str>`; equality is by content.
pub type Atom = Arc<str>;

pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";

/// An expanded name. Equality and hashing ignore the prefix.
#[derive(Clone)]
pub struct QName {
    pub ns: Atom,
    pub local: Atom,
    pub prefix: Atom,
}

impl QName {
    pub fn new(ns: &str, local: &str) -> QName {
        QName {
            ns: ns.into(),
            local: local.into(),
            prefix: "".into(),
        }
    }
    pub fn with_prefix(ns: &str, local: &str, prefix: &str) -> QName {
        QName {
            ns: ns.into(),
            local: local.into(),
            prefix: prefix.into(),
        }
    }
    pub fn is(&self, ns: &str, local: &str) -> bool {
        &*self.local == local && &*self.ns == ns
    }
    /// `{ns}local` (James Clark notation); `local` when there is no namespace.
    pub fn clark(&self) -> String {
        if self.ns.is_empty() {
            self.local.to_string()
        } else {
            format!("{{{}}}{}", self.ns, self.local)
        }
    }
    /// `prefix:local` or `local`.
    pub fn lexical(&self) -> String {
        if self.prefix.is_empty() {
            self.local.to_string()
        } else {
            format!("{}:{}", self.prefix, self.local)
        }
    }
    /// Parse `{ns}local` or `local`.
    pub fn from_clark(s: &str) -> QName {
        if let Some(rest) = s.strip_prefix('{') {
            if let Some(i) = rest.find('}') {
                return QName::new(&rest[..i], &rest[i + 1..]);
            }
        }
        QName::new("", s)
    }
}

impl PartialEq for QName {
    fn eq(&self, o: &QName) -> bool {
        self.local == o.local && self.ns == o.ns
    }
}
impl Eq for QName {}
impl std::hash::Hash for QName {
    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
        self.ns.hash(h);
        self.local.hash(h);
    }
}
impl PartialOrd for QName {
    fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(o))
    }
}
impl Ord for QName {
    fn cmp(&self, o: &Self) -> std::cmp::Ordering {
        (&*self.ns, &*self.local).cmp(&(&*o.ns, &*o.local))
    }
}
impl fmt::Debug for QName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.prefix.is_empty() {
            write!(f, "{}", self.clark())
        } else {
            write!(f, "{}({})", self.lexical(), self.ns)
        }
    }
}
impl fmt::Display for QName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.prefix.is_empty() {
            write!(f, "{}", self.clark())
        } else {
            write!(f, "{}", self.lexical())
        }
    }
}
impl serde::Serialize for QName {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.clark())
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize)]
pub struct NodeId(pub u32);

const NONE: u32 = u32::MAX;

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum NodeKind {
    Document,
    Element,
    Text,
    Comment,
    ProcessingInstruction,
}

#[derive(Clone, Debug)]
pub(crate) struct NodeData {
    pub kind: NodeKind,
    /// Element name, or PI target in `local`.
    pub name: Option<QName>,
    /// Text, comment or PI content.
    pub text: Option<Atom>,
    pub parent: u32,
    pub first_child: u32,
    pub last_child: u32,
    pub next_sibling: u32,
    pub prev_sibling: u32,
    pub attr_start: u32,
    pub attr_end: u32,
    pub ns_start: u32,
    pub ns_end: u32,
    /// Byte offset of the node start in the (normalized) source text.
    pub offset: u32,
    /// Index of the last descendant (inclusive) for fast subtree ranges.
    pub subtree_end: u32,
}

#[derive(Clone, Debug)]
pub struct Attribute {
    pub name: QName,
    pub value: Atom,
    pub offset: u32,
}

/// Immutable parsed document.
pub struct Document {
    pub uri: Atom,
    pub(crate) nodes: Vec<NodeData>,
    pub(crate) attrs: Vec<Attribute>,
    /// Namespace declarations: (prefix, uri); prefix "" is the default namespace.
    pub(crate) nsdecls: Vec<(Atom, Atom)>,
    pub(crate) line_starts: Vec<u32>,
    pub(crate) ids: HashMap<Atom, NodeId>,
    /// Internal general entities declared in the DOCTYPE, if any.
    pub has_doctype: bool,
    pub xml_version: Atom,
    pub encoding: Atom,
}

impl fmt::Debug for Document {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Document({}, {} nodes)", self.uri, self.nodes.len())
    }
}

/// A well-formedness or encoding error.
#[derive(Clone, Debug)]
pub struct XmlError {
    pub message: String,
    pub line: u32,
    pub col: u32,
}

impl fmt::Display for XmlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}: {}", self.line, self.col, self.message)
    }
}
impl std::error::Error for XmlError {}

impl Document {
    pub fn root(&self) -> Node<'_> {
        Node {
            doc: self,
            id: NodeId(0),
        }
    }
    /// The document element.
    pub fn document_element(&self) -> Option<Node<'_>> {
        self.root().children().find(|n| n.is_element())
    }
    pub fn node(&self, id: NodeId) -> Node<'_> {
        Node { doc: self, id }
    }
    pub fn len(&self) -> usize {
        self.nodes.len()
    }
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }
    /// Element with the given `id` (or `xml:id`) attribute.
    pub fn by_id(&self, id: &str) -> Option<Node<'_>> {
        self.ids.get(id).map(|&n| self.node(n))
    }
    /// 1-based (line, column) of a byte offset.
    pub fn line_col(&self, offset: u32) -> (u32, u32) {
        let i = match self.line_starts.binary_search(&offset) {
            Ok(i) => i,
            Err(i) => i - 1,
        };
        (i as u32 + 1, offset - self.line_starts[i] + 1)
    }
    /// Every element node in document order.
    pub fn elements(&self) -> impl Iterator<Item = Node<'_>> + '_ {
        (0..self.nodes.len() as u32)
            .filter(move |&i| self.nodes[i as usize].kind == NodeKind::Element)
            .map(move |i| Node {
                doc: self,
                id: NodeId(i),
            })
    }
}

/// A borrowed handle on a node.
#[derive(Copy, Clone)]
pub struct Node<'a> {
    pub doc: &'a Document,
    pub id: NodeId,
}

impl PartialEq for Node<'_> {
    fn eq(&self, o: &Self) -> bool {
        self.id == o.id && std::ptr::eq(self.doc, o.doc)
    }
}
impl Eq for Node<'_> {}

impl fmt::Debug for Node<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind() {
            NodeKind::Element => write!(f, "<{}>@{}", self.name().lexical(), self.line()),
            k => write!(f, "{:?}#{}", k, self.id.0),
        }
    }
}

impl<'a> Node<'a> {
    #[inline]
    fn d(&self) -> &'a NodeData {
        &self.doc.nodes[self.id.0 as usize]
    }
    #[inline]
    fn wrap(&self, i: u32) -> Option<Node<'a>> {
        if i == NONE {
            None
        } else {
            Some(Node {
                doc: self.doc,
                id: NodeId(i),
            })
        }
    }
    pub fn kind(&self) -> NodeKind {
        self.d().kind
    }
    pub fn is_element(&self) -> bool {
        self.d().kind == NodeKind::Element
    }
    pub fn is_text(&self) -> bool {
        self.d().kind == NodeKind::Text
    }
    /// Element name. Panics on non-element non-PI nodes; use `try_name`.
    pub fn name(&self) -> &'a QName {
        self.d().name.as_ref().expect("node has no name")
    }
    pub fn try_name(&self) -> Option<&'a QName> {
        self.d().name.as_ref()
    }
    pub fn local(&self) -> &'a str {
        self.d().name.as_ref().map(|q| &*q.local).unwrap_or("")
    }
    pub fn ns(&self) -> &'a str {
        self.d().name.as_ref().map(|q| &*q.ns).unwrap_or("")
    }
    pub fn is(&self, ns: &str, local: &str) -> bool {
        self.d()
            .name
            .as_ref()
            .map(|q| q.is(ns, local))
            .unwrap_or(false)
            && self.is_element()
    }
    /// Text, comment or PI content.
    pub fn text(&self) -> Option<&'a str> {
        self.d().text.as_deref()
    }
    pub fn text_atom(&self) -> Option<&'a Atom> {
        self.d().text.as_ref()
    }
    pub fn parent(&self) -> Option<Node<'a>> {
        self.wrap(self.d().parent)
    }
    pub fn parent_element(&self) -> Option<Node<'a>> {
        self.parent().filter(|p| p.is_element())
    }
    pub fn first_child(&self) -> Option<Node<'a>> {
        self.wrap(self.d().first_child)
    }
    pub fn last_child(&self) -> Option<Node<'a>> {
        self.wrap(self.d().last_child)
    }
    pub fn next_sibling(&self) -> Option<Node<'a>> {
        self.wrap(self.d().next_sibling)
    }
    pub fn prev_sibling(&self) -> Option<Node<'a>> {
        self.wrap(self.d().prev_sibling)
    }
    pub fn next_sibling_element(&self) -> Option<Node<'a>> {
        let mut n = self.next_sibling();
        while let Some(x) = n {
            if x.is_element() {
                return Some(x);
            }
            n = x.next_sibling();
        }
        None
    }
    pub fn children(&self) -> Children<'a> {
        Children {
            doc: self.doc,
            next: self.d().first_child,
        }
    }
    /// Child elements.
    pub fn elements(&self) -> impl Iterator<Item = Node<'a>> + 'a {
        self.children().filter(|n| n.is_element())
    }
    /// Child elements with the given name.
    pub fn elements_named(
        &self,
        ns: &'a str,
        local: &'a str,
    ) -> impl Iterator<Item = Node<'a>> + 'a {
        self.children().filter(move |n| n.is(ns, local))
    }
    pub fn first_element_named(&self, ns: &str, local: &str) -> Option<Node<'a>> {
        self.children().find(|n| n.is(ns, local))
    }
    /// Descendants (not including self) in document order.
    pub fn descendants(&self) -> impl Iterator<Item = Node<'a>> + 'a {
        let doc = self.doc;
        let start = self.id.0 + 1;
        let end = self.d().subtree_end;
        (start..=end)
            .filter(move |_| end >= start)
            .map(move |i| Node { doc, id: NodeId(i) })
    }
    /// Self and descendants in document order.
    pub fn descendants_or_self(&self) -> impl Iterator<Item = Node<'a>> + 'a {
        let doc = self.doc;
        let start = self.id.0;
        let end = self.d().subtree_end;
        (start..=end).map(move |i| Node { doc, id: NodeId(i) })
    }
    pub fn descendant_elements(&self) -> impl Iterator<Item = Node<'a>> + 'a {
        self.descendants().filter(|n| n.is_element())
    }
    pub fn ancestors(&self) -> impl Iterator<Item = Node<'a>> + 'a {
        let mut cur = self.parent();
        std::iter::from_fn(move || {
            let r = cur;
            cur = cur.and_then(|c| c.parent());
            r
        })
    }
    pub fn is_ancestor_of(&self, other: &Node<'_>) -> bool {
        std::ptr::eq(self.doc, other.doc)
            && other.id.0 > self.id.0
            && other.id.0 <= self.d().subtree_end
    }
    pub fn attributes(&self) -> &'a [Attribute] {
        let d = self.d();
        &self.doc.attrs[d.attr_start as usize..d.attr_end as usize]
    }
    /// Attribute value by expanded name.
    pub fn attr(&self, ns: &str, local: &str) -> Option<&'a str> {
        self.attributes()
            .iter()
            .find(|a| a.name.is(ns, local))
            .map(|a| &*a.value)
    }
    /// Unqualified attribute value (`attr("", local)`).
    pub fn att(&self, local: &str) -> Option<&'a str> {
        self.attr("", local)
    }
    pub fn attr_atom(&self, ns: &str, local: &str) -> Option<&'a Atom> {
        self.attributes()
            .iter()
            .find(|a| a.name.is(ns, local))
            .map(|a| &a.value)
    }
    /// Namespace declarations on this element.
    pub fn ns_decls(&self) -> &'a [(Atom, Atom)] {
        let d = self.d();
        &self.doc.nsdecls[d.ns_start as usize..d.ns_end as usize]
    }
    /// Resolve a prefix ("" = default namespace) in scope at this node.
    pub fn lookup_namespace(&self, prefix: &str) -> Option<&'a str> {
        if prefix == "xml" {
            return Some(XML_NS);
        }
        let mut cur = Some(*self);
        while let Some(n) = cur {
            if n.is_element() {
                for (p, u) in n.ns_decls().iter().rev() {
                    if &**p == prefix {
                        return if u.is_empty() { None } else { Some(&**u) };
                    }
                }
            }
            cur = n.parent();
        }
        None
    }
    /// Prefix bound to a namespace in scope here (first found walking up).
    pub fn lookup_prefix(&self, ns: &str) -> Option<&'a str> {
        let mut cur = Some(*self);
        while let Some(n) = cur {
            if n.is_element() {
                for (p, u) in n.ns_decls().iter().rev() {
                    if &**u == ns && self.lookup_namespace(p) == Some(ns) {
                        return Some(&**p);
                    }
                }
            }
            cur = n.parent();
        }
        None
    }
    /// All in-scope namespace bindings (prefix, uri), nearest wins; excludes undeclarations.
    pub fn in_scope_namespaces(&self) -> Vec<(Atom, Atom)> {
        let mut out: Vec<(Atom, Atom)> = Vec::new();
        let mut cur = Some(*self);
        while let Some(n) = cur {
            if n.is_element() {
                for (p, u) in n.ns_decls() {
                    if !out.iter().any(|(q, _)| q == p) {
                        out.push((p.clone(), u.clone()));
                    }
                }
            }
            cur = n.parent();
        }
        out.retain(|(_, u)| !u.is_empty());
        out
    }
    /// Resolve a lexical QName (`p:local` or `local`) using the in-scope namespaces.
    /// Unprefixed names take the default namespace when `use_default` is set (XSD QName
    /// content does; attribute names do not).
    pub fn resolve_qname(&self, lexical: &str, use_default: bool) -> Option<QName> {
        let lexical = lexical.trim();
        if lexical.is_empty() {
            return None;
        }
        match lexical.split_once(':') {
            Some((p, l)) => {
                if p.is_empty() || l.is_empty() || l.contains(':') || !is_ncname(p) || !is_ncname(l)
                {
                    return None;
                }
                let ns = self.lookup_namespace(p)?;
                Some(QName::with_prefix(ns, l, p))
            }
            None => {
                if !is_ncname(lexical) {
                    return None;
                }
                let ns = if use_default {
                    self.lookup_namespace("").unwrap_or("")
                } else {
                    ""
                };
                Some(QName::new(ns, lexical))
            }
        }
    }
    /// Concatenated descendant text (XPath string value).
    pub fn string_value(&self) -> String {
        match self.kind() {
            NodeKind::Text | NodeKind::Comment | NodeKind::ProcessingInstruction => {
                self.text().unwrap_or("").to_string()
            }
            _ => {
                let mut s = String::new();
                for n in self.descendants() {
                    if n.is_text() {
                        s.push_str(n.text().unwrap_or(""));
                    }
                }
                s
            }
        }
    }
    /// Text of the direct text children only.
    pub fn child_text(&self) -> String {
        let mut s = String::new();
        for n in self.children() {
            if n.is_text() {
                s.push_str(n.text().unwrap_or(""));
            }
        }
        s
    }
    /// Base URI after applying `xml:base` attributes up the tree.
    pub fn base_uri(&self) -> String {
        let mut bases: Vec<&str> = Vec::new();
        let mut cur = Some(*self);
        while let Some(n) = cur {
            if n.is_element() {
                if let Some(b) = n.attr(XML_NS, "base") {
                    bases.push(b);
                }
            }
            cur = n.parent();
        }
        let mut base = self.doc.uri.to_string();
        for b in bases.iter().rev() {
            base = resolve_uri(&base, b);
        }
        base
    }
    /// Inherited `xml:lang`.
    pub fn lang(&self) -> Option<&'a str> {
        let mut cur = Some(*self);
        while let Some(n) = cur {
            if n.is_element() {
                if let Some(l) = n.attr(XML_NS, "lang") {
                    return Some(l);
                }
            }
            cur = n.parent();
        }
        None
    }
    pub fn offset(&self) -> u32 {
        self.d().offset
    }
    pub fn line(&self) -> u32 {
        self.doc.line_col(self.d().offset).0
    }
    pub fn line_col(&self) -> (u32, u32) {
        self.doc.line_col(self.d().offset)
    }
    /// Position among sibling elements (1-based), as used by XPointer element schemes.
    pub fn element_index(&self) -> usize {
        let mut i = 1;
        let mut n = self.prev_sibling();
        while let Some(x) = n {
            if x.is_element() {
                i += 1;
            }
            n = x.prev_sibling();
        }
        i
    }
    /// Serialize this subtree back to XML (for fragments such as segments and footnotes).
    pub fn to_xml(&self) -> String {
        let mut s = String::new();
        serialize(*self, &mut s, true);
        s
    }
}

fn serialize(n: Node<'_>, out: &mut String, top: bool) {
    match n.kind() {
        NodeKind::Document => {
            for c in n.children() {
                serialize(c, out, false);
            }
        }
        NodeKind::Text => escape_text(n.text().unwrap_or(""), out),
        NodeKind::Comment => {
            out.push_str("<!--");
            out.push_str(n.text().unwrap_or(""));
            out.push_str("-->");
        }
        NodeKind::ProcessingInstruction => {
            out.push_str("<?");
            out.push_str(n.local());
            if let Some(t) = n.text() {
                if !t.is_empty() {
                    out.push(' ');
                    out.push_str(t);
                }
            }
            out.push_str("?>");
        }
        NodeKind::Element => {
            out.push('<');
            let name = n.name().lexical();
            out.push_str(&name);
            let decls = if top {
                n.in_scope_namespaces()
            } else {
                n.ns_decls().to_vec()
            };
            for (p, u) in decls {
                if p.is_empty() {
                    out.push_str(" xmlns=\"");
                } else {
                    out.push_str(" xmlns:");
                    out.push_str(&p);
                    out.push_str("=\"");
                }
                escape_attr(&u, out);
                out.push('"');
            }
            for a in n.attributes() {
                out.push(' ');
                if a.name.ns.as_ref() == XML_NS {
                    out.push_str("xml:");
                    out.push_str(&a.name.local);
                } else {
                    out.push_str(&a.name.lexical());
                }
                out.push_str("=\"");
                escape_attr(&a.value, out);
                out.push('"');
            }
            if n.first_child().is_none() {
                out.push_str("/>");
            } else {
                out.push('>');
                for c in n.children() {
                    serialize(c, out, false);
                }
                out.push_str("</");
                out.push_str(&name);
                out.push('>');
            }
        }
    }
}

pub fn escape_text(s: &str, out: &mut String) {
    for c in s.chars() {
        match c {
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '&' => out.push_str("&amp;"),
            '\r' => out.push_str("&#xD;"),
            _ => out.push(c),
        }
    }
}

pub fn escape_attr(s: &str, out: &mut String) {
    for c in s.chars() {
        match c {
            '<' => out.push_str("&lt;"),
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            '\n' => out.push_str("&#xA;"),
            '\r' => out.push_str("&#xD;"),
            '\t' => out.push_str("&#x9;"),
            _ => out.push(c),
        }
    }
}

pub struct Children<'a> {
    doc: &'a Document,
    next: u32,
}

impl<'a> Iterator for Children<'a> {
    type Item = Node<'a>;
    fn next(&mut self) -> Option<Node<'a>> {
        if self.next == NONE {
            return None;
        }
        let n = Node {
            doc: self.doc,
            id: NodeId(self.next),
        };
        self.next = self.doc.nodes[self.next as usize].next_sibling;
        Some(n)
    }
}

pub fn is_name_start(c: char) -> bool {
    matches!(c, ':' | 'A'..='Z' | '_' | 'a'..='z'
        | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}'
        | '\u{370}'..='\u{37D}' | '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}'
        | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
        | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
}

pub fn is_name_char(c: char) -> bool {
    is_name_start(c)
        || matches!(c, '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
}

pub fn is_ncname(s: &str) -> bool {
    let mut it = s.chars();
    match it.next() {
        Some(c) if c != ':' && is_name_start(c) => it.all(|c| c != ':' && is_name_char(c)),
        _ => false,
    }
}

pub fn is_name(s: &str) -> bool {
    let mut it = s.chars();
    match it.next() {
        Some(c) if is_name_start(c) => it.all(is_name_char),
        _ => false,
    }
}

/// Resolve a URI reference against a base (RFC 3986 §5.2), tolerant of Windows-ish and
/// opaque bases. Works for `http(s):`, `file:` and plain relative paths.
pub fn resolve_uri(base: &str, reference: &str) -> String {
    let r = reference.trim();
    if r.is_empty() {
        return strip_fragment(base).to_string();
    }
    if has_scheme(r) {
        return remove_dot_segments_uri(r);
    }
    if r.starts_with('#') {
        return format!("{}{}", strip_fragment(base), r);
    }
    let base = strip_fragment(base);
    // split base into scheme://authority and path
    let (prefix, path) = split_authority(base);
    if r.starts_with("//") {
        let scheme = base.split_once(':').map(|(s, _)| s).unwrap_or("http");
        return remove_dot_segments_uri(&format!("{}:{}", scheme, r));
    }
    let joined = if r.starts_with('/') {
        r.to_string()
    } else {
        let path_no_query = path.split('?').next().unwrap_or("");
        match path_no_query.rfind('/') {
            Some(i) => format!("{}{}", &path_no_query[..=i], r),
            None => {
                if prefix.is_empty() {
                    r.to_string()
                } else {
                    format!("/{}", r)
                }
            }
        }
    };
    format!("{}{}", prefix, remove_dots(&joined))
}

fn strip_fragment(s: &str) -> &str {
    s.split('#').next().unwrap_or(s)
}

pub fn has_scheme(s: &str) -> bool {
    match s.find(':') {
        Some(i) if i > 1 => {
            let sch = &s[..i];
            sch.chars()
                .next()
                .map(|c| c.is_ascii_alphabetic())
                .unwrap_or(false)
                && sch
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
        }
        _ => false,
    }
}

fn split_authority(s: &str) -> (&str, &str) {
    if let Some(i) = s.find("://") {
        let after = &s[i + 3..];
        match after.find('/') {
            Some(j) => (&s[..i + 3 + j], &after[j..]),
            None => (s, ""),
        }
    } else if let Some(rest) = s.strip_prefix("file:") {
        // file:/path
        let _ = rest;
        ("file:", &s[5..])
    } else if has_scheme(s) {
        let i = s.find(':').unwrap();
        (&s[..=i], &s[i + 1..])
    } else {
        ("", s)
    }
}

fn remove_dot_segments_uri(s: &str) -> String {
    let (prefix, path) = split_authority(s);
    format!("{}{}", prefix, remove_dots(path))
}

fn remove_dots(path: &str) -> String {
    let (path, query) = match path.find('?') {
        Some(i) => (&path[..i], &path[i..]),
        None => (path, ""),
    };
    if !path.contains("./")
        && !path.ends_with("/.")
        && !path.ends_with("/..")
        && path != "."
        && path != ".."
    {
        return format!("{}{}", path, query);
    }
    let abs = path.starts_with('/');
    let mut out: Vec<&str> = Vec::new();
    let segs: Vec<&str> = path.split('/').collect();
    let n = segs.len();
    for (i, seg) in segs.iter().enumerate() {
        match *seg {
            "." => {
                if i == n - 1 {
                    out.push("");
                }
            }
            ".." => {
                if out.len() > 1 || (out.len() == 1 && !abs && out[0] != "..") {
                    if out.last() == Some(&"..") {
                        out.push("..");
                    } else {
                        out.pop();
                    }
                } else if !abs {
                    out.push("..");
                }
                if i == n - 1 {
                    out.push("");
                }
            }
            s => out.push(s),
        }
    }
    let mut r = out.join("/");
    if abs && !r.starts_with('/') {
        r.insert(0, '/');
    }
    format!("{}{}", r, query)
}

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

    #[test]
    fn uri_resolution() {
        assert_eq!(
            resolve_uri("http://a/b/c/d.xsd", "e.xml"),
            "http://a/b/c/e.xml"
        );
        assert_eq!(
            resolve_uri("http://a/b/c/d.xsd", "../e.xml"),
            "http://a/b/e.xml"
        );
        assert_eq!(
            resolve_uri("http://a/b/c/d.xsd", "/e.xml"),
            "http://a/e.xml"
        );
        assert_eq!(
            resolve_uri("file:///x/y/z.xml", "q.xsd#el"),
            "file:///x/y/q.xsd#el"
        );
        assert_eq!(resolve_uri("/x/y/z.xml", "../q.xsd"), "/x/q.xsd");
        assert_eq!(resolve_uri("x/y/z.xml", "q.xsd"), "x/y/q.xsd");
        assert_eq!(
            resolve_uri("http://a/b/c.xsd", "http://z/y.xsd"),
            "http://z/y.xsd"
        );
        assert_eq!(resolve_uri("http://a/b/c.xsd", "#f"), "http://a/b/c.xsd#f");
        assert_eq!(
            resolve_uri("http://a/b/c/d.xsd", "./././e.xml"),
            "http://a/b/c/e.xml"
        );
    }

    #[test]
    fn parse_basic() {
        let d = parse_str(
            "file:///t.xml",
            r#"<?xml version="1.0"?>
<a xmlns="urn:a" xmlns:b="urn:b" xml:lang="en"><b:c id="x" b:k="v">t&amp;u<![CDATA[<z>]]></b:c><!--c--><d/></a>"#,
        )
        .unwrap();
        let a = d.document_element().unwrap();
        assert!(a.is("urn:a", "a"));
        let c = a.elements().next().unwrap();
        assert!(c.is("urn:b", "c"));
        assert_eq!(c.attr("urn:b", "k"), Some("v"));
        assert_eq!(c.string_value(), "t&u<z>");
        assert_eq!(c.lang(), Some("en"));
        assert_eq!(d.by_id("x").unwrap().id, c.id);
        assert_eq!(
            c.resolve_qname("b:q", true).unwrap(),
            QName::new("urn:b", "q")
        );
        assert_eq!(
            c.resolve_qname("q", true).unwrap(),
            QName::new("urn:a", "q")
        );
        assert_eq!(a.line(), 2);
        assert_eq!(a.descendant_elements().count(), 2);
    }

    #[test]
    fn wellformedness_errors() {
        assert!(parse_str("t", "<a><b></a>").is_err());
        assert!(parse_str("t", "<a x='1' x='2'/>").is_err());
        assert!(parse_str("t", "<p:a/>").is_err());
        assert!(parse_str("t", "<a>&foo;</a>").is_err());
        assert!(parse_str("t", "<a/><b/>").is_err());
        assert!(parse_str("t", "<!DOCTYPE a [<!ENTITY foo 'bar'>]><a>&foo;</a>").is_ok());
    }
}