Skip to main content

cim_kit/
validate.rs

1//! Structural validation derived from the schema.
2//!
3//! The checks the RDFS vocabulary justifies: cardinality, datatype, class membership,
4//! reference targets, profile membership and identifier conformance. ENTSO-E's SHACL
5//! rules are out of scope; export with [`rdf`](crate::rdf) and use a SHACL engine.
6
7use std::collections::BTreeMap;
8
9use crate::dataset::Dataset;
10use crate::error::{Diagnostic, Report, Rule, Severity};
11use crate::header::ModelHeader;
12use crate::mrid::{Mrid, MridForm};
13use crate::object::Object;
14use crate::schema::{AttrId, AttrKind, ProfileId, ProfileMask, Schema};
15use crate::value::Value;
16
17/// Which checks to run.
18#[derive(Clone, Debug)]
19pub struct ValidateOptions {
20    /// Check that required attributes are present.
21    pub required_attributes: bool,
22    /// Check that multiplicities are respected.
23    pub cardinality: bool,
24    /// Check that references resolve within the dataset.
25    pub references: bool,
26    /// Check that a reference points at an object of the declared target class.
27    pub reference_targets: bool,
28    /// Check that every stored value's attribute belongs to the object's class.
29    ///
30    /// The one check about what the *store* holds rather than about what a document said.
31    /// Everything else walks the class's attribute list, so a value filed under an
32    /// attribute the class does not have is examined by nothing and dropped on export.
33    pub class_membership: bool,
34    /// Check that each stored value has the shape its attribute declares.
35    ///
36    /// CIM/XML carries no datatype information, so this is only decidable against the
37    /// RDFS — which is exactly why ENTSO-E's own guidance tells importers to enrich the
38    /// data graph from the profile before validating it.
39    pub datatypes: bool,
40    /// Check attributes the schema pins with `cims:isFixed`.
41    pub fixed_values: bool,
42    /// Check that identifiers conform to IEC 61970-552.
43    pub mrid_conformance: bool,
44    /// Report use of deprecated classes and attributes.
45    pub deprecation: bool,
46    /// Check that headers declare dependencies that were actually loaded.
47    pub dependencies: bool,
48    /// Report attributes whose data belongs to a profile none of the loaded files
49    /// declares — a header that under-declares what its file contains.
50    pub profile_reach: bool,
51    /// Check each loaded file's header against the structural requirements of
52    /// IEC 61970-552.
53    pub headers: bool,
54    /// Report single-valued attributes two loaded files gave different values for.
55    ///
56    /// Recorded by [`Dataset`] as the files are merged, because by the time validation
57    /// runs one of the two values is gone.
58    pub merge_conflicts: bool,
59    /// Check that the model can actually be serialized as CIM/XML.
60    ///
61    /// Text values must hold only characters XML 1.0 can represent (`CIM0019`), and
62    /// identifiers must have an `rdf:ID` or `rdf:about` form (`CIM0020`). Always true for
63    /// conforming input; reachable from a mis-encoded file or
64    /// [`Object::set`](crate::Object::set). See [`xml`](crate::xml).
65    pub serializable: bool,
66    /// Restrict checks to these profiles. Empty means "the profiles the headers declare",
67    /// falling back to every profile the schema knows.
68    pub profiles: ProfileMask,
69    /// Stop after this many diagnostics. Prevents a broken file producing millions.
70    pub max_diagnostics: usize,
71}
72
73impl Default for ValidateOptions {
74    fn default() -> Self {
75        ValidateOptions {
76            required_attributes: true,
77            cardinality: true,
78            class_membership: true,
79            references: true,
80            reference_targets: true,
81            datatypes: true,
82            fixed_values: true,
83            mrid_conformance: true,
84            deprecation: false,
85            dependencies: true,
86            profile_reach: true,
87            headers: true,
88            merge_conflicts: true,
89            serializable: true,
90            profiles: 0,
91            max_diagnostics: 10_000,
92        }
93    }
94}
95
96impl ValidateOptions {
97    /// Only the checks that indicate genuinely broken data.
98    pub fn essential() -> ValidateOptions {
99        ValidateOptions {
100            required_attributes: false,
101            cardinality: true,
102            // A value nothing will ever look at is broken data by any definition.
103            class_membership: true,
104            references: true,
105            reference_targets: true,
106            datatypes: true,
107            fixed_values: false,
108            mrid_conformance: false,
109            deprecation: false,
110            dependencies: false,
111            profile_reach: false,
112            headers: false,
113            // A model set whose files contradict each other is broken data by any
114            // definition, so this stays on even in the reduced set.
115            merge_conflicts: true,
116            // So is a model that cannot be written back out.
117            serializable: true,
118            ..Default::default()
119        }
120    }
121
122    /// Every check, including advisory ones.
123    pub fn thorough() -> ValidateOptions {
124        ValidateOptions {
125            deprecation: true,
126            ..Default::default()
127        }
128    }
129
130    pub fn for_profiles(mut self, profiles: ProfileMask) -> Self {
131        self.profiles = profiles;
132        self
133    }
134}
135
136/// Validate a dataset with default options.
137pub fn validate(dataset: &Dataset) -> Report {
138    validate_with(dataset, &ValidateOptions::default())
139}
140
141/// Validate a dataset.
142pub fn validate_with(dataset: &Dataset, options: &ValidateOptions) -> Report {
143    let schema = dataset.schema();
144    let mut report = Report::default();
145
146    // Which profiles to judge required-ness against. An attribute that is mandatory in
147    // Equipment must not be reported as missing when only a Topology file is loaded.
148    let scope = if options.profiles != 0 {
149        options.profiles
150    } else {
151        let declared = dataset.profiles();
152        if declared != 0 {
153            declared
154        } else {
155            ProfileMask::MAX
156        }
157    };
158
159    if options.headers {
160        for h in dataset.headers() {
161            report.extend(validate_header(h));
162        }
163    }
164    if options.dependencies {
165        check_dependencies(dataset, &mut report);
166    }
167    if options.profile_reach {
168        check_profile_reach(dataset, &mut report);
169    }
170    if options.merge_conflicts {
171        check_merge_conflicts(dataset, &mut report);
172    }
173
174    for (_, obj) in dataset.iter() {
175        if report.len() >= options.max_diagnostics {
176            report.push(Diagnostic::warning(
177                Rule::Structure,
178                format!(
179                    "validation stopped after {} diagnostics",
180                    options.max_diagnostics
181                ),
182            ));
183            break;
184        }
185        check_object(schema, dataset, obj, scope, options, &mut report);
186    }
187
188    report
189}
190
191fn check_object(
192    schema: &'static Schema,
193    dataset: &Dataset,
194    obj: &Object,
195    scope: ProfileMask,
196    options: &ValidateOptions,
197    report: &mut Report,
198) {
199    let class = schema.class(obj.class());
200    let mrid = obj.mrid();
201
202    if options.mrid_conformance && !mrid.is_conforming() {
203        report.push(
204            Diagnostic::warning(Rule::NonConformingMrid, mrid_complaint(mrid))
205                .with_class(class.name)
206                .with_object(mrid.clone()),
207        );
208    }
209
210    if options.serializable {
211        check_serializable(schema, obj, class.name, mrid, report);
212    }
213
214    if !class.concrete {
215        report.push(
216            Diagnostic::error(
217                Rule::AbstractInstantiated,
218                format!("abstract class {} has an instance", class.name),
219            )
220            .with_class(class.name)
221            .with_object(mrid.clone()),
222        );
223    }
224
225    if options.deprecation && class.deprecated {
226        report.push(
227            Diagnostic::info(
228                Rule::Deprecated,
229                format!("class {} is deprecated", class.name),
230            )
231            .with_class(class.name)
232            .with_object(mrid.clone()),
233        );
234    }
235
236    // A value stored under an attribute this class does not have is otherwise *invisible*:
237    // every other check below walks `class.all_attrs`, and so does the writer, so such a
238    // value is never examined and is silently dropped on the next export. The reader
239    // refuses to store one and so does `apply_difference`, but `Object::set` is public and
240    // a class can be reclassified out from under its values, so the finished model is
241    // checked rather than only the paths into it.
242    if options.class_membership {
243        for slot in obj.slots() {
244            // A compound is an object in miniature, so the same question applies to its
245            // fields — and the consequence is worse there. An object's stray value is
246            // dropped by the writer's schema-ordered walk; a compound's fields are written
247            // exactly as held, so a foreign one leaves inside a document that is
248            // well-formed XML and not a conforming CGMES file.
249            check_compound_membership(schema, &slot.value, class.name, mrid, report);
250
251            let def = schema.attr(slot.attr);
252            if !schema.is_a(obj.class(), def.owner) {
253                report.push(
254                    Diagnostic::error(
255                        Rule::UnknownAttribute,
256                        format!(
257                            "{} is declared on {} and cannot be stored on a {}; it would be \
258                             dropped on export",
259                            def.name,
260                            schema.class(def.owner).name,
261                            class.name
262                        ),
263                    )
264                    .with_class(class.name)
265                    .with_object(mrid.clone())
266                    .with_attribute(def.name),
267                );
268            }
269        }
270    }
271
272    for attr_id in class.all_attrs {
273        let def = schema.attr(*attr_id);
274        let in_scope = def.profiles & scope != 0;
275        let count = obj.count(*attr_id) as u32;
276
277        if count == 0 {
278            // An association side marked `AssociationUsed = No` is never written; it is
279            // derived by inverting the other side, so its absence is not a defect.
280            let derived = matches!(def.kind, AttrKind::Association { .. }) && def.used_in == 0;
281            if options.required_attributes && in_scope && def.mult.is_required() && !derived {
282                // Judge only with enough of the model loaded: the object participates in
283                // a profile declaring the attribute, and some loaded file *defines* its
284                // class (a Topology file referring to an EQ `ConnectivityNode` need not
285                // carry its mandatory attributes).
286                let object_in_profile = obj.profiles() == 0 || obj.profiles() & def.profiles != 0;
287                //
288                // A class that no profile both introduces and declares concrete is never
289                // the subject of a definition at all — `Equipment` is abstract in the
290                // Equipment profile and concrete only in Steady State Hypothesis, where it
291                // is the generic carrier for `inService` — so there is no file whose
292                // absence or presence would settle the question.
293                let defining = class.defined_in & class.concrete_in;
294                let definition_loaded = defining & scope != 0;
295                if object_in_profile && definition_loaded {
296                    report.push(
297                        Diagnostic::error(
298                            Rule::MissingRequired,
299                            format!("required attribute {} is missing", def.name),
300                        )
301                        .with_class(class.name)
302                        .with_object(mrid.clone())
303                        .with_attribute(def.name),
304                    );
305                }
306            }
307            continue;
308        }
309
310        if options.cardinality && count > def.mult.max() {
311            report.push(
312                Diagnostic::error(
313                    Rule::CardinalityExceeded,
314                    format!(
315                        "{} occurs {} times but permits at most {}",
316                        def.name,
317                        count,
318                        def.mult.max()
319                    ),
320                )
321                .with_class(class.name)
322                .with_object(mrid.clone())
323                .with_attribute(def.name),
324            );
325        }
326        // A bounded lower limit above one — `M:2..2` and friends — is not covered by the
327        // "required attribute is missing" check, which only sees absence.
328        if options.cardinality && in_scope && count < def.mult.min() && count > 0 {
329            report.push(
330                Diagnostic::error(
331                    Rule::MissingRequired,
332                    format!(
333                        "{} occurs {} times but requires at least {}",
334                        def.name,
335                        count,
336                        def.mult.min()
337                    ),
338                )
339                .with_class(class.name)
340                .with_object(mrid.clone())
341                .with_attribute(def.name),
342            );
343        }
344
345        if options.datatypes || options.fixed_values {
346            for slot in obj.get_all(*attr_id) {
347                check_value(
348                    schema,
349                    &slot.value,
350                    *attr_id,
351                    class.name,
352                    mrid,
353                    options,
354                    report,
355                );
356            }
357        }
358
359        if options.deprecation && def.deprecated {
360            report.push(
361                Diagnostic::info(
362                    Rule::Deprecated,
363                    format!("attribute {} is deprecated", def.name),
364                )
365                .with_class(class.name)
366                .with_object(mrid.clone())
367                .with_attribute(def.name),
368            );
369        }
370
371        // Reference checks.
372        if let AttrKind::Association { target, .. } = def.kind {
373            for slot in obj.get_all(*attr_id) {
374                let Value::Reference(m) = &slot.value else {
375                    continue;
376                };
377                match dataset.by_mrid(m) {
378                    None => {
379                        if options.references {
380                            report.push(
381                                Diagnostic::warning(
382                                    Rule::DanglingReference,
383                                    format!(
384                                        "{} points at {} which is not in the dataset",
385                                        def.name,
386                                        m.canonical()
387                                    ),
388                                )
389                                .with_class(class.name)
390                                .with_object(mrid.clone())
391                                .with_attribute(def.name),
392                            );
393                        }
394                    }
395                    Some(t) => {
396                        // An object may be known only through a base class: a Steady State
397                        // Hypothesis file writes `<cim:Equipment rdf:about="…">` for a
398                        // breaker whose own class only the Equipment file declares. Until
399                        // that file is loaded the object *is* an `Equipment`, and that is
400                        // not evidence it is the wrong kind of thing — only two classes on
401                        // different branches are.
402                        let compatible =
403                            schema.is_a(t.class(), target) || schema.is_a(target, t.class());
404                        if options.reference_targets && !compatible {
405                            report.push(
406                                Diagnostic::error(
407                                    Rule::WrongReferenceTarget,
408                                    format!(
409                                        "{} must point at {} but {} is a {}",
410                                        def.name,
411                                        schema.class(target).name,
412                                        m.canonical(),
413                                        schema.class(t.class()).name
414                                    ),
415                                )
416                                .with_class(class.name)
417                                .with_object(mrid.clone())
418                                .with_attribute(def.name),
419                            );
420                        }
421                    }
422                }
423            }
424        }
425    }
426}
427
428/// Report fields a compound's class does not declare, at any nesting depth.
429fn check_compound_membership(
430    schema: &'static Schema,
431    value: &Value,
432    class: &'static str,
433    mrid: &Mrid,
434    report: &mut Report,
435) {
436    let Value::Compound(c) = value else { return };
437    for (attr, v) in c.values() {
438        let def = schema.attr(*attr);
439        if !schema.is_a(c.class(), def.owner) {
440            report.push(
441                Diagnostic::error(
442                    Rule::UnknownAttribute,
443                    format!(
444                        "{} is declared on {} and cannot be stored on a {} compound; it \
445                         would be written into the document anyway, which no consumer of \
446                         that profile will accept",
447                        def.name,
448                        schema.class(def.owner).name,
449                        schema.class(c.class()).name
450                    ),
451                )
452                .with_class(class)
453                .with_object(mrid.clone())
454                .with_attribute(def.name),
455            );
456        }
457        // Compounds nest: a `StreetAddress` holds a `StreetDetail`.
458        check_compound_membership(schema, v, class, mrid, report);
459    }
460}
461
462/// Check that an object can be written back out as CIM/XML.
463///
464/// The writer already strips illegal characters and picks a valid identifier form; this
465/// tells the caller, per object, before an export differs from what was put in.
466fn check_serializable(
467    schema: &'static Schema,
468    obj: &Object,
469    class: &'static str,
470    mrid: &Mrid,
471    report: &mut Report,
472) {
473    use crate::xml::{IdentifierForm, describe_char, find_illegal};
474
475    if mrid.form_in_xml() == IdentifierForm::Unwritable {
476        report.push(
477            Diagnostic::error(
478                Rule::UnserializableIdentifier,
479                format!(
480                    "identifier {:?} is neither an XML NCName nor an absolute IRI, so it has \
481                     no valid rdf:ID or rdf:about form; the document written will be \
482                     well-formed XML but not valid RDF/XML",
483                    mrid.as_written()
484                ),
485            )
486            .with_class(class)
487            .with_object(mrid.clone()),
488        );
489    }
490
491    // Only text carries characters; enumerations, references and compounds serialize
492    // through forms of their own — except that a compound's fields are text again.
493    fn scan(
494        schema: &'static Schema,
495        value: &Value,
496        attr: AttrId,
497        class: &'static str,
498        mrid: &Mrid,
499        report: &mut Report,
500    ) {
501        match value {
502            Value::Text(s) => {
503                if let Some((offset, c)) = find_illegal(s) {
504                    let def = schema.attr(attr);
505                    report.push(
506                        Diagnostic::error(
507                            Rule::IllegalXmlCharacter,
508                            format!(
509                                "{} holds {}, which XML 1.0 cannot represent in any form; it \
510                                 will be dropped on export (first at byte {offset} of the value)",
511                                def.name,
512                                describe_char(c)
513                            ),
514                        )
515                        .with_class(class)
516                        .with_object(mrid.clone())
517                        .with_attribute(def.name),
518                    );
519                }
520            }
521            Value::Compound(c) => {
522                for (a, v) in c.values() {
523                    scan(schema, v, *a, class, mrid, report);
524                }
525            }
526            _ => {}
527        }
528    }
529
530    for slot in obj.slots() {
531        scan(schema, &slot.value, slot.attr, class, mrid, report);
532    }
533}
534
535/// Check one stored value against what its attribute declares, recursing into compounds.
536///
537/// This is the check CIM/XML cannot make for itself. IEC 61970-552 exchanges no datatype
538/// information, so a parser without the profile reads every value as a string; only the
539/// RDFS says that `ACLineSegment.r` is a float or that `Terminal.phases` must be a
540/// `PhaseCode`, and only here can a value that is neither be caught.
541fn check_value(
542    schema: &'static Schema,
543    value: &Value,
544    attr: AttrId,
545    class: &'static str,
546    mrid: &Mrid,
547    options: &ValidateOptions,
548    report: &mut Report,
549) {
550    let def = schema.attr(attr);
551    let mut mismatch = |expected: &str, found: &str| {
552        report.push(
553            Diagnostic::error(
554                Rule::DatatypeMismatch,
555                format!("{} expects {expected} but holds {found}", def.name),
556            )
557            .with_class(class)
558            .with_object(mrid.clone())
559            .with_attribute(def.name),
560        );
561    };
562
563    if options.datatypes {
564        match def.kind {
565            AttrKind::Primitive(p) => {
566                if let Some(found) = primitive_mismatch(p, value) {
567                    mismatch(&format!("{p:?}"), found);
568                }
569            }
570            AttrKind::Datatype(dt) => {
571                let p = schema.datatype(dt).value;
572                if let Some(found) = primitive_mismatch(p, value) {
573                    mismatch(&format!("{} ({p:?})", schema.datatype(dt).name), found);
574                }
575            }
576            AttrKind::Enumeration(want) => match value {
577                // A literal recovered from the wrong namespace can belong to a different
578                // enumeration; the qualified name alone cannot rule that out.
579                Value::Enum(v) if schema.enum_value(*v).owner != want => mismatch(
580                    schema.enumeration(want).name,
581                    schema.enumeration(schema.enum_value(*v).owner).name,
582                ),
583                Value::Enum(_) => {}
584                other => mismatch(schema.enumeration(want).name, shape_of(other)),
585            },
586            AttrKind::Association { .. } => {
587                if !matches!(value, Value::Reference(_)) {
588                    mismatch("a reference", shape_of(value));
589                }
590            }
591            AttrKind::Compound(want) => match value {
592                Value::Compound(c) if c.class() != want => {
593                    mismatch(schema.class(want).name, schema.class(c.class()).name)
594                }
595                Value::Compound(c) => {
596                    // Compounds nest, and their fields are ordinary attributes.
597                    for (a, v) in c.values() {
598                        check_value(schema, v, *a, class, mrid, options, report);
599                    }
600                }
601                other => mismatch(schema.class(want).name, shape_of(other)),
602            },
603        }
604    }
605
606    if options.fixed_values
607        && let Some(fixed) = def.fixed
608    {
609        let actual = crate::value::display_value(schema, value);
610        // A fixed value is compared as text: the schema pins the lexical form.
611        if actual != fixed && !actual.is_empty() {
612            report.push(
613                Diagnostic::warning(
614                    Rule::FixedValueMismatch,
615                    format!("{} is fixed to {fixed:?} but holds {actual:?}", def.name),
616                )
617                .with_class(class)
618                .with_object(mrid.clone())
619                .with_attribute(def.name),
620            );
621        }
622    }
623}
624
625/// Whether `value` can serve as `p`, and what it is if not.
626///
627/// The compatibility rule itself lives on [`Value::fits`], because the RDF writer has to
628/// answer the same question — whether to label a literal with the type the profile
629/// declares — and the two must not drift apart.
630fn primitive_mismatch(p: crate::schema::Primitive, value: &Value) -> Option<&'static str> {
631    (!value.fits(p)).then(|| value.shape())
632}
633
634fn shape_of(v: &Value) -> &'static str {
635    v.shape()
636}
637
638/// Report values whose own file declared no profile that declares the attribute.
639///
640/// A header/content mismatch (e.g. an Equipment file carrying ShortCircuit attributes
641/// without declaring that profile), checked against each value's own file, not the union.
642/// Aggregated **per attribute**, not per value.
643fn check_profile_reach(dataset: &Dataset, report: &mut Report) {
644    let schema = dataset.schema();
645    // Attribute -> (number of values affected, an example object).
646    let mut undeclared: BTreeMap<AttrId, (usize, Mrid)> = BTreeMap::new();
647
648    for (_, obj) in dataset.iter() {
649        for slot in obj.slots() {
650            if !schema.declaration_covers(slot.attr, slot.profiles) {
651                let entry = undeclared
652                    .entry(slot.attr)
653                    .or_insert_with(|| (0, obj.mrid().clone()));
654                entry.0 += 1;
655            }
656        }
657    }
658
659    for (attr, (count, example)) in undeclared {
660        let def = schema.attr(attr);
661        let profiles: Vec<&str> = schema
662            .profiles
663            .iter()
664            .enumerate()
665            // `ProfileId::mask` rather than a bare shift, which Rust masks in release
666            // builds: an over-wide shift would name the wrong profile instead of failing.
667            .filter(|(i, _)| def.used_in & ProfileId(*i as u16).mask() != 0)
668            .map(|(_, p)| p.keyword)
669            .collect();
670        report.push(
671            Diagnostic::warning(
672                Rule::AttributeNotInProfile,
673                format!(
674                    "{} is set on {count} object(s) by files whose header does not declare \
675                     profile(s) {}, which is where the schema puts it",
676                    def.name,
677                    profiles.join("+")
678                ),
679            )
680            .with_class(schema.class(def.owner).name)
681            .with_object(example)
682            .with_attribute(def.name),
683        );
684    }
685}
686
687/// Report the disagreements that assembling the model set had to resolve.
688///
689/// Read back from [`Dataset`], which records conflicts while merging. A warning, not an
690/// error: a change file loaded over its base produces them legitimately.
691fn check_merge_conflicts(dataset: &Dataset, report: &mut Report) {
692    let schema = dataset.schema();
693    for c in dataset.merge_conflicts() {
694        let def = schema.attr(c.attr);
695        report.push(
696            Diagnostic::warning(
697                Rule::ConflictingValue,
698                format!(
699                    "{} was given {} by one file and {} by another; the later value is kept",
700                    def.name,
701                    crate::value::display_value(schema, &c.discarded),
702                    crate::value::display_value(schema, &c.kept),
703                ),
704            )
705            .with_class(schema.class(def.owner).name)
706            .with_object(c.object.clone())
707            .with_attribute(def.name),
708        );
709    }
710    let dropped = dataset.merge_conflicts_dropped();
711    if dropped > 0 {
712        report.push(Diagnostic::warning(
713            Rule::ConflictingValue,
714            format!("{dropped} further conflicting value(s) were counted but not recorded"),
715        ));
716    }
717}
718
719/// Check that every `md:Model.DependentOn` was satisfied by a loaded file.
720fn check_dependencies(dataset: &Dataset, report: &mut Report) {
721    let loaded: Vec<&Mrid> = dataset
722        .headers()
723        .iter()
724        .filter_map(|h| h.id.as_ref())
725        .collect();
726    for h in dataset.headers() {
727        for dep in &h.dependent_on {
728            if !loaded.contains(&dep) {
729                report.push(
730                    Diagnostic::warning(
731                        Rule::UnsatisfiedDependency,
732                        format!("model depends on {} which was not loaded", dep.canonical()),
733                    )
734                    .with_source(h.source.clone().unwrap_or_else(|| "<header>".into())),
735                );
736            }
737        }
738    }
739}
740
741/// Say precisely what is wrong with an identifier IEC 61970-552 would reject.
742///
743/// The two cases call for different action and must not read alike: a compact UUID is the
744/// right value in the wrong spelling — every tool can still resolve it, and re-hyphenating
745/// it fixes the file — while an opaque identifier has no UUID behind it at all, so it has
746/// no `urn:uuid:` IRI and no amount of reformatting will give it one.
747fn mrid_complaint(mrid: &Mrid) -> String {
748    match mrid.form() {
749        MridForm::Uuid => format!("identifier {:?} conforms", mrid.canonical()),
750        MridForm::Compact => format!(
751            "identifier {:?} is a UUID written without hyphens; IEC 61970-552 requires \
752             the {:?} form",
753            mrid.as_written(),
754            mrid.canonical()
755        ),
756        MridForm::Opaque => format!(
757            "identifier {:?} is not a UUID, which IEC 61970-552 requires",
758            mrid.canonical()
759        ),
760    }
761}
762
763/// Check a set of headers for the structural requirements of IEC 61970-552.
764pub fn validate_header(header: &ModelHeader) -> Report {
765    let mut report = Report::default();
766    let src = header.source.clone().unwrap_or_else(|| "<header>".into());
767
768    if header.id.is_none() {
769        report.push(
770            Diagnostic::error(Rule::MalformedHeader, "header has no rdf:about identifier")
771                .with_source(src.clone()),
772        );
773    } else if let Some(id) = &header.id
774        && !id.is_conforming()
775    {
776        report.push(
777            Diagnostic::warning(
778                Rule::MalformedHeader,
779                format!("header identifier: {}", mrid_complaint(id)),
780            )
781            .with_source(src.clone()),
782        );
783    }
784    if header.profiles.is_empty() {
785        report.push(
786            Diagnostic::error(Rule::MalformedHeader, "header declares no md:Model.profile")
787                .with_source(src.clone()),
788        );
789    }
790    if header.scenario_time.is_none() {
791        report.push(
792            Diagnostic::warning(Rule::MalformedHeader, "header has no md:Model.scenarioTime")
793                .with_source(src.clone()),
794        );
795    }
796    if header.created.is_none() {
797        report.push(
798            Diagnostic::warning(Rule::MalformedHeader, "header has no md:Model.created")
799                .with_source(src),
800        );
801    }
802    report
803}
804
805/// Summarize a dataset against one profile: what it would export, and what is missing.
806#[derive(Clone, Debug)]
807pub struct ProfileCoverage {
808    pub profile: ProfileId,
809    pub keyword: &'static str,
810    /// Objects that would appear in an export of this profile.
811    pub objects: usize,
812    /// Attribute occurrences that would be written.
813    pub attributes: usize,
814    /// Required attributes of in-profile objects that are absent.
815    pub missing_required: usize,
816}
817
818/// Report, per profile, how much of it the dataset actually carries.
819///
820/// One pass over the model rather than one per profile: on a nation-scale model the
821/// difference is eleven walks of a quarter of a million objects versus one.
822pub fn profile_coverage(dataset: &Dataset) -> Vec<ProfileCoverage> {
823    let schema = dataset.schema();
824    let n = schema.profiles.len();
825    let mut objects = vec![0usize; n];
826    let mut attributes = vec![0usize; n];
827    let mut missing_required = vec![0usize; n];
828
829    for (_, obj) in dataset.iter() {
830        let class = schema.class(obj.class());
831        // Profiles this object contributes at least one value to.
832        let mut touched: ProfileMask = 0;
833        for attr_id in class.all_attrs {
834            let def = schema.attr(*attr_id);
835            let slots = obj.get_all(*attr_id);
836            if slots.is_empty() {
837                if def.mult.is_required() {
838                    for (i, missing) in missing_required.iter_mut().enumerate() {
839                        let mask = ProfileId(i as u16).mask();
840                        if class.profiles & mask != 0 && def.used_in & mask != 0 {
841                            *missing += 1;
842                        }
843                    }
844                }
845                continue;
846            }
847            // Count exactly what the writer would emit, so the report cannot drift from
848            // the export: both go through `effective_profiles`.
849            for s in slots {
850                let effective = schema.effective_profiles(s.attr, s.profiles);
851                for (i, count) in attributes.iter_mut().enumerate() {
852                    let mask = ProfileId(i as u16).mask();
853                    if effective & mask != 0 && class.profiles & mask != 0 {
854                        *count += 1;
855                        touched |= mask;
856                    }
857                }
858            }
859        }
860        for (i, count) in objects.iter_mut().enumerate() {
861            if touched & ProfileId(i as u16).mask() != 0 {
862                *count += 1;
863            }
864        }
865    }
866
867    schema
868        .profiles
869        .iter()
870        .enumerate()
871        .map(|(i, p)| ProfileCoverage {
872            profile: ProfileId(i as u16),
873            keyword: p.keyword,
874            objects: objects[i],
875            attributes: attributes[i],
876            missing_required: missing_required[i],
877        })
878        .collect()
879}
880
881/// Convenience: does this report block a conforming export?
882pub fn is_conforming(report: &Report) -> bool {
883    report.count(Severity::Error) == 0
884}