1use crate::shapes::ShapeDef;
32
33pub 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
49pub 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 pub const SHACL_DIR_ENV: &str = "CIMOXIDE_SHACL_DIR";
96
97 #[derive(Debug)]
98 pub enum ShapeError {
99 TooLate,
101 AlreadyLoaded,
103 UnknownFamily(String),
105 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 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 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 static RESOLVED: AtomicBool = AtomicBool::new(false);
151
152 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 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 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 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 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 fn load(family: &'static Family, dir: &Path) -> Result<Loaded, ShapeError> {
275 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 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 let root = shacl_dir.parent().and_then(Path::parent);
334
335 let spec = import(family, &schema_glob(family, shacl_dir, root))?;
336
337 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 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 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 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 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 #[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 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}