cim-kit 0.4.1

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Errors and structured diagnostics.

use std::fmt;

pub type Result<T> = std::result::Result<T, Error>;

/// A hard failure: the operation could not be completed.
///
/// Problems that leave the data usable (an unknown class, an unresolved reference in
/// lenient mode) are [`Diagnostic`]s instead.
///
/// `#[non_exhaustive]`: match with a wildcard arm.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    Io(std::io::Error),
    /// The document is not well-formed XML.
    Xml(String),
    /// The document is well-formed XML but not a CIM/XML document.
    NotCimXml(String),
    /// A reference could not be resolved and the link policy is strict.
    DanglingReference {
        object: String,
        attribute: &'static str,
        target: String,
        /// Total number of unresolved references found.
        total: usize,
    },
    /// Two models built from different CIM vintages cannot be combined.
    ///
    /// Class and attribute identifiers index one vintage's tables and mean something else
    /// in another.
    SchemaMismatch {
        left: &'static str,
        right: &'static str,
    },
    /// No file under the given path declares a CIM vocabulary this build recognises.
    ///
    /// Either the input is not CIM/XML, or it is a vintage this build has no feature for.
    UnknownVintage {
        path: String,
        /// The vintages that *are* compiled in.
        known: Vec<&'static str>,
    },
    /// A zip archive could not be read.
    #[cfg(feature = "zip")]
    Zip(String),
    /// The input exceeded [`ReadOptions::max_input_bytes`](crate::reader::ReadOptions::max_input_bytes).
    ///
    /// The budget covers one load call, every file and decompressed archive entry of it.
    /// Never downgraded to a diagnostic by lenient reading: the dataset is incomplete and
    /// should be discarded.
    InputTooLarge {
        /// The budget in force, in bytes.
        limit: u64,
        /// Bytes accepted, across the whole load call, when the budget was exceeded.
        read: u64,
        /// The document being read: a file name or an archive entry.
        source: Option<String>,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Io(e) => write!(f, "i/o error: {e}"),
            Error::Xml(m) => write!(f, "malformed XML: {m}"),
            Error::NotCimXml(m) => write!(f, "not a CIM/XML document: {m}"),
            Error::DanglingReference {
                object,
                attribute,
                target,
                total,
            } => write!(
                f,
                "unresolved reference {object}.{attribute} -> {target} \
                 ({total} unresolved in total); load the missing profile or \
                 use LinkPolicy::Lenient"
            ),
            Error::SchemaMismatch { left, right } => write!(
                f,
                "cannot combine a {left} model with a {right} one: class and attribute \
                 identifiers belong to one vintage's tables"
            ),
            Error::UnknownVintage { path, known } => write!(
                f,
                "no CIM vintage recognised in {path}: not a CIM/XML input, or a vocabulary \
                 this build has no feature for (it has {known:?})"
            ),
            #[cfg(feature = "zip")]
            Error::Zip(m) => write!(f, "zip archive error: {m}"),
            Error::InputTooLarge {
                limit,
                read,
                source,
            } => {
                write!(
                    f,
                    "input exceeds the {} input budget after reading {}",
                    human_bytes(*limit),
                    human_bytes(*read)
                )?;
                if let Some(source) = source {
                    write!(f, " (while reading {source})")?;
                }
                write!(
                    f,
                    "; raise it with ReadOptions::with_max_input_bytes, or pass 0 for no limit"
                )
            }
        }
    }
}

/// A byte count the way a person reads one: `2 GiB`, `512 KiB`, `17 B`.
///
/// Exact multiples print as integers, everything else to one decimal.
pub(crate) fn human_bytes(n: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
    let mut unit = 0;
    let mut value = n;
    while unit + 1 < UNITS.len() && value >= 1024 && value.is_multiple_of(1024) {
        value /= 1024;
        unit += 1;
    }
    if unit > 0 || n < 1024 {
        return format!("{value} {}", UNITS[unit]);
    }
    #[allow(clippy::cast_precision_loss)] // one decimal of a human-facing figure
    let mut f = n as f64;
    let mut unit = 0;
    while unit + 1 < UNITS.len() && f >= 1024.0 {
        f /= 1024.0;
        unit += 1;
    }
    format!("{f:.1} {}", UNITS[unit])
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Error {
        Error::Io(e)
    }
}

impl From<quick_xml::Error> for Error {
    fn from(e: quick_xml::Error) -> Error {
        Error::Xml(e.to_string())
    }
}

impl From<quick_xml::events::attributes::AttrError> for Error {
    fn from(e: quick_xml::events::attributes::AttrError) -> Error {
        Error::Xml(e.to_string())
    }
}

/// How much a diagnostic matters.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Severity {
    /// Violates the standard; the model is not conforming.
    Error,
    /// Legal but suspect, or a tolerated deviation.
    Warning,
    /// Informational, e.g. a deprecated attribute in use.
    Info,
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Info => "info",
        })
    }
}

/// A stable identifier for the rule that produced a diagnostic.
///
/// Rule codes let a pipeline filter, suppress or fail on specific classes of problem
/// without matching message text.
///
/// One macro declares the variants, their codes and [`Rule::ALL`], so they cannot drift.
macro_rules! rules {
    ($($(#[$doc:meta])* $name:ident => $code:literal,)*) => {
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
        pub enum Rule {
            $($(#[$doc])* $name,)*
        }

        impl Rule {
            /// Short stable code, e.g. `CIM0007`, suitable for CI filters.
            pub const fn code(self) -> &'static str {
                match self {
                    $(Rule::$name => $code,)*
                }
            }

            /// Every rule, so tooling can enumerate the catalogue.
            pub const ALL: &'static [Rule] = &[$(Rule::$name,)*];
        }
    };
}

rules! {
    /// An element names a class the schema does not define.
    UnknownClass => "CIM0001",
    /// An element names an attribute the schema does not define for its class.
    UnknownAttribute => "CIM0002",
    /// An attribute value could not be parsed as its declared type.
    InvalidValue => "CIM0003",
    /// An identifier is not a UUID, as IEC 61970-552 requires.
    NonConformingMrid => "CIM0004",
    /// Two objects share an mRID.
    DuplicateMrid => "CIM0005",
    /// A reference points at an object not present in the dataset.
    DanglingReference => "CIM0006",
    /// A required attribute is missing.
    MissingRequired => "CIM0007",
    /// An attribute occurs more often than its multiplicity permits.
    CardinalityExceeded => "CIM0008",
    /// A reference points at an object of the wrong class.
    WrongReferenceTarget => "CIM0009",
    /// An attribute is used outside the profiles that declare it.
    AttributeNotInProfile => "CIM0010",
    /// An abstract class was instantiated.
    AbstractInstantiated => "CIM0011",
    /// A deprecated element is in use.
    Deprecated => "CIM0012",
    /// The file header is missing or incomplete.
    MalformedHeader => "CIM0013",
    /// A header declares a dependency that was not loaded; or a change set's base or
    /// precondition is not satisfied, and it was not applied.
    UnsatisfiedDependency => "CIM0014",
    /// A structural problem in the document that did not prevent reading.
    Structure => "CIM0015",
    /// A stored value does not have the shape its attribute declares.
    ///
    /// CIM/XML carries no datatype information, so this is only detectable against the
    /// schema (e.g. text where a float is declared, or another enumeration's literal).
    DatatypeMismatch => "CIM0016",
    /// An attribute the schema pins with `cims:isFixed` carries a different value.
    FixedValueMismatch => "CIM0017",
    /// Two loaded files gave different values for one single-valued attribute.
    ///
    /// Merging keeps one value and discards the other; see [`Dataset::merge_conflicts`].
    ///
    /// [`Dataset::merge_conflicts`]: crate::Dataset::merge_conflicts
    ConflictingValue => "CIM0018",
    /// A value holds a character XML 1.0 cannot represent.
    ///
    /// XML's `Char` production excludes most of the C0 range, even as a character
    /// reference, so it cannot be written at all. The reader strips such characters and
    /// reports them; validation also flags values set through the API.
    IllegalXmlCharacter => "CIM0019",
    /// A file in the model set could not be read at all.
    ///
    /// Under [`Strictness::Lenient`](crate::reader::Strictness::Lenient) the load records
    /// this and reads the remaining files; under `Strict` it is an [`Error`].
    UnreadableFile => "CIM0022",
    /// The document is written against a different schema vintage than the one reading it.
    ///
    /// Detected from the root's namespaces (`…/CIM100#` for CGMES 3.0,
    /// `…/CIM-schema-cim16#` for 2.4.15), reported once instead of one `CIM0001` per element.
    WrongVintage => "CIM0021",
    /// An identifier has no valid RDF/XML serialization.
    ///
    /// `rdf:ID` is an XML `NCName` and `rdf:about` an IRI reference; every UUID is fine.
    /// An identifier that is neither (one containing a space, say) is still written, but
    /// the document is not valid RDF/XML, though it is well-formed XML.
    UnserializableIdentifier => "CIM0020",
}

impl fmt::Display for Rule {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.code())
    }
}

/// A structured finding, usable by CI and tooling rather than only printable.
///
/// The object and attribute fields hold the identifier and the schema's name, not
/// rendered text, so callers can group or look up findings without parsing messages.
#[derive(Clone, Debug)]
pub struct Diagnostic {
    pub severity: Severity,
    pub rule: Rule,
    /// Identifier of the object concerned, when the finding is object-scoped.
    pub object: Option<crate::mrid::Mrid>,
    /// Class name of that object.
    pub class: Option<&'static str>,
    /// Qualified attribute name, when the finding is attribute-scoped.
    pub attribute: Option<&'static str>,
    /// Source file the finding came from.
    pub source: Option<String>,
    /// Byte offset in the source document, when the finding came from parsing.
    ///
    /// An offset, not a line, because the reader streams; [`line_and_column`] converts.
    pub position: Option<u64>,
    pub message: String,
}

/// Convert a byte offset in `source` to a 1-based line and column.
///
/// Pairs with [`Diagnostic::position`], which the streaming reader records instead of a
/// line number. Reads `source` up to `position` only.
pub fn line_and_column(source: &str, position: u64) -> (u64, u64) {
    let upto = &source.as_bytes()[..(position as usize).min(source.len())];
    let line = upto.iter().filter(|&&b| b == b'\n').count() as u64 + 1;
    let col = match upto.iter().rposition(|&b| b == b'\n') {
        Some(i) => (upto.len() - i) as u64,
        None => upto.len() as u64 + 1,
    };
    (line, col)
}

impl Diagnostic {
    pub fn new(severity: Severity, rule: Rule, message: impl Into<String>) -> Diagnostic {
        Diagnostic {
            severity,
            rule,
            object: None,
            class: None,
            attribute: None,
            source: None,
            position: None,
            message: message.into(),
        }
    }

    pub fn error(rule: Rule, message: impl Into<String>) -> Diagnostic {
        Diagnostic::new(Severity::Error, rule, message)
    }
    pub fn warning(rule: Rule, message: impl Into<String>) -> Diagnostic {
        Diagnostic::new(Severity::Warning, rule, message)
    }
    pub fn info(rule: Rule, message: impl Into<String>) -> Diagnostic {
        Diagnostic::new(Severity::Info, rule, message)
    }

    pub fn with_object(mut self, mrid: impl Into<crate::mrid::Mrid>) -> Diagnostic {
        self.object = Some(mrid.into());
        self
    }
    pub fn with_class(mut self, class: &'static str) -> Diagnostic {
        self.class = Some(class);
        self
    }
    pub fn with_attribute(mut self, attr: &'static str) -> Diagnostic {
        self.attribute = Some(attr);
        self
    }
    pub fn with_source(mut self, source: impl Into<String>) -> Diagnostic {
        self.source = Some(source.into());
        self
    }
    /// Record the byte offset in the source document the finding came from.
    pub fn with_position(mut self, position: u64) -> Diagnostic {
        self.position = Some(position);
        self
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}[{}]", self.severity, self.rule.code())?;
        if let Some(src) = &self.source {
            write!(f, " {src}")?;
            if let Some(pos) = self.position {
                // `@` rather than `:` so the number is not mistaken for a line.
                write!(f, "@{pos}")?;
            }
        }
        write!(f, ": {}", self.message)?;
        if let Some(class) = self.class {
            write!(f, " [{class}")?;
            match &self.object {
                Some(o) => write!(f, " {o}]")?,
                None => write!(f, "]")?,
            }
        } else if let Some(o) = &self.object {
            write!(f, " [{o}]")?;
        }
        Ok(())
    }
}

/// A collection of diagnostics with convenience queries.
#[derive(Clone, Debug, Default)]
pub struct Report {
    pub diagnostics: Vec<Diagnostic>,
}

impl Report {
    pub fn push(&mut self, d: Diagnostic) {
        self.diagnostics.push(d);
    }

    pub fn extend(&mut self, other: Report) {
        self.diagnostics.extend(other.diagnostics);
    }

    pub fn is_empty(&self) -> bool {
        self.diagnostics.is_empty()
    }

    pub fn len(&self) -> usize {
        self.diagnostics.len()
    }

    pub fn count(&self, severity: Severity) -> usize {
        self.diagnostics
            .iter()
            .filter(|d| d.severity == severity)
            .count()
    }

    /// Whether any diagnostic is an error, i.e. the model is non-conforming.
    pub fn has_errors(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| d.severity == Severity::Error)
    }

    pub fn iter(&self) -> std::slice::Iter<'_, Diagnostic> {
        self.diagnostics.iter()
    }

    pub fn by_rule(&self, rule: Rule) -> impl Iterator<Item = &Diagnostic> {
        self.diagnostics.iter().filter(move |d| d.rule == rule)
    }

    /// Number of findings per rule, most frequent first — a useful CI summary.
    pub fn summary(&self) -> Vec<(Rule, usize)> {
        let mut counts: Vec<(Rule, usize)> = Vec::new();
        for d in &self.diagnostics {
            match counts.iter_mut().find(|(r, _)| *r == d.rule) {
                Some((_, n)) => *n += 1,
                None => counts.push((d.rule, 1)),
            }
        }
        counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
        counts
    }
}

impl IntoIterator for Report {
    type Item = Diagnostic;
    type IntoIter = std::vec::IntoIter<Diagnostic>;
    fn into_iter(self) -> Self::IntoIter {
        self.diagnostics.into_iter()
    }
}

impl fmt::Display for Report {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for d in &self.diagnostics {
            writeln!(f, "{d}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn byte_counts_read_the_way_a_budget_was_written() {
        assert_eq!(human_bytes(2 << 30), "2 GiB");
        assert_eq!(human_bytes(512 << 10), "512 KiB");
        assert_eq!(human_bytes(17), "17 B");
        assert_eq!(human_bytes((1 << 20) + 1), "1.0 MiB");
        assert_eq!(human_bytes(1536 << 20), "1536 MiB");
    }

    #[test]
    fn rule_codes_are_unique() {
        let mut codes: Vec<&str> = Rule::ALL.iter().map(|r| r.code()).collect();
        codes.sort_unstable();
        let n = codes.len();
        codes.dedup();
        assert_eq!(codes.len(), n, "duplicate rule codes");

        // Contiguous from CIM0001, because the codes are a published catalogue and a hole
        // in it means a rule was removed and every citation after it now means something
        // else — the same reasoning the `concepts/` registers are held to.
        let expected: Vec<String> = (1..=n).map(|i| format!("CIM{i:04}")).collect();
        assert_eq!(
            codes, expected,
            "the rule codes are not contiguous from CIM0001"
        );
    }

    #[test]
    fn byte_offsets_convert_to_lines_and_columns() {
        let src = "one\ntwo\nthree";
        assert_eq!(line_and_column(src, 0), (1, 1));
        assert_eq!(line_and_column(src, 4), (2, 1));
        assert_eq!(line_and_column(src, 6), (2, 3));
        // Past the end clamps rather than panicking.
        assert_eq!(line_and_column(src, 9_999).0, 3);
    }

    #[test]
    fn report_summarizes_by_rule() {
        let mut r = Report::default();
        r.push(Diagnostic::error(Rule::MissingRequired, "a"));
        r.push(Diagnostic::error(Rule::MissingRequired, "b"));
        r.push(Diagnostic::warning(Rule::Deprecated, "c"));
        assert!(r.has_errors());
        assert_eq!(r.count(Severity::Error), 2);
        assert_eq!(
            r.summary(),
            vec![(Rule::MissingRequired, 2), (Rule::Deprecated, 1)]
        );
    }

    #[test]
    fn diagnostic_display_includes_location_and_code() {
        let d = Diagnostic::error(Rule::MissingRequired, "missing name")
            .with_class("ACLineSegment")
            .with_object("abc")
            .with_source("EQ.xml")
            .with_position(1234);
        let s = d.to_string();
        assert!(s.contains("error[CIM0007]"), "{s}");
        assert!(s.contains("EQ.xml@1234"), "{s}");
        assert!(s.contains("[ACLineSegment abc]"), "{s}");
    }
}