1use crate::base::Schema;
21
22pub fn resolve(family: &'static str, generated: &'static Schema) -> &'static Schema {
26 #[cfg(feature = "dynamic-schema")]
27 {
28 dynamic::resolve(family, generated)
29 }
30 #[cfg(not(feature = "dynamic-schema"))]
31 {
32 let _ = family;
33 generated
34 }
35}
36
37#[cfg(feature = "dynamic-schema")]
38pub use dynamic::{RDFS_DIR_ENV, SchemaError, family_of_dir, load_from, load_table};
39
40#[cfg(feature = "dynamic-schema")]
41mod dynamic {
42 use std::collections::HashMap;
43 use std::path::{Path, PathBuf};
44 use std::sync::atomic::{AtomicBool, Ordering};
45 use std::sync::{Mutex, OnceLock};
46
47 use cimschema::family::{self, Family};
48 use cimschema::model::{CimAttribute, CimSpecification};
49
50 use crate::base::{AttrDef, AttrKind, ClassDef, EnumDef, EnumValueDef, Schema};
51
52 pub const RDFS_DIR_ENV: &str = "CIMOXIDE_RDFS_DIR";
55
56 #[derive(Debug)]
57 pub enum SchemaError {
58 TooLate,
60 AlreadyLoaded,
62 UnknownFamily(String),
64 Parse(String),
65 }
66
67 impl std::fmt::Display for SchemaError {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 match self {
70 Self::TooLate => write!(
71 f,
72 "the type registry is already built; load the schema before decoding"
73 ),
74 Self::AlreadyLoaded => write!(f, "a schema is already loaded for this family"),
75 Self::UnknownFamily(id) => write!(f, "unknown family: {id}"),
76 Self::Parse(e) => write!(f, "{e}"),
77 }
78 }
79 }
80
81 impl std::error::Error for SchemaError {}
82
83 fn explicit() -> &'static Mutex<HashMap<&'static str, &'static Schema>> {
84 static E: OnceLock<Mutex<HashMap<&'static str, &'static Schema>>> = OnceLock::new();
85 E.get_or_init(|| Mutex::new(HashMap::new()))
86 }
87
88 static RESOLVED: AtomicBool = AtomicBool::new(false);
91
92 pub fn load_from(family_id: &str, dir: &Path) -> Result<(), SchemaError> {
98 let family = family::by_id(family_id)
99 .ok_or_else(|| SchemaError::UnknownFamily(family_id.to_string()))?;
100 if RESOLVED.load(Ordering::SeqCst) {
101 return Err(SchemaError::TooLate);
102 }
103 let classes = load_table(family.id, dir)?;
104 let mut map = explicit().lock().unwrap();
105 if map.contains_key(family.id) {
106 return Err(SchemaError::AlreadyLoaded);
107 }
108 map.insert(family.id, classes);
109 Ok(())
110 }
111
112 pub(super) fn resolve(family_id: &'static str, generated: &'static Schema) -> &'static Schema {
113 RESOLVED.store(true, Ordering::SeqCst);
114
115 if let Some(classes) = explicit().lock().unwrap().get(family_id) {
116 return classes;
117 }
118
119 let Some(dirs) = env_dirs() else {
120 return generated;
121 };
122 let Some(family) = family::by_id(family_id) else {
123 return generated;
124 };
125 let Some(dir) = dirs
126 .iter()
127 .find(|d| family_of_dir(d).is_some_and(|f| f.id == family.id))
128 else {
129 return generated;
130 };
131 match load_family(family, dir) {
132 Ok(classes) => classes,
133 Err(e) => {
134 eprintln!(
135 "warning: {RDFS_DIR_ENV} set but the {family_id} schema could not be \
136 loaded ({e}); falling back to the generated class table"
137 );
138 generated
139 }
140 }
141 }
142
143 fn env_dirs() -> Option<&'static [PathBuf]> {
146 static DIRS: OnceLock<Option<Vec<PathBuf>>> = OnceLock::new();
147 DIRS.get_or_init(|| {
148 let value = std::env::var_os(RDFS_DIR_ENV)?;
149 let dirs: Vec<PathBuf> = std::env::split_paths(&value).collect();
150 for d in &dirs {
151 if family_of_dir(d).is_none() {
152 eprintln!(
153 "warning: {RDFS_DIR_ENV} lists {}, which holds no CGMES or NC RDFS \
154 vocabularies; ignoring it",
155 d.display()
156 );
157 }
158 }
159 Some(dirs)
160 })
161 .as_deref()
162 }
163
164 pub fn family_of_dir(dir: &Path) -> Option<&'static Family> {
168 let names: Vec<String> = std::fs::read_dir(dir)
169 .ok()?
170 .filter_map(|e| e.ok())
171 .map(|e| e.file_name().to_string_lossy().into_owned())
172 .collect();
173 let matches = |f: &Family| {
174 let pattern = Path::new(f.default_schema)
175 .file_name()
176 .map(|n| n.to_string_lossy().into_owned())
177 .unwrap_or_default();
178 let (prefix, suffix) = pattern.split_once('*').unwrap_or((&pattern, ""));
179 names
180 .iter()
181 .any(|n| n.starts_with(prefix) && n.ends_with(suffix))
182 };
183 [&family::CGMES, &family::NC]
184 .into_iter()
185 .find(|f| matches(f))
186 }
187
188 pub fn load_table(family_id: &str, dir: &Path) -> Result<&'static Schema, SchemaError> {
193 let family = family::by_id(family_id)
194 .ok_or_else(|| SchemaError::UnknownFamily(family_id.to_string()))?;
195 load_family(family, dir)
196 }
197
198 fn load_family(family: &'static Family, dir: &Path) -> Result<&'static Schema, SchemaError> {
199 let file_pattern = Path::new(family.default_schema)
202 .file_name()
203 .map(|n| n.to_string_lossy().into_owned())
204 .unwrap_or_else(|| "*.rdf".to_string());
205 let pattern = dir.join(file_pattern);
206
207 let spec =
208 cimschema::import::import_schema_files(&pattern.to_string_lossy(), family, false)
209 .map_err(|e| SchemaError::Parse(e.to_string()))?;
210 Ok(build(&spec))
211 }
212
213 #[derive(Default)]
217 struct Interner {
218 seen: HashMap<String, &'static str>,
219 }
220
221 impl Interner {
222 fn intern(&mut self, s: &str) -> &'static str {
223 if let Some(v) = self.seen.get(s) {
224 return v;
225 }
226 let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
227 self.seen.insert(s.to_string(), leaked);
228 leaked
229 }
230
231 fn intern_all(&mut self, items: &[String]) -> &'static [&'static str] {
232 let v: Vec<&'static str> = items.iter().map(|s| self.intern(s)).collect();
233 Vec::leak(v)
234 }
235 }
236
237 fn attr_kind(a: &CimAttribute) -> AttrKind {
241 match cimschema::table::attr_kind(a) {
242 cimschema::table::Kind::Literal => AttrKind::Literal,
243 cimschema::table::Kind::Association => AttrKind::Association,
244 cimschema::table::Kind::Enum => AttrKind::Enum,
245 }
246 }
247
248 fn build(spec: &CimSpecification) -> &'static Schema {
249 let mut ids: Vec<&String> = spec.types.keys().collect();
252 ids.sort();
253 let index_of: HashMap<&str, usize> = ids
254 .iter()
255 .enumerate()
256 .map(|(i, id)| (id.as_str(), i))
257 .collect();
258
259 let mut interner = Interner::default();
260 let mut out: Vec<ClassDef> = Vec::with_capacity(ids.len());
261
262 for id in &ids {
263 let t = &spec.types[*id];
264 let attrs: Vec<AttrDef> = t
265 .attributes
266 .iter()
267 .map(|a| AttrDef {
268 id: interner.intern(&a.id),
269 ns: interner.intern(&a.namespace),
270 kind: attr_kind(a),
271 range: interner.intern(cimschema::table::attr_range(a)),
272 is_list: a.is_list,
273 used: a.is_association_used,
274 xsd: cimschema::table::xsd_type(a),
275 value_ns: interner.intern(cimschema::table::value_namespace(spec, a)),
276 origins: interner.intern_all(&a.origins),
277 comment: interner.intern(&a.comment),
278 })
279 .collect();
280
281 let qualified = format!("{}{}", spec.family.type_prefix, t.id);
282 out.push(ClassDef {
283 ns: interner.intern(&t.namespace),
284 local: interner.intern(&t.id),
285 qualified: interner.intern(&qualified),
286 super_class: index_of.get(t.super_type.as_str()).copied(),
287 concrete: !t.concrete_in.is_empty(),
288 attrs: Vec::leak(attrs),
289 origins: interner.intern_all(&t.origins),
290 comment: interner.intern(&t.comment),
291 });
292 }
293
294 let pairs = |interner: &mut Interner,
295 v: Vec<(&str, &str)>|
296 -> &'static [(&'static str, &'static str)] {
297 Vec::leak(
298 v.into_iter()
299 .map(|(a, b)| (interner.intern(a), interner.intern(b)))
300 .collect(),
301 )
302 };
303 let profiles = pairs(&mut interner, cimschema::table::profile_uris(spec));
304 let namespaces = pairs(&mut interner, cimschema::table::namespaces(spec));
305 let enums: Vec<EnumDef> = cimschema::table::enums(spec)
306 .into_iter()
307 .map(|e| EnumDef {
308 ns: interner.intern(&e.namespace),
309 local: interner.intern(&e.id),
310 comment: interner.intern(&e.comment),
311 values: Vec::leak(
312 e.values
313 .iter()
314 .map(|v| EnumValueDef {
315 id: interner.intern(&v.id),
316 comment: interner.intern(&v.comment),
317 })
318 .collect(),
319 ),
320 })
321 .collect();
322 Box::leak(Box::new(Schema {
323 classes: Vec::leak(out),
324 profiles,
325 namespaces,
326 enums: Vec::leak(enums),
327 }))
328 }
329}