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