Skip to main content

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