Skip to main content

cimmodel/
decode.rs

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