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