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