Skip to main content

cimvalidation/
shape_source.rs

1//! Where a family's shape table comes from.
2//!
3//! By default it is the table `cimgen` generated. With the `dynamic-shapes`
4//! feature, a directory of SHACL TTL files can supply it instead, so a new
5//! profile version is a data load rather than a recompile.
6//!
7//! Resolution order, highest first:
8//!
9//! 1. [`load_from`] — an explicit call, for libraries and tests
10//! 2. `CIMOXIDE_SHACL_DIR` — for the CLI and the Python bindings. It may list
11//!    several directories, separated as in `PATH`; each serves the family
12//!    whose files it holds (see [`family_of_dir`]), so `…/NCP/SHACL` alone
13//!    still loads only NC, as it always did
14//! 3. the generated table
15//!
16//! CGMES classes are compiled structs, so a CGMES table loaded from another
17//! release can name classes this build cannot decode; shapes on those simply
18//! match nothing.
19//!
20//! A directory that is missing or fails to parse falls back to the generated
21//! table **with a warning**. Silently validating against a stale profile
22//! because a path had a typo is the worst outcome available here.
23//!
24//! This mirrors [`cimmodel::schema_source`] closely enough that the two
25//! should be read side by side. The one difference that matters: there, the
26//! generator and the loader build the table by separate code paths and a test
27//! compares them. Here both call `cimschema::shacl::resolve`, so there is no
28//! second implementation to drift — this module only turns the resolved model
29//! into the `&'static` form the interpreter needs.
30
31use crate::shapes::ShapeDef;
32
33/// Resolve the shape table for a family.
34///
35/// `generated` is the table `cimgen` emitted, used unless something overrides
36/// it.
37pub fn resolve(family: &'static str, generated: &'static [ShapeDef]) -> &'static [ShapeDef] {
38    #[cfg(feature = "dynamic-shapes")]
39    {
40        dynamic::resolve(family, generated)
41    }
42    #[cfg(not(feature = "dynamic-shapes"))]
43    {
44        let _ = family;
45        generated
46    }
47}
48
49/// Resolve the profile index for a bag family.
50///
51/// Loaded from the same directory as the shapes, because a shape table and a
52/// profile index that disagree would run the wrong rules — the index decides
53/// which profile a dataset is, the table decides what that profile checks.
54pub fn resolve_profiles(
55    family: &'static str,
56    generated_iris: &'static [(&'static str, &'static str)],
57    generated_codes: &'static [&'static str],
58) -> (
59    &'static [(&'static str, &'static str)],
60    &'static [&'static str],
61) {
62    #[cfg(feature = "dynamic-shapes")]
63    {
64        dynamic::resolve_profiles(family, generated_iris, generated_codes)
65    }
66    #[cfg(not(feature = "dynamic-shapes"))]
67    {
68        let _ = family;
69        (generated_iris, generated_codes)
70    }
71}
72
73#[cfg(feature = "dynamic-shapes")]
74pub use dynamic::{SHACL_DIR_ENV, ShapeError, family_of_dir, intern_shapes, load_from, load_table};
75
76#[cfg(feature = "dynamic-shapes")]
77mod dynamic {
78    use std::collections::HashMap;
79    use std::path::{Path, PathBuf};
80    use std::sync::atomic::{AtomicBool, Ordering};
81    use std::sync::{Mutex, OnceLock};
82
83    use cimschema::family::{self, Family};
84    use cimschema::shacl::resolve as r;
85    use cimschema::shacl::skip::SkipCollector;
86
87    use crate::shapes::{
88        AltBranch, Branch, Check, ClosedShape, Constraint, Logic, LogicOp, NodeKind, Path as SPath,
89        PropShape, ShapeDef, Step, Target,
90    };
91
92    /// Environment variable naming SHACL constraint directories — one, or
93    /// several separated as in `PATH`, each serving the family whose files it
94    /// holds.
95    pub const SHACL_DIR_ENV: &str = "CIMOXIDE_SHACL_DIR";
96
97    #[derive(Debug)]
98    pub enum ShapeError {
99        /// The table was already resolved, so this load would have been ignored.
100        TooLate,
101        /// A table was already loaded for this family.
102        AlreadyLoaded,
103        /// No family with this id.
104        UnknownFamily(String),
105        /// The RDFS the shapes resolve against could not be read.
106        Schema(String),
107        Parse(String),
108    }
109
110    impl std::fmt::Display for ShapeError {
111        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112            match self {
113                Self::TooLate => write!(
114                    f,
115                    "the shape table is already resolved; load the shapes before validating"
116                ),
117                Self::AlreadyLoaded => write!(f, "shapes are already loaded for this family"),
118                Self::UnknownFamily(id) => write!(f, "unknown family: {id}"),
119                Self::Schema(e) => {
120                    write!(f, "cannot read the schema the shapes resolve against: {e}")
121                }
122                Self::Parse(e) => write!(f, "{e}"),
123            }
124        }
125    }
126
127    impl std::error::Error for ShapeError {}
128
129    /// A loaded table: shapes and the profile index that selects them.
130    type Loaded = (
131        &'static [ShapeDef],
132        &'static [(&'static str, &'static str)],
133        &'static [&'static str],
134    );
135
136    fn explicit() -> &'static Mutex<HashMap<&'static str, Loaded>> {
137        static E: OnceLock<Mutex<HashMap<&'static str, Loaded>>> = OnceLock::new();
138        E.get_or_init(|| Mutex::new(HashMap::new()))
139    }
140
141    /// Memoizes what the environment variable produced, so shapes and profiles
142    /// come from one load rather than two.
143    fn from_env() -> &'static Mutex<HashMap<&'static str, Option<Loaded>>> {
144        static E: OnceLock<Mutex<HashMap<&'static str, Option<Loaded>>>> = OnceLock::new();
145        E.get_or_init(|| Mutex::new(HashMap::new()))
146    }
147
148    /// Set once `resolve` has run, so a late [`load_from`] can report that it
149    /// would have had no effect instead of silently doing nothing.
150    static RESOLVED: AtomicBool = AtomicBool::new(false);
151
152    /// Load a bag family's shapes from a directory of SHACL TTL files.
153    ///
154    /// Takes precedence over `CIMOXIDE_SHACL_DIR`. Must be called before the
155    /// first validation: the table is memoized, so afterwards this returns
156    /// [`ShapeError::TooLate`] rather than being quietly ignored.
157    ///
158    /// As in `cimmodel::schema_source`, the guard is best-effort — there is a
159    /// narrow race between the check and the insert — and is documented rather
160    /// than locked, because the contract is "call before validating".
161    pub fn load_from(family_id: &str, dir: &Path) -> Result<(), ShapeError> {
162        let family = bag_family(family_id)?;
163        if RESOLVED.load(Ordering::SeqCst) {
164            return Err(ShapeError::TooLate);
165        }
166        let loaded = load(family, dir)?;
167        let mut map = explicit().lock().unwrap();
168        if map.contains_key(family.id) {
169            return Err(ShapeError::AlreadyLoaded);
170        }
171        map.insert(family.id, loaded);
172        Ok(())
173    }
174
175    /// Build a family's shape table from SHACL without installing it.
176    pub fn load_table(family_id: &str, dir: &Path) -> Result<&'static [ShapeDef], ShapeError> {
177        let family = bag_family(family_id)?;
178        Ok(load(family, dir)?.0)
179    }
180
181    fn bag_family(id: &str) -> Result<&'static Family, ShapeError> {
182        family::by_id(id).ok_or_else(|| ShapeError::UnknownFamily(id.to_string()))
183    }
184
185    /// Which family's constraint files a SHACL directory holds: NC ships
186    /// per-profile manifests in `Validation/`, CGMES files named in its
187    /// written-out manifest. `None` when it is neither.
188    pub fn family_of_dir(dir: &Path) -> Option<&'static Family> {
189        if dir.join("Validation").is_dir() {
190            return family::by_id("nc");
191        }
192        family::FAMILIES.iter().copied().find(|f| {
193            f.shacl_manifest.is_some_and(|m| {
194                m.iter()
195                    .any(|(stem, _)| dir.join(format!("{stem}.ttl")).is_file())
196            })
197        })
198    }
199
200    pub(super) fn resolve(
201        family_id: &'static str,
202        generated: &'static [ShapeDef],
203    ) -> &'static [ShapeDef] {
204        env_loaded(family_id).map_or(generated, |l| l.0)
205    }
206
207    pub(super) fn resolve_profiles(
208        family_id: &'static str,
209        generated_iris: &'static [(&'static str, &'static str)],
210        generated_codes: &'static [&'static str],
211    ) -> (
212        &'static [(&'static str, &'static str)],
213        &'static [&'static str],
214    ) {
215        env_loaded(family_id).map_or((generated_iris, generated_codes), |l| (l.1, l.2))
216    }
217
218    /// The loaded table for this family, from an explicit call or the
219    /// environment, or `None` to use the generated one.
220    fn env_loaded(family_id: &'static str) -> Option<Loaded> {
221        RESOLVED.store(true, Ordering::SeqCst);
222
223        if let Some(l) = explicit().lock().unwrap().get(family_id) {
224            return Some(*l);
225        }
226
227        let mut cache = from_env().lock().unwrap();
228        if let Some(cached) = cache.get(family_id) {
229            return *cached;
230        }
231
232        // The directory, if any, that holds this family's files. A directory
233        // holding neither family's files is reported once, by the first family
234        // to look, rather than silently ignored.
235        let dir: Option<PathBuf> = std::env::var_os(SHACL_DIR_ENV).and_then(|dirs| {
236            let dirs: Vec<PathBuf> = std::env::split_paths(&dirs).collect();
237            static REPORTED: AtomicBool = AtomicBool::new(false);
238            if !REPORTED.swap(true, Ordering::SeqCst) {
239                for d in dirs.iter().filter(|d| family_of_dir(d).is_none()) {
240                    eprintln!(
241                        "warning: {SHACL_DIR_ENV} names {}, which holds no NC or CGMES \
242                         constraint files; ignoring it",
243                        d.display()
244                    );
245                }
246            }
247            dirs.into_iter()
248                .find(|d| family_of_dir(d).is_some_and(|f| f.id == family_id))
249        });
250        let loaded = match (dir, bag_family(family_id)) {
251            (Some(dir), Ok(family)) => match load(family, &dir) {
252                Ok(l) => Some(l),
253                Err(e) => {
254                    eprintln!(
255                        "warning: {SHACL_DIR_ENV} names {} but the {family_id} shapes could not \
256                         be loaded ({e}); falling back to the generated shape table",
257                        dir.display()
258                    );
259                    None
260                }
261            },
262            _ => None,
263        };
264        cache.insert(family_id, loaded);
265        loaded
266    }
267
268    /// Read and intern one family's shapes and profile index.
269    ///
270    /// The shapes resolve against the family's RDFS, which
271    /// `cimmodel::schema_source` already knows how to find: a shape naming a
272    /// class this workspace has no schema for cannot be checked, so the two
273    /// have to agree on what the family contains.
274    fn load(family: &'static Family, dir: &Path) -> Result<Loaded, ShapeError> {
275        // Fail on the SHACL directory before the schema one, so a bad path is
276        // reported as what it is rather than as a missing vocabulary.
277        if !dir.is_dir() {
278            return Err(ShapeError::Parse(format!(
279                "not a directory: {}",
280                dir.display()
281            )));
282        }
283        let (spec, others) = specs(family, dir)?;
284        let other_refs: Vec<&cimschema::model::CimSpecification> = others.iter().collect();
285
286        let mut collector = SkipCollector::new();
287        let table = r::load_shape_table(family, &spec, &other_refs, dir, &mut collector)
288            .map_err(|e| ShapeError::Parse(e.to_string()))?;
289
290        let mut interner = Interner::default();
291        let shapes: Vec<ShapeDef> = table
292            .shapes
293            .iter()
294            .map(|s| shape(s, &mut interner))
295            .collect();
296
297        let iris: Vec<(&'static str, &'static str)> = table
298            .profile_iris
299            .iter()
300            .map(|(iri, code)| (interner.intern(iri), interner.intern(code)))
301            .collect();
302        let codes: Vec<&'static str> = table.profiles.iter().map(|c| interner.intern(c)).collect();
303
304        Ok((Vec::leak(shapes), Vec::leak(iris), Vec::leak(codes)))
305    }
306
307    /// Import the RDFS the shapes resolve against.
308    ///
309    /// Found the way `PROF` is: beside the SHACL directory, which is how the
310    /// ENTSO-E library is laid out. That keeps a load self-contained — one
311    /// directory decides both what the classes are and what the rules are —
312    /// and avoids depending on the process's working directory, which the
313    /// family's compiled-in glob does.
314    ///
315    /// `CIMOXIDE_RDFS_DIR` still wins, so a caller already pointing the class
316    /// table somewhere is not silently overridden.
317    fn specs(
318        family: &'static Family,
319        shacl_dir: &Path,
320    ) -> Result<
321        (
322            cimschema::model::CimSpecification,
323            Vec<cimschema::model::CimSpecification>,
324        ),
325        ShapeError,
326    > {
327        let import = |f: &'static Family, pattern: &str| {
328            cimschema::import::import_schema_files(pattern, f, false)
329                .map_err(|e| ShapeError::Schema(e.to_string()))
330        };
331
332        // `.../NCP/SHACL` → `.../`, the library root every family sits under.
333        let root = shacl_dir.parent().and_then(Path::parent);
334
335        let spec = import(family, &schema_glob(family, shacl_dir, root))?;
336
337        // Every other family, for the cross-family class lists the value-type
338        // rules use: NCP's association value-type shapes name CGMES classes
339        // beside NC ones. A family whose schema cannot be read is skipped so
340        // one missing tree does not fail the load — but it **warns**, because
341        // the failure mode is silent: those classes simply drop out of the
342        // allowed lists, and a reference that should have passed starts
343        // reporting as the wrong class.
344        let mut others = Vec::new();
345        for f in family::FAMILIES.iter().filter(|f| f.id != family.id) {
346            match import(f, &schema_glob(f, shacl_dir, root)) {
347                Ok(s) => others.push(s),
348                Err(e) => eprintln!(
349                    "warning: the {} schema could not be read ({e}); its classes will be \
350                     missing from {}'s cross-family value-type rules",
351                    f.id, family.id
352                ),
353            }
354        }
355        Ok((spec, others))
356    }
357
358    /// Where to look for a family's RDFS.
359    ///
360    /// `CIMOXIDE_RDFS_DIR` wins, so a caller already pointing the class table
361    /// somewhere is not silently overridden — but it names one family's
362    /// directory, so it applies only to the family being loaded.
363    ///
364    /// Otherwise the family's compiled-in glob is re-rooted at the library the
365    /// SHACL directory came from, which keeps a load self-contained and
366    /// independent of the process's working directory.
367    fn schema_glob(f: &'static Family, shacl_dir: &Path, root: Option<&Path>) -> String {
368        let file_name = |p: &str| {
369            Path::new(p)
370                .file_name()
371                .map(|n| n.to_string_lossy().into_owned())
372                .unwrap_or_else(|| "*.rdf".to_string())
373        };
374
375        // Only for the family whose SHACL directory this is.
376        if shacl_dir
377            .parent()
378            .and_then(|p| p.file_name())
379            .zip(
380                Path::new(f.default_schema)
381                    .parent()
382                    .and_then(Path::parent)
383                    .and_then(|p| p.file_name()),
384            )
385            .is_some_and(|(a, b)| a == b)
386            && let Some(dir) = std::env::var_os(cimmodel::schema_source::RDFS_DIR_ENV)
387        {
388            return PathBuf::from(dir)
389                .join(file_name(f.default_schema))
390                .to_string_lossy()
391                .into_owned();
392        }
393
394        // `application-profiles-library/CGMES/RDFS/<glob>` → `<root>/CGMES/RDFS/<glob>`.
395        let tail: Option<PathBuf> =
396            Path::new(f.default_schema)
397                .components()
398                .skip(1)
399                .fold(None::<PathBuf>, |acc, c| {
400                    Some(
401                        acc.map_or_else(|| PathBuf::from(c.as_os_str()), |p| p.join(c.as_os_str())),
402                    )
403                });
404        match (root, tail) {
405            (Some(root), Some(tail)) => {
406                let candidate = root.join(tail);
407                if candidate.parent().is_some_and(|p| p.is_dir()) {
408                    return candidate.to_string_lossy().into_owned();
409                }
410                f.default_schema.to_string()
411            }
412            _ => f.default_schema.to_string(),
413        }
414    }
415
416    /// Convert an already-resolved table into the `&'static` IR, for a caller
417    /// that resolved the shapes itself (e.g. with its own profile mapping).
418    /// Leaked once per call.
419    pub fn intern_shapes(shapes: &[r::ShapeDef]) -> &'static [ShapeDef] {
420        let mut interner = Interner::default();
421        Vec::leak(shapes.iter().map(|s| shape(s, &mut interner)).collect())
422    }
423
424    /// Interns resolved strings so they satisfy the `&'static` signatures the
425    /// IR and the violation types require. Bounded by schema size and leaked
426    /// once per process.
427    #[derive(Default)]
428    struct Interner {
429        seen: HashMap<String, &'static str>,
430    }
431
432    impl Interner {
433        fn intern(&mut self, s: &str) -> &'static str {
434            if let Some(v) = self.seen.get(s) {
435                return v;
436            }
437            let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
438            self.seen.insert(s.to_string(), leaked);
439            leaked
440        }
441
442        fn intern_all(&mut self, items: &[String]) -> &'static [&'static str] {
443            Vec::leak(items.iter().map(|s| self.intern(s)).collect::<Vec<_>>())
444        }
445    }
446
447    // The conversions below are mechanical and total: the resolved model and
448    // the IR have the same shape, and a variant added to one without the other
449    // is a compile error rather than silent drift.
450
451    fn shape(s: &r::ShapeDef, i: &mut Interner) -> ShapeDef {
452        ShapeDef {
453            targets: Vec::leak(s.targets.iter().map(|t| target(t, i)).collect::<Vec<_>>()),
454            props: Vec::leak(
455                s.props
456                    .iter()
457                    .map(|p| &*Box::leak(Box::new(prop(p, i))))
458                    .collect::<Vec<_>>(),
459            ),
460            closed: s
461                .closed
462                .as_ref()
463                .map(|c| &*Box::leak(Box::new(closed(c, i)))),
464            logic: Vec::leak(s.logic.iter().map(|l| logic(l, i)).collect::<Vec<_>>()),
465            profiles: i.intern_all(&s.profiles),
466            file: i.intern(&s.file),
467        }
468    }
469
470    fn target(t: &r::Target, i: &mut Interner) -> Target {
471        match t {
472            r::Target::Class(classes) => Target::Class(i.intern_all(classes)),
473            r::Target::SubjectsOf(f) => Target::SubjectsOf(i.intern(f)),
474        }
475    }
476
477    fn prop(p: &r::PropShape, i: &mut Interner) -> PropShape {
478        PropShape {
479            path: path(&p.path, i),
480            checks: Vec::leak(p.checks.iter().map(|c| check(c, i)).collect::<Vec<_>>()),
481        }
482    }
483
484    fn path(p: &r::Path, i: &mut Interner) -> SPath {
485        match p {
486            r::Path::Forward(f) => SPath::Forward(i.intern(f)),
487            r::Path::Inverse(f) => SPath::Inverse(i.intern(f)),
488            r::Path::Chain(steps) => SPath::Chain(Vec::leak(
489                steps
490                    .iter()
491                    .map(|s| match s {
492                        r::Step::Forward(f) => Step::Forward(i.intern(f)),
493                        r::Step::Inverse(f) => Step::Inverse(i.intern(f)),
494                        r::Step::Type => Step::Type,
495                    })
496                    .collect::<Vec<_>>(),
497            )),
498            r::Path::Alternative(branches) => SPath::Alternative(Vec::leak(
499                branches
500                    .iter()
501                    .map(|b| match b {
502                        r::AltBranch::Forward(f) => AltBranch::Forward(i.intern(f)),
503                        r::AltBranch::Inverse(f) => AltBranch::Inverse(i.intern(f)),
504                    })
505                    .collect::<Vec<_>>(),
506            )),
507        }
508    }
509
510    fn check(c: &r::Check, i: &mut Interner) -> Check {
511        Check {
512            constraint: constraint(&c.constraint, i),
513            rule_id: i.intern(&c.rule_id),
514            name: i.intern(&c.name),
515            message: i.intern(&c.message),
516            description: i.intern(&c.description),
517            severity: i.intern(&c.severity),
518        }
519    }
520
521    fn constraint(c: &r::Constraint, i: &mut Interner) -> Constraint {
522        match c {
523            r::Constraint::MinCount(n) => Constraint::MinCount(*n),
524            r::Constraint::MaxCount(n) => Constraint::MaxCount(*n),
525            r::Constraint::MaxLength(n) => Constraint::MaxLength(*n),
526            r::Constraint::MinLength(n) => Constraint::MinLength(*n),
527            r::Constraint::Datatype(d) => Constraint::Datatype(i.intern(d)),
528            r::Constraint::HasValue(v) => Constraint::HasValue(i.intern(v)),
529            r::Constraint::NodeKind(k) => Constraint::NodeKind(match k {
530                r::NodeKind::Iri => NodeKind::Iri,
531                r::NodeKind::Literal => NodeKind::Literal,
532                r::NodeKind::BlankNode => NodeKind::BlankNode,
533            }),
534            r::Constraint::Class(v) => Constraint::Class(i.intern_all(v)),
535            r::Constraint::RefClass(v) => Constraint::RefClass(i.intern_all(v)),
536            r::Constraint::In(v) => Constraint::In(i.intern_all(v)),
537            r::Constraint::MinInclusive(v) => Constraint::MinInclusive(*v),
538            r::Constraint::MaxInclusive(v) => Constraint::MaxInclusive(*v),
539            r::Constraint::MinExclusive(v) => Constraint::MinExclusive(*v),
540            r::Constraint::MaxExclusive(v) => Constraint::MaxExclusive(*v),
541            r::Constraint::LessThan(f) => Constraint::LessThan(i.intern(f)),
542            r::Constraint::LessThanOrEquals(f) => Constraint::LessThanOrEquals(i.intern(f)),
543            r::Constraint::NotClass(v) => Constraint::NotClass(i.intern_all(v)),
544            r::Constraint::Length(n) => Constraint::Length(*n),
545            r::Constraint::QualifiedIn { allowed, min } => Constraint::QualifiedIn {
546                allowed: i.intern_all(allowed),
547                min: *min,
548            },
549        }
550    }
551
552    fn logic(l: &r::Logic, i: &mut Interner) -> Logic {
553        Logic {
554            op: match l.op {
555                r::LogicOp::And => LogicOp::And,
556                r::LogicOp::Or => LogicOp::Or,
557                r::LogicOp::Xone => LogicOp::Xone,
558            },
559            branches: Vec::leak(
560                l.branches
561                    .iter()
562                    .map(|b| Branch {
563                        props: Vec::leak(b.props.iter().map(|p| prop(p, i)).collect::<Vec<_>>()),
564                        negate: b.negate,
565                    })
566                    .collect::<Vec<_>>(),
567            ),
568            rule_id: i.intern(&l.rule_id),
569            name: i.intern(&l.name),
570            message: i.intern(&l.message),
571            description: i.intern(&l.description),
572            severity: i.intern(&l.severity),
573        }
574    }
575
576    fn closed(c: &r::ClosedShape, i: &mut Interner) -> ClosedShape {
577        ClosedShape {
578            allowed: i.intern_all(&c.allowed),
579            rule_id: i.intern(&c.rule_id),
580            name: i.intern(&c.name),
581            message: i.intern(&c.message),
582            description: i.intern(&c.description),
583            severity: i.intern(&c.severity),
584        }
585    }
586}