use std::collections::BTreeMap;
use crate::dataset::Dataset;
use crate::error::{Diagnostic, Report, Rule, Severity};
use crate::header::ModelHeader;
use crate::mrid::{Mrid, MridForm};
use crate::object::Object;
use crate::schema::{AttrId, AttrKind, ProfileId, ProfileMask, Schema};
use crate::value::Value;
#[derive(Clone, Debug)]
pub struct ValidateOptions {
pub required_attributes: bool,
pub cardinality: bool,
pub references: bool,
pub reference_targets: bool,
pub class_membership: bool,
pub datatypes: bool,
pub fixed_values: bool,
pub mrid_conformance: bool,
pub deprecation: bool,
pub dependencies: bool,
pub profile_reach: bool,
pub headers: bool,
pub merge_conflicts: bool,
pub serializable: bool,
pub profiles: ProfileMask,
pub max_diagnostics: usize,
}
impl Default for ValidateOptions {
fn default() -> Self {
ValidateOptions {
required_attributes: true,
cardinality: true,
class_membership: true,
references: true,
reference_targets: true,
datatypes: true,
fixed_values: true,
mrid_conformance: true,
deprecation: false,
dependencies: true,
profile_reach: true,
headers: true,
merge_conflicts: true,
serializable: true,
profiles: 0,
max_diagnostics: 10_000,
}
}
}
impl ValidateOptions {
pub fn essential() -> ValidateOptions {
ValidateOptions {
required_attributes: false,
cardinality: true,
class_membership: true,
references: true,
reference_targets: true,
datatypes: true,
fixed_values: false,
mrid_conformance: false,
deprecation: false,
dependencies: false,
profile_reach: false,
headers: false,
merge_conflicts: true,
serializable: true,
..Default::default()
}
}
pub fn thorough() -> ValidateOptions {
ValidateOptions {
deprecation: true,
..Default::default()
}
}
pub fn for_profiles(mut self, profiles: ProfileMask) -> Self {
self.profiles = profiles;
self
}
}
pub fn validate(dataset: &Dataset) -> Report {
validate_with(dataset, &ValidateOptions::default())
}
pub fn validate_with(dataset: &Dataset, options: &ValidateOptions) -> Report {
let schema = dataset.schema();
let mut report = Report::default();
let scope = if options.profiles != 0 {
options.profiles
} else {
let declared = dataset.profiles();
if declared != 0 {
declared
} else {
ProfileMask::MAX
}
};
if options.headers {
for h in dataset.headers() {
report.extend(validate_header(h));
}
}
if options.dependencies {
check_dependencies(dataset, &mut report);
}
if options.profile_reach {
check_profile_reach(dataset, &mut report);
}
if options.merge_conflicts {
check_merge_conflicts(dataset, &mut report);
}
for (_, obj) in dataset.iter() {
if report.len() >= options.max_diagnostics {
report.push(Diagnostic::warning(
Rule::Structure,
format!(
"validation stopped after {} diagnostics",
options.max_diagnostics
),
));
break;
}
check_object(schema, dataset, obj, scope, options, &mut report);
}
report
}
fn check_object(
schema: &'static Schema,
dataset: &Dataset,
obj: &Object,
scope: ProfileMask,
options: &ValidateOptions,
report: &mut Report,
) {
let class = schema.class(obj.class());
let mrid = obj.mrid();
if options.mrid_conformance && !mrid.is_conforming() {
report.push(
Diagnostic::warning(Rule::NonConformingMrid, mrid_complaint(mrid))
.with_class(class.name)
.with_object(mrid.clone()),
);
}
if options.serializable {
check_serializable(schema, obj, class.name, mrid, report);
}
if !class.concrete {
report.push(
Diagnostic::error(
Rule::AbstractInstantiated,
format!("abstract class {} has an instance", class.name),
)
.with_class(class.name)
.with_object(mrid.clone()),
);
}
if options.deprecation && class.deprecated {
report.push(
Diagnostic::info(
Rule::Deprecated,
format!("class {} is deprecated", class.name),
)
.with_class(class.name)
.with_object(mrid.clone()),
);
}
if options.class_membership {
for slot in obj.slots() {
check_compound_membership(schema, &slot.value, class.name, mrid, report);
let def = schema.attr(slot.attr);
if !schema.is_a(obj.class(), def.owner) {
report.push(
Diagnostic::error(
Rule::UnknownAttribute,
format!(
"{} is declared on {} and cannot be stored on a {}; it would be \
dropped on export",
def.name,
schema.class(def.owner).name,
class.name
),
)
.with_class(class.name)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
}
}
for attr_id in class.all_attrs {
let def = schema.attr(*attr_id);
let in_scope = def.profiles & scope != 0;
let count = obj.count(*attr_id) as u32;
if count == 0 {
let derived = matches!(def.kind, AttrKind::Association { .. }) && def.used_in == 0;
if options.required_attributes && in_scope && def.mult.is_required() && !derived {
let object_in_profile = obj.profiles() == 0 || obj.profiles() & def.profiles != 0;
let defining = class.defined_in & class.concrete_in;
let definition_loaded = defining & scope != 0;
if object_in_profile && definition_loaded {
report.push(
Diagnostic::error(
Rule::MissingRequired,
format!("required attribute {} is missing", def.name),
)
.with_class(class.name)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
}
continue;
}
if options.cardinality && count > def.mult.max() {
report.push(
Diagnostic::error(
Rule::CardinalityExceeded,
format!(
"{} occurs {} times but permits at most {}",
def.name,
count,
def.mult.max()
),
)
.with_class(class.name)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
if options.cardinality && in_scope && count < def.mult.min() && count > 0 {
report.push(
Diagnostic::error(
Rule::MissingRequired,
format!(
"{} occurs {} times but requires at least {}",
def.name,
count,
def.mult.min()
),
)
.with_class(class.name)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
if options.datatypes || options.fixed_values {
for slot in obj.get_all(*attr_id) {
check_value(
schema,
&slot.value,
*attr_id,
class.name,
mrid,
options,
report,
);
}
}
if options.deprecation && def.deprecated {
report.push(
Diagnostic::info(
Rule::Deprecated,
format!("attribute {} is deprecated", def.name),
)
.with_class(class.name)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
if let AttrKind::Association { target, .. } = def.kind {
for slot in obj.get_all(*attr_id) {
let Value::Reference(m) = &slot.value else {
continue;
};
match dataset.by_mrid(m) {
None => {
if options.references {
report.push(
Diagnostic::warning(
Rule::DanglingReference,
format!(
"{} points at {} which is not in the dataset",
def.name,
m.canonical()
),
)
.with_class(class.name)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
}
Some(t) => {
let compatible =
schema.is_a(t.class(), target) || schema.is_a(target, t.class());
if options.reference_targets && !compatible {
report.push(
Diagnostic::error(
Rule::WrongReferenceTarget,
format!(
"{} must point at {} but {} is a {}",
def.name,
schema.class(target).name,
m.canonical(),
schema.class(t.class()).name
),
)
.with_class(class.name)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
}
}
}
}
}
}
fn check_compound_membership(
schema: &'static Schema,
value: &Value,
class: &'static str,
mrid: &Mrid,
report: &mut Report,
) {
let Value::Compound(c) = value else { return };
for (attr, v) in c.values() {
let def = schema.attr(*attr);
if !schema.is_a(c.class(), def.owner) {
report.push(
Diagnostic::error(
Rule::UnknownAttribute,
format!(
"{} is declared on {} and cannot be stored on a {} compound; it \
would be written into the document anyway, which no consumer of \
that profile will accept",
def.name,
schema.class(def.owner).name,
schema.class(c.class()).name
),
)
.with_class(class)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
check_compound_membership(schema, v, class, mrid, report);
}
}
fn check_serializable(
schema: &'static Schema,
obj: &Object,
class: &'static str,
mrid: &Mrid,
report: &mut Report,
) {
use crate::xml::{IdentifierForm, describe_char, find_illegal};
if mrid.form_in_xml() == IdentifierForm::Unwritable {
report.push(
Diagnostic::error(
Rule::UnserializableIdentifier,
format!(
"identifier {:?} is neither an XML NCName nor an absolute IRI, so it has \
no valid rdf:ID or rdf:about form; the document written will be \
well-formed XML but not valid RDF/XML",
mrid.as_written()
),
)
.with_class(class)
.with_object(mrid.clone()),
);
}
fn scan(
schema: &'static Schema,
value: &Value,
attr: AttrId,
class: &'static str,
mrid: &Mrid,
report: &mut Report,
) {
match value {
Value::Text(s) => {
if let Some((offset, c)) = find_illegal(s) {
let def = schema.attr(attr);
report.push(
Diagnostic::error(
Rule::IllegalXmlCharacter,
format!(
"{} holds {}, which XML 1.0 cannot represent in any form; it \
will be dropped on export (first at byte {offset} of the value)",
def.name,
describe_char(c)
),
)
.with_class(class)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
}
Value::Compound(c) => {
for (a, v) in c.values() {
scan(schema, v, *a, class, mrid, report);
}
}
_ => {}
}
}
for slot in obj.slots() {
scan(schema, &slot.value, slot.attr, class, mrid, report);
}
}
fn check_value(
schema: &'static Schema,
value: &Value,
attr: AttrId,
class: &'static str,
mrid: &Mrid,
options: &ValidateOptions,
report: &mut Report,
) {
let def = schema.attr(attr);
let mut mismatch = |expected: &str, found: &str| {
report.push(
Diagnostic::error(
Rule::DatatypeMismatch,
format!("{} expects {expected} but holds {found}", def.name),
)
.with_class(class)
.with_object(mrid.clone())
.with_attribute(def.name),
);
};
if options.datatypes {
match def.kind {
AttrKind::Primitive(p) => {
if let Some(found) = primitive_mismatch(p, value) {
mismatch(&format!("{p:?}"), found);
}
}
AttrKind::Datatype(dt) => {
let p = schema.datatype(dt).value;
if let Some(found) = primitive_mismatch(p, value) {
mismatch(&format!("{} ({p:?})", schema.datatype(dt).name), found);
}
}
AttrKind::Enumeration(want) => match value {
Value::Enum(v) if schema.enum_value(*v).owner != want => mismatch(
schema.enumeration(want).name,
schema.enumeration(schema.enum_value(*v).owner).name,
),
Value::Enum(_) => {}
other => mismatch(schema.enumeration(want).name, shape_of(other)),
},
AttrKind::Association { .. } => {
if !matches!(value, Value::Reference(_)) {
mismatch("a reference", shape_of(value));
}
}
AttrKind::Compound(want) => match value {
Value::Compound(c) if c.class() != want => {
mismatch(schema.class(want).name, schema.class(c.class()).name)
}
Value::Compound(c) => {
for (a, v) in c.values() {
check_value(schema, v, *a, class, mrid, options, report);
}
}
other => mismatch(schema.class(want).name, shape_of(other)),
},
}
}
if options.fixed_values
&& let Some(fixed) = def.fixed
{
let actual = crate::value::display_value(schema, value);
if actual != fixed && !actual.is_empty() {
report.push(
Diagnostic::warning(
Rule::FixedValueMismatch,
format!("{} is fixed to {fixed:?} but holds {actual:?}", def.name),
)
.with_class(class)
.with_object(mrid.clone())
.with_attribute(def.name),
);
}
}
}
fn primitive_mismatch(p: crate::schema::Primitive, value: &Value) -> Option<&'static str> {
(!value.fits(p)).then(|| value.shape())
}
fn shape_of(v: &Value) -> &'static str {
v.shape()
}
fn check_profile_reach(dataset: &Dataset, report: &mut Report) {
let schema = dataset.schema();
let mut undeclared: BTreeMap<AttrId, (usize, Mrid)> = BTreeMap::new();
for (_, obj) in dataset.iter() {
for slot in obj.slots() {
if !schema.declaration_covers(slot.attr, slot.profiles) {
let entry = undeclared
.entry(slot.attr)
.or_insert_with(|| (0, obj.mrid().clone()));
entry.0 += 1;
}
}
}
for (attr, (count, example)) in undeclared {
let def = schema.attr(attr);
let profiles: Vec<&str> = schema
.profiles
.iter()
.enumerate()
.filter(|(i, _)| def.used_in & ProfileId(*i as u16).mask() != 0)
.map(|(_, p)| p.keyword)
.collect();
report.push(
Diagnostic::warning(
Rule::AttributeNotInProfile,
format!(
"{} is set on {count} object(s) by files whose header does not declare \
profile(s) {}, which is where the schema puts it",
def.name,
profiles.join("+")
),
)
.with_class(schema.class(def.owner).name)
.with_object(example)
.with_attribute(def.name),
);
}
}
fn check_merge_conflicts(dataset: &Dataset, report: &mut Report) {
let schema = dataset.schema();
for c in dataset.merge_conflicts() {
let def = schema.attr(c.attr);
report.push(
Diagnostic::warning(
Rule::ConflictingValue,
format!(
"{} was given {} by one file and {} by another; the later value is kept",
def.name,
crate::value::display_value(schema, &c.discarded),
crate::value::display_value(schema, &c.kept),
),
)
.with_class(schema.class(def.owner).name)
.with_object(c.object.clone())
.with_attribute(def.name),
);
}
let dropped = dataset.merge_conflicts_dropped();
if dropped > 0 {
report.push(Diagnostic::warning(
Rule::ConflictingValue,
format!("{dropped} further conflicting value(s) were counted but not recorded"),
));
}
}
fn check_dependencies(dataset: &Dataset, report: &mut Report) {
let loaded: Vec<&Mrid> = dataset
.headers()
.iter()
.filter_map(|h| h.id.as_ref())
.collect();
for h in dataset.headers() {
for dep in &h.dependent_on {
if !loaded.contains(&dep) {
report.push(
Diagnostic::warning(
Rule::UnsatisfiedDependency,
format!("model depends on {} which was not loaded", dep.canonical()),
)
.with_source(h.source.clone().unwrap_or_else(|| "<header>".into())),
);
}
}
}
}
fn mrid_complaint(mrid: &Mrid) -> String {
match mrid.form() {
MridForm::Uuid => format!("identifier {:?} conforms", mrid.canonical()),
MridForm::Compact => format!(
"identifier {:?} is a UUID written without hyphens; IEC 61970-552 requires \
the {:?} form",
mrid.as_written(),
mrid.canonical()
),
MridForm::Opaque => format!(
"identifier {:?} is not a UUID, which IEC 61970-552 requires",
mrid.canonical()
),
}
}
pub fn validate_header(header: &ModelHeader) -> Report {
let mut report = Report::default();
let src = header.source.clone().unwrap_or_else(|| "<header>".into());
if header.id.is_none() {
report.push(
Diagnostic::error(Rule::MalformedHeader, "header has no rdf:about identifier")
.with_source(src.clone()),
);
} else if let Some(id) = &header.id
&& !id.is_conforming()
{
report.push(
Diagnostic::warning(
Rule::MalformedHeader,
format!("header identifier: {}", mrid_complaint(id)),
)
.with_source(src.clone()),
);
}
if header.profiles.is_empty() {
report.push(
Diagnostic::error(Rule::MalformedHeader, "header declares no md:Model.profile")
.with_source(src.clone()),
);
}
if header.scenario_time.is_none() {
report.push(
Diagnostic::warning(Rule::MalformedHeader, "header has no md:Model.scenarioTime")
.with_source(src.clone()),
);
}
if header.created.is_none() {
report.push(
Diagnostic::warning(Rule::MalformedHeader, "header has no md:Model.created")
.with_source(src),
);
}
report
}
#[derive(Clone, Debug)]
pub struct ProfileCoverage {
pub profile: ProfileId,
pub keyword: &'static str,
pub objects: usize,
pub attributes: usize,
pub missing_required: usize,
}
pub fn profile_coverage(dataset: &Dataset) -> Vec<ProfileCoverage> {
let schema = dataset.schema();
let n = schema.profiles.len();
let mut objects = vec![0usize; n];
let mut attributes = vec![0usize; n];
let mut missing_required = vec![0usize; n];
for (_, obj) in dataset.iter() {
let class = schema.class(obj.class());
let mut touched: ProfileMask = 0;
for attr_id in class.all_attrs {
let def = schema.attr(*attr_id);
let slots = obj.get_all(*attr_id);
if slots.is_empty() {
if def.mult.is_required() {
for (i, missing) in missing_required.iter_mut().enumerate() {
let mask = ProfileId(i as u16).mask();
if class.profiles & mask != 0 && def.used_in & mask != 0 {
*missing += 1;
}
}
}
continue;
}
for s in slots {
let effective = schema.effective_profiles(s.attr, s.profiles);
for (i, count) in attributes.iter_mut().enumerate() {
let mask = ProfileId(i as u16).mask();
if effective & mask != 0 && class.profiles & mask != 0 {
*count += 1;
touched |= mask;
}
}
}
}
for (i, count) in objects.iter_mut().enumerate() {
if touched & ProfileId(i as u16).mask() != 0 {
*count += 1;
}
}
}
schema
.profiles
.iter()
.enumerate()
.map(|(i, p)| ProfileCoverage {
profile: ProfileId(i as u16),
keyword: p.keyword,
objects: objects[i],
attributes: attributes[i],
missing_required: missing_required[i],
})
.collect()
}
pub fn is_conforming(report: &Report) -> bool {
report.count(Severity::Error) == 0
}