Skip to main content

einvoice_xpath/
names.rs

1//! Qualified names, namespace resolution and the XML name character classes.
2
3use std::collections::BTreeMap;
4use std::fmt;
5
6/// The namespace of the XPath functions (`fn:`), the default function namespace.
7pub const FN_NAMESPACE: &str = "http://www.w3.org/2005/xpath-functions";
8/// The XML Schema namespace (`xs:`), home of the atomic types.
9pub const XS_NAMESPACE: &str = "http://www.w3.org/2001/XMLSchema";
10/// The namespace bound to the `xml` prefix in every XML document.
11pub const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
12
13/// A qualified name as written (`prefix:local` or `local`) together with the namespace
14/// it was resolved to when it was parsed.
15///
16/// Two names are equal when prefix, namespace and local part are all equal; use
17/// [`QName::same_expanded_name`] to compare expanded names only.
18#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct QName {
20    /// The prefix as written, if any.
21    pub prefix: Option<String>,
22    /// The namespace URI the name belongs to; `None` for a name in no namespace.
23    pub namespace: Option<String>,
24    /// The local part.
25    pub local: String,
26}
27
28impl QName {
29    /// A name in no namespace, without prefix.
30    #[must_use]
31    pub fn local(local: &str) -> Self {
32        Self {
33            prefix: None,
34            namespace: None,
35            local: local.to_owned(),
36        }
37    }
38
39    /// Whether both names have the same namespace and local part (the prefix is ignored).
40    #[must_use]
41    pub fn same_expanded_name(&self, other: &Self) -> bool {
42        self.namespace == other.namespace && self.local == other.local
43    }
44}
45
46impl fmt::Display for QName {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match &self.prefix {
49            Some(prefix) => write!(f, "{prefix}:{}", self.local),
50            None => f.write_str(&self.local),
51        }
52    }
53}
54
55/// The statically known namespaces of an expression: what its prefixes are bound to.
56///
57/// The `xml` prefix is always bound to [`XML_NAMESPACE`] by the parser and is never
58/// looked up here.
59pub trait Namespaces {
60    /// The namespace URI bound to a (non-empty) prefix, or `None` when it is not declared.
61    fn namespace_uri(&self, prefix: &str) -> Option<String>;
62
63    /// The default namespace for unprefixed element and type names (XSLT's
64    /// `xpath-default-namespace`); `None`, the default, puts them in no namespace.
65    fn default_element_namespace(&self) -> Option<String> {
66        None
67    }
68}
69
70/// A fixed set of prefix bindings.
71#[derive(Debug, Clone, Default, PartialEq, Eq)]
72pub struct NamespaceMap {
73    bindings: BTreeMap<String, String>,
74    default_element: Option<String>,
75}
76
77impl NamespaceMap {
78    /// An empty map: no prefix is bound (except `xml`, implicitly).
79    #[must_use]
80    pub fn new() -> Self {
81        Self::default()
82    }
83
84    /// Binds `prefix` to `uri`, replacing any earlier binding of the prefix.
85    #[must_use]
86    pub fn bind(mut self, prefix: &str, uri: &str) -> Self {
87        self.bindings.insert(prefix.to_owned(), uri.to_owned());
88        self
89    }
90
91    /// Sets the default namespace for unprefixed element and type names.
92    #[must_use]
93    pub fn with_default_element_namespace(mut self, uri: &str) -> Self {
94        self.default_element = Some(uri.to_owned());
95        self
96    }
97}
98
99impl Namespaces for NamespaceMap {
100    fn namespace_uri(&self, prefix: &str) -> Option<String> {
101        self.bindings.get(prefix).cloned()
102    }
103
104    fn default_element_namespace(&self) -> Option<String> {
105        self.default_element.clone()
106    }
107}
108
109/// `NameStartChar` of XML 1.0 (fifth edition) production \[4\], without `:`.
110#[must_use]
111pub fn is_name_start_char(c: char) -> bool {
112    matches!(c,
113        'A'..='Z' | '_' | 'a'..='z'
114        | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}'
115        | '\u{370}'..='\u{37D}' | '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}'
116        | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
117        | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
118}
119
120/// `NameChar` of XML 1.0 (fifth edition) production \[4a\], without `:`.
121#[must_use]
122pub fn is_name_char(c: char) -> bool {
123    is_name_start_char(c)
124        || matches!(c,
125            '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
126}
127
128/// Whether `s` is an `NCName` (a name without a colon).
129#[must_use]
130pub fn is_ncname(s: &str) -> bool {
131    let mut chars = s.chars();
132    chars.next().is_some_and(is_name_start_char) && chars.all(is_name_char)
133}
134
135/// The whitespace of XML and XPath: space, tab, carriage return and line feed.
136#[must_use]
137pub fn is_xml_whitespace(c: char) -> bool {
138    matches!(c, ' ' | '\t' | '\r' | '\n')
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn ncnames() {
147        for ok in [
148            "a",
149            "_x",
150            "a-b",
151            "a.b",
152            "schematron-get-full-path",
153            "é1",
154            "M11",
155        ] {
156            assert!(is_ncname(ok), "{ok}");
157        }
158        for bad in ["", "1a", "-a", ".a", "a:b", "a b", "*"] {
159            assert!(!is_ncname(bad), "{bad}");
160        }
161    }
162
163    #[test]
164    fn qname_display_and_expanded_equality() {
165        let a = QName {
166            prefix: Some("p".into()),
167            namespace: Some("urn:x".into()),
168            local: "n".into(),
169        };
170        let b = QName {
171            prefix: Some("q".into()),
172            ..a.clone()
173        };
174        assert_eq!(a.to_string(), "p:n");
175        assert_eq!(QName::local("n").to_string(), "n");
176        assert!(a.same_expanded_name(&b));
177        assert_ne!(a, b);
178    }
179}