Skip to main content

cim_kit/
xml.rs

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