Skip to main content

cimvalidation/
lib.rs

1pub mod violation;
2pub use violation::Violation;
3
4pub mod detect;
5pub mod sparql;
6pub use detect::{detect_config, detect_nc_profiles};
7
8use std::collections::HashSet;
9
10#[derive(Debug, Default, Clone)]
11pub struct Config {
12    /// Profile short names to validate (e.g. "EQ", "SSH"). Empty = all detected.
13    pub profiles: Vec<String>,
14    /// True if SV profile (power-flow results) is present.
15    pub solved: bool,
16    /// True if SV profile is absent.
17    pub not_solved: bool,
18    /// Run common cross-profile checks.
19    pub common: bool,
20    /// Run CIMdesk modeling quality checks.
21    pub quality: bool,
22    /// Rule IDs to suppress in the output.
23    pub silenced_rules: Vec<String>,
24    /// When non-empty, enables the EQBD2 base voltage check.
25    pub eqbd_base_voltage_ids: Option<HashSet<String>>,
26}
27
28pub mod helpers;
29mod par;
30
31// ── property-bag families ──────────────────────────────────────────────────
32//
33// Elements of both families are property bags; each family's shapes are a
34// data table interpreted by `bag`.
35pub mod bag;
36pub mod shape_source;
37pub mod shapes;
38#[rustfmt::skip] // written by cimgen
39pub mod nc_shapes;
40#[rustfmt::skip] // written by cimgen
41pub mod nc_profiles;
42
43/// The NC shape table in force: loaded from SHACL if the `dynamic-shapes`
44/// feature is on and a directory was supplied, otherwise the generated one.
45pub fn nc_shapes() -> &'static [shapes::ShapeDef] {
46    static R: std::sync::OnceLock<&'static [shapes::ShapeDef]> = std::sync::OnceLock::new();
47    R.get_or_init(|| shape_source::resolve("nc", nc_shapes::SHAPES))
48}
49
50/// Profile IRI → short code, and every short code.
51pub type ProfileIndex = (
52    &'static [(&'static str, &'static str)],
53    &'static [&'static str],
54);
55
56/// The NC profile index in force. Loaded together with the shapes, since an
57/// index and a table from different releases would run the wrong rules.
58pub fn nc_profile_index() -> ProfileIndex {
59    static R: std::sync::OnceLock<ProfileIndex> = std::sync::OnceLock::new();
60    *R.get_or_init(|| {
61        shape_source::resolve_profiles("nc", nc_profiles::PROFILE_IRIS, nc_profiles::PROFILES)
62    })
63}
64
65/// Run one NC profile's shapes against a dataset, and the hand-written rules
66/// of the files every NC profile imports (`sparql::nc::validate_local`).
67///
68/// Separate from `validate_profile_local` so a caller can drive it with an
69/// explicit profile code, without depending on header detection.
70pub fn validate_nc_profile(
71    dataset: &cimmodel::CimDataset,
72    profile: &str,
73    cfg: &Config,
74) -> Vec<Violation> {
75    validate_nc_profile_in(dataset, &[], profile, cfg)
76}
77
78/// [`validate_nc_profile`] on one file of a set, as [`validate_profile_local_in`].
79pub fn validate_nc_profile_in(
80    dataset: &cimmodel::CimDataset,
81    set: &[cimmodel::CimDataset],
82    profile: &str,
83    cfg: &Config,
84) -> Vec<Violation> {
85    let mut v = bag::validate_profile_in(dataset, set, profile, nc_shapes(), cfg);
86    // Every NC profile's manifest imports the files these come from, and no
87    // other code names one.
88    if nc_profile_index().1.contains(&profile) {
89        v.extend(sparql::nc::validate_local(dataset));
90    }
91    v
92}
93
94/// The NC rules that relate datasets: the Complex files only the combined
95/// manifest imports, as table shapes and hand-written rules, on the merged
96/// dataset. [`validate_crossprofile`] runs this when an NC profile is in play.
97pub fn validate_nc_merged(dataset: &cimmodel::CimDataset, cfg: &Config) -> Vec<Violation> {
98    let mut v = bag::validate_profile(dataset, MERGED_PROFILE, nc_shapes(), cfg);
99    v.extend(sparql::nc::validate_merged(dataset));
100    v
101}
102
103/// The profile code of the shapes [`validate_nc_merged`] runs: the combined
104/// manifest's keyword, as `cimschema::shacl::resolve::MERGED_PROFILE` assigns it.
105/// Repeated here because `cimoxide-schema` is optional; a test holds the two
106/// together.
107pub const MERGED_PROFILE: &str = "ALL";
108
109// ── CGMES shape table ──────────────────────────────────────────────────────
110//
111// CGMES runs through the same interpreter as NC, reading the typed elements'
112// decoder blocks; it replaced ~250k lines of generated per-check functions.
113// Its constraint files carry tags rather than profile codes — see
114// `cimschema::shacl::cgmes_manifest` — so one table holds the local,
115// not-solved, cross-profile and header rules apart.
116#[rustfmt::skip] // written by cimgen
117pub mod cgmes_shapes;
118#[rustfmt::skip] // written by cimgen
119pub mod cgmes_profiles;
120
121/// The CGMES shape table in force: loaded from SHACL if the `dynamic-shapes`
122/// feature is on and a directory was supplied, otherwise the generated one.
123pub fn cgmes_shapes() -> &'static [shapes::ShapeDef] {
124    static R: std::sync::OnceLock<&'static [shapes::ShapeDef]> = std::sync::OnceLock::new();
125    R.get_or_init(|| shape_source::resolve("cgmes", cgmes_shapes::SHAPES))
126}
127
128/// The CGMES shapes carrying one manifest tag, indexed once per process.
129fn cgmes_tagged(tag: &str) -> &'static [&'static shapes::ShapeDef] {
130    type Index = std::collections::HashMap<&'static str, Vec<&'static shapes::ShapeDef>>;
131    static IDX: std::sync::OnceLock<Index> = std::sync::OnceLock::new();
132    let idx = IDX.get_or_init(|| {
133        let mut idx = Index::new();
134        for shape in cgmes_shapes() {
135            for tag in shape.profiles {
136                idx.entry(*tag).or_default().push(shape);
137            }
138        }
139        idx
140    });
141    idx.get(tag).map_or(&[], Vec::as_slice)
142}
143
144fn run_cgmes(dataset: &cimmodel::CimDataset, active: &[&shapes::ShapeDef]) -> Vec<Violation> {
145    bag::validate_shapes(dataset, bag::Source::Cgmes, active)
146}
147
148fn run_cgmes_in(
149    dataset: &cimmodel::CimDataset,
150    set: &[cimmodel::CimDataset],
151    active: &[&shapes::ShapeDef],
152) -> Vec<Violation> {
153    bag::validate_shapes_in(dataset, set, bag::Source::Cgmes, active)
154}
155
156// ── public two-phase API ───────────────────────────────────────────────────
157
158/// Phase 1 — header: validate FullModel/DifferenceModel rules for a single file's dataset.
159pub fn validate_header(dataset: &cimmodel::CimDataset, _cfg: &Config) -> Vec<Violation> {
160    run_cgmes(dataset, cgmes_tagged("HDR"))
161}
162
163/// The SHACL half of [`validate_profile_local`] for one CGMES profile: its
164/// local rules. Without the hand-written `sparql` rules or the `cfg.profiles`
165/// filter.
166pub fn validate_profile_shacl(
167    dataset: &cimmodel::CimDataset,
168    profile: &str,
169    _cfg: &Config,
170) -> Vec<Violation> {
171    run_cgmes(dataset, cgmes_tagged(profile))
172}
173
174/// The SHACL half of [`validate_crossprofile`]: every enabled profile's
175/// cross-profile rules on the merged dataset, its not-solved (`!NS`, the
176/// NotSolvedMAS files) rules when `cfg.not_solved` — written for a model
177/// authority set, like the hand-written ones in [`sparql::mas_groups`] — and
178/// the rules for every profile when `cfg.common`.
179pub fn validate_crossprofile_shacl(dataset: &cimmodel::CimDataset, cfg: &Config) -> Vec<Violation> {
180    let has = |p: &str| cfg.profiles.is_empty() || cfg.profiles.iter().any(|x| x == p);
181    let mut active: Vec<&shapes::ShapeDef> = cimschema_cross_profiles()
182        .iter()
183        .filter(|p| has(p))
184        .flat_map(|p| cgmes_tagged(&format!("X:{p}")).iter().copied())
185        .collect();
186    if cfg.not_solved {
187        for p in cgmes_profile_index().1.iter().filter(|p| has(p)) {
188            active.extend_from_slice(cgmes_tagged(&format!("{p}!NS")));
189        }
190    }
191    if cfg.common {
192        active.extend_from_slice(cgmes_tagged("COMMON"));
193    }
194    run_cgmes(dataset, &active)
195}
196
197/// The CGMES profile index in force: `md:Model.profile` IRI → short code, and
198/// every short code, read from `CGMES/PROF`. Loaded together with the shapes,
199/// like [`nc_profile_index`].
200pub fn cgmes_profile_index() -> ProfileIndex {
201    static R: std::sync::OnceLock<ProfileIndex> = std::sync::OnceLock::new();
202    *R.get_or_init(|| {
203        shape_source::resolve_profiles(
204            "cgmes",
205            cgmes_profiles::PROFILE_IRIS,
206            cgmes_profiles::PROFILES,
207        )
208    })
209}
210
211/// The profiles with cross-profile rules. Mirrors
212/// `cimschema::shacl::cgmes_manifest::CROSS_PROFILES`, which this crate does
213/// not depend on outside the `dynamic-shapes` feature.
214fn cimschema_cross_profiles() -> &'static [&'static str] {
215    &["DL", "DY", "GL", "OP", "SV", "TP"]
216}
217
218/// Phase 1 — per-profile: run the local (non-crossprofile) SHACL rules and the SPARQL
219/// rules for one profile.
220///
221/// Pass the single-file dataset for the profile and the combined config (solved/not_solved
222/// must reflect the full set of files, not just this file). If `cfg.profiles` is non-empty
223/// and does not include `profile`, returns an empty vec — this filter applies to both the
224/// SHACL and SPARQL checks.
225pub fn validate_profile_local(
226    dataset: &cimmodel::CimDataset,
227    profile: &str,
228    cfg: &Config,
229) -> Vec<Violation> {
230    validate_profile_local_in(dataset, &[], profile, cfg)
231}
232
233/// [`validate_profile_local`] on `dataset`, one of the files `set` validated
234/// together, as [`validate_files`] runs it. The rules still see `dataset`
235/// alone, except that an NC class check (`sh:class`, `sh:in` on a type) finds
236/// the type of a referenced object in whichever file of `set` holds it: a
237/// schedule's unit, a remedial action's equipment. Without the set those
238/// checks are silent on every association that leaves the file. CGMES's
239/// per-profile value types are written for one file and stay so
240/// (`bag::any_type`).
241pub fn validate_profile_local_in(
242    dataset: &cimmodel::CimDataset,
243    set: &[cimmodel::CimDataset],
244    profile: &str,
245    cfg: &Config,
246) -> Vec<Violation> {
247    if !cfg.profiles.is_empty() && !cfg.profiles.iter().any(|p| p == profile) {
248        return Vec::new();
249    }
250    // NC profile codes cannot collide with CGMES ones, so one flat
251    // `Config::profiles` list carries both families. The CGMES codes are
252    // checked first: asking the NC index loads the NC table — 170 ms when it
253    // comes from SHACL — for data that has no NC in it.
254    if !cgmes_profile_index().1.contains(&profile) && nc_profile_index().1.contains(&profile) {
255        return validate_nc_profile_in(dataset, set, profile, cfg);
256    }
257
258    let mut v = run_cgmes_in(dataset, set, cgmes_tagged(profile));
259    v.extend(sparql::validate_profile_local(dataset, profile, cfg));
260    v
261}
262
263/// Phase 2 — crossprofile: run crossprofile SHACL + cross-profile SPARQL on the merged dataset.
264///
265/// The two halves run concurrently; the SPARQL half spreads its rule groups
266/// over threads of its own.
267pub fn validate_crossprofile(dataset: &cimmodel::CimDataset, cfg: &Config) -> Vec<Violation> {
268    let (sparql, mut v) = par::par_two(
269        || sparql::validate_crossprofile(dataset, cfg),
270        || validate_crossprofile_shacl(dataset, cfg),
271    );
272    v.extend(sparql);
273    // CGMES codes first, as in `validate_profile_local`: data without NC
274    // never loads the NC table.
275    let cgmes = cgmes_profile_index().1;
276    if cfg
277        .profiles
278        .iter()
279        .any(|p| !cgmes.contains(&p.as_str()) && nc_profile_index().1.contains(&p.as_str()))
280    {
281        v.extend(validate_nc_merged(dataset, cfg));
282    }
283    v
284}
285
286/// Build a combined `Config` by auto-detecting profiles/solved-state across all files,
287/// then applying explicit overrides (each `None`/default leaves the detected value).
288pub fn combined_config(
289    per_file: &[cimmodel::CimDataset],
290    profiles: Option<Vec<String>>,
291    solved: Option<bool>,
292    common: bool,
293    quality: bool,
294    silenced_rules: Vec<String>,
295) -> Config {
296    let mut cfg = Config::default();
297    for ds in per_file {
298        let c = detect_config(ds);
299        for p in c.profiles.into_iter().chain(detect_nc_profiles(ds)) {
300            if !cfg.profiles.contains(&p) {
301                cfg.profiles.push(p);
302            }
303        }
304        cfg.solved |= c.solved;
305    }
306    cfg.not_solved = !cfg.solved;
307    if let Some(p) = profiles {
308        cfg.profiles = p;
309    }
310    if let Some(s) = solved {
311        cfg.solved = s;
312        cfg.not_solved = !s;
313    }
314    cfg.common = common;
315    cfg.quality = quality;
316    cfg.silenced_rules = silenced_rules;
317    cfg
318}
319
320/// Run full two-phase validation: per-file local checks (header + per-profile SHACL/SPARQL)
321/// in parallel, then crossprofile checks on the merged dataset, then apply rule silencing.
322///
323/// Consumes `per_file` since it merges them into one dataset for phase 2.
324pub fn validate_files(per_file: Vec<cimmodel::CimDataset>, cfg: &Config) -> Vec<Violation> {
325    validate_files_traced(per_file, cfg)
326        .into_iter()
327        .map(|(_, v)| v)
328        .collect()
329}
330
331/// [`validate_files`], with each finding's origin: the index into `per_file`
332/// of the file it was found in, or `None` for a finding on the merged dataset.
333/// An object several files write is reported against one of them, which
334/// `cimlsp` needs to put the finding there.
335pub fn validate_files_traced(
336    per_file: Vec<cimmodel::CimDataset>,
337    cfg: &Config,
338) -> Vec<(Option<usize>, Violation)> {
339    let set = per_file.as_slice();
340    let mut violations: Vec<(Option<usize>, Violation)> = par::par_each(set, |ds| {
341        let mut v = validate_header(ds, cfg);
342        let mut profiles = detect_config(ds).profiles;
343        profiles.extend(detect_nc_profiles(ds));
344        for profile in &profiles {
345            v.extend(validate_profile_local_in(ds, set, profile, cfg));
346        }
347        v
348    })
349    .into_iter()
350    .enumerate()
351    .flat_map(|(i, found)| found.into_iter().map(move |v| (Some(i), v)))
352    .collect();
353
354    let mut merged = cimmodel::CimDataset::new();
355    for ds in per_file {
356        merged.merge(ds);
357    }
358    violations.extend(
359        validate_crossprofile(&merged, cfg)
360            .into_iter()
361            .map(|v| (None, v)),
362    );
363
364    if !cfg.silenced_rules.is_empty() {
365        let silenced: HashSet<&str> = cfg.silenced_rules.iter().map(String::as_str).collect();
366        violations.retain(|(_, v)| !silenced.contains(v.rule_id.as_str()));
367    }
368    violations
369}