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.iter().map(|t| Value::Text(t)).chain(refs.iter().map(|r| Value::Resource(r)))
178    }
179}
180
181// --- Elements ----------------------------------------------------------------
182
183/// One decoded CIM object: its class, its mRID, and its fields as written.
184///
185/// Every family decodes into this one type. The fields are the document's
186/// own, keyed by `Class.attr` (the XML element's local name), with values
187/// unparsed: what a class declares lives in its [`ClassDef`], not in a
188/// generated type, so an attribute the class does not declare and a value
189/// that does not parse are kept rather than dropped.
190#[derive(Debug, Clone)]
191pub struct Element {
192    class: &'static ClassDef,
193    mrid: String,
194    fields: FieldMap,
195    /// Fields assigned more than once within the element, which `sh:maxCount`
196    /// reads.
197    duplicate_fields: FastSet<&'static str>,
198    /// The `xml:lang` of each text value written with one, by field, in the
199    /// order read. `None` until a value carries one, so an element without
200    /// language tags — nearly all of them — pays a pointer.
201    langs: Option<Box<Langs>>,
202    /// The other classes files wrote the object under, when merged datasets
203    /// disagree — an SSH file's `cim:Equipment` for an EQ file's
204    /// `cim:ACLineSegment`. In RDF the object has every one of those types;
205    /// `class` is the most specific. `None` for nearly every element, so it
206    /// costs a pointer, like `langs`.
207    also: Option<Box<Types>>,
208    /// Every file that wrote the object only described it (`rdf:about`) and
209    /// none defined it (`rdf:ID`): an SSH file's `inService` for equipment
210    /// the EQ file defines. Elements not decoded from RDF/XML are defined.
211    described: bool,
212}
213
214/// `(field key, xml:lang)` for each tagged text value of an element.
215type Langs = Vec<(&'static str, Box<str>)>;
216
217/// The classes besides its own a merged element was written under.
218type Types = Vec<&'static ClassDef>;
219
220impl Element {
221    pub fn new(class: &'static ClassDef, mrid: String) -> Self {
222        Self { class, mrid, fields: FieldMap::default(), duplicate_fields: FastSet::default(), langs: None, also: None, described: false }
223    }
224
225    pub fn with_fields(class: &'static ClassDef, mrid: String, fields: FieldMap) -> Self {
226        Self { class, mrid, fields, duplicate_fields: FastSet::default(), langs: None, also: None, described: false }
227    }
228
229    pub fn class(&self) -> &'static ClassDef {
230        self.class
231    }
232
233    /// Every class the object is typed as: its class, then any other a merged
234    /// file wrote it under ([`CimDataset::merge`](crate::CimDataset::merge)).
235    pub fn types(&self) -> impl Iterator<Item = &'static ClassDef> + '_ {
236        std::iter::once(self.class).chain(self.also.iter().flat_map(|v| v.iter().copied()))
237    }
238
239    /// Record that a file also typed the object as `other`. Becomes its class
240    /// when it is a subclass of the current one (field keys name each
241    /// attribute's declaring class, so they stay valid); otherwise it is kept
242    /// beside it. Returns whether the class changed.
243    pub(crate) fn add_type(&mut self, other: &'static ClassDef, reg: &TypeRegistry) -> bool {
244        if self.types().any(|c| c.qualified == other.qualified) {
245            return false;
246        }
247        let promote = reg.chain(other).iter().any(|c| c.qualified == self.class.qualified);
248        let kept = if promote { std::mem::replace(&mut self.class, other) } else { other };
249        self.also.get_or_insert_with(Default::default).push(kept);
250        promote
251    }
252
253    /// Whether some file defined the object (`rdf:ID`) rather than only
254    /// describing one defined elsewhere (`rdf:about`).
255    pub fn defined(&self) -> bool {
256        !self.described
257    }
258
259    /// Record that the file only described the object (`rdf:about`).
260    pub fn mark_described(&mut self) {
261        self.described = true;
262    }
263
264    pub fn mrid(&self) -> &str {
265        &self.mrid
266    }
267
268    /// Family-qualified class name, e.g. `"Terminal"` (CGMES) or
269    /// `"nc:Contingency"`. This is the `CimDataset::by_type` key.
270    pub fn type_name(&self) -> &'static str {
271        self.class.qualified
272    }
273
274    /// Bare CIM class name, without the family qualifier.
275    pub fn local_name(&self) -> &'static str {
276        self.class.local
277    }
278
279    /// RDF namespace IRI of the declaring class, trailing delimiter included.
280    pub fn type_ns(&self) -> &'static str {
281        self.class.ns
282    }
283
284    pub fn fields(&self) -> &FieldMap {
285        &self.fields
286    }
287
288    pub fn duplicate_fields(&self) -> &FastSet<&'static str> {
289        &self.duplicate_fields
290    }
291
292    /// The `xml:lang` tags of `key`'s text values, one per value that had
293    /// one. A value written without a tag has no entry, so a field whose
294    /// values outnumber its tags has an untagged value.
295    pub fn langs(&self, key: &str) -> impl Iterator<Item = &str> {
296        self.langs.iter().flat_map(|l| l.iter()).filter(move |(k, _)| *k == key).map(|(_, l)| &**l)
297    }
298
299    /// Record the `xml:lang` of a text value just added to `key`.
300    pub fn add_lang(&mut self, key: &'static str, lang: &str) {
301        self.langs.get_or_insert_with(Default::default).push((key, lang.into()));
302    }
303
304    /// Hold `key`'s values as references, or as text: what a caller knows
305    /// that the class table does not ([`crate::CimDataset::element_from_json`]).
306    pub fn retype(&mut self, key: &str, reference: bool) {
307        if let Some(value) = self.fields.get_mut(key) {
308            *value = match (std::mem::replace(value, FieldValue::Text(String::new())), reference) {
309                (FieldValue::Text(s), true) => FieldValue::Resource(s),
310                (FieldValue::TextList(v), true) => FieldValue::ResourceList(v),
311                (FieldValue::Resource(s), false) => FieldValue::Text(s),
312                (FieldValue::ResourceList(v), false) => FieldValue::TextList(v),
313                (other, _) => other,
314            };
315        }
316    }
317
318    pub fn get(&self, attr: &str) -> Option<&FieldValue> {
319        self.fields.get(attr)
320    }
321
322    pub fn get_str(&self, attr: &str) -> Option<&str> {
323        match self.fields.get(attr) {
324            Some(FieldValue::Text(s)) => Some(s.as_str()),
325            Some(FieldValue::TextList(v)) => v.first().map(String::as_str),
326            _ => None,
327        }
328    }
329
330    pub fn get_f64(&self, attr: &str) -> Option<f64> {
331        self.get_str(attr)?.parse().ok()
332    }
333
334    pub fn get_bool(&self, attr: &str) -> Option<bool> {
335        match self.get_str(attr)? {
336            "true" | "1" => Some(true),
337            "false" | "0" => Some(false),
338            _ => None,
339        }
340    }
341
342    /// Referenced MRIDs.
343    ///
344    /// Always a slice, even where the schema says the association is 1:1 — CGMES
345    /// has widened 1:1 to 1:many between versions, and a caller written against
346    /// a slice does not have to change when that happens.
347    pub fn get_refs(&self, attr: &str) -> &[String] {
348        match self.fields.get(attr) {
349            Some(FieldValue::Resource(s)) => std::slice::from_ref(s),
350            Some(FieldValue::ResourceList(v)) => v.as_slice(),
351            _ => &[],
352        }
353    }
354
355    /// First referenced MRID, for associations known to be single-valued.
356    pub fn get_ref(&self, attr: &str) -> Option<&str> {
357        self.get_refs(attr).first().map(String::as_str)
358    }
359
360    /// Add one value as the decoder reads it: a repeated key becomes a list
361    /// and is recorded in [`Element::duplicate_fields`].
362    pub fn add_field(&mut self, key: &'static str, val: FieldValue) {
363        match &val {
364            FieldValue::Resource(new_ref) => match self.fields.get_mut(key) {
365                Some(FieldValue::ResourceList(list)) => {
366                    list.push(new_ref.clone());
367                    self.duplicate_fields.insert(key);
368                    return;
369                }
370                Some(existing @ FieldValue::Resource(_)) => {
371                    let FieldValue::Resource(old) = std::mem::replace(existing, FieldValue::ResourceList(Vec::new())) else {
372                        unreachable!()
373                    };
374                    *existing = FieldValue::ResourceList(vec![old, new_ref.clone()]);
375                    self.duplicate_fields.insert(key);
376                    return;
377                }
378                _ => {}
379            },
380            FieldValue::Text(new_text) => match self.fields.get_mut(key) {
381                Some(FieldValue::TextList(list)) => {
382                    list.push(new_text.clone());
383                    self.duplicate_fields.insert(key);
384                    return;
385                }
386                Some(existing @ FieldValue::Text(_)) => {
387                    let FieldValue::Text(old) = std::mem::replace(existing, FieldValue::TextList(Vec::new())) else {
388                        unreachable!()
389                    };
390                    *existing = FieldValue::TextList(vec![old, new_text.clone()]);
391                    self.duplicate_fields.insert(key);
392                    return;
393                }
394                _ => {}
395            },
396            _ => {
397                if self.fields.contains_key(key) {
398                    self.duplicate_fields.insert(key);
399                }
400            }
401        }
402        self.fields.insert(key, val);
403    }
404
405    /// Whether `key` holds `value` (a [`FieldValue::Text`] or
406    /// [`FieldValue::Resource`]) among its values.
407    pub fn has_value(&self, key: &str, value: &FieldValue) -> bool {
408        self.fields.get(key).is_some_and(|held| held.values().any(|v| v == *value))
409    }
410
411    /// Remove one of `key`'s values (a [`FieldValue::Text`] or
412    /// [`FieldValue::Resource`]), as a difference model's reverse statement
413    /// does. A list left with one value holds it alone; a field left with none
414    /// is gone. Returns whether the field held the value.
415    pub fn remove_value(&mut self, key: &str, value: &FieldValue) -> bool {
416        let Some(held) = self.fields.get_mut(key) else { return false };
417        let left: Vec<FieldValue> = held.values().filter(|v| *v != *value).map(|v| v.owned()).collect();
418        if left.len() == held.values().count() {
419            return false;
420        }
421        let (k, _) = self.fields.remove_entry(key).expect("just held");
422        if let Some(langs) = self.langs.as_mut() {
423            langs.retain(|(l, _)| *l != k);
424        }
425        match left.len() {
426            0 => {
427                self.duplicate_fields.remove(k);
428            }
429            1 => {
430                self.duplicate_fields.remove(k);
431                self.fields.insert(k, left.into_iter().next().expect("one"));
432            }
433            _ => {
434                for v in left {
435                    self.add_field(k, v);
436                }
437            }
438        }
439        true
440    }
441
442    /// Make the object's types `types`: the first its class, the others kept
443    /// beside it ([`Element::types`]). Nothing for none.
444    pub(crate) fn set_types(&mut self, types: &[&'static ClassDef]) {
445        let Some((&first, rest)) = types.split_first() else { return };
446        self.class = first;
447        self.also = (!rest.is_empty()).then(|| Box::new(rest.to_vec()));
448    }
449
450    /// Combine another file's view of the same object: a later scalar wins,
451    /// reference lists are joined. Duplicate tracking stays per file.
452    pub fn merge_from(&mut self, other: &Element) {
453        self.described &= other.described;
454        for (k, v) in &other.fields {
455            match v {
456                FieldValue::ResourceList(new_list) => match self.fields.get_mut(k) {
457                    Some(FieldValue::ResourceList(existing)) => existing.extend(new_list.iter().cloned()),
458                    _ => {
459                        self.fields.insert(*k, v.clone());
460                    }
461                },
462                _ => {
463                    self.fields.insert(*k, v.clone());
464                    // The later file's text replaced ours, tags included.
465                    if let Some(l) = self.langs.as_mut() {
466                        l.retain(|(key, _)| key != k);
467                    }
468                    for lang in other.langs(k) {
469                        self.add_lang(k, lang);
470                    }
471                }
472            }
473        }
474    }
475
476    /// `{"id": mRID, "Class.attr": value, ...}`: a value is a string, a
477    /// repeated one an array of strings; when any text value had an
478    /// `xml:lang`, `"_lang"`: key → its tags in value order.
479    pub fn to_json_value(&self) -> serde_json::Value {
480        let mut map = serde_json::Map::with_capacity(self.fields.len() + 2);
481        map.insert("id".to_string(), serde_json::Value::String(self.mrid.clone()));
482        for (k, v) in &self.fields {
483            map.insert(k.to_string(), field_to_json(v));
484        }
485        if let Some(langs) = &self.langs {
486            let mut tags = serde_json::Map::new();
487            for (key, lang) in langs.iter() {
488                if let serde_json::Value::Array(list) =
489                    tags.entry(key.to_string()).or_insert_with(|| serde_json::Value::Array(Vec::new()))
490                {
491                    list.push(serde_json::Value::String(lang.to_string()));
492                }
493            }
494            map.insert(LANG_KEY.to_string(), serde_json::Value::Object(tags));
495        }
496        serde_json::Value::Object(map)
497    }
498
499    /// The inverse of [`Element::to_json_value`]. Whether a string is a
500    /// reference or text comes from the attribute's declaration; an attribute
501    /// the class does not declare is read as text.
502    pub fn from_json(
503        class: &'static ClassDef,
504        reg: &TypeRegistry,
505        value: &serde_json::Value,
506    ) -> Result<Self, String> {
507        let obj = value.as_object().ok_or("element is not a JSON object")?;
508        let mrid = obj.get("id").and_then(|v| v.as_str()).ok_or("element has no \"id\"")?.to_string();
509        let mut fields = FieldMap::default();
510        for (k, v) in obj {
511            if k == "id" || k == "_type" || k == LANG_KEY {
512                continue;
513            }
514            let is_ref = reg.attr(class, k).is_some_and(|a| a.kind != AttrKind::Literal);
515            let value = match v {
516                serde_json::Value::String(s) if is_ref => FieldValue::Resource(s.clone()),
517                serde_json::Value::String(s) => FieldValue::Text(s.clone()),
518                serde_json::Value::Array(items) => {
519                    let items: Vec<String> = items
520                        .iter()
521                        .map(|i| i.as_str().map(str::to_string).ok_or(format!("{k}: list item is not a string")))
522                        .collect::<Result<_, _>>()?;
523                    if is_ref { FieldValue::ResourceList(items) } else { FieldValue::TextList(items) }
524                }
525                other => return Err(format!("{k}: expected a string or an array, got {other}")),
526            };
527            fields.insert(reg.field_key(class, k), value);
528        }
529        let mut element = Self::with_fields(class, mrid, fields);
530        if let Some(tags) = obj.get(LANG_KEY).and_then(|t| t.as_object()) {
531            for (k, list) in tags {
532                let key = reg.field_key(class, k);
533                for lang in list.as_array().into_iter().flatten().filter_map(|l| l.as_str()) {
534                    element.add_lang(key, lang);
535                }
536            }
537        }
538        Ok(element)
539    }
540}
541
542/// The JSON key of an element's language tags ([`Element::to_json_value`]).
543pub const LANG_KEY: &str = "_lang";
544
545fn field_to_json(v: &FieldValue) -> serde_json::Value {
546    match v {
547        FieldValue::Text(s) | FieldValue::Resource(s) => serde_json::Value::String(s.clone()),
548        FieldValue::TextList(v) | FieldValue::ResourceList(v) => {
549            serde_json::Value::Array(v.iter().cloned().map(serde_json::Value::String).collect())
550        }
551    }
552}
553
554// --- Classes -----------------------------------------------------------------
555
556/// How an attribute's value is carried in RDF/XML.
557#[derive(Debug, Clone, Copy, PartialEq, Eq)]
558pub enum AttrKind {
559    /// A literal, written as element text.
560    Literal,
561    /// A reference to another object, written as `rdf:resource`.
562    Association,
563    /// An enumeration value, written as `rdf:resource` to a vocabulary IRI.
564    Enum,
565}
566
567/// One attribute of a class, as the schema declares it.
568#[derive(Debug)]
569pub struct AttrDef {
570    /// `Class.attr`, matching the key in [`Element::fields`].
571    pub id: &'static str,
572    /// The attribute's RDF namespace: its predicate IRI is `ns` + `id`.
573    pub ns: &'static str,
574    pub kind: AttrKind,
575    /// The CIM datatype of a literal; the class an association or enumeration
576    /// points to.
577    pub range: &'static str,
578    pub is_list: bool,
579    /// Whether a profile exchanges this end of the association — `false` for the
580    /// inverse ends the vocabularies declare but no dataset writes. Literals and
581    /// enumerations are always used.
582    pub used: bool,
583    /// The XSD datatype of a literal, as the local name after
584    /// `http://www.w3.org/2001/XMLSchema#` (`"double"`); `""` otherwise.
585    pub xsd: &'static str,
586    /// The namespace of an enumeration's values (the decoder keeps a value after
587    /// its `#`); `""` otherwise.
588    pub value_ns: &'static str,
589    /// Profile codes that carry this attribute.
590    pub origins: &'static [&'static str],
591    /// The vocabulary's `rdfs:comment`, HTML removed and on one line; `""`
592    /// if it has none.
593    pub comment: &'static str,
594}
595
596/// What one family's schema says, as a table: its classes, the profiles it
597/// defines and the namespaces its vocabularies bind. Generated by `cimgen`, or
598/// read from RDFS at runtime (`schema_source`).
599#[derive(Debug)]
600pub struct Schema {
601    pub classes: &'static [ClassDef],
602    /// Profile code → profile URI, the value a dataset's header declares; sorted
603    /// by code.
604    pub profiles: &'static [(&'static str, &'static str)],
605    /// XML prefix → namespace IRI; sorted by prefix.
606    pub namespaces: &'static [(&'static str, &'static str)],
607    /// Enumerations, sorted by name.
608    pub enums: &'static [EnumDef],
609}
610
611impl Schema {
612    /// The enumeration called `name` (`WindingConnection`).
613    pub fn enumeration(&self, name: &str) -> Option<&'static EnumDef> {
614        let enums: &'static [EnumDef] = self.enums;
615        enums.binary_search_by_key(&name, |e| e.local).ok().map(|i| &enums[i])
616    }
617
618    /// The enumeration value `id` names, as the decoder keeps it
619    /// (`WindingConnection.D`), with its enumeration.
620    pub fn enum_value(&self, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
621        let e = self.enumeration(id.split_once('.')?.0)?;
622        Some((e, e.values.iter().find(|v| v.id == id)?))
623    }
624}
625
626/// An enumeration of the schema and the values it allows.
627#[derive(Debug)]
628pub struct EnumDef {
629    pub ns: &'static str,
630    pub local: &'static str,
631    /// The vocabulary's `rdfs:comment`, as for [`ClassDef::comment`].
632    pub comment: &'static str,
633    /// In vocabulary order.
634    pub values: &'static [EnumValueDef],
635}
636
637/// One value of an enumeration.
638#[derive(Debug)]
639pub struct EnumValueDef {
640    /// `Enum.value`, as the decoder keeps a value after its `#`.
641    pub id: &'static str,
642    /// The vocabulary's `rdfs:comment`, as for [`ClassDef::comment`].
643    pub comment: &'static str,
644}
645
646/// A class of the schema: what it is called and what it declares.
647#[derive(Debug)]
648pub struct ClassDef {
649    pub ns: &'static str,
650    pub local: &'static str,
651    /// Family-qualified name; the `CimDataset::by_type` key.
652    pub qualified: &'static str,
653    /// Index of the super class within the same table.
654    pub super_class: Option<usize>,
655    pub concrete: bool,
656    /// The attributes this class declares itself, unused association ends
657    /// included ([`AttrDef::used`]); see [`TypeRegistry::attr`] for inherited
658    /// ones.
659    pub attrs: &'static [AttrDef],
660    pub origins: &'static [&'static str],
661    /// The vocabulary's `rdfs:comment`, HTML removed and on one line; `""`
662    /// if it has none.
663    pub comment: &'static str,
664}
665
666impl ClassDef {
667    /// An attribute this class declares itself (not an inherited one).
668    pub fn attr(&self, id: &str) -> Option<&'static AttrDef> {
669        self.attrs.iter().find(|a| a.id == id)
670    }
671}
672
673/// Namespace-aware class lookup, and every attribute each class declares.
674///
675/// RDF/XML identifies a class by `(namespace, local name)`, and the two profile
676/// families overlap on 164 local names — both even spell the prefix `cim`, so
677/// only the xmlns binding distinguishes them. Lookup is therefore keyed on the
678/// resolved namespace, with a bare-name fallback (CGMES only) that preserves
679/// the historical behaviour for files whose prefixes are unbound or unexpected.
680#[derive(Default)]
681pub struct TypeRegistry {
682    by_ns: FastMap<&'static str, FastMap<&'static str, &'static ClassDef>>,
683    bare: FastMap<&'static str, &'static ClassDef>,
684    by_type_name: FastMap<&'static str, &'static ClassDef>,
685    /// Qualified class name → every attribute it declares, inherited ones
686    /// included. Built once from the class tables.
687    declared: FastMap<&'static str, FastMap<&'static str, &'static AttrDef>>,
688    /// Qualified class name → the class and its ancestors, root first.
689    chain: FastMap<&'static str, Vec<&'static ClassDef>>,
690    /// Each registered family, in registration order.
691    families: Vec<FamilyTable>,
692}
693
694/// One family as registered: its schema, the `by_type` prefix its classes
695/// carry (`""` for CGMES, `"nc:"`), and its attributes by id.
696struct FamilyTable {
697    id: &'static str,
698    prefix: &'static str,
699    schema: &'static Schema,
700    /// Attribute id → its first declaration in table order. An id names one
701    /// predicate, whichever class declares it.
702    attrs: FastMap<&'static str, &'static AttrDef>,
703}
704
705impl TypeRegistry {
706    pub fn new() -> Self {
707        Self::default()
708    }
709
710    /// Register a family's schema under `id`. `bare_fallback` adds its classes
711    /// to the bare-name fallback: an unbound prefix means the families cannot
712    /// be told apart, so only the default family (CGMES) takes it.
713    pub fn add_family(&mut self, id: &'static str, schema: &'static Schema, bare_fallback: bool) {
714        let classes = schema.classes;
715        let prefix = classes
716            .first()
717            .and_then(|c| c.qualified.strip_suffix(c.local))
718            .unwrap_or("");
719        let mut by_id = FastMap::default();
720        for class in classes {
721            for a in class.attrs {
722                by_id.entry(a.id).or_insert(a);
723            }
724        }
725        self.families.push(FamilyTable { id, prefix, schema, attrs: by_id });
726        for class in classes {
727            self.by_ns.entry(class.ns).or_default().insert(class.local, class);
728            self.by_type_name.insert(class.qualified, class);
729            if bare_fallback {
730                self.bare.insert(class.local, class);
731            }
732            let mut attrs = FastMap::default();
733            let mut chain = Vec::new();
734            let mut next = Some(class);
735            while let Some(c) = next {
736                for a in c.attrs {
737                    attrs.entry(a.id).or_insert(a);
738                }
739                chain.push(c);
740                next = c.super_class.map(|i| &classes[i]);
741            }
742            chain.reverse();
743            self.declared.insert(class.qualified, attrs);
744            self.chain.insert(class.qualified, chain);
745        }
746    }
747
748    /// Lookup table for one namespace, resolved once per XML prefix per file.
749    pub fn ns_table(&self, ns: &str) -> Option<&FastMap<&'static str, &'static ClassDef>> {
750        self.by_ns.get(ns)
751    }
752
753    pub fn bare(&self) -> &FastMap<&'static str, &'static ClassDef> {
754        &self.bare
755    }
756
757    pub fn by_type_name(&self, name: &str) -> Option<&'static ClassDef> {
758        self.by_type_name.get(name).copied()
759    }
760
761    /// The attribute `id` if `class` declares it, itself or by inheritance.
762    pub fn attr(&self, class: &ClassDef, id: &str) -> Option<&'static AttrDef> {
763        self.declared.get(class.qualified)?.get(id).copied()
764    }
765
766    /// The attributes `class` declares, inherited ones included, by id — for a
767    /// caller that resolves many keys of one element.
768    pub fn declared(&self, class: &ClassDef) -> Option<&FastMap<&'static str, &'static AttrDef>> {
769        self.declared.get(class.qualified)
770    }
771
772    /// The `&'static` key a field `id` of `class` is stored under.
773    pub fn field_key(&self, class: &ClassDef, id: &str) -> &'static str {
774        self.attr(class, id).map_or_else(|| intern(id), |a| a.id)
775    }
776
777    /// `class` and its ancestors, root first.
778    pub fn chain(&self, class: &ClassDef) -> &[&'static ClassDef] {
779        self.chain.get(class.qualified).map_or(&[], Vec::as_slice)
780    }
781
782    /// The `by_type` keys of the concrete classes at or below `qualified`,
783    /// sorted: what instances of a class can be typed as.
784    pub fn concrete_descendants(&self, qualified: &str) -> Vec<&'static str> {
785        let mut out: Vec<&'static str> = self
786            .chain
787            .iter()
788            .filter(|(_, chain)| chain.iter().any(|c| c.qualified == qualified))
789            .filter_map(|(q, _)| self.by_type_name.get(q).filter(|c| c.concrete).map(|c| c.qualified))
790            .collect();
791        out.sort_unstable();
792        out
793    }
794
795    /// Every attribute `class` declares, inherited ones included.
796    pub fn attrs(&self, class: &ClassDef) -> impl Iterator<Item = &'static AttrDef> + '_ {
797        self.declared.get(class.qualified).into_iter().flat_map(|m| m.values().copied())
798    }
799
800    /// The schema registered as `family` (`"cgmes"`, `"nc"`).
801    pub fn schema(&self, family: &str) -> Option<&'static Schema> {
802        self.family(family).map(|f| f.schema)
803    }
804
805    fn family(&self, id: &str) -> Option<&FamilyTable> {
806        self.families.iter().find(|f| f.id == id)
807    }
808
809    /// The enumeration value `id` (`WindingConnection.D`) in the family of
810    /// `class`, which an element of `class` uses it on.
811    pub fn enum_value(&self, class: &ClassDef, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
812        self.schema(self.family_of(class.qualified)?)?.enum_value(id)
813    }
814
815    /// The family a `by_type` key belongs to, by its prefix.
816    pub fn family_of(&self, type_name: &str) -> Option<&'static str> {
817        // The longest matching prefix, so `nc:X` is not taken for CGMES's "".
818        self.families
819            .iter()
820            .filter(|f| type_name.starts_with(f.prefix))
821            .max_by_key(|f| f.prefix.len())
822            .map(|f| f.id)
823    }
824
825    /// The attribute `id` as `family` declares it on any class — what a field
826    /// key names when the element's own class does not declare it.
827    pub fn family_attr(&self, family: &str, id: &str) -> Option<&'static AttrDef> {
828        self.family(family)?.attrs.get(id).copied()
829    }
830
831    /// The attribute a field `key` of an element of `class` stands for: the
832    /// class's own declaration, else the family's.
833    pub fn attr_of(&self, class: &ClassDef, key: &str) -> Option<&'static AttrDef> {
834        self.attr(class, key)
835            .or_else(|| self.family_attr(self.family_of(class.qualified)?, key))
836    }
837}