Skip to main content

crossfoot_xml/
lib.rs

1//! crossfoot-xml: a namespace-aware XML 1.0 parser producing an immutable arena DOM.
2//!
3//! The DOM is `Send + Sync`, keeps byte offsets for every node (line/column on demand),
4//! resolves `xml:base`, `xml:lang` and QName-valued content, and indexes `id` attributes.
5//! It is the one XML representation every Crossfoot component reads.
6
7mod parse;
8
9use std::collections::HashMap;
10use std::fmt;
11use std::sync::Arc;
12
13pub use parse::{parse, parse_str, ParseOptions};
14
15/// Interned-ish string. Plain `Arc<str>`; equality is by content.
16pub type Atom = Arc<str>;
17
18pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
19pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
20
21/// An expanded name. Equality and hashing ignore the prefix.
22#[derive(Clone)]
23pub struct QName {
24    pub ns: Atom,
25    pub local: Atom,
26    pub prefix: Atom,
27}
28
29impl QName {
30    pub fn new(ns: &str, local: &str) -> QName {
31        QName {
32            ns: ns.into(),
33            local: local.into(),
34            prefix: "".into(),
35        }
36    }
37    pub fn with_prefix(ns: &str, local: &str, prefix: &str) -> QName {
38        QName {
39            ns: ns.into(),
40            local: local.into(),
41            prefix: prefix.into(),
42        }
43    }
44    pub fn is(&self, ns: &str, local: &str) -> bool {
45        &*self.local == local && &*self.ns == ns
46    }
47    /// `{ns}local` (James Clark notation); `local` when there is no namespace.
48    pub fn clark(&self) -> String {
49        if self.ns.is_empty() {
50            self.local.to_string()
51        } else {
52            format!("{{{}}}{}", self.ns, self.local)
53        }
54    }
55    /// `prefix:local` or `local`.
56    pub fn lexical(&self) -> String {
57        if self.prefix.is_empty() {
58            self.local.to_string()
59        } else {
60            format!("{}:{}", self.prefix, self.local)
61        }
62    }
63    /// Parse `{ns}local` or `local`.
64    pub fn from_clark(s: &str) -> QName {
65        if let Some(rest) = s.strip_prefix('{') {
66            if let Some(i) = rest.find('}') {
67                return QName::new(&rest[..i], &rest[i + 1..]);
68            }
69        }
70        QName::new("", s)
71    }
72}
73
74impl PartialEq for QName {
75    fn eq(&self, o: &QName) -> bool {
76        self.local == o.local && self.ns == o.ns
77    }
78}
79impl Eq for QName {}
80impl std::hash::Hash for QName {
81    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
82        self.ns.hash(h);
83        self.local.hash(h);
84    }
85}
86impl PartialOrd for QName {
87    fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
88        Some(self.cmp(o))
89    }
90}
91impl Ord for QName {
92    fn cmp(&self, o: &Self) -> std::cmp::Ordering {
93        (&*self.ns, &*self.local).cmp(&(&*o.ns, &*o.local))
94    }
95}
96impl fmt::Debug for QName {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        if self.prefix.is_empty() {
99            write!(f, "{}", self.clark())
100        } else {
101            write!(f, "{}({})", self.lexical(), self.ns)
102        }
103    }
104}
105impl fmt::Display for QName {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        if self.prefix.is_empty() {
108            write!(f, "{}", self.clark())
109        } else {
110            write!(f, "{}", self.lexical())
111        }
112    }
113}
114impl serde::Serialize for QName {
115    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
116        s.serialize_str(&self.clark())
117    }
118}
119
120#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize)]
121pub struct NodeId(pub u32);
122
123const NONE: u32 = u32::MAX;
124
125#[derive(Copy, Clone, PartialEq, Eq, Debug)]
126pub enum NodeKind {
127    Document,
128    Element,
129    Text,
130    Comment,
131    ProcessingInstruction,
132}
133
134#[derive(Clone, Debug)]
135pub(crate) struct NodeData {
136    pub kind: NodeKind,
137    /// Element name, or PI target in `local`.
138    pub name: Option<QName>,
139    /// Text, comment or PI content.
140    pub text: Option<Atom>,
141    pub parent: u32,
142    pub first_child: u32,
143    pub last_child: u32,
144    pub next_sibling: u32,
145    pub prev_sibling: u32,
146    pub attr_start: u32,
147    pub attr_end: u32,
148    pub ns_start: u32,
149    pub ns_end: u32,
150    /// Byte offset of the node start in the (normalized) source text.
151    pub offset: u32,
152    /// Index of the last descendant (inclusive) for fast subtree ranges.
153    pub subtree_end: u32,
154}
155
156#[derive(Clone, Debug)]
157pub struct Attribute {
158    pub name: QName,
159    pub value: Atom,
160    pub offset: u32,
161}
162
163/// Immutable parsed document.
164pub struct Document {
165    pub uri: Atom,
166    pub(crate) nodes: Vec<NodeData>,
167    pub(crate) attrs: Vec<Attribute>,
168    /// Namespace declarations: (prefix, uri); prefix "" is the default namespace.
169    pub(crate) nsdecls: Vec<(Atom, Atom)>,
170    pub(crate) line_starts: Vec<u32>,
171    pub(crate) ids: HashMap<Atom, NodeId>,
172    /// Internal general entities declared in the DOCTYPE, if any.
173    pub has_doctype: bool,
174    pub xml_version: Atom,
175    pub encoding: Atom,
176}
177
178impl fmt::Debug for Document {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        write!(f, "Document({}, {} nodes)", self.uri, self.nodes.len())
181    }
182}
183
184/// A well-formedness or encoding error.
185#[derive(Clone, Debug)]
186pub struct XmlError {
187    pub message: String,
188    pub line: u32,
189    pub col: u32,
190}
191
192impl fmt::Display for XmlError {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        write!(f, "{}:{}: {}", self.line, self.col, self.message)
195    }
196}
197impl std::error::Error for XmlError {}
198
199impl Document {
200    pub fn root(&self) -> Node<'_> {
201        Node {
202            doc: self,
203            id: NodeId(0),
204        }
205    }
206    /// The document element.
207    pub fn document_element(&self) -> Option<Node<'_>> {
208        self.root().children().find(|n| n.is_element())
209    }
210    pub fn node(&self, id: NodeId) -> Node<'_> {
211        Node { doc: self, id }
212    }
213    pub fn len(&self) -> usize {
214        self.nodes.len()
215    }
216    pub fn is_empty(&self) -> bool {
217        self.nodes.is_empty()
218    }
219    /// Element with the given `id` (or `xml:id`) attribute.
220    pub fn by_id(&self, id: &str) -> Option<Node<'_>> {
221        self.ids.get(id).map(|&n| self.node(n))
222    }
223    /// 1-based (line, column) of a byte offset.
224    pub fn line_col(&self, offset: u32) -> (u32, u32) {
225        let i = match self.line_starts.binary_search(&offset) {
226            Ok(i) => i,
227            Err(i) => i - 1,
228        };
229        (i as u32 + 1, offset - self.line_starts[i] + 1)
230    }
231    /// Every element node in document order.
232    pub fn elements(&self) -> impl Iterator<Item = Node<'_>> + '_ {
233        (0..self.nodes.len() as u32)
234            .filter(move |&i| self.nodes[i as usize].kind == NodeKind::Element)
235            .map(move |i| Node {
236                doc: self,
237                id: NodeId(i),
238            })
239    }
240}
241
242/// A borrowed handle on a node.
243#[derive(Copy, Clone)]
244pub struct Node<'a> {
245    pub doc: &'a Document,
246    pub id: NodeId,
247}
248
249impl PartialEq for Node<'_> {
250    fn eq(&self, o: &Self) -> bool {
251        self.id == o.id && std::ptr::eq(self.doc, o.doc)
252    }
253}
254impl Eq for Node<'_> {}
255
256impl fmt::Debug for Node<'_> {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        match self.kind() {
259            NodeKind::Element => write!(f, "<{}>@{}", self.name().lexical(), self.line()),
260            k => write!(f, "{:?}#{}", k, self.id.0),
261        }
262    }
263}
264
265impl<'a> Node<'a> {
266    #[inline]
267    fn d(&self) -> &'a NodeData {
268        &self.doc.nodes[self.id.0 as usize]
269    }
270    #[inline]
271    fn wrap(&self, i: u32) -> Option<Node<'a>> {
272        if i == NONE {
273            None
274        } else {
275            Some(Node {
276                doc: self.doc,
277                id: NodeId(i),
278            })
279        }
280    }
281    pub fn kind(&self) -> NodeKind {
282        self.d().kind
283    }
284    pub fn is_element(&self) -> bool {
285        self.d().kind == NodeKind::Element
286    }
287    pub fn is_text(&self) -> bool {
288        self.d().kind == NodeKind::Text
289    }
290    /// Element name. Panics on non-element non-PI nodes; use `try_name`.
291    pub fn name(&self) -> &'a QName {
292        self.d().name.as_ref().expect("node has no name")
293    }
294    pub fn try_name(&self) -> Option<&'a QName> {
295        self.d().name.as_ref()
296    }
297    pub fn local(&self) -> &'a str {
298        self.d().name.as_ref().map(|q| &*q.local).unwrap_or("")
299    }
300    pub fn ns(&self) -> &'a str {
301        self.d().name.as_ref().map(|q| &*q.ns).unwrap_or("")
302    }
303    pub fn is(&self, ns: &str, local: &str) -> bool {
304        self.d()
305            .name
306            .as_ref()
307            .map(|q| q.is(ns, local))
308            .unwrap_or(false)
309            && self.is_element()
310    }
311    /// Text, comment or PI content.
312    pub fn text(&self) -> Option<&'a str> {
313        self.d().text.as_deref()
314    }
315    pub fn text_atom(&self) -> Option<&'a Atom> {
316        self.d().text.as_ref()
317    }
318    pub fn parent(&self) -> Option<Node<'a>> {
319        self.wrap(self.d().parent)
320    }
321    pub fn parent_element(&self) -> Option<Node<'a>> {
322        self.parent().filter(|p| p.is_element())
323    }
324    pub fn first_child(&self) -> Option<Node<'a>> {
325        self.wrap(self.d().first_child)
326    }
327    pub fn last_child(&self) -> Option<Node<'a>> {
328        self.wrap(self.d().last_child)
329    }
330    pub fn next_sibling(&self) -> Option<Node<'a>> {
331        self.wrap(self.d().next_sibling)
332    }
333    pub fn prev_sibling(&self) -> Option<Node<'a>> {
334        self.wrap(self.d().prev_sibling)
335    }
336    pub fn next_sibling_element(&self) -> Option<Node<'a>> {
337        let mut n = self.next_sibling();
338        while let Some(x) = n {
339            if x.is_element() {
340                return Some(x);
341            }
342            n = x.next_sibling();
343        }
344        None
345    }
346    pub fn children(&self) -> Children<'a> {
347        Children {
348            doc: self.doc,
349            next: self.d().first_child,
350        }
351    }
352    /// Child elements.
353    pub fn elements(&self) -> impl Iterator<Item = Node<'a>> + 'a {
354        self.children().filter(|n| n.is_element())
355    }
356    /// Child elements with the given name.
357    pub fn elements_named(
358        &self,
359        ns: &'a str,
360        local: &'a str,
361    ) -> impl Iterator<Item = Node<'a>> + 'a {
362        self.children().filter(move |n| n.is(ns, local))
363    }
364    pub fn first_element_named(&self, ns: &str, local: &str) -> Option<Node<'a>> {
365        self.children().find(|n| n.is(ns, local))
366    }
367    /// Descendants (not including self) in document order.
368    pub fn descendants(&self) -> impl Iterator<Item = Node<'a>> + 'a {
369        let doc = self.doc;
370        let start = self.id.0 + 1;
371        let end = self.d().subtree_end;
372        (start..=end)
373            .filter(move |_| end >= start)
374            .map(move |i| Node { doc, id: NodeId(i) })
375    }
376    /// Self and descendants in document order.
377    pub fn descendants_or_self(&self) -> impl Iterator<Item = Node<'a>> + 'a {
378        let doc = self.doc;
379        let start = self.id.0;
380        let end = self.d().subtree_end;
381        (start..=end).map(move |i| Node { doc, id: NodeId(i) })
382    }
383    pub fn descendant_elements(&self) -> impl Iterator<Item = Node<'a>> + 'a {
384        self.descendants().filter(|n| n.is_element())
385    }
386    pub fn ancestors(&self) -> impl Iterator<Item = Node<'a>> + 'a {
387        let mut cur = self.parent();
388        std::iter::from_fn(move || {
389            let r = cur;
390            cur = cur.and_then(|c| c.parent());
391            r
392        })
393    }
394    pub fn is_ancestor_of(&self, other: &Node<'_>) -> bool {
395        std::ptr::eq(self.doc, other.doc)
396            && other.id.0 > self.id.0
397            && other.id.0 <= self.d().subtree_end
398    }
399    pub fn attributes(&self) -> &'a [Attribute] {
400        let d = self.d();
401        &self.doc.attrs[d.attr_start as usize..d.attr_end as usize]
402    }
403    /// Attribute value by expanded name.
404    pub fn attr(&self, ns: &str, local: &str) -> Option<&'a str> {
405        self.attributes()
406            .iter()
407            .find(|a| a.name.is(ns, local))
408            .map(|a| &*a.value)
409    }
410    /// Unqualified attribute value (`attr("", local)`).
411    pub fn att(&self, local: &str) -> Option<&'a str> {
412        self.attr("", local)
413    }
414    pub fn attr_atom(&self, ns: &str, local: &str) -> Option<&'a Atom> {
415        self.attributes()
416            .iter()
417            .find(|a| a.name.is(ns, local))
418            .map(|a| &a.value)
419    }
420    /// Namespace declarations on this element.
421    pub fn ns_decls(&self) -> &'a [(Atom, Atom)] {
422        let d = self.d();
423        &self.doc.nsdecls[d.ns_start as usize..d.ns_end as usize]
424    }
425    /// Resolve a prefix ("" = default namespace) in scope at this node.
426    pub fn lookup_namespace(&self, prefix: &str) -> Option<&'a str> {
427        if prefix == "xml" {
428            return Some(XML_NS);
429        }
430        let mut cur = Some(*self);
431        while let Some(n) = cur {
432            if n.is_element() {
433                for (p, u) in n.ns_decls().iter().rev() {
434                    if &**p == prefix {
435                        return if u.is_empty() { None } else { Some(&**u) };
436                    }
437                }
438            }
439            cur = n.parent();
440        }
441        None
442    }
443    /// Prefix bound to a namespace in scope here (first found walking up).
444    pub fn lookup_prefix(&self, ns: &str) -> Option<&'a str> {
445        let mut cur = Some(*self);
446        while let Some(n) = cur {
447            if n.is_element() {
448                for (p, u) in n.ns_decls().iter().rev() {
449                    if &**u == ns && self.lookup_namespace(p) == Some(ns) {
450                        return Some(&**p);
451                    }
452                }
453            }
454            cur = n.parent();
455        }
456        None
457    }
458    /// All in-scope namespace bindings (prefix, uri), nearest wins; excludes undeclarations.
459    pub fn in_scope_namespaces(&self) -> Vec<(Atom, Atom)> {
460        let mut out: Vec<(Atom, Atom)> = Vec::new();
461        let mut cur = Some(*self);
462        while let Some(n) = cur {
463            if n.is_element() {
464                for (p, u) in n.ns_decls() {
465                    if !out.iter().any(|(q, _)| q == p) {
466                        out.push((p.clone(), u.clone()));
467                    }
468                }
469            }
470            cur = n.parent();
471        }
472        out.retain(|(_, u)| !u.is_empty());
473        out
474    }
475    /// Resolve a lexical QName (`p:local` or `local`) using the in-scope namespaces.
476    /// Unprefixed names take the default namespace when `use_default` is set (XSD QName
477    /// content does; attribute names do not).
478    pub fn resolve_qname(&self, lexical: &str, use_default: bool) -> Option<QName> {
479        let lexical = lexical.trim();
480        if lexical.is_empty() {
481            return None;
482        }
483        match lexical.split_once(':') {
484            Some((p, l)) => {
485                if p.is_empty() || l.is_empty() || l.contains(':') || !is_ncname(p) || !is_ncname(l)
486                {
487                    return None;
488                }
489                let ns = self.lookup_namespace(p)?;
490                Some(QName::with_prefix(ns, l, p))
491            }
492            None => {
493                if !is_ncname(lexical) {
494                    return None;
495                }
496                let ns = if use_default {
497                    self.lookup_namespace("").unwrap_or("")
498                } else {
499                    ""
500                };
501                Some(QName::new(ns, lexical))
502            }
503        }
504    }
505    /// Concatenated descendant text (XPath string value).
506    pub fn string_value(&self) -> String {
507        match self.kind() {
508            NodeKind::Text | NodeKind::Comment | NodeKind::ProcessingInstruction => {
509                self.text().unwrap_or("").to_string()
510            }
511            _ => {
512                let mut s = String::new();
513                for n in self.descendants() {
514                    if n.is_text() {
515                        s.push_str(n.text().unwrap_or(""));
516                    }
517                }
518                s
519            }
520        }
521    }
522    /// Text of the direct text children only.
523    pub fn child_text(&self) -> String {
524        let mut s = String::new();
525        for n in self.children() {
526            if n.is_text() {
527                s.push_str(n.text().unwrap_or(""));
528            }
529        }
530        s
531    }
532    /// Base URI after applying `xml:base` attributes up the tree.
533    pub fn base_uri(&self) -> String {
534        let mut bases: Vec<&str> = Vec::new();
535        let mut cur = Some(*self);
536        while let Some(n) = cur {
537            if n.is_element() {
538                if let Some(b) = n.attr(XML_NS, "base") {
539                    bases.push(b);
540                }
541            }
542            cur = n.parent();
543        }
544        let mut base = self.doc.uri.to_string();
545        for b in bases.iter().rev() {
546            base = resolve_uri(&base, b);
547        }
548        base
549    }
550    /// Inherited `xml:lang`.
551    pub fn lang(&self) -> Option<&'a str> {
552        let mut cur = Some(*self);
553        while let Some(n) = cur {
554            if n.is_element() {
555                if let Some(l) = n.attr(XML_NS, "lang") {
556                    return Some(l);
557                }
558            }
559            cur = n.parent();
560        }
561        None
562    }
563    pub fn offset(&self) -> u32 {
564        self.d().offset
565    }
566    pub fn line(&self) -> u32 {
567        self.doc.line_col(self.d().offset).0
568    }
569    pub fn line_col(&self) -> (u32, u32) {
570        self.doc.line_col(self.d().offset)
571    }
572    /// Position among sibling elements (1-based), as used by XPointer element schemes.
573    pub fn element_index(&self) -> usize {
574        let mut i = 1;
575        let mut n = self.prev_sibling();
576        while let Some(x) = n {
577            if x.is_element() {
578                i += 1;
579            }
580            n = x.prev_sibling();
581        }
582        i
583    }
584    /// Serialize this subtree back to XML (for fragments such as segments and footnotes).
585    pub fn to_xml(&self) -> String {
586        let mut s = String::new();
587        serialize(*self, &mut s, true);
588        s
589    }
590}
591
592fn serialize(n: Node<'_>, out: &mut String, top: bool) {
593    match n.kind() {
594        NodeKind::Document => {
595            for c in n.children() {
596                serialize(c, out, false);
597            }
598        }
599        NodeKind::Text => escape_text(n.text().unwrap_or(""), out),
600        NodeKind::Comment => {
601            out.push_str("<!--");
602            out.push_str(n.text().unwrap_or(""));
603            out.push_str("-->");
604        }
605        NodeKind::ProcessingInstruction => {
606            out.push_str("<?");
607            out.push_str(n.local());
608            if let Some(t) = n.text() {
609                if !t.is_empty() {
610                    out.push(' ');
611                    out.push_str(t);
612                }
613            }
614            out.push_str("?>");
615        }
616        NodeKind::Element => {
617            out.push('<');
618            let name = n.name().lexical();
619            out.push_str(&name);
620            let decls = if top {
621                n.in_scope_namespaces()
622            } else {
623                n.ns_decls().to_vec()
624            };
625            for (p, u) in decls {
626                if p.is_empty() {
627                    out.push_str(" xmlns=\"");
628                } else {
629                    out.push_str(" xmlns:");
630                    out.push_str(&p);
631                    out.push_str("=\"");
632                }
633                escape_attr(&u, out);
634                out.push('"');
635            }
636            for a in n.attributes() {
637                out.push(' ');
638                if a.name.ns.as_ref() == XML_NS {
639                    out.push_str("xml:");
640                    out.push_str(&a.name.local);
641                } else {
642                    out.push_str(&a.name.lexical());
643                }
644                out.push_str("=\"");
645                escape_attr(&a.value, out);
646                out.push('"');
647            }
648            if n.first_child().is_none() {
649                out.push_str("/>");
650            } else {
651                out.push('>');
652                for c in n.children() {
653                    serialize(c, out, false);
654                }
655                out.push_str("</");
656                out.push_str(&name);
657                out.push('>');
658            }
659        }
660    }
661}
662
663pub fn escape_text(s: &str, out: &mut String) {
664    for c in s.chars() {
665        match c {
666            '<' => out.push_str("&lt;"),
667            '>' => out.push_str("&gt;"),
668            '&' => out.push_str("&amp;"),
669            '\r' => out.push_str("&#xD;"),
670            _ => out.push(c),
671        }
672    }
673}
674
675pub fn escape_attr(s: &str, out: &mut String) {
676    for c in s.chars() {
677        match c {
678            '<' => out.push_str("&lt;"),
679            '&' => out.push_str("&amp;"),
680            '"' => out.push_str("&quot;"),
681            '\n' => out.push_str("&#xA;"),
682            '\r' => out.push_str("&#xD;"),
683            '\t' => out.push_str("&#x9;"),
684            _ => out.push(c),
685        }
686    }
687}
688
689pub struct Children<'a> {
690    doc: &'a Document,
691    next: u32,
692}
693
694impl<'a> Iterator for Children<'a> {
695    type Item = Node<'a>;
696    fn next(&mut self) -> Option<Node<'a>> {
697        if self.next == NONE {
698            return None;
699        }
700        let n = Node {
701            doc: self.doc,
702            id: NodeId(self.next),
703        };
704        self.next = self.doc.nodes[self.next as usize].next_sibling;
705        Some(n)
706    }
707}
708
709pub fn is_name_start(c: char) -> bool {
710    matches!(c, ':' | 'A'..='Z' | '_' | 'a'..='z'
711        | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}'
712        | '\u{370}'..='\u{37D}' | '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}'
713        | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
714        | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
715}
716
717pub fn is_name_char(c: char) -> bool {
718    is_name_start(c)
719        || matches!(c, '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
720}
721
722pub fn is_ncname(s: &str) -> bool {
723    let mut it = s.chars();
724    match it.next() {
725        Some(c) if c != ':' && is_name_start(c) => it.all(|c| c != ':' && is_name_char(c)),
726        _ => false,
727    }
728}
729
730pub fn is_name(s: &str) -> bool {
731    let mut it = s.chars();
732    match it.next() {
733        Some(c) if is_name_start(c) => it.all(is_name_char),
734        _ => false,
735    }
736}
737
738/// Resolve a URI reference against a base (RFC 3986 ยง5.2), tolerant of Windows-ish and
739/// opaque bases. Works for `http(s):`, `file:` and plain relative paths.
740pub fn resolve_uri(base: &str, reference: &str) -> String {
741    let r = reference.trim();
742    if r.is_empty() {
743        return strip_fragment(base).to_string();
744    }
745    if has_scheme(r) {
746        return remove_dot_segments_uri(r);
747    }
748    if r.starts_with('#') {
749        return format!("{}{}", strip_fragment(base), r);
750    }
751    let base = strip_fragment(base);
752    // split base into scheme://authority and path
753    let (prefix, path) = split_authority(base);
754    if r.starts_with("//") {
755        let scheme = base.split_once(':').map(|(s, _)| s).unwrap_or("http");
756        return remove_dot_segments_uri(&format!("{}:{}", scheme, r));
757    }
758    let joined = if r.starts_with('/') {
759        r.to_string()
760    } else {
761        let path_no_query = path.split('?').next().unwrap_or("");
762        match path_no_query.rfind('/') {
763            Some(i) => format!("{}{}", &path_no_query[..=i], r),
764            None => {
765                if prefix.is_empty() {
766                    r.to_string()
767                } else {
768                    format!("/{}", r)
769                }
770            }
771        }
772    };
773    format!(
774        "{}{}",
775        prefix,
776        remove_dots(&collapse_slashes(prefix, &joined))
777    )
778}
779
780fn strip_fragment(s: &str) -> &str {
781    s.split('#').next().unwrap_or(s)
782}
783
784pub fn has_scheme(s: &str) -> bool {
785    match s.find(':') {
786        Some(i) if i > 1 => {
787            let sch = &s[..i];
788            sch.chars()
789                .next()
790                .map(|c| c.is_ascii_alphabetic())
791                .unwrap_or(false)
792                && sch
793                    .chars()
794                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
795        }
796        _ => false,
797    }
798}
799
800fn split_authority(s: &str) -> (&str, &str) {
801    if let Some(i) = s.find("://") {
802        let after = &s[i + 3..];
803        match after.find('/') {
804            Some(j) => (&s[..i + 3 + j], &after[j..]),
805            None => (s, ""),
806        }
807    } else if let Some(rest) = s.strip_prefix("file:") {
808        // file:/path
809        let _ = rest;
810        ("file:", &s[5..])
811    } else if has_scheme(s) {
812        let i = s.find(':').unwrap();
813        (&s[..=i], &s[i + 1..])
814    } else {
815        ("", s)
816    }
817}
818
819fn remove_dot_segments_uri(s: &str) -> String {
820    let (prefix, path) = split_authority(s);
821    format!("{}{}", prefix, remove_dots(&collapse_slashes(prefix, path)))
822}
823
824/// Empty path segments in http(s) URIs (`.../2021-03-24//full_ifrs/...`, written by some
825/// ESEF tools in locator hrefs) name the same taxonomy document as the single-slash form,
826/// as Arelle treats them; without this the schema is loaded twice and its elements are
827/// "declared more than once". The query and fragment are left alone.
828fn collapse_slashes<'a>(prefix: &str, path: &'a str) -> std::borrow::Cow<'a, str> {
829    let end = path.find(['?', '#']).unwrap_or(path.len());
830    if !(prefix.starts_with("http://") || prefix.starts_with("https://"))
831        || !path[..end].contains("//")
832    {
833        return std::borrow::Cow::Borrowed(path);
834    }
835    let mut out = String::with_capacity(path.len());
836    let mut prev_slash = false;
837    for c in path[..end].chars() {
838        if c == '/' && prev_slash {
839            continue;
840        }
841        prev_slash = c == '/';
842        out.push(c);
843    }
844    out.push_str(&path[end..]);
845    std::borrow::Cow::Owned(out)
846}
847
848fn remove_dots(path: &str) -> String {
849    let (path, query) = match path.find('?') {
850        Some(i) => (&path[..i], &path[i..]),
851        None => (path, ""),
852    };
853    if !path.contains("./")
854        && !path.ends_with("/.")
855        && !path.ends_with("/..")
856        && path != "."
857        && path != ".."
858    {
859        return format!("{}{}", path, query);
860    }
861    let abs = path.starts_with('/');
862    let mut out: Vec<&str> = Vec::new();
863    let segs: Vec<&str> = path.split('/').collect();
864    let n = segs.len();
865    for (i, seg) in segs.iter().enumerate() {
866        match *seg {
867            "." => {
868                if i == n - 1 {
869                    out.push("");
870                }
871            }
872            ".." => {
873                if out.len() > 1 || (out.len() == 1 && !abs && out[0] != "..") {
874                    if out.last() == Some(&"..") {
875                        out.push("..");
876                    } else {
877                        out.pop();
878                    }
879                } else if !abs {
880                    out.push("..");
881                }
882                if i == n - 1 {
883                    out.push("");
884                }
885            }
886            s => out.push(s),
887        }
888    }
889    let mut r = out.join("/");
890    if abs && !r.starts_with('/') {
891        r.insert(0, '/');
892    }
893    format!("{}{}", r, query)
894}
895
896#[cfg(test)]
897mod tests {
898    use super::*;
899
900    #[test]
901    fn empty_http_path_segments_collapse() {
902        assert_eq!(
903            resolve_uri(
904                "file:///p/ext_def.xml",
905                "http://xbrl.ifrs.org/taxonomy/2021-03-24//full_ifrs/full_ifrs-cor_2021-03-24.xsd#ifrs-full_Equity"
906            ),
907            "http://xbrl.ifrs.org/taxonomy/2021-03-24/full_ifrs/full_ifrs-cor_2021-03-24.xsd#ifrs-full_Equity"
908        );
909        assert_eq!(
910            resolve_uri("http://a/b/c/d.xsd", "x//y.xsd"),
911            "http://a/b/c/x/y.xsd"
912        );
913        assert_eq!(
914            resolve_uri("http://a/b/c/d.xsd", "y.xsd?q=a//b#p//q"),
915            "http://a/b/c/y.xsd?q=a//b#p//q"
916        );
917        // only http(s): other schemes keep their path as written
918        assert_eq!(
919            resolve_uri("file:///a/b.xsd", "x//y.xsd"),
920            "file:///a/x//y.xsd"
921        );
922    }
923
924    #[test]
925    fn uri_resolution() {
926        assert_eq!(
927            resolve_uri("http://a/b/c/d.xsd", "e.xml"),
928            "http://a/b/c/e.xml"
929        );
930        assert_eq!(
931            resolve_uri("http://a/b/c/d.xsd", "../e.xml"),
932            "http://a/b/e.xml"
933        );
934        assert_eq!(
935            resolve_uri("http://a/b/c/d.xsd", "/e.xml"),
936            "http://a/e.xml"
937        );
938        assert_eq!(
939            resolve_uri("file:///x/y/z.xml", "q.xsd#el"),
940            "file:///x/y/q.xsd#el"
941        );
942        assert_eq!(resolve_uri("/x/y/z.xml", "../q.xsd"), "/x/q.xsd");
943        assert_eq!(resolve_uri("x/y/z.xml", "q.xsd"), "x/y/q.xsd");
944        assert_eq!(
945            resolve_uri("http://a/b/c.xsd", "http://z/y.xsd"),
946            "http://z/y.xsd"
947        );
948        assert_eq!(resolve_uri("http://a/b/c.xsd", "#f"), "http://a/b/c.xsd#f");
949        assert_eq!(
950            resolve_uri("http://a/b/c/d.xsd", "./././e.xml"),
951            "http://a/b/c/e.xml"
952        );
953    }
954
955    #[test]
956    fn parse_basic() {
957        let d = parse_str(
958            "file:///t.xml",
959            r#"<?xml version="1.0"?>
960<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>"#,
961        )
962        .unwrap();
963        let a = d.document_element().unwrap();
964        assert!(a.is("urn:a", "a"));
965        let c = a.elements().next().unwrap();
966        assert!(c.is("urn:b", "c"));
967        assert_eq!(c.attr("urn:b", "k"), Some("v"));
968        assert_eq!(c.string_value(), "t&u<z>");
969        assert_eq!(c.lang(), Some("en"));
970        assert_eq!(d.by_id("x").unwrap().id, c.id);
971        assert_eq!(
972            c.resolve_qname("b:q", true).unwrap(),
973            QName::new("urn:b", "q")
974        );
975        assert_eq!(
976            c.resolve_qname("q", true).unwrap(),
977            QName::new("urn:a", "q")
978        );
979        assert_eq!(a.line(), 2);
980        assert_eq!(a.descendant_elements().count(), 2);
981    }
982
983    #[test]
984    fn wellformedness_errors() {
985        assert!(parse_str("t", "<a><b></a>").is_err());
986        assert!(parse_str("t", "<a x='1' x='2'/>").is_err());
987        assert!(parse_str("t", "<p:a/>").is_err());
988        assert!(parse_str("t", "<a>&foo;</a>").is_err());
989        assert!(parse_str("t", "<a/><b/>").is_err());
990        assert!(parse_str("t", "<!DOCTYPE a [<!ENTITY foo 'bar'>]><a>&foo;</a>").is_ok());
991        // billion laughs: refused by the expansion budget instead of exhausting memory
992        let mut d = String::from("<!DOCTYPE a [<!ENTITY l0 'lollollollollollollollollollol'>");
993        for i in 1..10 {
994            let prev = format!("&l{};", i - 1);
995            d.push_str(&format!("<!ENTITY l{} '{}'>", i, prev.repeat(10)));
996        }
997        d.push_str("]><a>&l9;</a>");
998        let e = parse_str("t", &d).unwrap_err();
999        assert!(
1000            e.message.contains("entity expansion limit"),
1001            "{}",
1002            e.message
1003        );
1004    }
1005}