Skip to main content

einvoice_validator/
detect.rs

1//! The syntax of a document, from the name of its root element: what picks the built-in
2//! rule set when none is named.
3
4use std::fmt;
5
6use crate::manifest::{CII, UBL_CREDIT_NOTE, UBL_INVOICE};
7
8/// The syntax of an e-invoice, as its root element names it.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum Syntax {
12    /// OASIS UBL 2: a root element `Invoice` or `CreditNote` in the UBL 2 namespace of
13    /// that name.
14    Ubl,
15    /// UN/CEFACT Cross Industry Invoice: a root element `CrossIndustryInvoice` in the
16    /// namespace `urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100`.
17    Cii,
18}
19
20impl Syntax {
21    /// The syntax of `document`, from its root element alone: its local name and
22    /// namespace. `None` when the document does not start like XML with one of the root
23    /// elements above (another root element, a document that is not XML, a document type
24    /// declaration before the root, an encoding other than UTF-8). Only the start of the
25    /// document is read; whether it is well-formed is for the validation to say.
26    #[must_use]
27    pub fn detect(document: &[u8]) -> Option<Self> {
28        let (local, namespace) = root_name(document)?;
29        match (local.as_str(), namespace.as_str()) {
30            ("Invoice", UBL_INVOICE) | ("CreditNote", UBL_CREDIT_NOTE) => Some(Self::Ubl),
31            ("CrossIndustryInvoice", CII) => Some(Self::Cii),
32            _ => None,
33        }
34    }
35
36    /// The name of the built-in rule set of this syntax: `cen-ubl` or `cen-cii`, the CEN
37    /// EN 16931 rules (whether this build has it is in
38    /// [`BUILTIN_RULE_SETS`](crate::BUILTIN_RULE_SETS)).
39    #[must_use]
40    pub const fn builtin_rule_set(self) -> &'static str {
41        match self {
42            Self::Ubl => "cen-ubl",
43            Self::Cii => "cen-cii",
44        }
45    }
46
47    /// `ubl` or `cii`.
48    #[must_use]
49    pub const fn as_str(self) -> &'static str {
50        match self {
51            Self::Ubl => "ubl",
52            Self::Cii => "cii",
53        }
54    }
55}
56
57impl fmt::Display for Syntax {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.write_str(self.as_str())
60    }
61}
62
63/// Whitespace in the sense of XML (`S`).
64const fn is_space(b: u8) -> bool {
65    matches!(b, b' ' | b'\t' | b'\r' | b'\n')
66}
67
68/// The local name and namespace of the root element: after an optional byte order mark,
69/// XML declaration, comments, processing instructions and whitespace, the first start
70/// tag, its name resolved with the namespace declarations of that tag (the root element
71/// has no ancestor to inherit others from).
72fn root_name(document: &[u8]) -> Option<(String, String)> {
73    let text = document.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(document);
74    let mut rest = text;
75    loop {
76        let skip = rest.iter().position(|&b| !is_space(b))?;
77        rest = &rest[skip..];
78        if let Some(after) = rest.strip_prefix(b"<?") {
79            rest = &after[find(after, b"?>")? + 2..];
80        } else if let Some(after) = rest.strip_prefix(b"<!--") {
81            rest = &after[find(after, b"-->")? + 3..];
82        } else if rest.starts_with(b"<!") {
83            // A document type declaration: refused by the validation.
84            return None;
85        } else {
86            rest = rest.strip_prefix(b"<")?;
87            break;
88        }
89    }
90    let (qname, mut rest) = name(rest)?;
91    let mut namespaces: Vec<(String, String)> = Vec::new();
92    loop {
93        let skip = rest.iter().position(|&b| !is_space(b))?;
94        let spaced = skip > 0;
95        rest = &rest[skip..];
96        if rest.starts_with(b">") || rest.starts_with(b"/>") {
97            break;
98        }
99        if !spaced {
100            return None;
101        }
102        let (attribute, after) = name(rest)?;
103        let after = trim_start(after).strip_prefix(b"=")?;
104        let after = trim_start(after);
105        let quote = *after.first().filter(|q| matches!(q, b'"' | b'\''))?;
106        let after = &after[1..];
107        let end = after.iter().position(|&b| b == quote)?;
108        let value = std::str::from_utf8(&after[..end]).ok()?;
109        rest = &after[end + 1..];
110        // A value with a reference would need decoding: not one of the namespaces above.
111        if value.contains(['&', '<']) {
112            continue;
113        }
114        if attribute == "xmlns" {
115            namespaces.push((String::new(), value.to_owned()));
116        } else if let Some(prefix) = attribute.strip_prefix("xmlns:") {
117            namespaces.push((prefix.to_owned(), value.to_owned()));
118        }
119    }
120    let (prefix, local) = qname.split_once(':').unwrap_or(("", &qname));
121    let namespace = namespaces
122        .iter()
123        .rev()
124        .find(|(p, _)| p == prefix)
125        .map(|(_, uri)| uri.clone())
126        .unwrap_or_default();
127    Some((local.to_owned(), namespace))
128}
129
130fn trim_start(bytes: &[u8]) -> &[u8] {
131    let skip = bytes
132        .iter()
133        .position(|&b| !is_space(b))
134        .unwrap_or(bytes.len());
135    &bytes[skip..]
136}
137
138fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
139    haystack.windows(needle.len()).position(|w| w == needle)
140}
141
142/// A name at the start of `bytes` (up to whitespace, `=`, `>` or `/`), and what follows.
143fn name(bytes: &[u8]) -> Option<(String, &[u8])> {
144    let end = bytes
145        .iter()
146        .position(|&b| is_space(b) || matches!(b, b'=' | b'>' | b'/'))
147        .unwrap_or(bytes.len());
148    if end == 0 {
149        return None;
150    }
151    let text = std::str::from_utf8(&bytes[..end]).ok()?;
152    Some((text.to_owned(), &bytes[end..]))
153}
154
155#[cfg(test)]
156mod tests {
157    use super::Syntax;
158
159    fn detect(text: &str) -> Option<Syntax> {
160        Syntax::detect(text.as_bytes())
161    }
162
163    #[test]
164    fn root_elements() {
165        assert_eq!(
166            detect(r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#),
167            Some(Syntax::Ubl)
168        );
169        assert_eq!(
170            detect(
171                "\u{feff}<?xml version='1.0'?>\n<!-- c --><?pi x?>\n<ubl:CreditNote a='1' xmlns:ubl='urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2'>"
172            ),
173            Some(Syntax::Ubl)
174        );
175        assert_eq!(
176            detect(
177                r#"<rsm:CrossIndustryInvoice xmlns:a="x" xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"><x/></rsm:CrossIndustryInvoice>"#
178            ),
179            Some(Syntax::Cii)
180        );
181        assert_eq!(
182            detect(
183                "<CrossIndustryInvoice\n xmlns = \"urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100\" >"
184            ),
185            Some(Syntax::Cii)
186        );
187    }
188
189    #[test]
190    fn anything_else() {
191        for text in [
192            "",
193            "   ",
194            "not xml",
195            "<Invoice/>",
196            r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"/>"#,
197            r#"<CreditNote xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
198            r#"<x:Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
199            r#"<rsm:CrossIndustryInvoice xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:13"/>"#,
200            r#"<!DOCTYPE Invoice><Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
201            r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2&#x31;"/>"#,
202            r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"x="1"/>"#,
203            "<!-- unterminated",
204            "<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
205        ] {
206            assert_eq!(detect(text), None, "{text}");
207        }
208    }
209
210    #[test]
211    fn rule_set_names() {
212        assert_eq!(Syntax::Ubl.builtin_rule_set(), "cen-ubl");
213        assert_eq!(Syntax::Cii.builtin_rule_set(), "cen-cii");
214        assert_eq!(Syntax::Cii.to_string(), "cii");
215    }
216}