Skip to main content

cim_kit/
xml.rs

1//! What XML and RDF/XML can actually represent.
2//!
3//! Two constraints of the output syntax the object model cannot express:
4//!
5//! **Not every character can appear in an XML document.** A character outside XML 1.0's
6//! `Char` production (NUL, most of the C0 range) has *no* representation, not even as a
7//! character reference, and `quick-xml` checks this in neither direction.
8//!
9//! **`rdf:ID` is an XML `NCName`.** `_` plus a UUID always is one, but a non-conforming
10//! identifier kept verbatim may not be: `rdf:ID="_http://host/EQ.xml#Sub1"` is well-formed
11//! XML and invalid RDF/XML. The writer asks [`identifier_form`] which serialization fits.
12
13/// Whether `c` is in XML 1.0's `Char` production.
14///
15/// Rust's `char` cannot hold a surrogate, so that range needs no test.
16#[inline]
17pub const fn is_xml_char(c: char) -> bool {
18    matches!(c, '\u{9}' | '\u{A}' | '\u{D}'
19        | '\u{20}'..='\u{D7FF}'
20        | '\u{E000}'..='\u{FFFD}'
21        | '\u{10000}'..='\u{10FFFF}')
22}
23
24/// The first character of `s` that XML 1.0 cannot represent, with its byte offset.
25///
26/// Hot path, so a byte pre-scan comes first: every illegal character is a C0 control other
27/// than tab, LF and CR, or `U+FFFE`/`U+FFFF` (UTF-8 `EF BF ..`).
28pub fn find_illegal(s: &str) -> Option<(usize, char)> {
29    if !s
30        .bytes()
31        .any(|b| (b < 0x20 && !matches!(b, b'\t' | b'\n' | b'\r')) || b == 0xEF)
32    {
33        return None;
34    }
35    s.char_indices().find(|&(_, c)| !is_xml_char(c))
36}
37
38/// Whether `s` contains a character XML 1.0 cannot represent.
39#[inline]
40pub fn has_illegal(s: &str) -> bool {
41    find_illegal(s).is_some()
42}
43
44/// `s` with every character XML cannot represent removed.
45///
46/// Borrows when there is nothing to remove. The loss is reported as
47/// [`Rule::IllegalXmlCharacter`](crate::Rule::IllegalXmlCharacter) by the reader and by
48/// [`validate`](mod@crate::validate).
49pub fn strip_illegal(s: &str) -> std::borrow::Cow<'_, str> {
50    match has_illegal(s) {
51        false => std::borrow::Cow::Borrowed(s),
52        true => std::borrow::Cow::Owned(s.chars().filter(|&c| is_xml_char(c)).collect()),
53    }
54}
55
56/// Render a character the way a diagnostic should name it.
57///
58/// The character itself must not go into the message: a diagnostic is printed, logged and
59/// put in a CI annotation, and embedding a control character in it spreads the problem
60/// rather than describing it.
61pub fn describe_char(c: char) -> String {
62    format!("U+{:04X}", c as u32)
63}
64
65// ---------------------------------------------------------------------------
66// Identifiers
67// ---------------------------------------------------------------------------
68
69/// Whether `s` is an XML `NCName` — a `Name` with no colon.
70///
71/// This is what `rdf:ID` requires. The character classes are XML 1.0's `NameStartChar` and
72/// `NameChar` minus `:`.
73pub fn is_ncname(s: &str) -> bool {
74    let mut chars = s.chars();
75    chars.next().is_some_and(is_name_start_char) && chars.all(is_name_char)
76}
77
78/// XML 1.0's `NameStartChar`, minus `:`.
79const fn is_name_start_char(c: char) -> bool {
80    matches!(c, 'A'..='Z' | 'a'..='z' | '_'
81        | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}'
82        | '\u{370}'..='\u{37D}' | '\u{37F}'..='\u{1FFF}'
83        | '\u{200C}'..='\u{200D}' | '\u{2070}'..='\u{218F}'
84        | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
85        | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}'
86        | '\u{10000}'..='\u{EFFFF}')
87}
88
89/// XML 1.0's `NameChar`, minus `:`.
90const fn is_name_char(c: char) -> bool {
91    is_name_start_char(c)
92        || matches!(c, '-' | '.' | '0'..='9' | '\u{B7}'
93            | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
94}
95
96/// Whether `s` is an absolute IRI: a scheme, a colon, and something after it.
97///
98/// Deliberately a shape test rather than a parse. It answers one question — may this be
99/// written into `rdf:about` unchanged — and for that the scheme grammar of RFC 3987 plus
100/// the absence of characters an IRI reference forbids is exactly the condition.
101pub fn is_absolute_iri(s: &str) -> bool {
102    let Some((scheme, rest)) = s.split_once(':') else {
103        return false;
104    };
105    let scheme_ok = !scheme.is_empty()
106        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
107        && scheme
108            .chars()
109            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
110    // One fragment at most, and none of the characters an IRI reference may not hold.
111    scheme_ok
112        && !rest.is_empty()
113        && s.matches('#').count() <= 1
114        && !s.chars().any(|c| {
115            (c as u32) <= 0x20
116                || matches!(c, '<' | '>' | '"' | '{' | '}' | '|' | '\\' | '^' | '`')
117                || !is_xml_char(c)
118        })
119}
120
121/// How an identifier can be written into a CIM/XML document.
122///
123/// Every UUID answers [`IdentifierForm::Name`]; the other forms exist for non-conforming
124/// identifiers kept verbatim (see `Mrid`).
125#[derive(Clone, Copy, PartialEq, Eq, Debug)]
126pub enum IdentifierForm {
127    /// `_<id>` is an `NCName`, so `rdf:ID`/`rdf:about="#_<id>"` are both available.
128    Name,
129    /// Not a name, but an absolute IRI, so `rdf:about="<id>"` states it exactly.
130    ///
131    /// This is the realistic non-conforming case: a producer writes a cross-document
132    /// reference as `rdf:about="http://host/EQ.xml#Sub1"`, whose fragment is not a UUID, so
133    /// the identifier stays opaque in one piece and cannot become an `NCName`.
134    Iri,
135    /// Neither. No conforming RDF/XML serialization of this identifier exists.
136    ///
137    /// The writer still emits the identifier — losing the object would be worse, and the
138    /// document remains well-formed XML — but the result is not valid RDF/XML, and
139    /// [`validate`](mod@crate::validate) says so as
140    /// [`Rule::UnserializableIdentifier`](crate::Rule::UnserializableIdentifier).
141    Unwritable,
142}
143
144/// Which serializations `id` — an identifier stripped of CIM/XML decoration — can carry.
145pub fn identifier_form(id: &str) -> IdentifierForm {
146    // `rdf:ID` carries the identifier under a leading underscore, which is what makes a
147    // UUID a name at all: `NCName` may not begin with a digit.
148    if !id.is_empty() && !id.contains(':') && is_ncname_tail(id) {
149        return IdentifierForm::Name;
150    }
151    if is_absolute_iri(id) {
152        return IdentifierForm::Iri;
153    }
154    IdentifierForm::Unwritable
155}
156
157/// Whether every character of `s` may follow the `_` that `rdf:ID` prefixes.
158///
159/// `_` is itself a `NameStartChar`, so only the tail is in question and the prefixed string
160/// need not be built.
161fn is_ncname_tail(s: &str) -> bool {
162    s.chars().all(is_name_char)
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn the_char_production_admits_text_and_refuses_the_c0_range() {
171        for legal in [
172            '\t', '\n', '\r', ' ', 'a', 'é', '\u{D7FF}', '\u{E000}', '🙂',
173        ] {
174            assert!(is_xml_char(legal), "{legal:?}");
175        }
176        for illegal in ['\u{0}', '\u{1}', '\u{8}', '\u{B}', '\u{C}', '\u{1F}'] {
177            assert!(!is_xml_char(illegal), "{illegal:?}");
178        }
179        // The two non-characters at the end of the BMP are excluded too.
180        assert!(!is_xml_char('\u{FFFE}'));
181        assert!(!is_xml_char('\u{FFFF}'));
182        assert!(is_xml_char('\u{FFFD}'));
183    }
184
185    #[test]
186    fn illegal_characters_are_found_at_their_byte_offset() {
187        assert_eq!(find_illegal("plain text"), None);
188        // Tab, newline and carriage return are legal and must not trip the fast path.
189        assert_eq!(find_illegal("a\tb\nc\rd"), None);
190        // Nor must ordinary non-ASCII, whose lead bytes include the one the scan watches.
191        assert_eq!(find_illegal("naïve ïnput ff"), None);
192        assert_eq!(find_illegal("ab\u{0}c"), Some((2, '\u{0}')));
193        // The offset is a byte offset, so it counts the multi-byte character before it.
194        assert_eq!(find_illegal("é\u{1}"), Some((2, '\u{1}')));
195        assert_eq!(find_illegal("x\u{FFFF}"), Some((1, '\u{FFFF}')));
196    }
197
198    #[test]
199    fn stripping_removes_only_what_cannot_be_written_and_borrows_otherwise() {
200        assert!(matches!(
201            strip_illegal("clean"),
202            std::borrow::Cow::Borrowed("clean")
203        ));
204        assert_eq!(strip_illegal("bad\u{0}\u{8}name"), "badname");
205        assert_eq!(
206            strip_illegal("keep\ttabs\nand\rreturns"),
207            "keep\ttabs\nand\rreturns"
208        );
209    }
210
211    #[test]
212    fn ncname_follows_the_xml_names_recommendation() {
213        for ok in ["_abc", "a", "A-1.2", "_1fa19c28-1c8f-4e1e", "é"] {
214            assert!(is_ncname(ok), "{ok}");
215        }
216        for bad in ["", "1abc", "-abc", "a:b", "a b", "a/b", "a#b", ".abc"] {
217            assert!(!is_ncname(bad), "{bad}");
218        }
219    }
220
221    #[test]
222    fn absolute_iris_are_recognised_without_being_parsed() {
223        for ok in [
224            "http://host/EQ.xml#Sub1",
225            "urn:uuid:70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
226            "file:///models/EQ.xml#x",
227        ] {
228            assert!(is_absolute_iri(ok), "{ok}");
229        }
230        for bad in [
231            "Substation1",    // no scheme
232            "1http://x",      // scheme may not start with a digit
233            "http://a b",     // space
234            "http://a#b#c",   // two fragments
235            "http://a\u{0}b", // unrepresentable character
236            ":no-scheme",
237        ] {
238            assert!(!is_absolute_iri(bad), "{bad}");
239        }
240    }
241
242    /// The classification the writer acts on, over the identifier shapes real files carry.
243    #[test]
244    fn identifiers_are_classified_by_what_can_be_written() {
245        // A UUID, in either spelling, is always a name once `rdf:ID`'s underscore is added.
246        for uuid in [
247            "70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
248            "1fa19c281c8f4e1eaad9e1cab70f923e",
249        ] {
250            assert_eq!(identifier_form(uuid), IdentifierForm::Name, "{uuid}");
251        }
252        // Ordinary opaque identifiers are names too, which is why this was never noticed.
253        // A leading digit is fine for the same reason a UUID is: `rdf:ID` writes the
254        // underscore, and `NCName` only forbids a digit in the *first* position.
255        for name in ["Substation1", "BE-Line_1", "a.b-c", "1leading-digit"] {
256            assert_eq!(identifier_form(name), IdentifierForm::Name, "{name}");
257        }
258        // A cross-document reference whose fragment is not a UUID: not a name, but an IRI.
259        assert_eq!(
260            identifier_form("http://host/EQ.xml#Sub1"),
261            IdentifierForm::Iri
262        );
263        // A colon alone disqualifies a name, since `NCName` is `Name` without one.
264        assert_eq!(identifier_form("a:b"), IdentifierForm::Iri);
265        // And what is neither is admitted to be neither, rather than written as a name.
266        for bad in ["has space", "a#b#c", "", "a/b"] {
267            assert_eq!(identifier_form(bad), IdentifierForm::Unwritable, "{bad}");
268        }
269    }
270}