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#[derive(Debug, Clone)]
105pub enum FieldValue {
106    Text(String),
107    /// Repeated text element within one parsed element (e.g. the multiple
108    /// `md:Model.profile` entries of a combined EQ+SC file header).
109    TextList(Vec<String>),
110    Resource(String),
111    ResourceList(Vec<String>),
112}
113
114// --- Elements ----------------------------------------------------------------
115
116/// One decoded CIM object: its class, its mRID, and its fields as written.
117///
118/// Every family decodes into this one type. The fields are the document's
119/// own, keyed by `Class.attr` (the XML element's local name), with values
120/// unparsed: what a class declares lives in its [`ClassDef`], not in a
121/// generated type, so an attribute the class does not declare and a value
122/// that does not parse are kept rather than dropped.
123#[derive(Debug, Clone)]
124pub struct Element {
125    class: &'static ClassDef,
126    mrid: String,
127    fields: FieldMap,
128    /// Fields assigned more than once within the element, which `sh:maxCount`
129    /// reads.
130    duplicate_fields: FastSet<&'static str>,
131    /// The `xml:lang` of each text value written with one, by field, in the
132    /// order read. `None` until a value carries one, so an element without
133    /// language tags — nearly all of them — pays a pointer.
134    langs: Option<Box<Langs>>,
135    /// The other classes files wrote the object under, when merged datasets
136    /// disagree — an SSH file's `cim:Equipment` for an EQ file's
137    /// `cim:ACLineSegment`. In RDF the object has every one of those types;
138    /// `class` is the most specific. `None` for nearly every element, so it
139    /// costs a pointer, like `langs`.
140    also: Option<Box<Types>>,
141}
142
143/// `(field key, xml:lang)` for each tagged text value of an element.
144type Langs = Vec<(&'static str, Box<str>)>;
145
146/// The classes besides its own a merged element was written under.
147type Types = Vec<&'static ClassDef>;
148
149impl Element {
150    pub fn new(class: &'static ClassDef, mrid: String) -> Self {
151        Self { class, mrid, fields: FieldMap::default(), duplicate_fields: FastSet::default(), langs: None, also: None }
152    }
153
154    pub fn with_fields(class: &'static ClassDef, mrid: String, fields: FieldMap) -> Self {
155        Self { class, mrid, fields, duplicate_fields: FastSet::default(), langs: None, also: None }
156    }
157
158    pub fn class(&self) -> &'static ClassDef {
159        self.class
160    }
161
162    /// Every class the object is typed as: its class, then any other a merged
163    /// file wrote it under ([`CimDataset::merge`](crate::CimDataset::merge)).
164    pub fn types(&self) -> impl Iterator<Item = &'static ClassDef> + '_ {
165        std::iter::once(self.class).chain(self.also.iter().flat_map(|v| v.iter().copied()))
166    }
167
168    /// Record that a file also typed the object as `other`. Becomes its class
169    /// when it is a subclass of the current one (field keys name each
170    /// attribute's declaring class, so they stay valid); otherwise it is kept
171    /// beside it. Returns whether the class changed.
172    pub(crate) fn add_type(&mut self, other: &'static ClassDef, reg: &TypeRegistry) -> bool {
173        if self.types().any(|c| c.qualified == other.qualified) {
174            return false;
175        }
176        let promote = reg.chain(other).iter().any(|c| c.qualified == self.class.qualified);
177        let kept = if promote { std::mem::replace(&mut self.class, other) } else { other };
178        self.also.get_or_insert_with(Default::default).push(kept);
179        promote
180    }
181
182    pub fn mrid(&self) -> &str {
183        &self.mrid
184    }
185
186    /// Family-qualified class name, e.g. `"Terminal"` (CGMES) or
187    /// `"nc:Contingency"`. This is the `CimDataset::by_type` key.
188    pub fn type_name(&self) -> &'static str {
189        self.class.qualified
190    }
191
192    /// Bare CIM class name, without the family qualifier.
193    pub fn local_name(&self) -> &'static str {
194        self.class.local
195    }
196
197    /// RDF namespace IRI of the declaring class, trailing delimiter included.
198    pub fn type_ns(&self) -> &'static str {
199        self.class.ns
200    }
201
202    pub fn fields(&self) -> &FieldMap {
203        &self.fields
204    }
205
206    pub fn duplicate_fields(&self) -> &FastSet<&'static str> {
207        &self.duplicate_fields
208    }
209
210    /// The `xml:lang` tags of `key`'s text values, one per value that had
211    /// one. A value written without a tag has no entry, so a field whose
212    /// values outnumber its tags has an untagged value.
213    pub fn langs(&self, key: &str) -> impl Iterator<Item = &str> {
214        self.langs.iter().flat_map(|l| l.iter()).filter(move |(k, _)| *k == key).map(|(_, l)| &**l)
215    }
216
217    /// Record the `xml:lang` of a text value just added to `key`.
218    pub fn add_lang(&mut self, key: &'static str, lang: &str) {
219        self.langs.get_or_insert_with(Default::default).push((key, lang.into()));
220    }
221
222    pub fn get(&self, attr: &str) -> Option<&FieldValue> {
223        self.fields.get(attr)
224    }
225
226    pub fn get_str(&self, attr: &str) -> Option<&str> {
227        match self.fields.get(attr) {
228            Some(FieldValue::Text(s)) => Some(s.as_str()),
229            Some(FieldValue::TextList(v)) => v.first().map(String::as_str),
230            _ => None,
231        }
232    }
233
234    pub fn get_f64(&self, attr: &str) -> Option<f64> {
235        self.get_str(attr)?.parse().ok()
236    }
237
238    pub fn get_bool(&self, attr: &str) -> Option<bool> {
239        match self.get_str(attr)? {
240            "true" | "1" => Some(true),
241            "false" | "0" => Some(false),
242            _ => None,
243        }
244    }
245
246    /// Referenced MRIDs.
247    ///
248    /// Always a slice, even where the schema says the association is 1:1 — CGMES
249    /// has widened 1:1 to 1:many between versions, and a caller written against
250    /// a slice does not have to change when that happens.
251    pub fn get_refs(&self, attr: &str) -> &[String] {
252        match self.fields.get(attr) {
253            Some(FieldValue::Resource(s)) => std::slice::from_ref(s),
254            Some(FieldValue::ResourceList(v)) => v.as_slice(),
255            _ => &[],
256        }
257    }
258
259    /// First referenced MRID, for associations known to be single-valued.
260    pub fn get_ref(&self, attr: &str) -> Option<&str> {
261        self.get_refs(attr).first().map(String::as_str)
262    }
263
264    /// Add one value as the decoder reads it: a repeated key becomes a list
265    /// and is recorded in [`Element::duplicate_fields`].
266    pub fn add_field(&mut self, key: &'static str, val: FieldValue) {
267        match &val {
268            FieldValue::Resource(new_ref) => match self.fields.get_mut(key) {
269                Some(FieldValue::ResourceList(list)) => {
270                    list.push(new_ref.clone());
271                    self.duplicate_fields.insert(key);
272                    return;
273                }
274                Some(existing @ FieldValue::Resource(_)) => {
275                    let FieldValue::Resource(old) = std::mem::replace(existing, FieldValue::ResourceList(Vec::new())) else {
276                        unreachable!()
277                    };
278                    *existing = FieldValue::ResourceList(vec![old, new_ref.clone()]);
279                    self.duplicate_fields.insert(key);
280                    return;
281                }
282                _ => {}
283            },
284            FieldValue::Text(new_text) => match self.fields.get_mut(key) {
285                Some(FieldValue::TextList(list)) => {
286                    list.push(new_text.clone());
287                    self.duplicate_fields.insert(key);
288                    return;
289                }
290                Some(existing @ FieldValue::Text(_)) => {
291                    let FieldValue::Text(old) = std::mem::replace(existing, FieldValue::TextList(Vec::new())) else {
292                        unreachable!()
293                    };
294                    *existing = FieldValue::TextList(vec![old, new_text.clone()]);
295                    self.duplicate_fields.insert(key);
296                    return;
297                }
298                _ => {}
299            },
300            _ => {
301                if self.fields.contains_key(key) {
302                    self.duplicate_fields.insert(key);
303                }
304            }
305        }
306        self.fields.insert(key, val);
307    }
308
309    /// Combine another file's view of the same object: a later scalar wins,
310    /// reference lists are joined. Duplicate tracking stays per file.
311    pub fn merge_from(&mut self, other: &Element) {
312        for (k, v) in &other.fields {
313            match v {
314                FieldValue::ResourceList(new_list) => match self.fields.get_mut(k) {
315                    Some(FieldValue::ResourceList(existing)) => existing.extend(new_list.iter().cloned()),
316                    _ => {
317                        self.fields.insert(*k, v.clone());
318                    }
319                },
320                _ => {
321                    self.fields.insert(*k, v.clone());
322                    // The later file's text replaced ours, tags included.
323                    if let Some(l) = self.langs.as_mut() {
324                        l.retain(|(key, _)| key != k);
325                    }
326                    for lang in other.langs(k) {
327                        self.add_lang(k, lang);
328                    }
329                }
330            }
331        }
332    }
333
334    /// `{"id": mRID, "Class.attr": value, ...}`: a value is a string, a
335    /// repeated one an array of strings.
336    pub fn to_json_value(&self) -> serde_json::Value {
337        let mut map = serde_json::Map::with_capacity(self.fields.len() + 1);
338        map.insert("id".to_string(), serde_json::Value::String(self.mrid.clone()));
339        for (k, v) in &self.fields {
340            map.insert(k.to_string(), field_to_json(v));
341        }
342        serde_json::Value::Object(map)
343    }
344
345    /// The inverse of [`Element::to_json_value`]. Whether a string is a
346    /// reference or text comes from the attribute's declaration; an attribute
347    /// the class does not declare is read as text.
348    pub fn from_json(
349        class: &'static ClassDef,
350        reg: &TypeRegistry,
351        value: &serde_json::Value,
352    ) -> Result<Self, String> {
353        let obj = value.as_object().ok_or("element is not a JSON object")?;
354        let mrid = obj.get("id").and_then(|v| v.as_str()).ok_or("element has no \"id\"")?.to_string();
355        let mut fields = FieldMap::default();
356        for (k, v) in obj {
357            if k == "id" || k == "_type" {
358                continue;
359            }
360            let is_ref = reg.attr(class, k).is_some_and(|a| a.kind != AttrKind::Literal);
361            let value = match v {
362                serde_json::Value::String(s) if is_ref => FieldValue::Resource(s.clone()),
363                serde_json::Value::String(s) => FieldValue::Text(s.clone()),
364                serde_json::Value::Array(items) => {
365                    let items: Vec<String> = items
366                        .iter()
367                        .map(|i| i.as_str().map(str::to_string).ok_or(format!("{k}: list item is not a string")))
368                        .collect::<Result<_, _>>()?;
369                    if is_ref { FieldValue::ResourceList(items) } else { FieldValue::TextList(items) }
370                }
371                other => return Err(format!("{k}: expected a string or an array, got {other}")),
372            };
373            fields.insert(reg.field_key(class, k), value);
374        }
375        Ok(Self::with_fields(class, mrid, fields))
376    }
377}
378
379fn field_to_json(v: &FieldValue) -> serde_json::Value {
380    match v {
381        FieldValue::Text(s) | FieldValue::Resource(s) => serde_json::Value::String(s.clone()),
382        FieldValue::TextList(v) | FieldValue::ResourceList(v) => {
383            serde_json::Value::Array(v.iter().cloned().map(serde_json::Value::String).collect())
384        }
385    }
386}
387
388// --- Classes -----------------------------------------------------------------
389
390/// How an attribute's value is carried in RDF/XML.
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392pub enum AttrKind {
393    /// A literal, written as element text.
394    Literal,
395    /// A reference to another object, written as `rdf:resource`.
396    Association,
397    /// An enumeration value, written as `rdf:resource` to a vocabulary IRI.
398    Enum,
399}
400
401/// One attribute of a class, as the schema declares it.
402#[derive(Debug)]
403pub struct AttrDef {
404    /// `Class.attr`, matching the key in [`Element::fields`].
405    pub id: &'static str,
406    /// The attribute's RDF namespace: its predicate IRI is `ns` + `id`.
407    pub ns: &'static str,
408    pub kind: AttrKind,
409    /// The CIM datatype of a literal; the class an association or enumeration
410    /// points to.
411    pub range: &'static str,
412    pub is_list: bool,
413    /// Whether a profile exchanges this end of the association — `false` for the
414    /// inverse ends the vocabularies declare but no dataset writes. Literals and
415    /// enumerations are always used.
416    pub used: bool,
417    /// The XSD datatype of a literal, as the local name after
418    /// `http://www.w3.org/2001/XMLSchema#` (`"double"`); `""` otherwise.
419    pub xsd: &'static str,
420    /// The namespace of an enumeration's values (the decoder keeps a value after
421    /// its `#`); `""` otherwise.
422    pub value_ns: &'static str,
423    /// Profile codes that carry this attribute.
424    pub origins: &'static [&'static str],
425    /// The vocabulary's `rdfs:comment`, HTML removed and on one line; `""`
426    /// if it has none.
427    pub comment: &'static str,
428}
429
430/// What one family's schema says, as a table: its classes, the profiles it
431/// defines and the namespaces its vocabularies bind. Generated by `cimgen`, or
432/// read from RDFS at runtime (`schema_source`).
433#[derive(Debug)]
434pub struct Schema {
435    pub classes: &'static [ClassDef],
436    /// Profile code → profile URI, the value a dataset's header declares; sorted
437    /// by code.
438    pub profiles: &'static [(&'static str, &'static str)],
439    /// XML prefix → namespace IRI; sorted by prefix.
440    pub namespaces: &'static [(&'static str, &'static str)],
441    /// Enumerations, sorted by name.
442    pub enums: &'static [EnumDef],
443}
444
445impl Schema {
446    /// The enumeration called `name` (`WindingConnection`).
447    pub fn enumeration(&self, name: &str) -> Option<&'static EnumDef> {
448        let enums: &'static [EnumDef] = self.enums;
449        enums.binary_search_by_key(&name, |e| e.local).ok().map(|i| &enums[i])
450    }
451
452    /// The enumeration value `id` names, as the decoder keeps it
453    /// (`WindingConnection.D`), with its enumeration.
454    pub fn enum_value(&self, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
455        let e = self.enumeration(id.split_once('.')?.0)?;
456        Some((e, e.values.iter().find(|v| v.id == id)?))
457    }
458}
459
460/// An enumeration of the schema and the values it allows.
461#[derive(Debug)]
462pub struct EnumDef {
463    pub ns: &'static str,
464    pub local: &'static str,
465    /// The vocabulary's `rdfs:comment`, as for [`ClassDef::comment`].
466    pub comment: &'static str,
467    /// In vocabulary order.
468    pub values: &'static [EnumValueDef],
469}
470
471/// One value of an enumeration.
472#[derive(Debug)]
473pub struct EnumValueDef {
474    /// `Enum.value`, as the decoder keeps a value after its `#`.
475    pub id: &'static str,
476    /// The vocabulary's `rdfs:comment`, as for [`ClassDef::comment`].
477    pub comment: &'static str,
478}
479
480/// A class of the schema: what it is called and what it declares.
481#[derive(Debug)]
482pub struct ClassDef {
483    pub ns: &'static str,
484    pub local: &'static str,
485    /// Family-qualified name; the `CimDataset::by_type` key.
486    pub qualified: &'static str,
487    /// Index of the super class within the same table.
488    pub super_class: Option<usize>,
489    pub concrete: bool,
490    /// The attributes this class declares itself, unused association ends
491    /// included ([`AttrDef::used`]); see [`TypeRegistry::attr`] for inherited
492    /// ones.
493    pub attrs: &'static [AttrDef],
494    pub origins: &'static [&'static str],
495    /// The vocabulary's `rdfs:comment`, HTML removed and on one line; `""`
496    /// if it has none.
497    pub comment: &'static str,
498}
499
500impl ClassDef {
501    /// An attribute this class declares itself (not an inherited one).
502    pub fn attr(&self, id: &str) -> Option<&'static AttrDef> {
503        self.attrs.iter().find(|a| a.id == id)
504    }
505}
506
507/// Namespace-aware class lookup, and every attribute each class declares.
508///
509/// RDF/XML identifies a class by `(namespace, local name)`, and the two profile
510/// families overlap on 164 local names — both even spell the prefix `cim`, so
511/// only the xmlns binding distinguishes them. Lookup is therefore keyed on the
512/// resolved namespace, with a bare-name fallback (CGMES only) that preserves
513/// the historical behaviour for files whose prefixes are unbound or unexpected.
514#[derive(Default)]
515pub struct TypeRegistry {
516    by_ns: FastMap<&'static str, FastMap<&'static str, &'static ClassDef>>,
517    bare: FastMap<&'static str, &'static ClassDef>,
518    by_type_name: FastMap<&'static str, &'static ClassDef>,
519    /// Qualified class name → every attribute it declares, inherited ones
520    /// included. Built once from the class tables.
521    declared: FastMap<&'static str, FastMap<&'static str, &'static AttrDef>>,
522    /// Qualified class name → the class and its ancestors, root first.
523    chain: FastMap<&'static str, Vec<&'static ClassDef>>,
524    /// Each registered family, in registration order.
525    families: Vec<FamilyTable>,
526}
527
528/// One family as registered: its schema, the `by_type` prefix its classes
529/// carry (`""` for CGMES, `"nc:"`), and its attributes by id.
530struct FamilyTable {
531    id: &'static str,
532    prefix: &'static str,
533    schema: &'static Schema,
534    /// Attribute id → its first declaration in table order. An id names one
535    /// predicate, whichever class declares it.
536    attrs: FastMap<&'static str, &'static AttrDef>,
537}
538
539impl TypeRegistry {
540    pub fn new() -> Self {
541        Self::default()
542    }
543
544    /// Register a family's schema under `id`. `bare_fallback` adds its classes
545    /// to the bare-name fallback: an unbound prefix means the families cannot
546    /// be told apart, so only the default family (CGMES) takes it.
547    pub fn add_family(&mut self, id: &'static str, schema: &'static Schema, bare_fallback: bool) {
548        let classes = schema.classes;
549        let prefix = classes
550            .first()
551            .and_then(|c| c.qualified.strip_suffix(c.local))
552            .unwrap_or("");
553        let mut by_id = FastMap::default();
554        for class in classes {
555            for a in class.attrs {
556                by_id.entry(a.id).or_insert(a);
557            }
558        }
559        self.families.push(FamilyTable { id, prefix, schema, attrs: by_id });
560        for class in classes {
561            self.by_ns.entry(class.ns).or_default().insert(class.local, class);
562            self.by_type_name.insert(class.qualified, class);
563            if bare_fallback {
564                self.bare.insert(class.local, class);
565            }
566            let mut attrs = FastMap::default();
567            let mut chain = Vec::new();
568            let mut next = Some(class);
569            while let Some(c) = next {
570                for a in c.attrs {
571                    attrs.entry(a.id).or_insert(a);
572                }
573                chain.push(c);
574                next = c.super_class.map(|i| &classes[i]);
575            }
576            chain.reverse();
577            self.declared.insert(class.qualified, attrs);
578            self.chain.insert(class.qualified, chain);
579        }
580    }
581
582    /// Lookup table for one namespace, resolved once per XML prefix per file.
583    pub fn ns_table(&self, ns: &str) -> Option<&FastMap<&'static str, &'static ClassDef>> {
584        self.by_ns.get(ns)
585    }
586
587    pub fn bare(&self) -> &FastMap<&'static str, &'static ClassDef> {
588        &self.bare
589    }
590
591    pub fn by_type_name(&self, name: &str) -> Option<&'static ClassDef> {
592        self.by_type_name.get(name).copied()
593    }
594
595    /// The attribute `id` if `class` declares it, itself or by inheritance.
596    pub fn attr(&self, class: &ClassDef, id: &str) -> Option<&'static AttrDef> {
597        self.declared.get(class.qualified)?.get(id).copied()
598    }
599
600    /// The attributes `class` declares, inherited ones included, by id — for a
601    /// caller that resolves many keys of one element.
602    pub fn declared(&self, class: &ClassDef) -> Option<&FastMap<&'static str, &'static AttrDef>> {
603        self.declared.get(class.qualified)
604    }
605
606    /// The `&'static` key a field `id` of `class` is stored under.
607    pub fn field_key(&self, class: &ClassDef, id: &str) -> &'static str {
608        self.attr(class, id).map_or_else(|| intern(id), |a| a.id)
609    }
610
611    /// `class` and its ancestors, root first.
612    pub fn chain(&self, class: &ClassDef) -> &[&'static ClassDef] {
613        self.chain.get(class.qualified).map_or(&[], Vec::as_slice)
614    }
615
616    /// The `by_type` keys of the concrete classes at or below `qualified`,
617    /// sorted: what instances of a class can be typed as.
618    pub fn concrete_descendants(&self, qualified: &str) -> Vec<&'static str> {
619        let mut out: Vec<&'static str> = self
620            .chain
621            .iter()
622            .filter(|(_, chain)| chain.iter().any(|c| c.qualified == qualified))
623            .filter_map(|(q, _)| self.by_type_name.get(q).filter(|c| c.concrete).map(|c| c.qualified))
624            .collect();
625        out.sort_unstable();
626        out
627    }
628
629    /// Every attribute `class` declares, inherited ones included.
630    pub fn attrs(&self, class: &ClassDef) -> impl Iterator<Item = &'static AttrDef> + '_ {
631        self.declared.get(class.qualified).into_iter().flat_map(|m| m.values().copied())
632    }
633
634    /// The schema registered as `family` (`"cgmes"`, `"nc"`).
635    pub fn schema(&self, family: &str) -> Option<&'static Schema> {
636        self.family(family).map(|f| f.schema)
637    }
638
639    fn family(&self, id: &str) -> Option<&FamilyTable> {
640        self.families.iter().find(|f| f.id == id)
641    }
642
643    /// The enumeration value `id` (`WindingConnection.D`) in the family of
644    /// `class`, which an element of `class` uses it on.
645    pub fn enum_value(&self, class: &ClassDef, id: &str) -> Option<(&'static EnumDef, &'static EnumValueDef)> {
646        self.schema(self.family_of(class.qualified)?)?.enum_value(id)
647    }
648
649    /// The family a `by_type` key belongs to, by its prefix.
650    pub fn family_of(&self, type_name: &str) -> Option<&'static str> {
651        // The longest matching prefix, so `nc:X` is not taken for CGMES's "".
652        self.families
653            .iter()
654            .filter(|f| type_name.starts_with(f.prefix))
655            .max_by_key(|f| f.prefix.len())
656            .map(|f| f.id)
657    }
658
659    /// The attribute `id` as `family` declares it on any class — what a field
660    /// key names when the element's own class does not declare it.
661    pub fn family_attr(&self, family: &str, id: &str) -> Option<&'static AttrDef> {
662        self.family(family)?.attrs.get(id).copied()
663    }
664
665    /// The attribute a field `key` of an element of `class` stands for: the
666    /// class's own declaration, else the family's.
667    pub fn attr_of(&self, class: &ClassDef, key: &str) -> Option<&'static AttrDef> {
668        self.attr(class, key)
669            .or_else(|| self.family_attr(self.family_of(class.qualified)?, key))
670    }
671}