1use 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#[derive(Clone, Debug)]
19pub struct ValidateOptions {
20 pub required_attributes: bool,
22 pub cardinality: bool,
24 pub references: bool,
26 pub reference_targets: bool,
28 pub class_membership: bool,
34 pub datatypes: bool,
40 pub fixed_values: bool,
42 pub mrid_conformance: bool,
44 pub deprecation: bool,
46 pub dependencies: bool,
48 pub profile_reach: bool,
51 pub headers: bool,
54 pub merge_conflicts: bool,
59 pub serializable: bool,
66 pub profiles: ProfileMask,
69 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 pub fn essential() -> ValidateOptions {
99 ValidateOptions {
100 required_attributes: false,
101 cardinality: true,
102 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 merge_conflicts: true,
116 serializable: true,
118 ..Default::default()
119 }
120 }
121
122 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
136pub fn validate(dataset: &Dataset) -> Report {
138 validate_with(dataset, &ValidateOptions::default())
139}
140
141pub fn validate_with(dataset: &Dataset, options: &ValidateOptions) -> Report {
143 let schema = dataset.schema();
144 let mut report = Report::default();
145
146 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 if options.class_membership {
243 for slot in obj.slots() {
244 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 let derived = matches!(def.kind, AttrKind::Association { .. }) && def.used_in == 0;
281 if options.required_attributes && in_scope && def.mult.is_required() && !derived {
282 let object_in_profile = obj.profiles() == 0 || obj.profiles() & def.profiles != 0;
287 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 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 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 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
428fn 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 check_compound_membership(schema, v, class, mrid, report);
459 }
460}
461
462fn 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 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
535fn 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 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 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 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
625fn 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
638fn check_profile_reach(dataset: &Dataset, report: &mut Report) {
644 let schema = dataset.schema();
645 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 .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
687fn 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
719fn 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
741fn 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
763pub 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#[derive(Clone, Debug)]
807pub struct ProfileCoverage {
808 pub profile: ProfileId,
809 pub keyword: &'static str,
810 pub objects: usize,
812 pub attributes: usize,
814 pub missing_required: usize,
816}
817
818pub 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 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 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
881pub fn is_conforming(report: &Report) -> bool {
883 report.count(Severity::Error) == 0
884}