Skip to main content

cimmodel/
decode.rs

1use std::path::Path;
2
3use quick_xml::Reader;
4use quick_xml::events::{BytesStart, Event};
5
6use crate::base::{
7    AttrDef, AttrKind, ClassDef, Element, FastMap, FastSet, FieldValue, TypeRegistry, intern,
8};
9use crate::difference::{Block, Differences};
10use crate::registry;
11
12/// Whether `text` looks like CGMES or NC RDF/XML: near the top it names one
13/// of the two CIM namespaces, an NC profile (`https://ap.cim4.eu/`, which a
14/// header's `dcterms:conformsTo` names: an NC dataset may be its DCAT header
15/// alone) or ENTSO-E reference data (`https://energy.referencedata.eu/`,
16/// SKOS/DCAT with no CIM namespace).
17pub fn is_cim(text: &str) -> bool {
18    let mut end = text.len().min(8192);
19    while !text.is_char_boundary(end) {
20        end -= 1;
21    }
22    let head = &text[..end];
23    [
24        "http://iec.ch/TC57/",
25        "https://cim.ucaiug.io/ns#",
26        "https://ap.cim4.eu/",
27        "https://energy.referencedata.eu/",
28    ]
29    .iter()
30    .any(|marker| head.contains(marker))
31}
32
33/// How a dataset's files wrote one field of one class
34/// ([`CimDataset::field_forms`]). Each part is the first the files showed;
35/// a field written two ways keeps the first.
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
37pub struct FieldForm {
38    /// The field's namespace IRI where it is not the declared one: for a key
39    /// the class tables do not declare (`conformsTo` →
40    /// `http://purl.org/dc/terms/`), or a declared attribute written in
41    /// another namespace (an NC file's `IdentifiedObject.mRID` in CIM100).
42    pub ns: Option<&'static str>,
43    /// The `rdf:datatype` its literals carried (`dcat:temporalResolution` →
44    /// `xsd:duration`).
45    pub datatype: Option<&'static str>,
46    /// The namespace its references were cut from, when not the document's
47    /// own (`#_x`) and not an enumeration's, whose namespace the class table
48    /// holds: a `PropertyReference` to `http://iec.ch/TC57/CIM100#Switch.open`
49    /// decodes as `Switch.open`.
50    pub resource_ns: Option<&'static str>,
51}
52
53impl FieldForm {
54    fn fill_from(&mut self, other: FieldForm) {
55        self.ns = self.ns.or(other.ns);
56        self.datatype = self.datatype.or(other.datatype);
57        self.resource_ns = self.resource_ns.or(other.resource_ns);
58    }
59}
60
61#[derive(Clone)]
62pub struct CimDataset {
63    pub entries: FastMap<String, Element>,
64    /// Maps `type_name()` → list of MRIDs of that type. Populated on insert, maintained on merge.
65    pub by_type: FastMap<String, Vec<String>>,
66    /// How the files wrote each field, by the class of its object
67    /// (`type_name()`) and its key, where the class tables cannot tell and the
68    /// decoded value no longer shows: what the encoder needs to write the
69    /// field back as it was read. By class, because one document may use one
70    /// local name in two vocabularies (`dcterms:type` on a dataset,
71    /// `prov:type` on an activity).
72    pub field_forms: FastMap<(&'static str, &'static str), FieldForm>,
73    /// The namespace an object's element was written in, by mRID, where it is
74    /// not its class's: a class the decoder found by local name only
75    /// (`cim:BoundaryPoint` for CIM100-European's, an NC file's
76    /// `cim:PhaseTapChangerLinear` for CGMES's). First file wins.
77    pub type_ns: FastMap<String, &'static str>,
78    /// The prefix the files bound each namespace to (`qudt` →
79    /// `http://qudt.org/schema/qudt/`), for the encoder to reuse. First file
80    /// wins.
81    pub prefixes: FastMap<&'static str, &'static str>,
82    /// Objects of classes no class table knows — reference data's SKOS
83    /// concepts, PROV agents, DCAT catalogues — keyed by their identifier as
84    /// written: the full IRI of `rdf:about`, `_:` and the `rdf:nodeID` of a
85    /// blank node. Kept apart from `entries` so that validation, SPARQL and
86    /// every lookup of a CIM object see only CIM objects; the encoder writes
87    /// them back ([`crate::convert::dataset_to_xml`]). Their classes come from
88    /// [`crate::base::foreign_class`].
89    pub foreign: FastMap<String, Element>,
90    /// The statements of the difference headers read: a CGMES
91    /// `dm:DifferenceModel`'s forward and reverse differences and
92    /// preconditions, an NC `dcatcim:DifferenceSet`'s forward and reverse
93    /// differences, each read into a dataset of its own. The decoder applies
94    /// none of them; [`CimDataset::apply`] does.
95    pub differences: Vec<Differences>,
96}
97
98impl Default for CimDataset {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104impl CimDataset {
105    pub fn new() -> Self {
106        Self {
107            entries: FastMap::default(),
108            by_type: FastMap::default(),
109            field_forms: FastMap::default(),
110            type_ns: FastMap::default(),
111            prefixes: FastMap::default(),
112            foreign: FastMap::default(),
113            differences: Vec::new(),
114        }
115    }
116
117    /// Decode an RDF/XML string into a CimDataset, using the provided type registry.
118    pub fn decode_str(content: &str) -> Result<Self, Box<dyn std::error::Error>> {
119        let mut ds = Self::new();
120        parse_rdf(content, registry::type_registry(), &mut ds)?;
121        Ok(ds)
122    }
123
124    /// Decode an RDF/XML file into a CimDataset, using the provided type registry.
125    pub fn decode_file(path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
126        Self::decode_str(&std::fs::read_to_string(path)?)
127    }
128
129    /// Decode multiple RDF/XML files into a single CimDataset, merging entries with the same MRID.
130    pub fn decode_files(paths: &[&Path]) -> Result<Self, Box<dyn std::error::Error>> {
131        let mut combined = Self::new();
132        for path in paths {
133            let file_ds = Self::decode_file(path)?;
134            combined.merge(file_ds);
135        }
136        Ok(combined)
137    }
138
139    /// Decode files in parallel using one thread per file, without merging.
140    /// Preserves input order. Falls back to sequential decoding for 0–1 paths
141    /// to avoid thread-spawn overhead.
142    pub fn decode_files_parallel_separate(
143        paths: &[&Path],
144    ) -> Result<Vec<Self>, Box<dyn std::error::Error>> {
145        // wasm32-unknown-unknown compiles `std::thread` and panics when it is used.
146        if paths.len() <= 1 || cfg!(target_family = "wasm") {
147            return paths.iter().map(|p| Self::decode_file(p)).collect();
148        }
149        let results: Vec<Result<Self, String>> = std::thread::scope(|s| {
150            paths
151                .iter()
152                .map(|p| s.spawn(|| Self::decode_file(p).map_err(|e| e.to_string())))
153                .collect::<Vec<_>>()
154                .into_iter()
155                .map(|h| h.join().expect("decode thread panicked"))
156                .collect()
157        });
158        results
159            .into_iter()
160            .collect::<Result<_, String>>()
161            .map_err(|e| e.into())
162    }
163
164    /// Decode files in parallel using one thread per file, then merge sequentially.
165    pub fn decode_files_parallel(paths: &[&Path]) -> Result<Self, Box<dyn std::error::Error>> {
166        let datasets = Self::decode_files_parallel_separate(paths)?;
167        Ok(datasets
168            .into_iter()
169            .reduce(|mut a, b| {
170                a.merge(b);
171                a
172            })
173            .unwrap_or_default())
174    }
175
176    /// Merge another dataset into self, combining objects with the same MRID:
177    /// a later scalar wins, reference lists are joined. An object keeps the
178    /// class it was first decoded as.
179    ///
180    /// Where the files type an object differently — an SSH file writing
181    /// `cim:Equipment` for what the EQ file wrote as `cim:ACLineSegment` — the
182    /// object keeps every type, as the RDF union does ([`Element::types`]),
183    /// and its class (and `by_type` bucket) is the most specific, whichever
184    /// file came first. Of unrelated classes the first stays the class.
185    pub fn merge(&mut self, other: CimDataset) {
186        self.differences.extend(other.differences);
187        for (key, form) in other.field_forms {
188            self.field_forms.entry(key).or_default().fill_from(form);
189        }
190        for (mrid, ns) in other.type_ns {
191            self.type_ns.entry(mrid).or_insert(ns);
192        }
193        for (ns, prefix) in other.prefixes {
194            self.prefixes.entry(ns).or_insert(prefix);
195        }
196        for (id, incoming) in other.foreign {
197            match self.foreign.get_mut(&id) {
198                Some(existing) => existing.merge_from(&incoming),
199                None => {
200                    self.foreign.insert(id, incoming);
201                }
202            }
203        }
204        let reg = registry::type_registry();
205        let mut moved: FastMap<&'static str, FastSet<String>> = FastMap::default();
206        for (mrid, incoming) in other.entries {
207            if let Some(existing) = self.entries.get_mut(&mrid) {
208                existing.merge_from(&incoming);
209                let old = existing.class();
210                let mut changed = false;
211                for t in incoming.types() {
212                    changed |= existing.add_type(t, reg);
213                }
214                if changed {
215                    moved.entry(old.qualified).or_default().insert(mrid.clone());
216                    self.by_type
217                        .entry(existing.type_name().to_string())
218                        .or_default()
219                        .push(mrid);
220                }
221            } else {
222                let type_name = incoming.type_name().to_string();
223                self.by_type
224                    .entry(type_name)
225                    .or_default()
226                    .push(mrid.clone());
227                self.entries.insert(mrid, incoming);
228            }
229        }
230        // One pass per bucket left, however many of its objects moved.
231        for (old, mrids) in moved {
232            if let Some(bucket) = self.by_type.get_mut(old) {
233                bucket.retain(|m| !mrids.contains(m));
234            }
235        }
236    }
237
238    /// An element of `class` from its JSON form ([`Element::from_json`]), with
239    /// the dataset as evidence for what JSON cannot say: whether a field's
240    /// string is a reference or text. Where this dataset holds the field on an
241    /// object of the same class, it is held the same way — a DCAT header's
242    /// undeclared `conformsTo` as a reference, `dcat:version`, which the NC
243    /// table declares an association, as the text the data writes. Otherwise
244    /// the class table decides, and an undeclared field is text.
245    pub fn element_from_json(
246        &self,
247        class: &'static ClassDef,
248        value: &serde_json::Value,
249    ) -> Result<Element, String> {
250        let reg = registry::type_registry();
251        let mut element = Element::from_json(class, reg, value)?;
252        let keys: Vec<&'static str> = element.fields().keys().copied().collect();
253        for key in keys {
254            if let Some(reference) = self.held_as_reference(class.qualified, key) {
255                element.retype(key, reference);
256            }
257        }
258        Ok(element)
259    }
260
261    /// How objects of class `type_name` hold field `key` in this dataset:
262    /// `Some(true)` as a reference, `Some(false)` as text, `None` if none
263    /// holds it. The first object found decides.
264    fn held_as_reference(&self, type_name: &str, key: &str) -> Option<bool> {
265        self.by_type
266            .get(type_name)
267            .into_iter()
268            .flatten()
269            .filter_map(|m| self.entries.get(m))
270            .find_map(|e| match e.get(key)? {
271                FieldValue::Resource(_) | FieldValue::ResourceList(_) => Some(true),
272                FieldValue::Text(_) | FieldValue::TextList(_) => Some(false),
273            })
274            .or_else(|| {
275                self.field_forms
276                    .get(&(type_name, key))
277                    .and_then(|f| f.resource_ns)
278                    .map(|_| true)
279            })
280    }
281
282    /// Insert or replace the element at `mrid`, keeping `by_type` consistent
283    /// (including the case where `mrid` already exists under a different type).
284    pub fn set(&mut self, mrid: String, element: Element) {
285        let new_type = element.type_name().to_string();
286        if let Some(old) = self.entries.get(&mrid) {
287            let old_type = old.type_name();
288            if old_type != new_type
289                && let Some(v) = self.by_type.get_mut(old_type)
290            {
291                v.retain(|m| m != &mrid);
292            }
293        }
294        let already_indexed = self
295            .by_type
296            .get(&new_type)
297            .is_some_and(|v| v.contains(&mrid));
298        if !already_indexed {
299            self.by_type.entry(new_type).or_default().push(mrid.clone());
300        }
301        self.entries.insert(mrid, element);
302    }
303
304    /// Remove the element at `mrid`, pruning it from `by_type`. Returns the
305    /// removed element, or `None` if `mrid` was not present.
306    pub fn remove(&mut self, mrid: &str) -> Option<Element> {
307        let removed = self.entries.remove(mrid)?;
308        if let Some(v) = self.by_type.get_mut(removed.type_name()) {
309            v.retain(|m| m != mrid);
310        }
311        Some(removed)
312    }
313
314    /// The objects the files typed with classes of which neither is the
315    /// other's ancestor, sorted, each with its types: what a merge of datasets
316    /// that disagree about an object leaves ([`CimDataset::merge`] keeps every
317    /// type). An SSH file's `cim:Equipment` for an EQ `cim:ACLineSegment` is a
318    /// superclass, not a conflict.
319    pub fn type_conflicts(&self) -> Vec<(&str, Vec<&'static str>)> {
320        let reg = registry::type_registry();
321        let related = |a: &ClassDef, b: &ClassDef| {
322            reg.chain(a).iter().any(|c| c.qualified == b.qualified)
323                || reg.chain(b).iter().any(|c| c.qualified == a.qualified)
324        };
325        let mut out: Vec<(&str, Vec<&'static str>)> = self
326            .entries
327            .iter()
328            .filter_map(|(mrid, e)| {
329                let types: Vec<&'static ClassDef> = e.types().collect();
330                let conflict = types
331                    .iter()
332                    .enumerate()
333                    .any(|(i, a)| types[i + 1..].iter().any(|b| !related(a, b)));
334                conflict.then(|| (mrid.as_str(), types.iter().map(|c| c.qualified).collect()))
335            })
336            .collect();
337        out.sort_unstable();
338        out
339    }
340}
341
342// --- XML streaming parser ---------------------------------------------------
343
344/// Push an MRID onto its type bucket, allocating the key only when the bucket
345/// is new rather than once per element.
346fn index(by_type: &mut FastMap<String, Vec<String>>, type_name: &'static str, mrid: String) {
347    if let Some(bucket) = by_type.get_mut(type_name) {
348        bucket.push(mrid);
349    } else {
350        by_type.insert(type_name.to_string(), vec![mrid]);
351    }
352}
353
354type Table = FastMap<&'static str, &'static ClassDef>;
355
356/// The document's `xmlns` bindings, resolved once to dispatch tables.
357///
358/// Resolving a prefix per element rather than a namespace IRI is what keeps
359/// this cheap: prefixes are two to four bytes, IRIs are thirty-odd, and a
360/// document binds a handful of them and then repeats them on every element.
361#[derive(Default, Clone)]
362struct Scope {
363    /// Prefix → its namespace IRI (interned) and that namespace's table.
364    prefixes: Vec<(Vec<u8>, &'static str, Option<&'static Table>)>,
365    default: Option<&'static Table>,
366    default_ns: &'static str,
367}
368
369impl Scope {
370    /// Collect `xmlns:*` and `xmlns` declarations from an element.
371    fn absorb(&mut self, e: &BytesStart, reg: &'static TypeRegistry) {
372        for attr in e.attributes().flatten() {
373            let key = attr.key.as_ref();
374            let Some(rest) = key.strip_prefix(b"xmlns".as_slice()) else {
375                continue;
376            };
377            let Ok(ns) = std::str::from_utf8(&attr.value) else {
378                continue;
379            };
380            // A namespace written without its delimiter still names the same vocabulary.
381            let table = reg.ns_table(ns).or_else(|| {
382                if ns.ends_with('#') || ns.ends_with('/') {
383                    None
384                } else {
385                    reg.ns_table(&format!("{ns}#"))
386                }
387            });
388            let ns = intern(ns);
389            match rest.strip_prefix(b":".as_slice()) {
390                Some(prefix) => {
391                    let prefix = prefix.to_vec();
392                    match self.prefixes.iter_mut().find(|(k, _, _)| *k == prefix) {
393                        Some(slot) => (slot.1, slot.2) = (ns, table),
394                        None => self.prefixes.push((prefix, ns, table)),
395                    }
396                }
397                None if rest.is_empty() => (self.default, self.default_ns) = (table, ns),
398                None => {}
399            }
400        }
401    }
402
403    fn table(&self, prefix: Option<&[u8]>) -> Option<&'static Table> {
404        match prefix {
405            None => self.default,
406            Some(p) => self
407                .prefixes
408                .iter()
409                .find(|(k, _, _)| k.as_slice() == p)
410                .and_then(|(_, _, t)| *t),
411        }
412    }
413
414    /// The namespace IRI `prefix` is bound to, `""` if none.
415    fn ns(&self, prefix: Option<&[u8]>) -> &'static str {
416        match prefix {
417            None => self.default_ns,
418            Some(p) => self
419                .prefixes
420                .iter()
421                .find(|(k, _, _)| k.as_slice() == p)
422                .map_or("", |(_, ns, _)| ns),
423        }
424    }
425}
426
427/// What an object element's attributes say about it.
428struct Subject {
429    /// A CIM object's key: the text after the last `#` of `rdf:about` or
430    /// `rdf:ID`, an IRI without one whole; `_:` and the label of a blank node.
431    mrid: String,
432    /// A foreign object's key ([`CimDataset::foreign`]): `rdf:about` as
433    /// written (less a leading `#`), `rdf:ID`, or `_:` and the `rdf:nodeID`.
434    id: String,
435    /// The element only describes the object (`rdf:about`, no `rdf:ID`).
436    described: bool,
437    has_xmlns: bool,
438}
439
440/// One pass over an element's attributes, yielding what the parser needs.
441/// Scanning twice costs more than the nested-`xmlns` case it would serve,
442/// because every element pays for it and almost none declare one.
443fn scan_attrs(e: &BytesStart) -> Result<Subject, Box<dyn std::error::Error>> {
444    let mut subject = Subject {
445        mrid: String::new(),
446        id: String::new(),
447        described: false,
448        has_xmlns: false,
449    };
450    let mut defined = false;
451    for attr in e.attributes().flatten() {
452        let key = attr.key.as_ref();
453        if key == b"rdf:about" || key == b"rdf:ID" {
454            let value = std::str::from_utf8(&attr.value)?;
455            subject.mrid = strip_fragment(value);
456            subject.id = value.strip_prefix('#').unwrap_or(value).to_string();
457            subject.described |= key == b"rdf:about";
458            defined |= key == b"rdf:ID";
459        } else if key == b"rdf:nodeID" {
460            subject.mrid = format!("_:{}", std::str::from_utf8(&attr.value)?);
461            subject.id = subject.mrid.clone();
462        } else if key.starts_with(b"xmlns") {
463            subject.has_xmlns = true;
464        }
465    }
466    subject.described &= !defined;
467    Ok(subject)
468}
469
470/// The object an element starts: of its class when a table knows it, else a
471/// foreign object (`true`) of a class named by the element; and the
472/// namespace the element was written in, when it is not the class's. `None`
473/// for an element with no identifier, which nothing can refer to.
474fn object(
475    scope: &Scope,
476    reg: &'static TypeRegistry,
477    e: &BytesStart,
478    subject: Subject,
479) -> Result<Option<(Element, bool, Option<&'static str>)>, Box<dyn std::error::Error>> {
480    if subject.id.is_empty() {
481        return Ok(None);
482    }
483    let name = e.name();
484    let (prefix, local) = split_qname(name.as_ref());
485    let ns = scope.ns(prefix);
486    let (mut element, foreign) = match resolve(scope, reg, name.as_ref())? {
487        Some(class) => (Element::new(class, subject.mrid), false),
488        None => (
489            Element::new(
490                crate::base::foreign_class(ns, std::str::from_utf8(local)?),
491                subject.id,
492            ),
493            true,
494        ),
495    };
496    if subject.described {
497        element.mark_described();
498    }
499    let written = (!ns.is_empty() && !same_ns(element.type_ns(), ns)).then_some(ns);
500    Ok(Some((element, foreign, written)))
501}
502
503/// Whether two namespace IRIs name the same vocabulary: a document may write
504/// one without its trailing `#`, which the decoder's tables accept.
505fn same_ns(a: &str, b: &str) -> bool {
506    a == b || a.strip_suffix('#') == Some(b) || b.strip_suffix('#') == Some(a)
507}
508
509/// Add a decoded object to the dataset, a foreign one apart.
510fn store(ds: &mut CimDataset, element: Element, foreign: bool, written: Option<&'static str>) {
511    if let Some(ns) = written
512        && !foreign
513        && !element.mrid().is_empty()
514    {
515        ds.type_ns.entry(element.mrid().to_string()).or_insert(ns);
516    }
517    if foreign {
518        ds.foreign.insert(element.mrid().to_string(), element);
519    } else if !element.mrid().is_empty() {
520        index(
521            &mut ds.by_type,
522            element.type_name(),
523            element.mrid().to_string(),
524        );
525        ds.entries.insert(element.mrid().to_string(), element);
526    }
527}
528
529/// Split a qualified name into its prefix and local part.
530fn split_qname(raw: &[u8]) -> (Option<&[u8]>, &[u8]) {
531    match raw.iter().position(|b| *b == b':') {
532        Some(i) => (Some(&raw[..i]), &raw[i + 1..]),
533        None => (None, raw),
534    }
535}
536
537/// Resolve an element name to its class.
538///
539/// The namespace wins when the document binds one we know. Otherwise we fall
540/// back to the bare local name, which is what every pre-namespace release did:
541/// real files bind prefixes we do not expect (one CGMES test file binds the
542/// ModelDescription IRI to `mdc`), and write elements under a namespace their
543/// class was not declared in (`<cim:BoundaryPoint>` where `BoundaryPoint` is
544/// declared in `CIM100-European#`). The fallback is therefore per element, not
545/// per document.
546fn resolve(
547    scope: &Scope,
548    reg: &'static TypeRegistry,
549    raw: &[u8],
550) -> Result<Option<&'static ClassDef>, Box<dyn std::error::Error>> {
551    let (prefix, local_bytes) = split_qname(raw);
552    let local = std::str::from_utf8(local_bytes)?;
553    if let Some(class) = scope.table(prefix).and_then(|t| t.get(local)) {
554        return Ok(Some(*class));
555    }
556    Ok(reg.bare().get(local).copied())
557}
558
559/// Parse an RDF/XML string into a CimDataset, using the provided type registry.
560fn parse_rdf(
561    content: &str,
562    reg: &'static TypeRegistry,
563    ds: &mut CimDataset,
564) -> Result<(), Box<dyn std::error::Error>> {
565    let mut reader = Reader::from_str(content);
566    parse_events(&mut reader, reg, ds, Scope::default(), false)
567}
568
569/// Which statements of a difference header a field holds: the key of a
570/// CGMES `dm:DifferenceModel`'s or an NC `dcatcim:DifferenceSet`'s field.
571fn block_of(key: &str) -> Option<Block> {
572    match key.rsplit('.').next()? {
573        "forwardDifferences" | "forwardDifference" => Some(Block::Forward),
574        "reverseDifferences" | "reverseDifference" => Some(Block::Reverse),
575        "preconditions" => Some(Block::Preconditions),
576        _ => None,
577    }
578}
579
580/// Read objects into `ds` from `reader`: a whole document, or, with `block`,
581/// the statements of one difference block (`rdf:parseType="Statements"`),
582/// whose start tag was just read, up to its end tag. A block's objects are
583/// one level deeper than a document's, so it is read as if it were the
584/// document's root, in the namespaces its document declared.
585fn parse_events(
586    reader: &mut Reader<&[u8]>,
587    reg: &'static TypeRegistry,
588    ds: &mut CimDataset,
589    mut scope: Scope,
590    block: bool,
591) -> Result<(), Box<dyn std::error::Error>> {
592    let mut buf = Vec::new();
593
594    let mut depth: u32 = u32::from(block);
595    // The differences of the header being read, once one of its fields holds statements.
596    let mut differences: Option<Differences> = None;
597    // Outer scope parked while a nested `xmlns` override is in effect.
598    let mut nested: Option<Scope> = None;
599    // Resolved at the element's start tag, so an unregistered element never
600    // accumulates fields.
601    let mut current: Option<Element> = None;
602    // `current` is an object of a class no table knows ([`CimDataset::foreign`]).
603    let mut current_foreign = false;
604    // The namespace `current` was written in, when not its class's.
605    let mut current_ns: Option<&'static str> = None;
606    // The attributes `current`'s class declares, which supply most field keys.
607    let mut declared: Option<&'static FastMap<&'static str, &'static AttrDef>> = None;
608    let mut pending_key: Option<&'static str> = None;
609    // The `xml:lang` of the field element whose text comes next.
610    let mut pending_lang: Option<String> = None;
611    // The literal field's text so far. Stored at its end tag, as written —
612    // untrimmed, and empty for `<cim:X></cim:X>` — since a comment or CDATA
613    // section splits it into several events.
614    let mut pending_text = String::new();
615    // A field element's key as stored — the class table's id when the class
616    // declares it, else the interned name — and its attributes. What the key
617    // and value lose of how it was written goes to `field_forms`: an
618    // undeclared key's namespace, a datatype, the namespace a reference was
619    // cut from.
620    let field = |declared: Option<&'static FastMap<&'static str, &'static AttrDef>>,
621                 class: &'static str,
622                 e: &BytesStart,
623                 scope: &Scope,
624                 forms: &mut FastMap<(&'static str, &'static str), FieldForm>|
625     -> Result<(&'static str, FieldAttrs), Box<dyn std::error::Error>> {
626        let name = e.name();
627        let (prefix, local_bytes) = split_qname(name.as_ref());
628        let local = std::str::from_utf8(local_bytes)?;
629        let attr = declared.and_then(|d| d.get(local));
630        let key = attr.map_or_else(|| intern(local), |a| a.id);
631        let attrs = field_attrs(e.attributes())?;
632        let ns = scope.ns(prefix);
633        let undeclared_ns =
634            (!ns.is_empty() && attr.is_none_or(|a| !same_ns(a.ns, ns))).then_some(ns);
635        let resource_ns = attrs
636            .resource_ns
637            .filter(|_| attr.is_none_or(|a| a.kind != AttrKind::Enum));
638        if undeclared_ns.is_some() || attrs.datatype.is_some() || resource_ns.is_some() {
639            forms.entry((class, key)).or_default().fill_from(FieldForm {
640                ns: undeclared_ns,
641                datatype: attrs.datatype,
642                resource_ns,
643            });
644        }
645        Ok((key, attrs))
646    };
647
648    loop {
649        match reader.read_event_into(&mut buf) {
650            Ok(Event::Start(ref e)) => {
651                depth += 1;
652
653                match depth {
654                    1 => {
655                        scope.absorb(e, reg);
656                        for (prefix, ns, _) in &scope.prefixes {
657                            if let Ok(prefix) = std::str::from_utf8(prefix) {
658                                ds.prefixes.entry(ns).or_insert_with(|| intern(prefix));
659                            }
660                        }
661                    }
662                    2 => {
663                        // Every CGMES and NC file declares its namespaces on the
664                        // root, but a nested redeclaration is legal RDF/XML, so
665                        // honour one when it appears. The End arm restores the
666                        // outer scope.
667                        let subject = scan_attrs(e)?;
668                        if subject.has_xmlns {
669                            let mut inner = Scope {
670                                prefixes: scope.prefixes.clone(),
671                                default: scope.default,
672                                default_ns: scope.default_ns,
673                            };
674                            inner.absorb(e, reg);
675                            nested = Some(std::mem::replace(&mut scope, inner));
676                        }
677
678                        (current, current_foreign, current_ns) =
679                            match object(&scope, reg, e, subject)? {
680                                Some((element, foreign, written)) => {
681                                    (Some(element), foreign, written)
682                                }
683                                None => (None, false, None),
684                            };
685                        declared = current.as_ref().and_then(|c| reg.declared(c.class()));
686                    }
687                    3 => {
688                        if let Some(element) = current.as_mut() {
689                            let (key, attrs) = field(
690                                declared,
691                                element.type_name(),
692                                e,
693                                &scope,
694                                &mut ds.field_forms,
695                            )?;
696                            if attrs.nodes
697                                && let Some(which) = block_of(key)
698                            {
699                                // A difference header's statements: objects of their own,
700                                // read up to the block's end tag, which closes this field.
701                                let found = differences
702                                    .get_or_insert_with(|| Differences::new(element.mrid()));
703                                parse_events(
704                                    reader,
705                                    reg,
706                                    found.block_mut(which),
707                                    scope.clone(),
708                                    true,
709                                )?;
710                                depth -= 1;
711                                buf.clear();
712                                continue;
713                            }
714                            if let Some(res) = attrs.resource {
715                                element.add_field(key, FieldValue::Resource(res));
716                            } else if !attrs.nodes {
717                                pending_key = Some(key);
718                                pending_lang = attrs.lang;
719                                pending_text.clear();
720                            }
721                        }
722                    }
723                    // A child element: the field holds statements or XML
724                    // (`rdf:parseType`), not a literal.
725                    _ => pending_key = None,
726                }
727            }
728
729            Ok(Event::Empty(ref e)) => {
730                match depth {
731                    1 => {
732                        // Top-level self-closing element: <cim:Foo rdf:ID="x" />
733                        // It can carry its own xmlns; with no children there is
734                        // nothing to restore afterwards, so resolve against a
735                        // throwaway scope.
736                        let subject = scan_attrs(e)?;
737                        let local_scope = if subject.has_xmlns {
738                            let mut inner = Scope {
739                                prefixes: scope.prefixes.clone(),
740                                default: scope.default,
741                                default_ns: scope.default_ns,
742                            };
743                            inner.absorb(e, reg);
744                            Some(inner)
745                        } else {
746                            None
747                        };
748                        let active = local_scope.as_ref().unwrap_or(&scope);
749                        if let Some((element, foreign, written)) = object(active, reg, e, subject)?
750                        {
751                            store(ds, element, foreign, written);
752                        }
753                    }
754                    2 => {
755                        // Self-closing field element within the current type
756                        // block: a reference, or else an empty literal.
757                        if let Some(element) = current.as_mut() {
758                            let (key, attrs) = field(
759                                declared,
760                                element.type_name(),
761                                e,
762                                &scope,
763                                &mut ds.field_forms,
764                            )?;
765                            if attrs.nodes
766                                && let Some(which) = block_of(key)
767                            {
768                                // An empty statements block: no statements, but the block is there.
769                                differences
770                                    .get_or_insert_with(|| Differences::new(element.mrid()))
771                                    .block_mut(which);
772                            } else if let Some(res) = attrs.resource {
773                                element.add_field(key, FieldValue::Resource(res));
774                            } else if !attrs.nodes {
775                                element.add_field(key, FieldValue::Text(String::new()));
776                                if let Some(lang) = attrs.lang {
777                                    element.add_lang(key, &lang);
778                                }
779                            }
780                        }
781                    }
782                    _ => pending_key = None,
783                }
784            }
785
786            Ok(Event::Text(ref e)) if depth == 3 && pending_key.is_some() => {
787                pending_text.push_str(&e.unescape()?);
788            }
789
790            Ok(Event::CData(ref e)) if depth == 3 && pending_key.is_some() => {
791                pending_text.push_str(std::str::from_utf8(e)?);
792            }
793
794            Ok(Event::End(_)) => {
795                if depth == 3
796                    && let (Some(element), Some(key)) = (current.as_mut(), pending_key.take())
797                {
798                    element.add_field(key, FieldValue::Text(std::mem::take(&mut pending_text)));
799                    if let Some(lang) = pending_lang.take() {
800                        element.add_lang(key, &lang);
801                    }
802                }
803                if depth == 2 {
804                    pending_key = None;
805                    pending_lang = None;
806                    if let Some(element) = current.take() {
807                        store(ds, element, current_foreign, current_ns.take());
808                    }
809                    if let Some(found) = differences.take() {
810                        ds.differences.push(found);
811                    }
812                    if let Some(outer) = nested.take() {
813                        scope = outer;
814                    }
815                }
816                depth = depth.saturating_sub(1);
817                // A difference block's end tag: its statements are read.
818                if block && depth == 0 {
819                    break;
820                }
821            }
822
823            Ok(Event::Eof) if block => return Err("a difference block is not closed".into()),
824            Ok(Event::Eof) => break,
825            Err(e) => return Err(Box::new(e)),
826            _ => {}
827        }
828        buf.clear();
829    }
830
831    Ok(())
832}
833
834// --- helpers ----------------------------------------------------------------
835
836/// Strip the fragment from a URI, e.g. "http://example.com#foo" → "foo".
837///
838/// An IRI whose fragment is empty names a vocabulary, not an object
839/// (`dcterms:conformsTo rdf:resource="http://iec.ch/TC57/CIM100#"`), and is
840/// kept whole: stripped, it was the empty string, which no encoder can write
841/// back.
842fn strip_fragment(s: &str) -> String {
843    match s.rfind('#') {
844        Some(i) if i + 1 == s.len() && i > 0 => s.to_string(),
845        Some(i) => s[i + 1..].to_string(),
846        None => s.to_string(),
847    }
848}
849
850/// What a field element's attributes say about its value.
851struct FieldAttrs {
852    /// `rdf:resource`, as [`strip_fragment`] keeps it.
853    resource: Option<String>,
854    /// The part of `rdf:resource` that was cut off, when the IRI has one
855    /// before its `#` (not a reference into the document itself).
856    resource_ns: Option<&'static str>,
857    lang: Option<String>,
858    datatype: Option<&'static str>,
859    /// Its `rdf:parseType` makes its content nodes rather than a literal
860    /// (`Resource`, `Collection`, a difference model's `Statements`; not
861    /// `Literal`).
862    nodes: bool,
863}
864
865/// A field element's attributes, in one pass.
866fn field_attrs(
867    attrs: quick_xml::events::attributes::Attributes<'_>,
868) -> Result<FieldAttrs, Box<dyn std::error::Error>> {
869    let mut out = FieldAttrs {
870        resource: None,
871        resource_ns: None,
872        lang: None,
873        datatype: None,
874        nodes: false,
875    };
876    for attr in attrs.flatten() {
877        match attr.key.as_ref() {
878            b"rdf:resource" => {
879                let iri = std::str::from_utf8(&attr.value)?;
880                let kept = strip_fragment(iri);
881                if kept.len() < iri.len() && kept.len() + 1 < iri.len() {
882                    out.resource_ns = Some(intern(&iri[..iri.len() - kept.len()]));
883                }
884                out.resource = Some(kept);
885            }
886            b"rdf:nodeID" => {
887                out.resource = Some(format!("_:{}", std::str::from_utf8(&attr.value)?))
888            }
889            b"xml:lang" => out.lang = Some(std::str::from_utf8(&attr.value)?.to_string()),
890            b"rdf:datatype" => out.datatype = Some(intern(std::str::from_utf8(&attr.value)?)),
891            b"rdf:parseType" => out.nodes = attr.value.as_ref() != b"Literal",
892            _ => {}
893        }
894    }
895    Ok(out)
896}