cim_kit/error.rs
1//! Errors and structured diagnostics.
2
3use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7/// A hard failure: the operation could not be completed.
8///
9/// Problems that leave the data usable — an unknown class, an unresolved reference in
10/// lenient mode — are reported as [`Diagnostic`]s instead, so that reading a
11/// non-conforming file still yields a model plus a precise report.
12///
13/// `#[non_exhaustive]`: a new CIM vintage or a new input syntax is a regeneration away, and
14/// a variant added for one should not be a breaking change for everyone. Match with a
15/// wildcard arm.
16#[derive(Debug)]
17#[non_exhaustive]
18pub enum Error {
19 Io(std::io::Error),
20 /// The document is not well-formed XML.
21 Xml(String),
22 /// The document is well-formed XML but not a CIM/XML document.
23 NotCimXml(String),
24 /// A reference could not be resolved and the link policy is strict.
25 DanglingReference {
26 object: String,
27 attribute: &'static str,
28 target: String,
29 /// Total number of unresolved references found.
30 total: usize,
31 },
32 /// Two models built from different CIM vintages cannot be combined.
33 ///
34 /// Class and attribute identifiers are indices into one vintage's tables, so the same
35 /// number means different things in two of them. Combining the models regardless would
36 /// not fail loudly — it would silently file `ACLineSegment.r` under whatever the other
37 /// vintage happens to put at that index.
38 SchemaMismatch {
39 left: &'static str,
40 right: &'static str,
41 },
42 /// No file under the given path declares a CIM vocabulary this build recognises.
43 ///
44 /// Either the input is not CIM/XML, or it is a vintage this build has no feature for.
45 UnknownVintage {
46 path: String,
47 /// The vintages that *are* compiled in.
48 known: Vec<&'static str>,
49 },
50 /// A zip archive could not be read.
51 #[cfg(feature = "zip")]
52 Zip(String),
53 /// The input exceeded [`ReadOptions::max_input_bytes`](crate::reader::ReadOptions::max_input_bytes).
54 ///
55 /// The budget covers one load call — every file and every decompressed archive entry
56 /// of it — so a small archive that inflates without bound stops here rather than at
57 /// the host's memory limit. Unlike a damaged file this is never downgraded to a
58 /// diagnostic by lenient reading: the model is incomplete, and a load that returned it
59 /// would look like a success. Discard the dataset.
60 InputTooLarge {
61 /// The budget in force, in bytes.
62 limit: u64,
63 /// Bytes accepted, across the whole load call, when the budget was exceeded.
64 read: u64,
65 /// The document being read: a file name or an archive entry.
66 source: Option<String>,
67 },
68}
69
70impl fmt::Display for Error {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 match self {
73 Error::Io(e) => write!(f, "i/o error: {e}"),
74 Error::Xml(m) => write!(f, "malformed XML: {m}"),
75 Error::NotCimXml(m) => write!(f, "not a CIM/XML document: {m}"),
76 Error::DanglingReference {
77 object,
78 attribute,
79 target,
80 total,
81 } => write!(
82 f,
83 "unresolved reference {object}.{attribute} -> {target} \
84 ({total} unresolved in total); load the missing profile or \
85 use LinkPolicy::Lenient"
86 ),
87 Error::SchemaMismatch { left, right } => write!(
88 f,
89 "cannot combine a {left} model with a {right} one: class and attribute \
90 identifiers belong to one vintage's tables"
91 ),
92 Error::UnknownVintage { path, known } => write!(
93 f,
94 "no CIM vintage recognised in {path}: not a CIM/XML input, or a vocabulary \
95 this build has no feature for (it has {known:?})"
96 ),
97 #[cfg(feature = "zip")]
98 Error::Zip(m) => write!(f, "zip archive error: {m}"),
99 Error::InputTooLarge {
100 limit,
101 read,
102 source,
103 } => {
104 write!(
105 f,
106 "input exceeds the {} input budget after reading {}",
107 human_bytes(*limit),
108 human_bytes(*read)
109 )?;
110 if let Some(source) = source {
111 write!(f, " (while reading {source})")?;
112 }
113 write!(
114 f,
115 "; raise it with ReadOptions::with_max_input_bytes, or pass 0 for no limit"
116 )
117 }
118 }
119 }
120}
121
122/// A byte count the way a person reads one: `2 GiB`, `512 KiB`, `17 B`.
123///
124/// Exact multiples print as integers and everything else to one decimal, so a budget
125/// someone set reads back the way they wrote it.
126pub(crate) fn human_bytes(n: u64) -> String {
127 const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
128 let mut unit = 0;
129 let mut value = n;
130 while unit + 1 < UNITS.len() && value >= 1024 && value.is_multiple_of(1024) {
131 value /= 1024;
132 unit += 1;
133 }
134 if unit > 0 || n < 1024 {
135 return format!("{value} {}", UNITS[unit]);
136 }
137 #[allow(clippy::cast_precision_loss)] // one decimal of a human-facing figure
138 let mut f = n as f64;
139 let mut unit = 0;
140 while unit + 1 < UNITS.len() && f >= 1024.0 {
141 f /= 1024.0;
142 unit += 1;
143 }
144 format!("{f:.1} {}", UNITS[unit])
145}
146
147impl std::error::Error for Error {
148 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
149 match self {
150 Error::Io(e) => Some(e),
151 _ => None,
152 }
153 }
154}
155
156impl From<std::io::Error> for Error {
157 fn from(e: std::io::Error) -> Error {
158 Error::Io(e)
159 }
160}
161
162impl From<quick_xml::Error> for Error {
163 fn from(e: quick_xml::Error) -> Error {
164 Error::Xml(e.to_string())
165 }
166}
167
168impl From<quick_xml::events::attributes::AttrError> for Error {
169 fn from(e: quick_xml::events::attributes::AttrError) -> Error {
170 Error::Xml(e.to_string())
171 }
172}
173
174/// How much a diagnostic matters.
175#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
176pub enum Severity {
177 /// Violates the standard; the model is not conforming.
178 Error,
179 /// Legal but suspect, or a tolerated deviation.
180 Warning,
181 /// Informational, e.g. a deprecated attribute in use.
182 Info,
183}
184
185impl fmt::Display for Severity {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 f.write_str(match self {
188 Severity::Error => "error",
189 Severity::Warning => "warning",
190 Severity::Info => "info",
191 })
192 }
193}
194
195/// A stable identifier for the rule that produced a diagnostic.
196///
197/// Rule codes let a pipeline filter, suppress or fail on specific classes of problem
198/// without matching message text.
199///
200/// The variants, their codes and [`Rule::ALL`] are one list rather than three. They used
201/// to be three, and the third was hand-maintained: a rule added to the enum and given a
202/// code was simply missing from the catalogue tooling enumerates, and the only test on it
203/// checked that the codes it *did* contain were distinct. One declaration cannot drift
204/// from itself.
205macro_rules! rules {
206 ($($(#[$doc:meta])* $name:ident => $code:literal,)*) => {
207 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
208 pub enum Rule {
209 $($(#[$doc])* $name,)*
210 }
211
212 impl Rule {
213 /// Short stable code, e.g. `CIM0007`, suitable for CI filters.
214 pub const fn code(self) -> &'static str {
215 match self {
216 $(Rule::$name => $code,)*
217 }
218 }
219
220 /// Every rule, so tooling can enumerate the catalogue.
221 pub const ALL: &'static [Rule] = &[$(Rule::$name,)*];
222 }
223 };
224}
225
226rules! {
227 /// An element names a class the schema does not define.
228 UnknownClass => "CIM0001",
229 /// An element names an attribute the schema does not define for its class.
230 UnknownAttribute => "CIM0002",
231 /// An attribute value could not be parsed as its declared type.
232 InvalidValue => "CIM0003",
233 /// An identifier is not a UUID, as IEC 61970-552 requires.
234 NonConformingMrid => "CIM0004",
235 /// Two objects share an mRID.
236 DuplicateMrid => "CIM0005",
237 /// A reference points at an object not present in the dataset.
238 DanglingReference => "CIM0006",
239 /// A required attribute is missing.
240 MissingRequired => "CIM0007",
241 /// An attribute occurs more often than its multiplicity permits.
242 CardinalityExceeded => "CIM0008",
243 /// A reference points at an object of the wrong class.
244 WrongReferenceTarget => "CIM0009",
245 /// An attribute is used outside the profiles that declare it.
246 AttributeNotInProfile => "CIM0010",
247 /// An abstract class was instantiated.
248 AbstractInstantiated => "CIM0011",
249 /// A deprecated element is in use.
250 Deprecated => "CIM0012",
251 /// The file header is missing or incomplete.
252 MalformedHeader => "CIM0013",
253 /// A header declares a dependency that was not loaded; or a change set's base or
254 /// precondition is not satisfied, and it was not applied.
255 UnsatisfiedDependency => "CIM0014",
256 /// A structural problem in the document that did not prevent reading.
257 Structure => "CIM0015",
258 /// A stored value does not have the shape its attribute declares.
259 ///
260 /// CIM/XML carries no datatype information — IEC 61970-552 leaves it to the RDFS —
261 /// so a value read as text from an element the schema types as a float, or an
262 /// enumeration literal belonging to a different enumeration, is only detectable
263 /// against the schema.
264 DatatypeMismatch => "CIM0016",
265 /// An attribute the schema pins with `cims:isFixed` carries a different value.
266 FixedValueMismatch => "CIM0017",
267 /// Two loaded files gave different values for one single-valued attribute.
268 ///
269 /// Merging by mRID assembles a model from files that each describe part of it. Where
270 /// two of them disagree, one value has to be discarded — so the disagreement is
271 /// reported rather than resolved silently.
272 ConflictingValue => "CIM0018",
273 /// A value holds a character XML 1.0 cannot represent.
274 ///
275 /// Not a matter of escaping: XML's `Char` production excludes most of the C0 range,
276 /// and forbids a numeric character reference to it as well, so there is no way to
277 /// write such a character at all. A document containing one is rejected by every
278 /// conforming parser at the offending byte. `quick-xml` does not enforce the
279 /// production, so nothing else catches one arriving from a mis-encoded or corrupted
280 /// source file. The reader strips the character and reports it; this rule also fires
281 /// for a value put in through the public API.
282 IllegalXmlCharacter => "CIM0019",
283 /// A file in the model set could not be read at all.
284 ///
285 /// A model set is several files, and one of them being unreadable — not XML, truncated
286 /// mid-entity, an archive that will not open — says nothing about the others. Under
287 /// [`Strictness::Lenient`](crate::reader::Strictness::Lenient) the load records this
288 /// and carries on, so a report covers the whole set and names the file that failed;
289 /// under `Strict` the same condition is an [`Error`].
290 UnreadableFile => "CIM0022",
291 /// The document is written against a different schema vintage than the one reading it.
292 ///
293 /// CIM/XML declares its vocabulary — `…/CIM100#` for CGMES 3.0, `…/CIM-schema-cim16#`
294 /// for 2.4.15 — so this is knowable from the root element. Without it a vintage mismatch
295 /// surfaces only as one `CIM0001` per element and a model with nothing in it.
296 WrongVintage => "CIM0021",
297 /// An identifier has no valid RDF/XML serialization.
298 ///
299 /// `rdf:ID` is an XML `NCName` and `rdf:about` is an IRI reference. Every UUID
300 /// satisfies the first, so this cannot fire on conforming input; an identifier that is
301 /// neither a name nor an IRI — one containing a space, say — is written anyway,
302 /// because losing the object would be worse, but the document is not valid RDF/XML and
303 /// a general RDF toolchain will refuse it. Well-formedness checking cannot see this:
304 /// the document *is* well-formed XML.
305 UnserializableIdentifier => "CIM0020",
306}
307
308impl fmt::Display for Rule {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 f.write_str(self.code())
311 }
312}
313
314/// A structured finding, usable by CI and tooling rather than only printable.
315///
316/// The object and attribute fields hold the identifier and the schema's own name rather
317/// than rendered text: a caller that wants to look the object up, group findings by it or
318/// re-serialize it should not have to parse a diagnostic message back into data, and
319/// rendering a UUID costs an allocation on a path that fires once per finding.
320#[derive(Clone, Debug)]
321pub struct Diagnostic {
322 pub severity: Severity,
323 pub rule: Rule,
324 /// Identifier of the object concerned, when the finding is object-scoped.
325 pub object: Option<crate::mrid::Mrid>,
326 /// Class name of that object.
327 pub class: Option<&'static str>,
328 /// Qualified attribute name, when the finding is attribute-scoped.
329 pub attribute: Option<&'static str>,
330 /// Source file the finding came from.
331 pub source: Option<String>,
332 /// Byte offset in the source document, when the finding came from parsing.
333 ///
334 /// A byte offset rather than a line number, because the reader is streaming: it never
335 /// holds the document, so it cannot count lines without either buffering it or
336 /// carrying an index proportional to its size. An offset is exact, free to record and
337 /// what an editor or a `dd`-style seek wants anyway; [`line_and_column`] converts one
338 /// when a human needs to read it.
339 pub position: Option<u64>,
340 pub message: String,
341}
342
343/// Convert a byte offset in `source` to a 1-based line and column.
344///
345/// Pairs with [`Diagnostic::position`], which the streaming reader records instead of a
346/// line number. Reads `source` up to `position` only.
347pub fn line_and_column(source: &str, position: u64) -> (u64, u64) {
348 let upto = &source.as_bytes()[..(position as usize).min(source.len())];
349 let line = upto.iter().filter(|&&b| b == b'\n').count() as u64 + 1;
350 let col = match upto.iter().rposition(|&b| b == b'\n') {
351 Some(i) => (upto.len() - i) as u64,
352 None => upto.len() as u64 + 1,
353 };
354 (line, col)
355}
356
357impl Diagnostic {
358 pub fn new(severity: Severity, rule: Rule, message: impl Into<String>) -> Diagnostic {
359 Diagnostic {
360 severity,
361 rule,
362 object: None,
363 class: None,
364 attribute: None,
365 source: None,
366 position: None,
367 message: message.into(),
368 }
369 }
370
371 pub fn error(rule: Rule, message: impl Into<String>) -> Diagnostic {
372 Diagnostic::new(Severity::Error, rule, message)
373 }
374 pub fn warning(rule: Rule, message: impl Into<String>) -> Diagnostic {
375 Diagnostic::new(Severity::Warning, rule, message)
376 }
377 pub fn info(rule: Rule, message: impl Into<String>) -> Diagnostic {
378 Diagnostic::new(Severity::Info, rule, message)
379 }
380
381 pub fn with_object(mut self, mrid: impl Into<crate::mrid::Mrid>) -> Diagnostic {
382 self.object = Some(mrid.into());
383 self
384 }
385 pub fn with_class(mut self, class: &'static str) -> Diagnostic {
386 self.class = Some(class);
387 self
388 }
389 pub fn with_attribute(mut self, attr: &'static str) -> Diagnostic {
390 self.attribute = Some(attr);
391 self
392 }
393 pub fn with_source(mut self, source: impl Into<String>) -> Diagnostic {
394 self.source = Some(source.into());
395 self
396 }
397 /// Record the byte offset in the source document the finding came from.
398 pub fn with_position(mut self, position: u64) -> Diagnostic {
399 self.position = Some(position);
400 self
401 }
402}
403
404impl fmt::Display for Diagnostic {
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 write!(f, "{}[{}]", self.severity, self.rule.code())?;
407 if let Some(src) = &self.source {
408 write!(f, " {src}")?;
409 if let Some(pos) = self.position {
410 // `@` rather than `:` so the number is not mistaken for a line.
411 write!(f, "@{pos}")?;
412 }
413 }
414 write!(f, ": {}", self.message)?;
415 if let Some(class) = self.class {
416 write!(f, " [{class}")?;
417 match &self.object {
418 Some(o) => write!(f, " {o}]")?,
419 None => write!(f, "]")?,
420 }
421 } else if let Some(o) = &self.object {
422 write!(f, " [{o}]")?;
423 }
424 Ok(())
425 }
426}
427
428/// A collection of diagnostics with convenience queries.
429#[derive(Clone, Debug, Default)]
430pub struct Report {
431 pub diagnostics: Vec<Diagnostic>,
432}
433
434impl Report {
435 pub fn push(&mut self, d: Diagnostic) {
436 self.diagnostics.push(d);
437 }
438
439 pub fn extend(&mut self, other: Report) {
440 self.diagnostics.extend(other.diagnostics);
441 }
442
443 pub fn is_empty(&self) -> bool {
444 self.diagnostics.is_empty()
445 }
446
447 pub fn len(&self) -> usize {
448 self.diagnostics.len()
449 }
450
451 pub fn count(&self, severity: Severity) -> usize {
452 self.diagnostics
453 .iter()
454 .filter(|d| d.severity == severity)
455 .count()
456 }
457
458 /// Whether any diagnostic is an error, i.e. the model is non-conforming.
459 pub fn has_errors(&self) -> bool {
460 self.diagnostics
461 .iter()
462 .any(|d| d.severity == Severity::Error)
463 }
464
465 pub fn iter(&self) -> std::slice::Iter<'_, Diagnostic> {
466 self.diagnostics.iter()
467 }
468
469 pub fn by_rule(&self, rule: Rule) -> impl Iterator<Item = &Diagnostic> {
470 self.diagnostics.iter().filter(move |d| d.rule == rule)
471 }
472
473 /// Number of findings per rule, most frequent first — a useful CI summary.
474 pub fn summary(&self) -> Vec<(Rule, usize)> {
475 let mut counts: Vec<(Rule, usize)> = Vec::new();
476 for d in &self.diagnostics {
477 match counts.iter_mut().find(|(r, _)| *r == d.rule) {
478 Some((_, n)) => *n += 1,
479 None => counts.push((d.rule, 1)),
480 }
481 }
482 counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
483 counts
484 }
485}
486
487impl IntoIterator for Report {
488 type Item = Diagnostic;
489 type IntoIter = std::vec::IntoIter<Diagnostic>;
490 fn into_iter(self) -> Self::IntoIter {
491 self.diagnostics.into_iter()
492 }
493}
494
495impl fmt::Display for Report {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 for d in &self.diagnostics {
498 writeln!(f, "{d}")?;
499 }
500 Ok(())
501 }
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507
508 #[test]
509 fn byte_counts_read_the_way_a_budget_was_written() {
510 assert_eq!(human_bytes(2 << 30), "2 GiB");
511 assert_eq!(human_bytes(512 << 10), "512 KiB");
512 assert_eq!(human_bytes(17), "17 B");
513 assert_eq!(human_bytes((1 << 20) + 1), "1.0 MiB");
514 assert_eq!(human_bytes(1536 << 20), "1536 MiB");
515 }
516
517 #[test]
518 fn rule_codes_are_unique() {
519 let mut codes: Vec<&str> = Rule::ALL.iter().map(|r| r.code()).collect();
520 codes.sort_unstable();
521 let n = codes.len();
522 codes.dedup();
523 assert_eq!(codes.len(), n, "duplicate rule codes");
524
525 // Contiguous from CIM0001, because the codes are a published catalogue and a hole
526 // in it means a rule was removed and every citation after it now means something
527 // else — the same reasoning the `concepts/` registers are held to.
528 let expected: Vec<String> = (1..=n).map(|i| format!("CIM{i:04}")).collect();
529 assert_eq!(
530 codes, expected,
531 "the rule codes are not contiguous from CIM0001"
532 );
533 }
534
535 #[test]
536 fn byte_offsets_convert_to_lines_and_columns() {
537 let src = "one\ntwo\nthree";
538 assert_eq!(line_and_column(src, 0), (1, 1));
539 assert_eq!(line_and_column(src, 4), (2, 1));
540 assert_eq!(line_and_column(src, 6), (2, 3));
541 // Past the end clamps rather than panicking.
542 assert_eq!(line_and_column(src, 9_999).0, 3);
543 }
544
545 #[test]
546 fn report_summarizes_by_rule() {
547 let mut r = Report::default();
548 r.push(Diagnostic::error(Rule::MissingRequired, "a"));
549 r.push(Diagnostic::error(Rule::MissingRequired, "b"));
550 r.push(Diagnostic::warning(Rule::Deprecated, "c"));
551 assert!(r.has_errors());
552 assert_eq!(r.count(Severity::Error), 2);
553 assert_eq!(
554 r.summary(),
555 vec![(Rule::MissingRequired, 2), (Rule::Deprecated, 1)]
556 );
557 }
558
559 #[test]
560 fn diagnostic_display_includes_location_and_code() {
561 let d = Diagnostic::error(Rule::MissingRequired, "missing name")
562 .with_class("ACLineSegment")
563 .with_object("abc")
564 .with_source("EQ.xml")
565 .with_position(1234);
566 let s = d.to_string();
567 assert!(s.contains("error[CIM0007]"), "{s}");
568 assert!(s.contains("EQ.xml@1234"), "{s}");
569 assert!(s.contains("[ACLineSegment abc]"), "{s}");
570 }
571}