Skip to main content

cimmodel/
base.rs

1use std::collections::{HashMap, HashSet};
2use std::hash::{BuildHasherDefault, Hasher};
3
4// --- Hashing -----------------------------------------------------------------
5
6/// A fast, non-cryptographic hasher for the decoder's maps.
7///
8/// Every field read during validation and every element lookup goes through a
9/// `String`-keyed map, and std's SipHash made those lookups a measurable share
10/// of a validation run. This is the multiply-rotate scheme of FxHash (as in
11/// `rustc-hash` 2): a word at a time, with the high bits rotated down at the
12/// end because hashbrown takes its bucket index from the low bits.
13///
14/// Written out rather than imported so the core crates carry no dependency for
15/// it. Not resistant to deliberately colliding keys, which is acceptable for a
16/// tool that reads grid model files rather than serving untrusted requests.
17#[derive(Default, Clone, Copy)]
18pub struct FastHasher {
19    hash: u64,
20}
21
22const SEED: u64 = 0xf135_7aea_2e62_a9c5;
23
24impl FastHasher {
25    #[inline]
26    fn add(&mut self, word: u64) {
27        self.hash = self.hash.wrapping_add(word).wrapping_mul(SEED);
28    }
29}
30
31impl Hasher for FastHasher {
32    #[inline]
33    fn write(&mut self, bytes: &[u8]) {
34        let mut chunks = bytes.chunks_exact(8);
35        for c in &mut chunks {
36            self.add(u64::from_le_bytes(c.try_into().expect("chunk of 8")));
37        }
38        let rest = chunks.remainder();
39        if !rest.is_empty() {
40            let mut buf = [0u8; 8];
41            buf[..rest.len()].copy_from_slice(rest);
42            self.add(u64::from_le_bytes(buf));
43        }
44    }
45    #[inline]
46    fn write_u8(&mut self, i: u8) {
47        self.add(i as u64);
48    }
49    #[inline]
50    fn write_u32(&mut self, i: u32) {
51        self.add(i as u64);
52    }
53    #[inline]
54    fn write_u64(&mut self, i: u64) {
55        self.add(i);
56    }
57    #[inline]
58    fn write_usize(&mut self, i: usize) {
59        self.add(i as u64);
60    }
61    #[inline]
62    fn finish(&self) -> u64 {
63        self.hash.rotate_left(26)
64    }
65}
66
67pub type FastBuildHasher = BuildHasherDefault<FastHasher>;
68pub type FastMap<K, V> = HashMap<K, V, FastBuildHasher>;
69pub type FastSet<T> = HashSet<T, FastBuildHasher>;
70/// An element's fields, keyed by `Class.attr`. Keys are `&'static`: a declared
71/// attribute's key is its id in the class table, any other goes through
72/// [`intern`], so a key is allocated once per process rather than per field.
73pub type FieldMap = FastMap<&'static str, FieldValue>;
74
75/// The one `&'static` copy of a field key the class tables do not hold — an
76/// attribute the element's class does not declare, as written in the file or
77/// set from JSON. Each distinct key is leaked once and kept for the process;
78/// there are as many as distinct undeclared attribute names, not fields.
79pub fn intern(key: &str) -> &'static str {
80    use std::cell::RefCell;
81    use std::sync::{Mutex, OnceLock};
82    thread_local! {
83        static LOCAL: RefCell<FastSet<&'static str>> = RefCell::new(FastSet::default());
84    }
85    static GLOBAL: OnceLock<Mutex<FastSet<&'static str>>> = OnceLock::new();
86    if let Some(k) = LOCAL.with(|l| l.borrow().get(key).copied()) {
87        return k;
88    }
89    let k = {
90        let mut global = GLOBAL.get_or_init(Default::default).lock().unwrap();
91        match global.get(key) {
92            Some(k) => *k,
93            None => {
94                let k: &'static str = Box::leak(key.to_owned().into_boxed_str());
95                global.insert(k);
96                k
97            }
98        }
99    };
100    LOCAL.with(|l| l.borrow_mut().insert(k));
101    k
102}
103
104/// The class of an object no class table knows — a SKOS concept, a PROV
105/// agent, a DCAT catalogue — named by its namespace and local name. One leaked
106/// `ClassDef` per distinct class, kept for the process like [`intern`]'s keys.
107/// Its `qualified` name is the class IRI, which no family's `by_type` keys use.
108pub fn foreign_class(ns: &str, local: &str) -> &'static ClassDef {
109    use std::sync::{Mutex, OnceLock};
110    static CLASSES: OnceLock<Mutex<FastMap<String, &'static ClassDef>>> = OnceLock::new();
111    let iri = format!("{ns}{local}");
112    let mut classes = CLASSES.get_or_init(Default::default).lock().unwrap();
113    if let Some(c) = classes.get(&iri) {
114        return c;
115    }
116    let qualified: &'static str = Box::leak(iri.clone().into_boxed_str());
117    let class: &'static ClassDef = Box::leak(Box::new(ClassDef {
118        ns: intern(ns),
119        local: &qualified[ns.len()..],
120        qualified,
121        super_class: None,
122        concrete: true,
123        attrs: &[],
124        origins: &[],
125        comment: "",
126    }));
127    classes.insert(iri, class);
128    class
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum FieldValue {
133    Text(String),
134    /// Repeated text element within one parsed element (e.g. the multiple
135    /// `md:Model.profile` entries of a combined EQ+SC file header).
136    TextList(Vec<String>),
137    Resource(String),
138    ResourceList(Vec<String>),
139}
140
141/// One value of a field, as a statement holds it: a text or a reference.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
143pub enum Value<'a> {
144    Text(&'a str),
145    Resource(&'a str),
146}
147
148impl Value<'_> {
149    /// As a field's single value.
150    pub fn owned(&self) -> FieldValue {
151        match *self {
152            Value::Text(t) => FieldValue::Text(t.to_string()),
153            Value::Resource(r) => FieldValue::Resource(r.to_string()),
154        }
155    }
156}
157
158impl PartialEq<FieldValue> for Value<'_> {
159    fn eq(&self, other: &FieldValue) -> bool {
160        match (self, other) {
161            (Value::Text(a), FieldValue::Text(b)) => *a == b,
162            (Value::Resource(a), FieldValue::Resource(b)) => *a == b,
163            _ => false,
164        }
165    }
166}
167
168impl FieldValue {
169    /// Its values one by one: a list's each, a single one alone.
170    pub fn values(&self) -> impl Iterator<Item = Value<'_>> {
171        let (texts, refs): (&[String], &[String]) = match self {
172            FieldValue::Text(t) => (std::slice::from_ref(t), &[]),
173            FieldValue::TextList(l) => (l.as_slice(), &[]),
174            FieldValue::Resource(r) => (&[], std::slice::from_ref(r)),
175            FieldValue::ResourceList(l) => (&[], l.as_slice()),
176        };
177        texts
178            .iter()
179            .map(|t| Value::Text(t))
180            .chain(refs.iter().map(|r| Value::Resource(r)))
181    }
182}
183
184// --- Elements ----------------------------------------------------------------
185
186/// One decoded CIM object: its class, its mRID, and its fields as written.
187///
188/// Every family decodes into this one type. The fields are the document's
189/// own, keyed by `Class.attr` (the XML element's local name), with values
190/// unparsed: what a class declares lives in its [`ClassDef`], not in a
191/// generated type, so an attribute the class does not declare and a value
192/// that does not parse are kept rather than dropped.
193#[derive(Debug, Clone)]
194pub struct Element {
195    class: &'static ClassDef,
196    mrid: String,
197    fields: FieldMap,
198    /// Fields assigned more than once within the element, which `sh:maxCount`
199    /// reads.
200    duplicate_fields: FastSet<&'static str>,
201    /// The `xml:lang` of each text value written with one, by field, in the
202    /// order read. `None` until a value carries one, so an element without
203    /// language tags — nearly all of them — pays a pointer.
204    langs: Option<Box<Langs>>,
205    /// The other classes files wrote the object under, when merged datasets
206    /// disagree — an SSH file's `cim:Equipment` for an EQ file's
207    /// `cim:ACLineSegment`. In RDF the object has every one of those types;
208    /// `class` is the most specific. `None` for nearly every element, so it
209    /// costs a pointer, like `langs`.
210    also: Option<Box<Types>>,
211    /// Every file that wrote the object only described it (`rdf:about`) and
212    /// none defined it (`rdf:ID`): an SSH file's `inService` for equipment
213    /// the EQ file defines. Elements not decoded from RDF/XML are defined.
214    described: bool,
215}
216
217/// `(field key, xml:lang)` for each tagged text value of an element.
218type Langs = Vec<(&'static str, Box<str>)>;
219
220/// The classes besides its own a merged element was written under.
221type Types = Vec<&'static ClassDef>;
222
223impl Element {
224    pub fn new(class: &'static ClassDef, mrid: String) -> Self {
225        Self {
226            class,
227            mrid,
228            fields: FieldMap::default(),
229            duplicate_fields: FastSet::default(),
230            langs: None,
231            also: None,
232            described: false,
233        }
234    }
235
236    pub fn with_fields(class: &'static ClassDef, mrid: String, fields: FieldMap) -> Self {
237        Self {
238            class,
239            mrid,
240            fields,
241            duplicate_fields: FastSet::default(),
242            langs: None,
243            also: None,
244            described: false,
245        }
246    }
247
248    pub fn class(&self) -> &'static ClassDef {
249        self.class
250    }
251
252    /// Every class the object is typed as: its class, then any other a merged
253    /// file wrote it under ([`CimDataset::merge`](crate::CimDataset::merge)).
254    pub fn types(&self) -> impl Iterator<Item = &'static ClassDef> + '_ {
255        std::iter::once(self.class).chain(self.also.iter().flat_map(|v| v.iter().copied()))
256    }
257
258    /// Record that a file also typed the object as `other`. Becomes its class
259    /// when it is a subclass of the current one (field keys name each
260    /// attribute's declaring class, so they stay valid); otherwise it is kept
261    /// beside it. Returns whether the class changed.
262    pub(crate) fn add_type(&mut self, other: &'static ClassDef, reg: &TypeRegistry) -> bool {
263        if self.types().any(|c| c.qualified == other.qualified) {
264            return false;
265        }
266        let promote = reg
267            .chain(other)
268            .iter()
269            .any(|c| c.qualified == self.class.qualified);
270        let kept = if promote {
271            std::mem::replace(&mut self.class, other)
272        } else {
273            other
274        };
275        self.also.get_or_insert_with(Default::default).push(kept);
276        promote
277    }
278
279    /// Whether some file defined the object (`rdf:ID`) rather than only
280    /// describing one defined elsewhere (`rdf:about`).
281    pub fn defined(&self) -> bool {
282        !self.described
283    }
284
285    /// Record that the file only described the object (`rdf:about`).
286    pub fn mark_described(&mut self) {
287        self.described = true;
288    }
289
290    pub fn mrid(&self) -> &str {
291        &self.mrid
292    }
293
294    /// Family-qualified class name, e.g. `"Terminal"` (CGMES) or
295    /// `"nc:Contingency"`. This is the `CimDataset::by_type` key.
296    pub fn type_name(&self) -> &'static str {
297        self.class.qualified
298    }
299
300    /// Bare CIM class name, without the family qualifier.
301    pub fn local_name(&self) -> &'static str {
302        self.class.local
303    }
304
305    /// RDF namespace IRI of the declaring class, trailing delimiter included.
306    pub fn type_ns(&self) -> &'static str {
307        self.class.ns
308    }
309
310    pub fn fields(&self) -> &FieldMap {
311        &self.fields
312    }
313
314    pub fn duplicate_fields(&self) -> &FastSet<&'static str> {
315        &self.duplicate_fields
316    }
317
318    /// The `xml:lang` tags of `key`'s text values, one per value that had
319    /// one. A value written without a tag has no entry, so a field whose
320    /// values outnumber its tags has an untagged value.
321    pub fn langs(&self, key: &str) -> impl Iterator<Item = &str> {
322        self.langs
323            .iter()
324            .flat_map(|l| l.iter())
325            .filter(move |(k, _)| *k == key)
326            .map(|(_, l)| &**l)
327    }
328
329    /// Record the `xml:lang` of a text value just added to `key`.
330    pub fn add_lang(&mut self, key: &'static str, lang: &str) {
331        self.langs
332            .get_or_insert_with(Default::default)
333            .push((key, lang.into()));
334    }
335
336    /// Hold `key`'s values as references, or as text: what a caller knows
337    /// that the class table does not ([`crate::CimDataset::element_from_json`]).
338    pub fn retype(&mut self, key: &str, reference: bool) {
339        if let Some(value) = self.fields.get_mut(key) {
340            *value = match (
341                std::mem::replace(value, FieldValue::Text(String::new())),
342                reference,
343            ) {
344                (FieldValue::Text(s), true) => FieldValue::Resource(s),
345                (FieldValue::TextList(v), true) => FieldValue::ResourceList(v),
346                (FieldValue::Resource(s), false) => FieldValue::Text(s),
347                (FieldValue::ResourceList(v), false) => FieldValue::TextList(v),
348                (other, _) => other,
349            };
350        }
351    }
352
353    pub fn get(&self, attr: &str) -> Option<&FieldValue> {
354        self.fields.get(attr)
355    }
356
357    pub fn get_str(&self, attr: &str) -> Option<&str> {
358        match self.fields.get(attr) {
359            Some(FieldValue::Text(s)) => Some(s.as_str()),
360            Some(FieldValue::TextList(v)) => v.first().map(String::as_str),
361            _ => None,
362        }
363    }
364
365    pub fn get_f64(&self, attr: &str) -> Option<f64> {
366        self.get_str(attr)?.parse().ok()
367    }
368
369    pub fn get_bool(&self, attr: &str) -> Option<bool> {
370        match self.get_str(attr)? {
371            "true" | "1" => Some(true),
372            "false" | "0" => Some(false),
373            _ => None,
374        }
375    }
376
377    /// Referenced MRIDs.
378    ///
379    /// Always a slice, even where the schema says the association is 1:1 — CGMES
380    /// has widened 1:1 to 1:many between versions, and a caller written against
381    /// a slice does not have to change when that happens.
382    pub fn get_refs(&self, attr: &str) -> &[String] {
383        match self.fields.get(attr) {
384            Some(FieldValue::Resource(s)) => std::slice::from_ref(s),
385            Some(FieldValue::ResourceList(v)) => v.as_slice(),
386            _ => &[],
387        }
388    }
389
390    /// First referenced MRID, for associations known to be single-valued.
391    pub fn get_ref(&self, attr: &str) -> Option<&str> {
392        self.get_refs(attr).first().map(String::as_str)
393    }
394
395    /// Add one value as the decoder reads it: a repeated key becomes a list
396    /// and is recorded in [`Element::duplicate_fields`].
397    pub fn add_field(&mut self, key: &'static str, val: FieldValue) {
398        match &val {
399            FieldValue::Resource(new_ref) => match self.fields.get_mut(key) {
400                Some(FieldValue::ResourceList(list)) => {
401                    list.push(new_ref.clone());
402                    self.duplicate_fields.insert(key);
403                    return;
404                }
405                Some(existing @ FieldValue::Resource(_)) => {
406                    let FieldValue::Resource(old) =
407                        std::mem::replace(existing, FieldValue::ResourceList(Vec::new()))
408                    else {
409                        unreachable!()
410                    };
411                    *existing = FieldValue::ResourceList(vec![old, new_ref.clone()]);
412                    self.duplicate_fields.insert(key);
413                    return;
414                }
415                _ => {}
416            },
417            FieldValue::Text(new_text) => match self.fields.get_mut(key) {
418                Some(FieldValue::TextList(list)) => {
419                    list.push(new_text.clone());
420                    self.duplicate_fields.insert(key);
421                    return;
422                }
423                Some(existing @ FieldValue::Text(_)) => {
424                    let FieldValue::Text(old) =
425                        std::mem::replace(existing, FieldValue::TextList(Vec::new()))
426                    else {
427                        unreachable!()
428                    };
429                    *existing = FieldValue::TextList(vec![old, new_text.clone()]);
430                    self.duplicate_fields.insert(key);
431                    return;
432                }
433                _ => {}
434            },
435            _ => {
436                if self.fields.contains_key(key) {
437                    self.duplicate_fields.insert(key);
438                }
439            }
440        }
441        self.fields.insert(key, val);
442    }
443
444    /// Whether `key` holds `value` (a [`FieldValue::Text`] or
445    /// [`FieldValue::Resource`]) among its values.
446    pub fn has_value(&self, key: &str, value: &FieldValue) -> bool {
447        self.fields
448            .get(key)
449            .is_some_and(|held| held.values().any(|v| v == *value))
450    }
451
452    /// Remove one of `key`'s values (a [`FieldValue::Text`] or
453    /// [`FieldValue::Resource`]), as a difference model's reverse statement
454    /// does. A list left with one value holds it alone; a field left with none
455    /// is gone. Returns whether the field held the value.
456    pub fn remove_value(&mut self, key: &str, value: &FieldValue) -> bool {
457        let Some(held) = self.fields.get_mut(key) else {
458            return false;
459        };
460        let left: Vec<FieldValue> = held
461            .values()
462            .filter(|v| *v != *value)
463            .map(|v| v.owned())
464            .collect();
465        if left.len() == held.values().count() {
466            return false;
467        }
468        let (k, _) = self.fields.remove_entry(key).expect("just held");
469        if let Some(langs) = self.langs.as_mut() {
470            langs.retain(|(l, _)| *l != k);
471        }
472        match left.len() {
473            0 => {
474                self.duplicate_fields.remove(k);
475            }
476            1 => {
477                self.duplicate_fields.remove(k);
478                self.fields.insert(k, left.into_iter().next().expect("one"));
479            }
480            _ => {
481                for v in left {
482                    self.add_field(k, v);
483                }
484            }
485        }
486        true
487    }
488
489    /// Make the object's types `types`: the first its class, the others kept
490    /// beside it ([`Element::types`]). Nothing for none.
491    pub(crate) fn set_types(&mut self, types: &[&'static ClassDef]) {
492        let Some((&first, rest)) = types.split_first() else {
493            return;
494        };
495        self.class = first;
496        self.also = (!rest.is_empty()).then(|| Box::new(rest.to_vec()));
497    }
498
499    /// Combine another file's view of the same object: a later scalar wins,
500    /// reference lists are joined. Duplicate tracking stays per file.
501    pub fn merge_from(&mut self, other: &Element) {
502        self.described &= other.described;
503        for (k, v) in &other.fields {
504            match v {
505                FieldValue::ResourceList(new_list) => match self.fields.get_mut(k) {
506                    Some(FieldValue::ResourceList(existing)) => {
507                        existing.extend(new_list.iter().cloned())
508                    }
509                    _ => {
510                        self.fields.insert(*k, v.clone());
511                    }
512                },
513                _ => {
514                    self.fields.insert(*k, v.clone());
515                    // The later file's text replaced ours, tags included.
516                    if let Some(l) = self.langs.as_mut() {
517                        l.retain(|(key, _)| key != k);
518                    }
519                    for lang in other.langs(k) {
520                        self.add_lang(k, lang);
521                    }
522                }
523            }
524        }
525    }
526
527    /// `{"id": mRID, "Class.attr": value, ...}`: a value is a string, a
528    /// repeated one an array of strings; when any text value had an
529    /// `xml:lang`, `"_lang"`: key → its tags in value order.
530    pub fn to_json_value(&self) -> serde_json::Value {
531        let mut map = serde_json::Map::with_capacity(self.fields.len() + 2);
532        map.insert(
533            "id".to_string(),
534            serde_json::Value::String(self.mrid.clone()),
535        );
536        for (k, v) in &self.fields {
537            map.insert(k.to_string(), field_to_json(v));
538        }
539        if let Some(langs) = &self.langs {
540            let mut tags = serde_json::Map::new();
541            for (key, lang) in langs.iter() {
542                if let serde_json::Value::Array(list) = tags
543                    .entry(key.to_string())
544                    .or_insert_with(|| serde_json::Value::Array(Vec::new()))
545                {
546                    list.push(serde_json::Value::String(lang.to_string()));
547                }
548            }
549            map.insert(LANG_KEY.to_string(), serde_json::Value::Object(tags));
550        }
551        serde_json::Value::Object(map)
552    }
553
554    /// The inverse of [`Element::to_json_value`]. Whether a string is a
555    /// reference or text comes from the attribute's declaration; an attribute
556    /// the class does not declare is read as text.
557    pub fn from_json(
558        class: &'static ClassDef,
559        reg: &TypeRegistry,
560        value: &serde_json::Value,
561    ) -> Result<Self, String> {
562        let obj = value.as_object().ok_or("element is not a JSON object")?;
563        let mrid = obj
564            .get("id")
565            .and_then(|v| v.as_str())
566            .ok_or("element has no \"id\"")?
567            .to_string();
568        let mut fields = FieldMap::default();
569        for (k, v) in obj {
570            if k == "id" || k == "_type" || k == LANG_KEY {
571                continue;
572            }
573            let is_ref = reg
574                .attr(class, k)
575                .is_some_and(|a| a.kind != AttrKind::Literal);
576            let value = match v {
577                serde_json::Value::String(s) if is_ref => FieldValue::Resource(s.clone()),
578                serde_json::Value::String(s) => FieldValue::Text(s.clone()),
579                serde_json::Value::Array(items) => {
580                    let items: Vec<String> = items
581                        .iter()
582                        .map(|i| {
583                            i.as_str()
584                                .map(str::to_string)
585                                .ok_or(format!("{k}: list item is not a string"))
586                        })
587                        .collect::<Result<_, _>>()?;
588                    if is_ref {
589                        FieldValue::ResourceList(items)
590                    } else {
591                        FieldValue::TextList(items)
592                    }
593                }
594                other => return Err(format!("{k}: expected a string or an array, got {other}")),
595            };
596            fields.insert(reg.field_key(class, k), value);
597        }
598        let mut element = Self::with_fields(class, mrid, fields);
599        if let Some(tags) = obj.get(LANG_KEY).and_then(|t| t.as_object()) {
600            for (k, list) in tags {
601                let key = reg.field_key(class, k);
602                for lang in list
603                    .as_array()
604                    .into_iter()
605                    .flatten()
606                    .filter_map(|l| l.as_str())
607                {
608                    element.add_lang(key, lang);
609                }
610            }
611        }
612        Ok(element)
613    }
614}
615
616/// The JSON key of an element's language tags ([`Element::to_json_value`]).
617pub const LANG_KEY: &str = "_lang";
618
619fn field_to_json(v: &FieldValue) -> serde_json::Value {
620    match v {
621        FieldValue::Text(s) | FieldValue::Resource(s) => serde_json::Value::String(s.clone()),
622        FieldValue::TextList(v) | FieldValue::ResourceList(v) => {
623            serde_json::Value::Array(v.iter().cloned().map(serde_json::Value::String).collect())
624        }
625    }
626}
627
628// --- Classes -----------------------------------------------------------------
629
630/// How an attribute's value is carried in RDF/XML.
631#[derive(Debug, Clone, Copy, PartialEq, Eq)]
632pub enum AttrKind {
633    /// A literal, written as element text.
634    Literal,
635    /// A reference to another object, written as `rdf:resource`.
636    Association,
637    /// An enumeration value, written as `rdf:resource` to a vocabulary IRI.
638    Enum,
639}
640
641/// One attribute of a class, as the schema declares it.
642#[derive(Debug)]
643pub struct AttrDef {
644    /// `Class.attr`, matching the key in [`Element::fields`].
645    pub id: &'static str,
646    /// The attribute's RDF namespace: its predicate IRI is `ns` + `id`.
647    pub ns: &'static str,
648    pub kind: AttrKind,
649    /// The CIM datatype of a literal; the class an association or enumeration
650    /// points to.
651    pub range: &'static str,
652    pub is_list: bool,
653    /// Whether a profile exchanges this end of the association — `false` for the
654    /// inverse ends the vocabularies declare but no dataset writes. Literals and
655    /// enumerations are always used.
656    pub used: bool,
657    /// The XSD datatype of a literal, as the local name after
658    /// `http://www.w3.org/2001/XMLSchema#` (`"double"`); `""` otherwise.
659    pub xsd: &'static str,
660    /// The namespace of an enumeration's values (the decoder keeps a value after
661    /// its `#`); `""` otherwise.
662    pub value_ns: &'static str,
663    /// Profile codes that carry this attribute.
664    pub origins: &'static [&'static str],
665    /// The vocabulary's `rdfs:comment`, HTML removed and on one line; `""`
666    /// if it has none.
667    pub comment: &'static str,
668}
669
670/// What one family's schema says, as a table: its classes, the profiles it
671/// defines and the namespaces its vocabularies bind. Generated by `cimgen`, or
672/// read from RDFS at runtime (`schema_source`).
673#[derive(Debug)]
674pub struct Schema {
675    pub classes: &'static [ClassDef],
676    /// Profile code → profile URI, the value a dataset's header declares; sorted
677    /// by code.
678    pub profiles: &'static [(&'static str, &'static str)],
679    /// XML prefix → namespace IRI; sorted by prefix.
680    pub namespaces: &'static [(&'static str, &'static str)],
681    /// Enumerations, sorted by name.
682    pub enums: &'static [EnumDef],
683}
684
685impl Schema {
686    /// The enumeration called `name` (`WindingConnection`).
687    pub fn enumeration(&self, name: &str) -> Option<&'static EnumDef> {
688        let enums: &'static [EnumDef] = self.enums;
689        enums
690            .binary_search_by_key(&name, |e| e.local)
691            .ok()
692            .map(|i| &enums[i])
693    }
694
695    /// The enumeration value `id` names, as the decoder keeps it
696    /// (`WindingConnection.D`), with its enumeration.
697    pub fn enum_value(&self, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
698        let e = self.enumeration(id.split_once('.')?.0)?;
699        Some((e, e.values.iter().find(|v| v.id == id)?))
700    }
701}
702
703/// An enumeration of the schema and the values it allows.
704#[derive(Debug)]
705pub struct EnumDef {
706    pub ns: &'static str,
707    pub local: &'static str,
708    /// The vocabulary's `rdfs:comment`, as for [`ClassDef::comment`].
709    pub comment: &'static str,
710    /// In vocabulary order.
711    pub values: &'static [EnumValueDef],
712}
713
714/// One value of an enumeration.
715#[derive(Debug)]
716pub struct EnumValueDef {
717    /// `Enum.value`, as the decoder keeps a value after its `#`.
718    pub id: &'static str,
719    /// The vocabulary's `rdfs:comment`, as for [`ClassDef::comment`].
720    pub comment: &'static str,
721}
722
723/// A class of the schema: what it is called and what it declares.
724#[derive(Debug)]
725pub struct ClassDef {
726    pub ns: &'static str,
727    pub local: &'static str,
728    /// Family-qualified name; the `CimDataset::by_type` key.
729    pub qualified: &'static str,
730    /// Index of the super class within the same table.
731    pub super_class: Option<usize>,
732    pub concrete: bool,
733    /// The attributes this class declares itself, unused association ends
734    /// included ([`AttrDef::used`]); see [`TypeRegistry::attr`] for inherited
735    /// ones.
736    pub attrs: &'static [AttrDef],
737    pub origins: &'static [&'static str],
738    /// The vocabulary's `rdfs:comment`, HTML removed and on one line; `""`
739    /// if it has none.
740    pub comment: &'static str,
741}
742
743impl ClassDef {
744    /// An attribute this class declares itself (not an inherited one).
745    pub fn attr(&self, id: &str) -> Option<&'static AttrDef> {
746        self.attrs.iter().find(|a| a.id == id)
747    }
748}
749
750/// Namespace-aware class lookup, and every attribute each class declares.
751///
752/// RDF/XML identifies a class by `(namespace, local name)`, and the two profile
753/// families overlap on 164 local names — both even spell the prefix `cim`, so
754/// only the xmlns binding distinguishes them. Lookup is therefore keyed on the
755/// resolved namespace, with a bare-name fallback (CGMES only) that preserves
756/// the historical behaviour for files whose prefixes are unbound or unexpected.
757#[derive(Default)]
758pub struct TypeRegistry {
759    by_ns: FastMap<&'static str, FastMap<&'static str, &'static ClassDef>>,
760    bare: FastMap<&'static str, &'static ClassDef>,
761    by_type_name: FastMap<&'static str, &'static ClassDef>,
762    /// Qualified class name → every attribute it declares, inherited ones
763    /// included. Built once from the class tables.
764    declared: FastMap<&'static str, FastMap<&'static str, &'static AttrDef>>,
765    /// Qualified class name → the class and its ancestors, root first.
766    chain: FastMap<&'static str, Vec<&'static ClassDef>>,
767    /// Each registered family, in registration order.
768    families: Vec<FamilyTable>,
769}
770
771/// One family as registered: its schema, the `by_type` prefix its classes
772/// carry (`""` for CGMES, `"nc:"`), and its attributes by id.
773struct FamilyTable {
774    id: &'static str,
775    prefix: &'static str,
776    schema: &'static Schema,
777    /// Attribute id → its first declaration in table order. An id names one
778    /// predicate, whichever class declares it.
779    attrs: FastMap<&'static str, &'static AttrDef>,
780}
781
782impl TypeRegistry {
783    pub fn new() -> Self {
784        Self::default()
785    }
786
787    /// Register a family's schema under `id`. `bare_fallback` adds its classes
788    /// to the bare-name fallback: an unbound prefix means the families cannot
789    /// be told apart, so only the default family (CGMES) takes it.
790    pub fn add_family(&mut self, id: &'static str, schema: &'static Schema, bare_fallback: bool) {
791        let classes = schema.classes;
792        let prefix = classes
793            .first()
794            .and_then(|c| c.qualified.strip_suffix(c.local))
795            .unwrap_or("");
796        let mut by_id = FastMap::default();
797        for class in classes {
798            for a in class.attrs {
799                by_id.entry(a.id).or_insert(a);
800            }
801        }
802        self.families.push(FamilyTable {
803            id,
804            prefix,
805            schema,
806            attrs: by_id,
807        });
808        for class in classes {
809            self.by_ns
810                .entry(class.ns)
811                .or_default()
812                .insert(class.local, class);
813            self.by_type_name.insert(class.qualified, class);
814            if bare_fallback {
815                self.bare.insert(class.local, class);
816            }
817            let mut attrs = FastMap::default();
818            let mut chain = Vec::new();
819            let mut next = Some(class);
820            while let Some(c) = next {
821                for a in c.attrs {
822                    attrs.entry(a.id).or_insert(a);
823                }
824                chain.push(c);
825                next = c.super_class.map(|i| &classes[i]);
826            }
827            chain.reverse();
828            self.declared.insert(class.qualified, attrs);
829            self.chain.insert(class.qualified, chain);
830        }
831    }
832
833    /// Lookup table for one namespace, resolved once per XML prefix per file.
834    pub fn ns_table(&self, ns: &str) -> Option<&FastMap<&'static str, &'static ClassDef>> {
835        self.by_ns.get(ns)
836    }
837
838    pub fn bare(&self) -> &FastMap<&'static str, &'static ClassDef> {
839        &self.bare
840    }
841
842    pub fn by_type_name(&self, name: &str) -> Option<&'static ClassDef> {
843        self.by_type_name.get(name).copied()
844    }
845
846    /// The attribute `id` if `class` declares it, itself or by inheritance.
847    pub fn attr(&self, class: &ClassDef, id: &str) -> Option<&'static AttrDef> {
848        self.declared.get(class.qualified)?.get(id).copied()
849    }
850
851    /// The attributes `class` declares, inherited ones included, by id — for a
852    /// caller that resolves many keys of one element.
853    pub fn declared(&self, class: &ClassDef) -> Option<&FastMap<&'static str, &'static AttrDef>> {
854        self.declared.get(class.qualified)
855    }
856
857    /// The `&'static` key a field `id` of `class` is stored under.
858    pub fn field_key(&self, class: &ClassDef, id: &str) -> &'static str {
859        self.attr(class, id).map_or_else(|| intern(id), |a| a.id)
860    }
861
862    /// `class` and its ancestors, root first.
863    pub fn chain(&self, class: &ClassDef) -> &[&'static ClassDef] {
864        self.chain.get(class.qualified).map_or(&[], Vec::as_slice)
865    }
866
867    /// The `by_type` keys of the concrete classes at or below `qualified`,
868    /// sorted: what instances of a class can be typed as.
869    pub fn concrete_descendants(&self, qualified: &str) -> Vec<&'static str> {
870        let mut out: Vec<&'static str> = self
871            .chain
872            .iter()
873            .filter(|(_, chain)| chain.iter().any(|c| c.qualified == qualified))
874            .filter_map(|(q, _)| {
875                self.by_type_name
876                    .get(q)
877                    .filter(|c| c.concrete)
878                    .map(|c| c.qualified)
879            })
880            .collect();
881        out.sort_unstable();
882        out
883    }
884
885    /// Every attribute `class` declares, inherited ones included.
886    pub fn attrs(&self, class: &ClassDef) -> impl Iterator<Item = &'static AttrDef> + '_ {
887        self.declared
888            .get(class.qualified)
889            .into_iter()
890            .flat_map(|m| m.values().copied())
891    }
892
893    /// The schema registered as `family` (`"cgmes"`, `"nc"`).
894    pub fn schema(&self, family: &str) -> Option<&'static Schema> {
895        self.family(family).map(|f| f.schema)
896    }
897
898    fn family(&self, id: &str) -> Option<&FamilyTable> {
899        self.families.iter().find(|f| f.id == id)
900    }
901
902    /// The enumeration value `id` (`WindingConnection.D`) in the family of
903    /// `class`, which an element of `class` uses it on.
904    pub fn enum_value(
905        &self,
906        class: &ClassDef,
907        id: &str,
908    ) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
909        self.schema(self.family_of(class.qualified)?)?
910            .enum_value(id)
911    }
912
913    /// The family a `by_type` key belongs to, by its prefix.
914    pub fn family_of(&self, type_name: &str) -> Option<&'static str> {
915        // The longest matching prefix, so `nc:X` is not taken for CGMES's "".
916        self.families
917            .iter()
918            .filter(|f| type_name.starts_with(f.prefix))
919            .max_by_key(|f| f.prefix.len())
920            .map(|f| f.id)
921    }
922
923    /// The attribute `id` as `family` declares it on any class — what a field
924    /// key names when the element's own class does not declare it.
925    pub fn family_attr(&self, family: &str, id: &str) -> Option<&'static AttrDef> {
926        self.family(family)?.attrs.get(id).copied()
927    }
928
929    /// The attribute a field `key` of an element of `class` stands for: the
930    /// class's own declaration, else the family's.
931    pub fn attr_of(&self, class: &ClassDef, key: &str) -> Option<&'static AttrDef> {
932        self.attr(class, key)
933            .or_else(|| self.family_attr(self.family_of(class.qualified)?, key))
934    }
935}