1use crate::shapes::ShapeDef;
34
35pub 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
51pub 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 TooLate,
103 AlreadyLoaded,
105 UnknownFamily(String),
107 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 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 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 static RESOLVED: AtomicBool = AtomicBool::new(false);
153
154 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 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 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 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 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 fn load(family: &'static Family, dir: &Path) -> Result<Loaded, ShapeError> {
264 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 let root = dir.parent().and_then(Path::parent);
277 build(family, &files, &|f| vocabulary(f, dir, root))
278 }
279
280 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 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 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 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 fn vocabulary(f: &'static Family, shacl_dir: &Path, root: Option<&Path>) -> Vocabulary {
388 use cimschema::profile_file::{in_dir, near};
389
390 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 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 enum Vocabulary {
427 Files(Vec<PathBuf>),
428 Pattern(String),
429 }
430
431 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 #[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 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}