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