Skip to main content

cimvalidation/
bag.rs

1//! Validates a dataset against a [`crate::shapes`] table.
2//!
3//! It replaced generated per-check validators that read typed struct fields.
4//! Here every value is the string the XML carried, so the checks those treated
5//! as tautologies — `sh:datatype`, `sh:nodeKind` — are real, and `sh:closed`
6//! becomes answerable at all.
7//!
8//! Which elements a run reads is a [`Source`]: each family's shapes read that
9//! family's elements. Every element holds every field the XML carried, which
10//! is what lets one interpreter serve both.
11
12use cimmodel::base::{FastMap, FastSet, FieldMap, FieldValue};
13use cimmodel::{CimDataset, Element};
14
15use crate::helpers;
16use crate::par::{par_concat, par_map, runs, threads_for};
17use crate::shapes::{
18    AltBranch, Branch, Check, ClosedShape, Constraint, Logic, LogicOp, NodeKind, Path, PropShape,
19    ShapeDef, Step, Target,
20};
21use crate::{Config, Violation};
22
23/// Maps a referenced mRID back to the elements pointing at it.
24///
25/// `sh:inversePath` asks "how many things point at me", which the forward
26/// fields cannot answer. Built once per call in O(associations) rather than
27/// rescanned per shape, and only over the fields some active shape asks about.
28///
29/// A plain inverse path needs only the count; an inverse step inside a
30/// [`Path::Chain`] has to continue from the elements themselves, so those
31/// fields keep the list. Keys borrow from the dataset: an owned key cost an
32/// allocation per reference at build time and another per lookup.
33#[derive(Default)]
34struct ReverseIndex<'a> {
35    /// `(target mrid, field key)` → how many elements point at it that way.
36    counts: FastMap<(&'a str, &'static str), u32>,
37    /// `(target mrid, field key)` → the elements pointing at it that way.
38    sources: FastMap<(&'a str, &'static str), Vec<&'a str>>,
39}
40
41impl<'a> ReverseIndex<'a> {
42    fn count(&self, mrid: &str, field: &'static str) -> u32 {
43        self.counts.get(&(mrid, field)).copied().unwrap_or(0)
44    }
45
46    fn sources<'s>(&'s self, mrid: &'a str, field: &'static str) -> &'s [&'a str] {
47        self.sources.get(&(mrid, field)).map_or(&[], Vec::as_slice)
48    }
49}
50
51/// Everything a check needs besides the element itself.
52struct Ctx<'a> {
53    ds: &'a CimDataset,
54    /// The other files validated with `ds`, read only for the type of an
55    /// object `ds` does not hold, and only by NC shapes ([`any_type`]).
56    set: &'a [CimDataset],
57    source: Source,
58    reverse: ReverseIndex<'a>,
59}
60
61/// What a [`Path::Chain`] collected.
62#[derive(Clone, Copy, PartialEq, Eq)]
63enum Kind {
64    Text,
65    Refs,
66}
67
68/// The values a path yields for one element, as far as a constraint needs them.
69enum Values<'a> {
70    /// Literal text values. A slice of the stored field, so a single value
71    /// costs no allocation — this runs once per property per target.
72    Text(&'a [String]),
73    /// `rdf:resource` references.
74    Refs(&'a [String]),
75    /// Only a count is available — an inverse or alternative path.
76    Count(u32),
77    Absent,
78    /// The end of a [`Path::Chain`]. Owned, because a chain gathers values
79    /// from several elements.
80    Chain(Kind, Vec<&'a str>),
81    /// A chain stepped onto an element this dataset does not hold. What lies
82    /// beyond is not known, so nothing can be said about it either way.
83    Unknown,
84}
85
86impl<'a> Values<'a> {
87    /// `None` when unknown: no cardinality can be asserted.
88    fn count(&self) -> Option<u32> {
89        Some(match self {
90            Values::Text(v) | Values::Refs(v) => v.len() as u32,
91            Values::Count(n) => *n,
92            Values::Absent => 0,
93            Values::Chain(_, v) => v.len() as u32,
94            Values::Unknown => return None,
95        })
96    }
97
98    /// Does `f` hold for any literal value?
99    fn any_text(&self, mut f: impl FnMut(&str) -> bool) -> bool {
100        match self {
101            Values::Text(vs) => vs.iter().any(|v| f(v)),
102            Values::Chain(Kind::Text, vs) => vs.iter().any(|v| f(v)),
103            _ => false,
104        }
105    }
106
107    /// Does `f` hold for any referenced mRID?
108    fn any_ref(&self, mut f: impl FnMut(&str) -> bool) -> bool {
109        match self {
110            Values::Refs(vs) => vs.iter().any(|v| f(v)),
111            Values::Chain(Kind::Refs, vs) => vs.iter().any(|v| f(v)),
112            _ => false,
113        }
114    }
115
116    fn is_text(&self) -> bool {
117        matches!(self, Values::Text(_) | Values::Chain(Kind::Text, _))
118    }
119
120    fn is_refs(&self) -> bool {
121        matches!(self, Values::Refs(_) | Values::Chain(Kind::Refs, _))
122    }
123}
124
125type Fields = FieldMap;
126
127/// Which elements a shape table reads: its own family's.
128///
129/// Not a convenience — the families' shapes would otherwise reach each other's
130/// elements. NC has `sh:targetSubjectsOf` shapes on `IdentifiedObject.name`,
131/// so reading typed elements would make every named CGMES element in a mixed
132/// dataset an NC target; and an inverse-path count would include references
133/// from the other family.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum Source {
136    /// Network Code profile elements (`nc:` classes).
137    Nc,
138    /// CGMES elements.
139    Cgmes,
140}
141
142impl Source {
143    /// The element's fields, or `None` if it is another family's.
144    fn fields(self, entry: &Element) -> Option<&Fields> {
145        self.owns(entry).then(|| entry.fields())
146    }
147
148    /// Whether `entry` belongs to this source's family. Families are told
149    /// apart by their class names: NC's carry the `nc:` prefix.
150    fn owns(self, entry: &Element) -> bool {
151        entry.type_name().starts_with("nc:") == (self == Source::Nc)
152    }
153}
154
155fn refs_of<'a>(f: &'a Fields, field: &str) -> &'a [String] {
156    match f.get(field) {
157        Some(FieldValue::Resource(s)) => std::slice::from_ref(s),
158        Some(FieldValue::ResourceList(v)) => v.as_slice(),
159        _ => &[],
160    }
161}
162
163fn field_values<'a>(f: &'a Fields, field: &str) -> Values<'a> {
164    match f.get(field) {
165        Some(FieldValue::Text(s)) => Values::Text(std::slice::from_ref(s)),
166        Some(FieldValue::TextList(v)) => Values::Text(v.as_slice()),
167        Some(FieldValue::Resource(_)) | Some(FieldValue::ResourceList(_)) => {
168            Values::Refs(refs_of(f, field))
169        }
170        None => Values::Absent,
171    }
172}
173
174/// A numeric value, or `None` if it does not parse — a typed numeric field
175/// that failed to parse is `None` and skipped the same way.
176fn number(v: &str) -> Option<f64> {
177    v.trim().parse::<f64>().ok()
178}
179
180fn resolve<'a>(ctx: &Ctx<'a>, el: &'a Fields, mrid: &'a str, path: &Path) -> Values<'a> {
181    match path {
182        Path::Forward(field) => field_values(el, field),
183        // `( X.y rdf:type )`: what the general walk below yields for it — the
184        // field's references, or its literal — without the allocations.
185        Path::Chain([Step::Forward(field), Step::Type]) => field_values(el, field),
186        Path::Inverse(field) => Values::Count(ctx.reverse.count(mrid, field)),
187        Path::Alternative(branches) => {
188            // The union across branches. Only the count is well defined: the
189            // branches can mix literals, references and inverse hops, and every
190            // NCP alternative shape asks a cardinality question.
191            let mut total = 0;
192            for b in *branches {
193                total += match b {
194                    AltBranch::Forward(field) => field_values(el, field).count().unwrap_or(0),
195                    AltBranch::Inverse(field) => ctx.reverse.count(mrid, field),
196                };
197            }
198            Values::Count(total)
199        }
200        Path::Chain(steps) => chain(ctx, el, mrid, steps),
201    }
202}
203
204/// Walk a sequence path from `mrid`.
205///
206/// Every element stepped *from* must be in the dataset and of this source,
207/// since its fields are read; otherwise the result is [`Values::Unknown`]. An
208/// inverse step never needs that — the reverse index holds what points here,
209/// and neither does a final `rdf:type` step. A literal reached before the last
210/// step ends that branch of the walk, unless `rdf:type` follows: then it is
211/// the value, the way a one-step path would report it.
212fn chain<'a>(ctx: &Ctx<'a>, focus: &'a Fields, mrid: &'a str, steps: &[Step]) -> Values<'a> {
213    let mut nodes: Vec<&'a str> = vec![mrid];
214    for (i, step) in steps.iter().enumerate() {
215        let last = i + 1 == steps.len();
216        match step {
217            Step::Forward(field) => {
218                let mut next: Vec<&'a str> = Vec::new();
219                let mut texts: Vec<&'a str> = Vec::new();
220                for &node in &nodes {
221                    let fields = if node == mrid {
222                        focus
223                    } else {
224                        match ctx.ds.entries.get(node).and_then(|e| ctx.source.fields(e)) {
225                            Some(f) => f,
226                            None => return Values::Unknown,
227                        }
228                    };
229                    match fields.get(*field) {
230                        Some(FieldValue::Text(s)) => texts.push(s),
231                        Some(FieldValue::TextList(v)) => texts.extend(v.iter().map(String::as_str)),
232                        Some(FieldValue::Resource(r)) => next.push(r),
233                        Some(FieldValue::ResourceList(v)) => {
234                            next.extend(v.iter().map(String::as_str))
235                        }
236                        None => {}
237                    }
238                }
239                // A literal where the path continues to rdf:type is reported
240                // as the literal it is, so `sh:nodeKind sh:IRI` can flag it.
241                let before_type = matches!(steps.get(i + 1), Some(Step::Type));
242                if (last || before_type) && !texts.is_empty() {
243                    return Values::Chain(Kind::Text, texts);
244                }
245                if last {
246                    return Values::Chain(Kind::Refs, next);
247                }
248                nodes = next;
249            }
250            Step::Inverse(field) => {
251                let next: Vec<&'a str> = nodes
252                    .iter()
253                    .flat_map(|n| ctx.reverse.sources(n, field).iter().copied())
254                    .collect();
255                if last {
256                    return Values::Chain(Kind::Refs, next);
257                }
258                nodes = next;
259            }
260            // The values are the elements reached. Nothing is read from them,
261            // so they count even when absent; the class constraints a type
262            // path carries look up the ones that are present.
263            Step::Type => return Values::Chain(Kind::Refs, nodes),
264        }
265    }
266    Values::Chain(Kind::Refs, nodes)
267}
268
269/// Is `s` a valid lexical form of this xsd type?
270///
271/// The whole reason `sh:datatype` is worth checking here: a bag holds the text
272/// as written, so a malformed integer survives decoding.
273fn datatype_ok(s: &str, xsd: &str) -> bool {
274    let t = s.trim();
275    match xsd {
276        "string" | "normalizedString" | "token" | "Name" | "NCName" | "language" => true,
277        "boolean" => matches!(t, "true" | "false" | "1" | "0"),
278        "integer" | "int" | "long" | "short" | "byte" | "nonPositiveInteger"
279        | "negativeInteger" => t.parse::<i64>().is_ok(),
280        "nonNegativeInteger" | "positiveInteger" | "unsignedInt" | "unsignedLong"
281        | "unsignedShort" | "unsignedByte" => t.parse::<u64>().is_ok(),
282        "decimal" | "float" | "double" => t.parse::<f64>().is_ok(),
283        "dateTime" | "dateTimeStamp" => helpers::is_xsd_datetime(t),
284        "date" => helpers::is_xsd_date(t),
285        "gMonthDay" => helpers::is_xsd_gmonthday(t),
286        "anyURI" => helpers::is_xsd_anyuri(t),
287        // An xsd type this does not model is not evidence of a violation.
288        _ => true,
289    }
290}
291
292fn violation(mrid: &str, class: &str, property: &str, c: &Check) -> Violation {
293    Violation {
294        object_id: mrid.to_string(),
295        rule_id: c.rule_id.to_string(),
296        class: class.to_string(),
297        property: property.to_string(),
298        message: c.message.to_string(),
299        severity: c.severity.to_string(),
300        name: c.name.to_string(),
301        description: c.description.to_string(),
302    }
303}
304
305/// A path's field key, for the `property` column of a violation: the property
306/// of the focus element the path starts from.
307fn path_label(path: &Path) -> std::borrow::Cow<'static, str> {
308    use std::borrow::Cow;
309    // An inverse step reads as SHACL writes it: `^Terminal.ConductingEquipment`
310    // on a Switch means the terminals pointing at it, not an attribute of its own.
311    let inverse = |f: &str| Cow::Owned(format!("^{f}"));
312    match path {
313        Path::Forward(f) => Cow::Borrowed(f),
314        Path::Inverse(f) => inverse(f),
315        Path::Alternative(branches) => match branches.first() {
316            Some(AltBranch::Forward(f)) => Cow::Borrowed(f),
317            Some(AltBranch::Inverse(f)) => inverse(f),
318            None => Cow::Borrowed(""),
319        },
320        Path::Chain(steps) => match steps.first() {
321            Some(Step::Forward(f)) => Cow::Borrowed(f),
322            Some(Step::Inverse(f)) => inverse(f),
323            _ => Cow::Borrowed(""),
324        },
325    }
326}
327
328/// Does any type of the referenced object `mrid` satisfy `test`? `None`
329/// when it is not found.
330///
331/// The types are those of `ds`'s element when it has one. Otherwise, for NC,
332/// every type the set's other files give it, as their merge would; for CGMES
333/// the check is silent.
334///
335/// The families' value types are written differently. NCP's list every class
336/// the association may reach in any namespace (`ps:PowerSchedule.GeneratingUnit`
337/// names the CGMES, CIM16, CIM17 and NC units), since the target is never in
338/// the referring file — a schedule points into EQ, a remedial action into
339/// another dataset. CGMES's per-profile files list only the classes of their
340/// own profile (`sv:SvStatus.ConductingEquipment` the two converters,
341/// `dl:DiagramObject.IdentifiedObject` the diagram classes): they hold on one
342/// file, where an EQ object has no type, and the cross-profile files
343/// (`sv456cpe:SvStatus.ConductingEquipment-valueType`, `sh:class
344/// ConductingEquipment`) check the type on the merged dataset. Read across
345/// the set, the CGMES ones failed some 31,000 times on the ENTSO-E test
346/// configurations, every association into EQ. An object no file holds is a
347/// dangling reference, which a cross-profile rule reports.
348fn any_type(
349    ctx: &Ctx<'_>,
350    mrid: &str,
351    test: impl Fn(&cimmodel::base::ClassDef) -> bool,
352) -> Option<bool> {
353    if let Some(e) = ctx.ds.entries.get(mrid) {
354        return Some(e.types().any(test));
355    }
356    if ctx.source != Source::Nc {
357        return None;
358    }
359    let mut held = false;
360    for e in ctx.set.iter().filter_map(|d| d.entries.get(mrid)) {
361        held = true;
362        if e.types().any(&test) {
363            return Some(true);
364        }
365    }
366    held.then_some(false)
367}
368
369/// Does `values` violate `constraint`? Unknown values violate nothing.
370fn fails(ctx: &Ctx<'_>, el: &Fields, values: &Values<'_>, constraint: &Constraint) -> bool {
371    if matches!(values, Values::Unknown) {
372        return false;
373    }
374    match constraint {
375        Constraint::MinCount(n) => values.count().is_some_and(|c| c < *n),
376        Constraint::MaxCount(n) => values.count().is_some_and(|c| c > *n),
377
378        // A literal constraint on a reference is a node-kind problem, which
379        // the shape's own sh:nodeKind check reports. Flagging it twice would
380        // double-count one mistake.
381        Constraint::Datatype(xsd) => values.any_text(|v| !datatype_ok(v, xsd)),
382
383        // An inverse or alternative path yields only a count, so there is no
384        // node to inspect.
385        Constraint::NodeKind(kind) => match kind {
386            NodeKind::Literal => values.is_refs() && values.count() != Some(0),
387            NodeKind::Iri => values.is_text() && values.count() != Some(0),
388            // A reference decodes the same whether the XML wrote an IRI or a
389            // blank node, so only a literal is certainly not one.
390            NodeKind::BlankNode => values.is_text() && values.count() != Some(0),
391        },
392
393        Constraint::In(allowed) => {
394            values.any_text(|v| !allowed.contains(&v.trim()))
395                || values.any_ref(|r| !allowed.contains(&r))
396        }
397        Constraint::HasValue(want) => match values {
398            v if v.is_text() => !v.any_text(|t| t.trim() == *want),
399            v if v.is_refs() => !v.any_ref(|r| r == *want),
400            _ => false,
401        },
402
403        Constraint::MaxLength(n) => values.any_text(|v| v.chars().count() as u32 > *n),
404        Constraint::MinLength(n) => values.any_text(|v| (v.chars().count() as u32) < *n),
405        Constraint::Length(n) => values.any_text(|v| v.chars().count() as u32 != *n),
406
407        // An element merged from files that typed it differently has several
408        // types (`Element::types`). `sh:class` needs one of them to be an
409        // instance; `sh:in` on an `rdf:type` path tests each type, as each is
410        // a value of the path — a type outside the list fails it.
411        Constraint::Class(allowed) => {
412            values.any_ref(|r| any_type(ctx, r, |t| allowed.contains(&t.qualified)) == Some(false))
413        }
414        Constraint::RefClass(allowed) => {
415            values.any_ref(|r| any_type(ctx, r, |t| !allowed.contains(&t.qualified)) == Some(true))
416        }
417        Constraint::NotClass(forbidden) => {
418            values.any_ref(|r| any_type(ctx, r, |t| forbidden.contains(&t.qualified)) == Some(true))
419        }
420        Constraint::QualifiedIn { allowed, min } => {
421            let mut n = 0u32;
422            values.any_text(|v| {
423                n += u32::from(allowed.contains(&v.trim()));
424                false
425            });
426            values.any_ref(|r| {
427                n += u32::from(allowed.contains(&r));
428                false
429            });
430            n < *min
431        }
432
433        Constraint::MinInclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x < *b)),
434        Constraint::MaxInclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x > *b)),
435        Constraint::MinExclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x <= *b)),
436        Constraint::MaxExclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x >= *b)),
437
438        // Every pairing of this property's values with the other's, as SHACL
439        // defines it. Silent unless both sides are present.
440        Constraint::LessThan(other) => pair(values, el, other, |a, b| a < b),
441        Constraint::LessThanOrEquals(other) => pair(values, el, other, |a, b| a <= b),
442    }
443}
444
445/// `IdentifiedObject.mRID`'s field key.
446const MRID: &str = "IdentifiedObject.mRID";
447
448/// Is `prop` an mRID cardinality the element need not meet here?
449///
450/// A CGMES object's mRID is exchanged where the object is defined
451/// (`rdf:ID`), not in the files that only add to it (`rdf:about`). The SSH
452/// SHACL nevertheless requires one on its `ssh:Equipment` shape, so every
453/// SSH file that writes `inService` under `cim:Equipment` — the ENTSO-E
454/// MicroGrid and Svedala among them — fails it once per piece of equipment.
455/// Only the minimum is skipped. NC objects are defined with `rdf:about`, so
456/// this never applies to them.
457fn mrid_exempt(t: &Resolved<'_>, prop: &PropShape) -> bool {
458    t.described && prop.path == Path::Forward(MRID)
459}
460
461fn check_prop<'a>(
462    ctx: &Ctx<'a>,
463    el: &'a Fields,
464    class: &str,
465    mrid: &'a str,
466    prop: &PropShape,
467    no_min: bool,
468    out: &mut Vec<Violation>,
469) {
470    let values = resolve(ctx, el, mrid, &prop.path);
471    for c in prop.checks {
472        if no_min && matches!(c.constraint, Constraint::MinCount(_)) {
473            continue;
474        }
475        if fails(ctx, el, &values, &c.constraint) {
476            out.push(violation(mrid, class, &path_label(&prop.path), c));
477        }
478    }
479}
480
481/// Does a [`Logic`] branch conform? `None` when a path in it left the
482/// dataset, so its conformance is not known.
483fn branch_conforms<'a>(
484    ctx: &Ctx<'a>,
485    el: &'a Fields,
486    mrid: &'a str,
487    branch: &Branch,
488) -> Option<bool> {
489    let mut holds = true;
490    for prop in branch.props {
491        let values = resolve(ctx, el, mrid, &prop.path);
492        if matches!(values, Values::Unknown) {
493            return None;
494        }
495        if prop
496            .checks
497            .iter()
498            .any(|c| fails(ctx, el, &values, &c.constraint))
499        {
500            holds = false;
501            break;
502        }
503    }
504    Some(holds != branch.negate)
505}
506
507/// Node-level `sh:and` / `sh:or` / `sh:xone`. Reported with the node shape's
508/// name as the property, which is what the generated validators report.
509fn check_logic<'a>(
510    ctx: &Ctx<'a>,
511    el: &'a Fields,
512    class: &str,
513    mrid: &'a str,
514    logic: &Logic,
515    out: &mut Vec<Violation>,
516) {
517    let mut conforming = 0usize;
518    for branch in logic.branches {
519        match branch_conforms(ctx, el, mrid, branch) {
520            Some(true) => conforming += 1,
521            Some(false) => {}
522            // An unknown branch could tip any of the three either way.
523            None => return,
524        }
525    }
526    let holds = match logic.op {
527        LogicOp::And => conforming == logic.branches.len(),
528        LogicOp::Or => conforming >= 1,
529        LogicOp::Xone => conforming == 1,
530    };
531    if !holds {
532        out.push(Violation {
533            object_id: mrid.to_string(),
534            rule_id: logic.rule_id.to_string(),
535            class: class.to_string(),
536            property: logic.name.to_string(),
537            message: logic.message.to_string(),
538            severity: logic.severity.to_string(),
539            name: logic.name.to_string(),
540            description: logic.description.to_string(),
541        });
542    }
543}
544
545/// Does any pairing of this property's numbers with `other`'s fail `holds`?
546fn pair(values: &Values, el: &Fields, other: &str, holds: impl Fn(f64, f64) -> bool) -> bool {
547    let others = field_values(el, other);
548    values.any_text(|a| {
549        number(a).is_some_and(|a| others.any_text(|b| number(b).is_some_and(|b| !holds(a, b))))
550    })
551}
552
553/// `sh:closed` — report every field the profile does not allow on this class.
554fn check_closed(
555    el: &Fields,
556    class: &str,
557    mrid: &str,
558    closed: &ClosedShape,
559    out: &mut Vec<Violation>,
560) {
561    let mut extra: Vec<&str> = el
562        .keys()
563        .copied()
564        .filter(|k| !closed.allowed.contains(k))
565        .collect();
566    // Deterministic order: HashMap iteration is not, and a violation list that
567    // reorders between runs is unusable in a diff.
568    extra.sort_unstable();
569
570    for field in extra {
571        out.push(Violation {
572            object_id: mrid.to_string(),
573            rule_id: closed.rule_id.to_string(),
574            class: class.to_string(),
575            property: field.to_string(),
576            message: closed.message.to_string(),
577            severity: closed.severity.to_string(),
578            name: closed.name.to_string(),
579            description: closed.description.to_string(),
580        });
581    }
582}
583
584/// A target element, resolved once per call: its mRID, its class, the
585/// fields it is read through, and whether it is a CGMES object no file
586/// defined ([`mrid_exempt`]).
587#[derive(Clone, Copy)]
588struct Resolved<'a> {
589    mrid: &'a String,
590    class: &'static str,
591    fields: &'a Fields,
592    described: bool,
593}
594
595impl<'a> Resolved<'a> {
596    fn new(source: Source, mrid: &'a String, entry: &'a Element, fields: &'a Fields) -> Self {
597        let described = source == Source::Cgmes && !entry.defined();
598        Resolved {
599            mrid,
600            class: entry.type_name(),
601            fields,
602            described,
603        }
604    }
605}
606
607/// Resolve `mrid` for `source`: `None` when it is missing or another family's
608/// element — e.g. a CGMES element under an NC shape, whose attributes that
609/// family does not define and would report as absent.
610fn resolve_target<'a>(
611    ds: &'a CimDataset,
612    source: Source,
613    mrid: &'a String,
614) -> Option<Resolved<'a>> {
615    let entry = ds.entries.get(mrid)?;
616    let fields = source.fields(entry)?;
617    Some(Resolved::new(source, mrid, entry, fields))
618}
619
620/// The reverse index and the `sh:targetSubjectsOf` index, built in one pass.
621///
622/// Both need a walk over every element, and that walk — random access into a
623/// map of every element, then into each one's fields — was most of their
624/// cost; one pass does it once. Only fields some active shape asks about are
625/// indexed, and nothing is scanned when no shape asks.
626///
627/// `sh:targetSubjectsOf` has no `by_type` to answer it, and scanning per shape
628/// is O(elements x shapes): on a 20k-element dataset that cost 10 ms for a
629/// profile whose shapes matched nothing.
630fn build_indexes<'a>(
631    ds: &'a CimDataset,
632    source: Source,
633    count_fields: &[&'static str],
634    list_fields: &[&'static str],
635    subject_fields: &[&'static str],
636) -> (ReverseIndex<'a>, FastMap<&'static str, Vec<Resolved<'a>>>) {
637    if count_fields.is_empty() && list_fields.is_empty() && subject_fields.is_empty() {
638        return (ReverseIndex::default(), FastMap::default());
639    }
640    type Partial<'a> = (ReverseIndex<'a>, FastMap<&'static str, Vec<Resolved<'a>>>);
641    let index = |entries: &mut dyn Iterator<Item = (&'a String, &'a Element)>| -> Partial<'a> {
642        let mut reverse = ReverseIndex::default();
643        let mut subjects: FastMap<&'static str, Vec<Resolved<'a>>> =
644            subject_fields.iter().map(|f| (*f, Vec::new())).collect();
645        for (mrid, entry) in entries {
646            let Some(f) = source.fields(entry) else {
647                continue;
648            };
649            for field in count_fields {
650                for target in refs_of(f, field) {
651                    *reverse.counts.entry((target.as_str(), *field)).or_insert(0) += 1;
652                }
653            }
654            for field in list_fields {
655                for target in refs_of(f, field) {
656                    reverse
657                        .sources
658                        .entry((target.as_str(), *field))
659                        .or_default()
660                        .push(mrid);
661                }
662            }
663            for field in subject_fields {
664                if f.contains_key(*field) {
665                    let r = Resolved::new(source, mrid, entry, f);
666                    subjects.get_mut(field).expect("seeded above").push(r);
667                }
668            }
669        }
670        (reverse, subjects)
671    };
672
673    let threads = threads_for(ds.entries.len());
674    if threads == 1 {
675        return index(&mut ds.entries.iter());
676    }
677    // One pass split into contiguous runs of the map's own order, each indexed
678    // on its own thread, then merged in run order: the lists come out exactly
679    // as the single pass builds them.
680    let all: Vec<(&'a String, &'a Element)> = ds.entries.iter().collect();
681    let parts: Vec<Partial<'a>> = par_map(&runs(&all, threads, |_| 1), |run| {
682        index(&mut run.iter().copied())
683    });
684    let mut parts = parts.into_iter();
685    let (mut reverse, mut subjects) = parts.next().expect("at least one run");
686    for (r, subj) in parts {
687        for (k, n) in r.counts {
688            *reverse.counts.entry(k).or_insert(0) += n;
689        }
690        for (k, list) in r.sources {
691            reverse.sources.entry(k).or_default().extend(list);
692        }
693        for (field, list) in subj {
694            subjects.get_mut(field).expect("seeded above").extend(list);
695        }
696    }
697    (reverse, subjects)
698}
699
700/// Every element a shape's targets select, in `by_type` order — for a shape
701/// that mixes target kinds; the others are walked element-major in
702/// [`validate_shapes`].
703///
704/// That order is reproducible from run to run: decoding appends in document
705/// order, and `merge` walks a map whose hasher has a fixed seed. A class's
706/// elements are resolved once per call and shared with the element-major walk.
707fn targets_of<'a>(
708    ds: &'a CimDataset,
709    source: Source,
710    shape: &ShapeDef,
711    subjects: &FastMap<&'static str, Vec<Resolved<'a>>>,
712    by_class: &mut FastMap<&'static str, Vec<Resolved<'a>>>,
713) -> Vec<Resolved<'a>> {
714    let mut out: Vec<Resolved<'a>> = Vec::new();
715    for target in shape.targets {
716        match target {
717            Target::Class(classes) => {
718                for class in *classes {
719                    let list = by_class.entry(class).or_insert_with(|| {
720                        ds.by_type
721                            .get(*class)
722                            .into_iter()
723                            .flatten()
724                            .filter_map(|mrid| resolve_target(ds, source, mrid))
725                            .collect()
726                    });
727                    out.extend_from_slice(list);
728                }
729            }
730            Target::SubjectsOf(field) => {
731                out.extend_from_slice(subjects.get(field).map_or(&[], Vec::as_slice));
732            }
733        }
734    }
735    // A shape's targets overlap whenever it lists a class and one of its
736    // subclasses (`cim:Switch, cim:Breaker`), and a subjectsOf target can pick
737    // any of them again. SHACL validates a focus node once per shape.
738    let mut seen = FastSet::default();
739    out.retain(|t| seen.insert(t.mrid));
740    out
741}
742
743/// Every check of one shape against one target.
744fn run_shape<'a>(ctx: &Ctx<'a>, shape: &ShapeDef, t: &Resolved<'a>, out: &mut Vec<Violation>) {
745    for prop in shape.props {
746        check_prop(
747            ctx,
748            t.fields,
749            t.class,
750            t.mrid,
751            prop,
752            mrid_exempt(t, prop),
753            out,
754        );
755    }
756    for logic in shape.logic {
757        check_logic(ctx, t.fields, t.class, t.mrid, logic, out);
758    }
759    if let Some(closed) = shape.closed {
760        check_closed(t.fields, t.class, t.mrid, closed, out);
761    }
762}
763
764/// Validate one profile's shapes against a dataset.
765///
766/// `shapes` is the whole table; only shapes belonging to `profile` run, which is
767/// what makes a shared constraint file (imported by 17 of 18 manifests) cost
768/// nothing on the profiles that do not use it.
769pub fn validate_profile(
770    ds: &CimDataset,
771    profile: &str,
772    shapes: &'static [ShapeDef],
773    cfg: &Config,
774) -> Vec<Violation> {
775    validate_profile_in(ds, &[], profile, shapes, cfg)
776}
777
778/// [`validate_profile`] on one file of a set: the class checks find a
779/// referenced object's type in the set's other files (see [`validate_shapes_in`]).
780pub fn validate_profile_in(
781    ds: &CimDataset,
782    set: &[CimDataset],
783    profile: &str,
784    shapes: &'static [ShapeDef],
785    _cfg: &Config,
786) -> Vec<Violation> {
787    let active: Vec<&ShapeDef> = shapes
788        .iter()
789        .filter(|s| s.profiles.contains(&profile))
790        .collect();
791    validate_shapes_in(ds, set, Source::Nc, &active)
792}
793
794/// Elements per slice of a class's targets, the unit of work a thread takes.
795const SLICE: usize = 2048;
796
797/// Validate a dataset against shapes the caller has already selected.
798///
799/// The selection is the caller's because the families select differently: NC
800/// by the profile codes its manifests assign, CGMES by profile plus the
801/// solved/not-solved and local/cross-profile split its file names encode.
802///
803/// Targets outside `source` are skipped: a family's shapes describe its own
804/// elements.
805pub fn validate_shapes(ds: &CimDataset, source: Source, active: &[&ShapeDef]) -> Vec<Violation> {
806    validate_shapes_in(ds, &[], source, active)
807}
808
809/// [`validate_shapes`] on `ds`, one file of the files `set` validated
810/// together. Only NC's class checks (`sh:class`, `sh:in` on a type, `sh:not`)
811/// read the set, for the type of a referenced object `ds` does not hold;
812/// every other check sees `ds` alone, as a per-file rule must.
813pub fn validate_shapes_in(
814    ds: &CimDataset,
815    set: &[CimDataset],
816    source: Source,
817    active: &[&ShapeDef],
818) -> Vec<Violation> {
819    if active.is_empty() {
820        return Vec::new();
821    }
822
823    // Build the reverse index only if something asks an inverse question, and
824    // only over the fields that are actually asked about.
825    let mut count_fields: Vec<&'static str> = Vec::new();
826    let mut list_fields: Vec<&'static str> = Vec::new();
827    let paths = active.iter().flat_map(|s| {
828        s.props
829            .iter()
830            .map(|p| &p.path)
831            .chain(s.logic.iter().flat_map(|l| {
832                l.branches
833                    .iter()
834                    .flat_map(|b| b.props.iter().map(|p| &p.path))
835            }))
836    });
837    for path in paths {
838        match path {
839            Path::Inverse(f) => count_fields.push(f),
840            Path::Alternative(branches) => {
841                count_fields.extend(branches.iter().filter_map(|b| match b {
842                    AltBranch::Inverse(f) => Some(*f),
843                    AltBranch::Forward(_) => None,
844                }))
845            }
846            Path::Chain(steps) => list_fields.extend(steps.iter().filter_map(|s| match s {
847                Step::Inverse(f) => Some(*f),
848                _ => None,
849            })),
850            Path::Forward(_) => {}
851        }
852    }
853    count_fields.sort_unstable();
854    count_fields.dedup();
855    list_fields.sort_unstable();
856    list_fields.dedup();
857
858    let mut subject_fields: Vec<&'static str> = active
859        .iter()
860        .flat_map(|s| s.targets.iter())
861        .filter_map(|t| match t {
862            Target::SubjectsOf(f) => Some(*f),
863            Target::Class(_) => None,
864        })
865        .collect();
866    subject_fields.sort_unstable();
867    subject_fields.dedup();
868
869    let (reverse, subjects) =
870        build_indexes(ds, source, &count_fields, &list_fields, &subject_fields);
871    let ctx = Ctx {
872        ds,
873        set,
874        source,
875        reverse,
876    };
877
878    // Element-major: visit each target once and apply every shape that
879    // targets it, rather than walking a class's elements once per shape. The
880    // cost per visit is reaching the element's fields — a cache miss into its
881    // own map — so doing it once for all of a class's shapes, not once per
882    // shape, is what pays. Shapes are grouped by their one kind of target; a
883    // shape mixing kinds can select an element twice and keeps the per-shape
884    // walk, which removes the duplicate. Within one kind, the classes are
885    // de-duplicated per shape: `sh:targetClass cim:Switch, cim:Breaker`
886    // expands `Switch` to its subclasses, Breaker among them, and a breaker
887    // must still be checked once.
888    let mut by_class_shapes: FastMap<&'static str, Vec<&ShapeDef>> = FastMap::default();
889    let mut by_subject_shapes: FastMap<&'static str, Vec<&ShapeDef>> = FastMap::default();
890    let mut mixed: Vec<&ShapeDef> = Vec::new();
891    for shape in active {
892        let all_class = shape.targets.iter().all(|t| matches!(t, Target::Class(_)));
893        match shape.targets {
894            _ if all_class => {
895                let mut classes: Vec<&'static str> = shape
896                    .targets
897                    .iter()
898                    .flat_map(|t| match t {
899                        Target::Class(cs) => cs.iter().copied(),
900                        Target::SubjectsOf(_) => [].iter().copied(),
901                    })
902                    .collect();
903                classes.sort_unstable();
904                classes.dedup();
905                for class in classes {
906                    by_class_shapes.entry(class).or_default().push(shape);
907                }
908            }
909            [Target::SubjectsOf(field)] => by_subject_shapes.entry(field).or_default().push(shape),
910            _ => mixed.push(shape),
911        }
912    }
913
914    // The class-targeted walk is most of the work, and it is memory-bound:
915    // each element costs a cache miss into its own field map, which threads
916    // overlap well. Each class's elements are cut into slices, and the slices,
917    // in order, are dealt out to threads in contiguous runs of about equal
918    // size. Concatenating the runs in order gives exactly the sequential
919    // result, order included.
920    let work: Vec<(&[&ShapeDef], &[String])> = by_class_shapes
921        .iter()
922        .flat_map(|(class, shapes)| {
923            ds.by_type
924                .get(*class)
925                .map_or(&[][..], Vec::as_slice)
926                .chunks(SLICE)
927                .map(move |mrids| (shapes.as_slice(), mrids))
928        })
929        .collect();
930    let total: usize = work.iter().map(|(_, m)| m.len()).sum();
931    let mut out = par_concat(
932        &runs(&work, threads_for(total), |(_, m)| m.len()),
933        |items| {
934            let mut out = Vec::new();
935            for (shapes, mrids) in items {
936                for t in mrids
937                    .iter()
938                    .filter_map(|mrid| resolve_target(ds, source, mrid))
939                {
940                    for shape in *shapes {
941                        run_shape(&ctx, shape, &t, &mut out);
942                    }
943                }
944            }
945            out
946        },
947    );
948
949    // The same for `sh:targetSubjectsOf`, whose targets the index pass found.
950    let work: Vec<(&[&ShapeDef], &[Resolved])> = by_subject_shapes
951        .iter()
952        .flat_map(|(field, shapes)| {
953            subjects
954                .get(field)
955                .map_or(&[][..], Vec::as_slice)
956                .chunks(SLICE)
957                .map(move |targets| (shapes.as_slice(), targets))
958        })
959        .collect();
960    let total: usize = work.iter().map(|(_, t)| t.len()).sum();
961    out.extend(par_concat(
962        &runs(&work, threads_for(total), |(_, t)| t.len()),
963        |items| {
964            let mut out = Vec::new();
965            for (shapes, targets) in items {
966                for t in *targets {
967                    for shape in *shapes {
968                        run_shape(&ctx, shape, t, &mut out);
969                    }
970                }
971            }
972            out
973        },
974    ));
975    let mut by_class: FastMap<&'static str, Vec<Resolved>> = FastMap::default();
976    for shape in mixed {
977        for t in targets_of(ds, source, shape, &subjects, &mut by_class) {
978            run_shape(&ctx, shape, &t, &mut out);
979        }
980    }
981
982    // One result per element and rule. A property shape that several node
983    // shapes share — `eq:Switch.retained-cardinality` under both `eq:Switch`
984    // and `eq:Breaker` — reaches a breaker through each once `Switch` is
985    // expanded to its subclasses, and would report the same finding twice.
986    let mut seen = FastSet::default();
987    let keep: Vec<bool> = out
988        .iter()
989        .map(|v| {
990            seen.insert((
991                v.object_id.as_str(),
992                v.rule_id.as_str(),
993                v.property.as_str(),
994                v.message.as_str(),
995            ))
996        })
997        .collect();
998    drop(seen);
999    let mut keep = keep.into_iter();
1000    out.retain(|_| keep.next().unwrap_or(true));
1001    out
1002}