Skip to main content

cim_kit/
reader.rs

1//! Streaming reader for CIM/XML instance documents (IEC 61970-552).
2//!
3//! IEC 61970-552 constrains RDF/XML to a small, regular subset: a flat `rdf:RDF` root
4//! containing a header and a list of objects, where each object is a class element whose
5//! property children are either element text or a single `rdf:resource`. A purpose-built
6//! pull parser over that subset is both much faster and much simpler than a general RDF
7//! toolchain, and it never holds the document in memory.
8
9use std::borrow::Cow;
10use std::cell::{Cell, RefCell};
11use std::collections::HashMap;
12use std::io::{self, BufRead, Read};
13
14use quick_xml::Reader;
15use quick_xml::events::{BytesStart, Event};
16
17use crate::dataset::Dataset;
18use crate::error::{Diagnostic, Error, Report, Result, Rule};
19use crate::header::{
20    DM_NS, DifferenceModel, HeaderProperty, MD_NS, ModelHeader, ModelKind, QualifiedName,
21    Statement, StatementValue,
22};
23use crate::mrid::Mrid;
24use crate::object::{Compound, Object};
25use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileId, ProfileMask, Schema};
26use crate::value::Value;
27
28const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
29
30/// Stand-in identifier for a diagnostic raised where no object is under construction.
31static UNKNOWN_MRID: Mrid = Mrid::nil();
32
33/// How strictly to treat schema deviations while reading.
34#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
35pub enum Strictness {
36    /// Unknown classes and attributes are recorded as diagnostics and skipped.
37    ///
38    /// The default: published models regularly carry vendor extensions, and refusing to
39    /// read them would make the library useless for real data.
40    #[default]
41    Lenient,
42    /// Unknown classes or attributes make the read fail.
43    Strict,
44}
45
46/// Options controlling a read.
47#[derive(Clone, Debug)]
48pub struct ReadOptions {
49    pub strictness: Strictness,
50    /// Profile to attribute the data to when the header does not declare one.
51    pub assume_profile: Option<ProfileId>,
52    /// Record `Info` diagnostics for deprecated classes and attributes.
53    pub report_deprecated: bool,
54    /// Record a diagnostic for every identifier that is not a UUID.
55    pub report_non_conforming_mrids: bool,
56    /// Stop recording after this many diagnostics.
57    ///
58    /// Lenient reading answers a malformed document with a diagnostic rather than an
59    /// error, which means the *report* is proportional to how broken the input is: a file
60    /// whose every element is unknown produces one finding per element, each carrying
61    /// several owned strings. On a hostile or merely corrupt hundred-megabyte document
62    /// that is memory the caller never asked for. Past the cap the reader keeps reading
63    /// and stops recording, closing the report with a note saying so, so nothing is
64    /// silently truncated. Zero means no limit.
65    pub max_diagnostics: usize,
66    /// Stop reading after this many bytes of input. Zero means no limit.
67    ///
68    /// The bytes counted are the ones the parser accepts — for a zip archive, the
69    /// *decompressed* bytes of its entries — summed across one load call, so a directory
70    /// or an archive of many entries shares one budget. Past it the read fails with
71    /// [`Error::InputTooLarge`], never with a diagnostic: what was read is not the model.
72    ///
73    /// The default, [`ReadOptions::DEFAULT_MAX_INPUT_BYTES`], is there because a dataset
74    /// grows linearly in what it accepts, so without one a 2 MB archive that inflates to
75    /// 50 GB is a request for 50 GB of memory.
76    pub max_input_bytes: u64,
77}
78
79impl Default for ReadOptions {
80    fn default() -> Self {
81        ReadOptions {
82            strictness: Strictness::Lenient,
83            assume_profile: None,
84            report_deprecated: false,
85            report_non_conforming_mrids: false,
86            max_diagnostics: ReadOptions::DEFAULT_MAX_DIAGNOSTICS,
87            max_input_bytes: ReadOptions::DEFAULT_MAX_INPUT_BYTES,
88        }
89    }
90}
91
92impl ReadOptions {
93    /// How many diagnostics one read records before it stops recording.
94    pub const DEFAULT_MAX_DIAGNOSTICS: usize = 10_000;
95
96    /// How many bytes one load call accepts by default: 2 GiB.
97    ///
98    /// The largest document either published conformity corpus contains is 80 MB
99    /// (`RealGrid_EQ.xml`) and the largest model set about 112 MiB, so this is roughly
100    /// eighteen times the biggest real input there is — room for merged pan-European
101    /// models, and still a bound. Raise it with [`ReadOptions::with_max_input_bytes`].
102    pub const DEFAULT_MAX_INPUT_BYTES: u64 = 2 << 30;
103
104    /// Tolerant defaults, suitable for real-world exchange files.
105    pub fn lenient() -> ReadOptions {
106        ReadOptions::default()
107    }
108
109    /// Fail on anything the schema does not describe, and report every deviation.
110    pub fn strict() -> ReadOptions {
111        ReadOptions {
112            strictness: Strictness::Strict,
113            report_deprecated: true,
114            report_non_conforming_mrids: true,
115            ..ReadOptions::default()
116        }
117    }
118
119    pub fn with_profile(mut self, profile: ProfileId) -> Self {
120        self.assume_profile = Some(profile);
121        self
122    }
123
124    /// Cap the number of diagnostics one read records. Zero means no limit.
125    pub fn with_max_diagnostics(mut self, max: usize) -> Self {
126        self.max_diagnostics = max;
127        self
128    }
129
130    /// Cap the bytes one load call accepts. Zero means no limit.
131    pub fn with_max_input_bytes(mut self, max: u64) -> Self {
132        self.max_input_bytes = max;
133        self
134    }
135}
136
137/// The input budget of one load call, shared by every document it reads.
138///
139/// Counted where the parser *consumes* input rather than where a file is read, which is
140/// what makes it count decompressed bytes and never an archive's own claim about its
141/// sizes. It overshoots by at most one byte.
142#[derive(Debug)]
143pub(crate) struct Budget {
144    limit: u64,
145    used: Cell<u64>,
146    tripped: Cell<bool>,
147}
148
149impl Budget {
150    pub(crate) fn new(options: &ReadOptions) -> Budget {
151        Budget {
152            limit: options.max_input_bytes,
153            used: Cell::new(0),
154            tripped: Cell::new(false),
155        }
156    }
157
158    /// `input`, charged against this budget.
159    pub(crate) fn meter<R: BufRead>(&self, input: R) -> Metered<'_, R> {
160        Metered {
161            inner: input,
162            used: self.used.get(),
163            // Zero is "no limit"; u64::MAX makes that the same comparison as any other.
164            limit: if self.limit == 0 {
165                u64::MAX
166            } else {
167                self.limit
168            },
169            budget: self,
170        }
171    }
172
173    /// Turn whatever error the parser surfaced into `InputTooLarge` when it was the budget
174    /// that stopped it.
175    ///
176    /// quick-xml reports the refusal as its own I/O error, which the reader flattens into
177    /// a string; recognising it by a flag rather than by that string keeps the typed error
178    /// independent of either.
179    pub(crate) fn check<T>(&self, result: Result<T>, source: Option<&str>) -> Result<T> {
180        match result {
181            Err(_) if self.tripped.get() => Err(Error::InputTooLarge {
182                limit: self.limit,
183                read: self.used.get(),
184                source: source.map(str::to_owned),
185            }),
186            other => other,
187        }
188    }
189
190    pub(crate) fn tripped(&self) -> bool {
191        self.tripped.get()
192    }
193}
194
195/// A [`BufRead`] that refuses to hand out more input once its [`Budget`] is spent.
196///
197/// The count lives in the reader itself and is written back to the shared budget when the
198/// reader is dropped, because the parser calls `fill_buf` and `consume` for nearly every
199/// event and this is the hot path of every read.
200pub(crate) struct Metered<'a, R> {
201    inner: R,
202    used: u64,
203    limit: u64,
204    budget: &'a Budget,
205}
206
207impl<R> Drop for Metered<'_, R> {
208    fn drop(&mut self) {
209        self.budget.used.set(self.used);
210    }
211}
212
213impl<R: BufRead> Read for Metered<'_, R> {
214    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
215        let available = self.fill_buf()?;
216        let n = available.len().min(out.len());
217        out[..n].copy_from_slice(&available[..n]);
218        self.consume(n);
219        Ok(n)
220    }
221}
222
223impl<R: BufRead> BufRead for Metered<'_, R> {
224    #[inline]
225    fn fill_buf(&mut self) -> io::Result<&[u8]> {
226        if self.used > self.limit {
227            self.budget.tripped.set(true);
228            self.budget.used.set(self.used);
229            return Err(io::Error::other("input budget exceeded"));
230        }
231        // Never offer more than one byte past the budget. An in-memory reader hands out
232        // everything it has in one slice, and a parser may take all of it in one step, so
233        // without this the overshoot would be the rest of the input rather than a byte.
234        let room = self.limit - self.used;
235        let buf = self.inner.fill_buf()?;
236        Ok(match usize::try_from(room) {
237            Ok(room) if room < buf.len() => &buf[..=room],
238            _ => buf,
239        })
240    }
241
242    #[inline]
243    fn consume(&mut self, amt: usize) {
244        self.used = self.used.saturating_add(amt as u64);
245        self.inner.consume(amt);
246    }
247}
248
249/// How much of a document [`sniff`] reads before concluding it names no known vocabulary.
250const SNIFF_PREFIX: u64 = 1 << 20;
251
252/// Result of reading one document.
253#[derive(Debug)]
254pub struct ReadOutcome {
255    pub header: Option<ModelHeader>,
256    /// Present when the document was a `dm:DifferenceModel`.
257    pub difference: Option<DifferenceModel>,
258    pub report: Report,
259    /// Number of object elements read from this document.
260    pub objects_read: usize,
261}
262
263/// Read a CIM/XML document into `dataset`, merging with what is already loaded.
264pub fn read_into<R: BufRead>(
265    dataset: &mut Dataset,
266    input: R,
267    source: Option<&str>,
268    options: &ReadOptions,
269) -> Result<ReadOutcome> {
270    let budget = Budget::new(options);
271    read_into_within(dataset, input, source, options, &budget)
272}
273
274/// [`read_into`], charged against a budget the caller shares across documents.
275pub(crate) fn read_into_within<R: BufRead>(
276    dataset: &mut Dataset,
277    input: R,
278    source: Option<&str>,
279    options: &ReadOptions,
280    budget: &Budget,
281) -> Result<ReadOutcome> {
282    let schema = dataset.schema();
283    let mut parser = Parser::new(schema, source, options, false);
284    let outcome = parser.run(budget.meter(input), Some(dataset));
285    budget.check(outcome, source)
286}
287
288/// Read only the header of a document, without storing objects.
289///
290/// Useful for planning a multi-file load: headers declare profiles and dependencies.
291pub fn read_header<R: BufRead>(
292    schema: &'static Schema,
293    input: R,
294    source: Option<&str>,
295) -> Result<Option<ModelHeader>> {
296    let options = ReadOptions::default();
297    let budget = Budget::new(&options);
298    let mut parser = Parser::new(schema, source, &options, true);
299    let outcome = parser.run(budget.meter(input), None);
300    Ok(budget.check(outcome, source)?.header)
301}
302
303/// Identify which schema vintage a document is written against, reading only its root.
304///
305/// CIM/XML names its vocabulary in the document, so the vintage is a fact to be read rather
306/// than a parameter to be guessed. Returns `None` when no compiled-in vintage recognises the
307/// namespaces — a document this build has no feature for, or not a CIM/XML document at all.
308///
309/// ```no_run
310/// # fn main() -> cim_kit::Result<()> {
311/// let file = std::io::BufReader::new(std::fs::File::open("EQ.xml")?);
312/// let schema = cim_kit::reader::sniff(file)?.expect("a known CIM vintage");
313/// let mut ds = cim_kit::Dataset::new(schema);
314/// # Ok(()) }
315/// ```
316///
317/// Only the first MiB is read: the vocabulary is declared on the root element, and
318/// [`detect_vintage`](crate::load::detect_vintage) sniffs every file of a set before
319/// loading any, so an unbounded sniff would be a second, uncounted pass over the input.
320pub fn sniff<R: BufRead>(input: R) -> Result<Option<&'static Schema>> {
321    let mut reader = Reader::from_reader(input.take(SNIFF_PREFIX));
322    reader.config_mut().check_end_names = false;
323    let mut buf = Vec::new();
324    loop {
325        let ev = match reader.read_event_into(&mut buf) {
326            Ok(ev) => ev,
327            // Cut off mid-token by the prefix: not a malformed document, just one whose
328            // vocabulary is not declared where every producer declares it.
329            Err(_) if reader.get_ref().limit() == 0 => return Ok(None),
330            Err(e) => return Err(Error::Xml(e.to_string())),
331        };
332        let e = match ev {
333            Event::Eof => return Ok(None),
334            Event::Start(e) | Event::Empty(e) => e,
335            _ => {
336                buf.clear();
337                continue;
338            }
339        };
340        // Producers occasionally wrap `rdf:RDF`, so keep looking rather than giving up on
341        // the first element — but only until something declares a namespace we know.
342        let mut iris: Vec<String> = Vec::new();
343        for attr in e.attributes().with_checks(false) {
344            let attr = attr?;
345            let key = attr.key.as_ref();
346            if key == "xmlns" || key.starts_with("xmlns:") {
347                iris.push(attr.value.into_owned());
348            }
349        }
350        if let Some(schema) = Schema::detect(iris.iter().map(String::as_str)) {
351            return Ok(Some(schema));
352        }
353        buf.clear();
354    }
355}
356
357/// Read a difference model document.
358///
359/// `options` bound it the way they bound an instance file — a change set arrives from
360/// somebody else too.
361pub fn read_difference<R: BufRead>(
362    schema: &'static Schema,
363    input: R,
364    source: Option<&str>,
365    options: &ReadOptions,
366) -> Result<Option<DifferenceModel>> {
367    let budget = Budget::new(options);
368    let mut parser = Parser::new(schema, source, options, false);
369    let outcome = parser.run(budget.meter(input), None);
370    Ok(budget.check(outcome, source)?.difference)
371}
372
373// ---------------------------------------------------------------------------
374// Parser
375// ---------------------------------------------------------------------------
376
377/// What an element name refers to, once resolved against the schema.
378#[derive(Clone, Copy)]
379enum Resolved {
380    Class(ClassId),
381    Attr(AttrId),
382    /// A name the schema does not define — typically a vendor extension.
383    Unknown,
384}
385
386/// Where the parser currently is in the document.
387#[derive(Clone, Copy, PartialEq, Eq, Debug)]
388enum Ctx {
389    /// Outside `rdf:RDF`.
390    Outside,
391    /// Directly inside `rdf:RDF`.
392    Body,
393    /// Inside `md:FullModel` or `dm:DifferenceModel`.
394    Header,
395    /// Inside an object element.
396    Object,
397    /// Inside a compound value — an `rdf:parseType="Resource"` element.
398    Compound,
399    /// Inside `dm:forwardDifferences` / `dm:reverseDifferences`.
400    DiffSet,
401    /// Inside an `rdf:Description` within a difference set.
402    DiffSubject,
403    /// Inside an element whose text content is being accumulated.
404    ///
405    /// Distinct from [`Ctx::Skip`] so that a value is exactly the text of *its own*
406    /// element. Without the distinction, markup nested inside a property element — which
407    /// IEC 61970-552 does not allow, and which malformed documents nonetheless contain —
408    /// donated its text to the property and ended it at the nested element's close tag,
409    /// so `<name><x>ignored</x></name>` read back as `ignored` rather than as empty.
410    Text,
411    /// Inside an element that is being skipped wholesale.
412    Skip,
413}
414
415/// What a resolved property element asks the parser to do.
416enum Prop {
417    /// Store this value immediately: it came from `rdf:resource` or an empty element.
418    Value(AttrId, Value),
419    /// Descend into a compound value of the named type.
420    Enter(AttrId, ClassId),
421    /// Accumulate the element's text for this attribute.
422    Text(AttrId),
423    /// Nothing to store.
424    Skip,
425}
426
427/// Everything being assembled while the document is walked.
428///
429/// Kept in one place rather than threaded through the element handlers as a dozen
430/// `&mut` parameters.
431#[derive(Default)]
432struct State {
433    saw_root: bool,
434    header: Option<ModelHeader>,
435    difference: Option<DifferenceModel>,
436    objects_read: usize,
437    /// Object under construction.
438    object: Option<Object>,
439    /// Compounds under construction, innermost last. Compounds nest: a `StreetAddress`
440    /// holds a `StreetDetail`.
441    compounds: Vec<(AttrId, Compound)>,
442    /// Property whose text is being accumulated.
443    pending: Option<PendingText>,
444    /// Profiles to attribute values to, taken from the header once it closes.
445    profile_mask: ProfileMask,
446    /// Subject of the statement group being read: identifier, class and whether the
447    /// group introduced it with `rdf:ID`.
448    diff_subject: Option<(Mrid, Option<QualifiedName>, bool)>,
449    /// Which statement set of a difference model is being read.
450    diff_set: DiffSet,
451    /// This file's slot among the dataset's headers, so an export can put each object
452    /// back in the file it came from.
453    source: Option<usize>,
454    /// Whether the header has been registered with the dataset yet.
455    header_registered: bool,
456    /// Slot claimed for a document that had not named itself yet, to be filled in if it
457    /// turns out to have an `md:FullModel` after all.
458    placeholder_slot: Option<usize>,
459}
460
461struct Parser<'a> {
462    schema: &'static Schema,
463    options: &'a ReadOptions,
464    source: Option<String>,
465    report: Report,
466    header_only: bool,
467    /// Whether the report has already been closed off at `max_diagnostics`.
468    truncated: bool,
469    /// Prefix bytes -> namespace IRI, as declared in the document.
470    ns: HashMap<Vec<u8>, String>,
471    /// Raw element QName -> resolution. Instance documents repeat a small set of element
472    /// names many thousands of times, so this cache removes nearly all lookup cost.
473    cache: HashMap<Vec<u8>, Resolved>,
474    /// Undefined entity references met in attribute values since the last element,
475    /// reported once the element is handled. `attr` borrows the parser immutably so that
476    /// it can lend from the element, hence the cell.
477    undefined_entities: RefCell<Vec<String>>,
478}
479
480impl<'a> Parser<'a> {
481    fn new(
482        schema: &'static Schema,
483        source: Option<&str>,
484        options: &'a ReadOptions,
485        header_only: bool,
486    ) -> Parser<'a> {
487        Parser {
488            schema,
489            options,
490            source: source.map(str::to_owned),
491            report: Report::default(),
492            header_only,
493            truncated: false,
494            ns: HashMap::new(),
495            cache: HashMap::new(),
496            undefined_entities: RefCell::new(Vec::new()),
497        }
498    }
499
500    /// Report the undefined entities `attr` met in the element just handled.
501    ///
502    /// Runs for every element and almost never has anything to do, so the check is inline
503    /// and the work is not.
504    #[inline]
505    fn flush_undefined_entities(&mut self, pos: u64) {
506        if !self.undefined_entities.get_mut().is_empty() {
507            self.report_undefined_entities(pos);
508        }
509    }
510
511    #[cold]
512    #[inline(never)]
513    fn report_undefined_entities(&mut self, pos: u64) {
514        let names = std::mem::take(self.undefined_entities.get_mut());
515        for name in names {
516            self.diag(undefined_entity(&name), pos);
517        }
518    }
519
520    /// An attribute's value, normalized per XML 1.0 — and, like element text, with any
521    /// entity this reader does not define kept literally rather than failing the document.
522    ///
523    /// quick-xml refuses an unknown entity in an attribute outright, which made one
524    /// `&x;` in an `rdf:resource` fail a whole document that a stray `&x;` in element
525    /// text merely passed through. Neither was right: both are now kept and reported.
526    fn attr_value<'e>(
527        &self,
528        attr: &quick_xml::events::attributes::Attribute<'e>,
529    ) -> Result<Cow<'e, str>> {
530        use quick_xml::escape::EscapeError;
531        match attr.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
532            Ok(v) => Ok(v),
533            Err(quick_xml::Error::Escape(EscapeError::UnrecognizedEntity(..))) => {
534                let (escaped, names) = escape_undefined_entities(&attr.value);
535                self.undefined_entities.borrow_mut().extend(names);
536                let rewritten = quick_xml::events::attributes::Attribute {
537                    key: attr.key,
538                    value: Cow::Owned(escaped),
539                };
540                let value = rewritten
541                    .normalized_value(quick_xml::XmlVersion::Explicit1_0)
542                    .map_err(|e| Error::Xml(e.to_string()))?;
543                Ok(Cow::Owned(value.into_owned()))
544            }
545            Err(e) => Err(Error::Xml(e.to_string())),
546        }
547    }
548
549    fn diag(&mut self, d: Diagnostic, pos: u64) {
550        let max = self.options.max_diagnostics;
551        if max != 0 && self.report.len() >= max {
552            if !self.truncated {
553                self.truncated = true;
554                self.report.push(Diagnostic::warning(
555                    Rule::Structure,
556                    format!(
557                        "stopped recording after {max} diagnostics; reading continued \
558                         (raise ReadOptions::max_diagnostics to see the rest)"
559                    ),
560                ));
561            }
562            return;
563        }
564        let mut d = d.with_position(pos);
565        if let Some(s) = &self.source {
566            d = d.with_source(s.clone());
567        }
568        self.report.push(d);
569    }
570
571    /// Expand an element QName to `(namespace IRI, local name)`, borrowing both.
572    fn expand<'q>(&self, qname: &'q str) -> Option<(&str, &'q str)> {
573        let (prefix, local) = match qname.split_once(':') {
574            Some((prefix, local)) => (prefix, local),
575            None => ("", qname),
576        };
577        let ns = self.ns.get(prefix.as_bytes())?;
578        Some((ns.as_str(), local))
579    }
580
581    fn resolve(&mut self, qname: &str) -> Resolved {
582        if let Some(r) = self.cache.get(qname.as_bytes()) {
583            return *r;
584        }
585        let resolved = match self.expand(qname) {
586            // A dot separates class from property: `cim:ACLineSegment.r`.
587            Some((ns, local)) if local.contains('.') => match self.schema.find_attr(ns, local) {
588                Some(a) => Resolved::Attr(a),
589                None => Resolved::Unknown,
590            },
591            Some((ns, local)) => match self.schema.find_class(ns, local) {
592                Some(c) => Resolved::Class(c),
593                None => Resolved::Unknown,
594            },
595            None => Resolved::Unknown,
596        };
597        self.cache.insert(qname.as_bytes().to_vec(), resolved);
598        resolved
599    }
600
601    fn run<R: BufRead>(
602        &mut self,
603        input: R,
604        mut dataset: Option<&mut Dataset>,
605    ) -> Result<ReadOutcome> {
606        let mut reader = Reader::from_reader(input);
607        reader.config_mut().trim_text(false);
608        reader.config_mut().expand_empty_elements = false;
609        reader.config_mut().check_end_names = false;
610
611        let mut buf = Vec::new();
612        let mut ctx = Ctx::Outside;
613        let mut stack: Vec<Ctx> = Vec::with_capacity(8);
614
615        let mut st = State {
616            profile_mask: self.options.assume_profile.map_or(0, |p| p.mask()),
617            ..Default::default()
618        };
619
620        loop {
621            let ev = reader.read_event_into(&mut buf).map_err(parse_error)?;
622            let pos = reader.buffer_position();
623
624            match ev {
625                Event::Eof => break,
626
627                Event::Start(e) => {
628                    let next = self.on_open(&e, false, ctx, &mut st, pos)?;
629                    self.flush_undefined_entities(pos);
630                    stack.push(ctx);
631                    ctx = next;
632                }
633
634                Event::Empty(e) => {
635                    // Self-closing element: open and close in one step, so the context
636                    // stack is untouched.
637                    let saved = ctx;
638                    let entered = self.on_open(&e, true, ctx, &mut st, pos)?;
639                    self.flush_undefined_entities(pos);
640                    match entered {
641                        // An object with no properties is written `<cim:Class rdf:ID="…"/>`.
642                        // It closes immediately, so commit it here — otherwise it would be
643                        // lost and would overwrite whichever object came next.
644                        Ctx::Object => {
645                            if let Some(o) = st.object.take() {
646                                self.ensure_source(&mut st, &mut dataset);
647                                self.commit(o, &st, &mut dataset, pos);
648                                st.objects_read += 1;
649                            }
650                        }
651                        // An empty compound: `<cim:X.y rdf:parseType="Resource"/>`.
652                        Ctx::Compound => self.close_compound(&mut st),
653                        Ctx::DiffSubject => st.diff_subject = None,
654                        // A header with no properties: `<md:FullModel rdf:about="…"/>`.
655                        // Legal, and degenerate, but it still identifies the file — and
656                        // registering it is what gives this file's objects a source slot,
657                        // so an export can put them back in the file they came from.
658                        Ctx::Header => self.register_header(&mut st, &mut dataset),
659                        _ => {}
660                    }
661                    ctx = saved;
662                }
663
664                // Text belongs to the element that is accumulating it and to no other, so
665                // it is taken only in `Ctx::Text`. Anything nested inside a property
666                // element is skipped along with its content.
667                Event::Text(t) if ctx == Ctx::Text => {
668                    if let Some(p) = st.pending.as_mut() {
669                        // XML 1.0 content: decoded, and with CR and CRLF normalized to LF
670                        // as the specification requires of every conforming parser. A
671                        // value that must keep a literal CR is written as `&#13;`, which
672                        // arrives as the reference event below rather than as text.
673                        let text = t.xml10_content();
674                        p.text.push_str(&text);
675                    }
676                }
677
678                // `&amp;`, `&lt;`, `&#13;`: a reference is its own event, delivered between
679                // the text runs around it. Ignoring it does not fail — it silently deletes
680                // the character, so `A &amp; B` reads back as `A  B`. The round-trip test
681                // over XML special characters is what says otherwise.
682                Event::GeneralRef(r) if ctx == Ctx::Text => {
683                    let mut undefined = None;
684                    if let Some(p) = st.pending.as_mut() {
685                        match r.resolve_char_ref() {
686                            // A numeric character reference: `&#13;` or `&#x0D;`.
687                            Ok(Some(c)) => p.text.push(c),
688                            // A named entity. Only the five XML predefines exist here:
689                            // IEC 61970-552 documents declare no DTD, so anything else is
690                            // undefined and keeping its literal form loses least.
691                            Ok(None) | Err(_) => {
692                                let name = r.as_ref();
693                                match quick_xml::escape::resolve_predefined_entity(name) {
694                                    Some(text) => p.text.push_str(text),
695                                    None => {
696                                        p.text.push('&');
697                                        p.text.push_str(name);
698                                        p.text.push(';');
699                                        undefined = Some(name.to_owned());
700                                    }
701                                }
702                            }
703                        }
704                    }
705                    // Kept, because it loses least — and said, because keeping it is a
706                    // tolerance like any other.
707                    if let Some(name) = undefined {
708                        self.diag(undefined_entity(&name), pos);
709                    }
710                }
711
712                Event::CData(t) if ctx == Ctx::Text => {
713                    if let Some(p) = st.pending.as_mut() {
714                        p.text.push_str(&t);
715                    }
716                }
717
718                Event::End(_) => {
719                    // The header precedes every object, so once it closes the profiles
720                    // the file declares are known, the header can be registered with the
721                    // dataset, and objects can be attributed to both.
722                    if ctx == Ctx::Header {
723                        self.register_header(&mut st, &mut dataset);
724                    }
725                    match ctx {
726                        // A value ends with its own element, never with a nested one.
727                        Ctx::Text => {
728                            if let Some(p) = st.pending.take() {
729                                self.finish_text(p, &mut st, pos);
730                            }
731                        }
732                        Ctx::Object => {
733                            if let Some(o) = st.object.take() {
734                                self.ensure_source(&mut st, &mut dataset);
735                                self.commit(o, &st, &mut dataset, pos);
736                                st.objects_read += 1;
737                            }
738                        }
739                        Ctx::Compound => self.close_compound(&mut st),
740                        Ctx::DiffSubject => st.diff_subject = None,
741                        _ => {}
742                    }
743                    ctx = stack.pop().unwrap_or(Ctx::Outside);
744                }
745
746                _ => {}
747            }
748            buf.clear();
749
750            // Reading only the header: stop as soon as it is complete.
751            if self.header_only && st.header.is_some() && ctx == Ctx::Body {
752                break;
753            }
754        }
755
756        if !st.saw_root {
757            return Err(Error::NotCimXml("no rdf:RDF root element found".to_owned()));
758        }
759
760        // A file without a header still occupies a slot, so that the slot a later file
761        // gets matches its position in `Dataset::headers`. `ensure_source` has normally
762        // claimed it already; this covers a document that declared no objects either.
763        if !st.header_registered
764            && let Some(ds) = dataset.as_mut()
765        {
766            ds.push_header(self.placeholder_header());
767        }
768
769        let mut header = st.header;
770        let mut difference = st.difference;
771        if let Some(d) = difference.as_mut()
772            && let Some(h) = header.clone()
773        {
774            d.header = h;
775        }
776        if let Some(h) = header.as_mut()
777            && h.source.is_none()
778        {
779            h.source = self.source.clone();
780        }
781        // A difference is not applied here — `Dataset::apply_difference` does that — but
782        // keeping it lets a model set containing change files be written back whole.
783        if let (Some(d), Some(ds)) = (difference.as_ref(), dataset.as_mut()) {
784            ds.push_difference(d.clone());
785        }
786
787        Ok(ReadOutcome {
788            header,
789            difference,
790            report: std::mem::take(&mut self.report),
791            objects_read: st.objects_read,
792        })
793    }
794
795    /// Report, once, that this document belongs to a different schema vintage.
796    ///
797    /// The namespaces are in the document, so a mismatch is knowable at the root — where it
798    /// is one error, rather than one "unknown class" warning per element and a model with
799    /// nothing in it.
800    fn check_vintage(&mut self, pos: u64) {
801        let declared: Vec<&str> = self.ns.values().map(String::as_str).collect();
802        // Comparative, not absolute: the header vocabulary is shared, so every vintage
803        // scores something on every CIM/XML document. What matters is whether another one
804        // scores higher.
805        let Some(actual) = Schema::detect(declared.iter().copied()) else {
806            return;
807        };
808        if std::ptr::eq(actual, self.schema) {
809            return;
810        }
811        self.diag(
812            Diagnostic::error(
813                Rule::WrongVintage,
814                format!(
815                    "this document is {} and is being read as {}; nothing in it will \
816                     resolve. Use `{}::SCHEMA`, or `reader::sniff` to detect it",
817                    actual.vintage, self.schema.vintage, actual.vintage
818                ),
819            ),
820            pos,
821        );
822    }
823
824    /// The header slot a document with no `md:FullModel` still gets.
825    ///
826    /// Named after the document it came from, and declaring the profile the caller assumed
827    /// where there is one: a file the caller has identified *is* a file of that profile,
828    /// and every export path asks the header which profiles it serves. Without this the
829    /// answer was "none", which made a headerless model export as an empty directory.
830    fn placeholder_header(&self) -> ModelHeader {
831        let mut h = ModelHeader::new(ModelKind::Full);
832        h.source = self.source.clone();
833        if let Some(p) = self.options.assume_profile {
834            h.profiles
835                .push(self.schema.profile(p).version_iri.to_owned());
836        }
837        h
838    }
839
840    /// Make sure this document owns a header slot before its first object is stored.
841    ///
842    /// Objects record the file they came from as they are committed, so the slot has to
843    /// exist by then: a document with no `md:FullModel` would otherwise leave its objects
844    /// belonging to no file, and nothing to export them back into.
845    fn ensure_source(&mut self, st: &mut State, dataset: &mut Option<&mut Dataset>) {
846        if st.header_registered || st.source.is_some() {
847            return;
848        }
849        st.header_registered = true;
850        if let Some(ds) = dataset.as_mut() {
851            let slot = ds.push_header(self.placeholder_header());
852            st.placeholder_slot = Some(slot);
853            st.source = Some(slot);
854        }
855    }
856
857    /// Register the just-parsed header with the dataset and adopt what it declares.
858    fn register_header(&mut self, st: &mut State, dataset: &mut Option<&mut Dataset>) {
859        let Some(h) = st.header.as_ref() else { return };
860        let declared = h
861            .profiles
862            .iter()
863            .filter_map(|iri| self.schema.profile_by_iri(iri))
864            .fold(0, |acc, p| acc | p.mask());
865        if declared != 0 {
866            st.profile_mask = declared;
867        }
868        // A document that names itself after its first object already has a slot; fill it
869        // in rather than describing the same file twice.
870        if let Some(slot) = st.placeholder_slot.take()
871            && let Some(ds) = dataset.as_mut()
872        {
873            let mut h = h.clone();
874            if h.source.is_none() {
875                h.source = self.source.clone();
876            }
877            ds.set_header(slot, h);
878            return;
879        }
880        if st.header_registered {
881            return;
882        }
883        st.header_registered = true;
884        if let Some(ds) = dataset.as_mut() {
885            let mut h = h.clone();
886            if h.source.is_none() {
887                h.source = self.source.clone();
888            }
889            // A caller who says which profile an undeclared file holds has said what the
890            // file *is*, so the header says so too. Without this the values are attributed
891            // and the file is still not reproducible as itself: every export path asks the
892            // header which profiles it serves, and this one would answer "none".
893            if h.profiles.is_empty()
894                && let Some(p) = self.options.assume_profile
895            {
896                h.profiles
897                    .push(self.schema.profile(p).version_iri.to_owned());
898            }
899            st.source = Some(ds.push_header(h));
900        }
901    }
902
903    /// Finish the innermost compound and attach it to whatever encloses it.
904    fn close_compound(&mut self, st: &mut State) {
905        let Some((attr, compound)) = st.compounds.pop() else {
906            return;
907        };
908        let value = Value::Compound(Box::new(compound));
909        let many = self.schema.attr(attr).mult.is_many();
910        match st.compounds.last_mut() {
911            Some((_, parent)) => {
912                if many {
913                    parent.push(attr, value)
914                } else {
915                    parent.set(attr, value)
916                }
917            }
918            None => {
919                if let Some(obj) = st.object.as_mut() {
920                    if many {
921                        obj.push_in(st.profile_mask, attr, value);
922                    } else {
923                        obj.set_in(st.profile_mask, attr, value);
924                    }
925                }
926            }
927        }
928    }
929
930    /// Store a finished object, reporting an identifier collision that is not a merge.
931    ///
932    /// Two files describing the same object is normal and is how profiles compose. Two
933    /// files giving the same identifier to *unrelated* classes is a defect, because one
934    /// of them will be silently absorbed into the other.
935    fn commit(
936        &mut self,
937        mut object: Object,
938        st: &State,
939        dataset: &mut Option<&mut Dataset>,
940        pos: u64,
941    ) {
942        object.mark_profile(st.profile_mask);
943        object.from_file = true;
944        object.shrink_for_load();
945        let Some(ds) = dataset.as_mut() else { return };
946
947        if let Some(existing) = ds.by_mrid(object.mrid()) {
948            let incoming = object.class();
949            let held = existing.class();
950            if !self.schema.is_a(incoming, held) && !self.schema.is_a(held, incoming) {
951                let d = Diagnostic::error(
952                    Rule::DuplicateMrid,
953                    format!(
954                        "identifier {} is used by both {} and {}, which are unrelated classes",
955                        object.mrid().canonical(),
956                        self.schema.class(held).name,
957                        self.schema.class(incoming).name
958                    ),
959                )
960                .with_class(self.schema.class(incoming).name)
961                .with_object(object.mrid().clone());
962                self.diag(d, pos);
963            }
964        }
965        // Re-borrow: `by_mrid` above held an immutable borrow.
966        if let Some(ds) = dataset.as_mut() {
967            let id = ds.insert(object);
968            if let Some(source) = st.source {
969                ds.record_source(source, id);
970            }
971        }
972    }
973
974    /// Handle an opening (or self-closing) element. Returns the context to enter.
975    fn on_open(
976        &mut self,
977        e: &BytesStart<'_>,
978        self_closing: bool,
979        ctx: Ctx,
980        st: &mut State,
981        pos: u64,
982    ) -> Result<Ctx> {
983        let qname = e.name();
984        let qname = qname.as_ref();
985
986        // The root element carries every namespace binding used in the document — but XML
987        // permits them anywhere, so a declaration further down is picked up too rather
988        // than leaving everything below it unresolvable. Scanning the element's own bytes
989        // for `xmlns` first keeps that off the hot path: instance documents declare
990        // nothing after the root.
991        if !st.saw_root || declares_namespace(e) {
992            self.collect_namespaces(e)?;
993        }
994        if !st.saw_root {
995            if let Some((ns, local)) = self.expand(qname)
996                && ns == RDF_NS
997                && local == "RDF"
998            {
999                st.saw_root = true;
1000                self.check_vintage(pos);
1001                return Ok(Ctx::Body);
1002            }
1003            // Some producers put the namespaces on a wrapper; keep looking.
1004            return Ok(ctx);
1005        }
1006
1007        match ctx {
1008            Ctx::Body => self.open_in_body(e, qname, st, pos),
1009            Ctx::Object => {
1010                let Some(obj) = st.object.as_ref() else {
1011                    return Ok(Ctx::Skip);
1012                };
1013                // Borrowed, not cloned: this runs once per property element, and the
1014                // identifier is only needed to label a diagnostic.
1015                let (class, mrid) = (obj.class(), obj.mrid());
1016                match self.property(e, self_closing, class, mrid, pos)? {
1017                    Prop::Value(attr, value) => {
1018                        let obj = st.object.as_mut().expect("object present");
1019                        if self.schema.attr(attr).mult.is_many() {
1020                            obj.push_in(st.profile_mask, attr, value);
1021                        } else {
1022                            obj.set_in(st.profile_mask, attr, value);
1023                        }
1024                        Ok(Ctx::Skip)
1025                    }
1026                    Prop::Enter(attr, class) => {
1027                        st.compounds.push((attr, Compound::new(class)));
1028                        Ok(Ctx::Compound)
1029                    }
1030                    Prop::Text(attr) => {
1031                        st.pending = Some(PendingText {
1032                            target: TextTarget::Attr(attr),
1033                            text: String::new(),
1034                        });
1035                        Ok(Ctx::Text)
1036                    }
1037                    Prop::Skip => Ok(Ctx::Skip),
1038                }
1039            }
1040            Ctx::Compound => {
1041                let Some((_, top)) = st.compounds.last() else {
1042                    return Ok(Ctx::Skip);
1043                };
1044                let class = top.class();
1045                let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1046                match self.property(e, self_closing, class, mrid, pos)? {
1047                    Prop::Value(attr, value) => {
1048                        let (_, top) = st.compounds.last_mut().expect("compound present");
1049                        if self.schema.attr(attr).mult.is_many() {
1050                            top.push(attr, value);
1051                        } else {
1052                            top.set(attr, value);
1053                        }
1054                        Ok(Ctx::Skip)
1055                    }
1056                    Prop::Enter(attr, class) => {
1057                        st.compounds.push((attr, Compound::new(class)));
1058                        Ok(Ctx::Compound)
1059                    }
1060                    Prop::Text(attr) => {
1061                        st.pending = Some(PendingText {
1062                            target: TextTarget::Compound(attr),
1063                            text: String::new(),
1064                        });
1065                        Ok(Ctx::Text)
1066                    }
1067                    Prop::Skip => Ok(Ctx::Skip),
1068                }
1069            }
1070            Ctx::Header => self.open_in_header(e, qname, self_closing, st),
1071            Ctx::DiffSet => {
1072                // Each statement group names its subject, either with a bare
1073                // `rdf:Description` or with the class element itself. The latter carries
1074                // real information: a difference may reclassify an object.
1075                let about = self.attr(e, RDF_NS, "about")?;
1076                let defines = about.is_none();
1077                if let Some(raw) = about.or(self.attr(e, RDF_NS, "ID")?) {
1078                    let class = self.expand(qname).and_then(|(ns, local)| {
1079                        (!(ns == RDF_NS && local == "Description")).then(|| QualifiedName {
1080                            ns: ns.to_owned(),
1081                            local: local.to_owned(),
1082                        })
1083                    });
1084                    st.diff_subject = Some((Mrid::parse(raw.trim()), class, defines));
1085                    return Ok(Ctx::DiffSubject);
1086                }
1087                Ok(Ctx::Skip)
1088            }
1089            Ctx::DiffSubject => {
1090                let Some((ns, local)) = self
1091                    .expand(qname)
1092                    .map(|(n, l)| (n.to_owned(), l.to_owned()))
1093                else {
1094                    return Ok(Ctx::Skip);
1095                };
1096                let Some((subject, class, defines_subject)) = st.diff_subject.clone() else {
1097                    return Ok(Ctx::Skip);
1098                };
1099                if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1100                    let res = res.trim().to_owned();
1101                    push_statement(
1102                        &mut st.difference,
1103                        st.diff_set,
1104                        Statement {
1105                            subject,
1106                            class,
1107                            defines_subject,
1108                            predicate_ns: ns,
1109                            predicate: local,
1110                            value: StatementValue::Resource(res),
1111                        },
1112                    );
1113                    return Ok(Ctx::Skip);
1114                }
1115                if self_closing {
1116                    return Ok(Ctx::Skip);
1117                }
1118                st.pending = Some(PendingText {
1119                    target: TextTarget::Statement {
1120                        subject,
1121                        class,
1122                        defines_subject,
1123                        ns,
1124                        local,
1125                        set: st.diff_set,
1126                    },
1127                    text: String::new(),
1128                });
1129                Ok(Ctx::Text)
1130            }
1131            // Markup inside a value. IEC 61970-552 property elements hold text, a single
1132            // `rdf:resource`, or an inline compound — never mixed content — so this is a
1133            // defect in the document. The nested element is skipped with its content
1134            // rather than silently donating its text to the value around it.
1135            Ctx::Text => {
1136                let name = qname.to_owned();
1137                self.diag(
1138                    Diagnostic::warning(
1139                        Rule::Structure,
1140                        format!("unexpected element <{name}> inside a value; skipped"),
1141                    ),
1142                    pos,
1143                );
1144                Ok(Ctx::Skip)
1145            }
1146            Ctx::Skip | Ctx::Outside => Ok(Ctx::Skip),
1147        }
1148    }
1149
1150    /// An element directly inside `rdf:RDF`: a header or an object.
1151    fn open_in_body(
1152        &mut self,
1153        e: &BytesStart<'_>,
1154        qname: &str,
1155        st: &mut State,
1156        pos: u64,
1157    ) -> Result<Ctx> {
1158        if let Some((ns, local)) = self.expand(qname)
1159            && ((ns == MD_NS && local == "FullModel")
1160                || (ns == DM_NS && local == "DifferenceModel"))
1161        {
1162            let kind = if ns == DM_NS {
1163                ModelKind::Difference
1164            } else {
1165                ModelKind::Full
1166            };
1167            let mut h = ModelHeader::new(kind);
1168            h.id = self
1169                .attr(e, RDF_NS, "about")?
1170                .map(|s| Mrid::parse(s.trim()));
1171            h.source = self.source.clone();
1172            st.header = Some(h);
1173            if kind == ModelKind::Difference {
1174                st.difference = Some(DifferenceModel::default());
1175            }
1176            return Ok(Ctx::Header);
1177        }
1178
1179        if self.header_only {
1180            return Ok(Ctx::Skip);
1181        }
1182
1183        match self.resolve(qname) {
1184            Resolved::Class(class) => {
1185                let def = self.schema.class(class);
1186                // A compound has no identity, so it cannot stand on its own; it only ever
1187                // appears inside the property that holds it.
1188                if def.compound {
1189                    self.diag(
1190                        Diagnostic::error(
1191                            Rule::Structure,
1192                            format!(
1193                                "compound type {} has no identity and cannot be a top-level object",
1194                                def.name
1195                            ),
1196                        )
1197                        .with_class(def.name),
1198                        pos,
1199                    );
1200                    return Ok(Ctx::Skip);
1201                }
1202                if !def.concrete {
1203                    self.diag(
1204                        Diagnostic::error(
1205                            Rule::AbstractInstantiated,
1206                            format!("abstract class {} instantiated", def.name),
1207                        )
1208                        .with_class(def.name),
1209                        pos,
1210                    );
1211                }
1212                if self.options.report_deprecated && def.deprecated {
1213                    self.diag(
1214                        Diagnostic::info(
1215                            Rule::Deprecated,
1216                            format!("deprecated class {}", def.name),
1217                        )
1218                        .with_class(def.name),
1219                        pos,
1220                    );
1221                }
1222                let mrid = self.object_identity(e, def.name, pos)?;
1223                let mut o = Object::new(class, mrid);
1224                o.mark_profile(st.profile_mask);
1225                st.object = Some(o);
1226                Ok(Ctx::Object)
1227            }
1228            Resolved::Attr(_) | Resolved::Unknown => {
1229                let name = qname.to_owned();
1230                if self.options.strictness == Strictness::Strict {
1231                    return Err(Error::NotCimXml(format!("unknown class element <{name}>")));
1232                }
1233                self.diag(
1234                    Diagnostic::warning(
1235                        Rule::UnknownClass,
1236                        format!("unknown class element <{name}>, skipped"),
1237                    ),
1238                    pos,
1239                );
1240                Ok(Ctx::Skip)
1241            }
1242        }
1243    }
1244
1245    /// An element inside `md:FullModel` or `dm:DifferenceModel`.
1246    fn open_in_header(
1247        &mut self,
1248        e: &BytesStart<'_>,
1249        qname: &str,
1250        self_closing: bool,
1251        st: &mut State,
1252    ) -> Result<Ctx> {
1253        let Some((ns, local)) = self
1254            .expand(qname)
1255            .map(|(n, l)| (n.to_owned(), l.to_owned()))
1256        else {
1257            return Ok(Ctx::Skip);
1258        };
1259        // Difference statement sets live inside the header element.
1260        let set = match (ns == DM_NS, local.as_str()) {
1261            (true, "forwardDifferences") => Some(DiffSet::Forward),
1262            (true, "reverseDifferences") => Some(DiffSet::Reverse),
1263            // Read like the other two. It used to fall through to the header-text path,
1264            // whose nested markup is skipped — so a change set's preconditions were lost on
1265            // the way in and absent on the way out, without a word.
1266            (true, "preconditions") => Some(DiffSet::Preconditions),
1267            _ => None,
1268        };
1269        if let Some(set) = set {
1270            st.diff_set = set;
1271            if st.difference.is_none() {
1272                st.difference = Some(DifferenceModel::default());
1273            }
1274            return Ok(Ctx::DiffSet);
1275        }
1276        let prefix = prefix_of(qname);
1277        if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1278            let res = res.trim().to_owned();
1279            apply_header_resource(&mut st.header, &prefix, &ns, &local, res);
1280            return Ok(Ctx::Skip);
1281        }
1282        if self_closing {
1283            return Ok(Ctx::Skip);
1284        }
1285        st.pending = Some(PendingText {
1286            target: TextTarget::Header { prefix, ns, local },
1287            text: String::new(),
1288        });
1289        Ok(Ctx::Text)
1290    }
1291
1292    /// Resolve a property element of `class` and decide what to do with it.
1293    fn property(
1294        &mut self,
1295        e: &BytesStart<'_>,
1296        self_closing: bool,
1297        class: ClassId,
1298        owner: &Mrid,
1299        pos: u64,
1300    ) -> Result<Prop> {
1301        let qname = e.name();
1302        let qname = qname.as_ref();
1303        let Resolved::Attr(attr) = self.resolve(qname) else {
1304            let name = qname.to_owned();
1305            if self.options.strictness == Strictness::Strict {
1306                return Err(Error::NotCimXml(format!(
1307                    "unknown property element <{name}>"
1308                )));
1309            }
1310            self.diag(
1311                Diagnostic::warning(
1312                    Rule::UnknownAttribute,
1313                    format!("unknown property <{name}>, skipped"),
1314                )
1315                .with_object(owner.clone()),
1316                pos,
1317            );
1318            return Ok(Prop::Skip);
1319        };
1320
1321        let def = self.schema.attr(attr);
1322        // Guard against a property being applied to the wrong class.
1323        if !self.schema.is_a(class, def.owner) {
1324            self.diag(
1325                Diagnostic::warning(
1326                    Rule::UnknownAttribute,
1327                    format!(
1328                        "{} does not apply to class {}",
1329                        def.name,
1330                        self.schema.class(class).name
1331                    ),
1332                )
1333                .with_attribute(def.name)
1334                .with_object(owner.clone()),
1335                pos,
1336            );
1337            return Ok(Prop::Skip);
1338        }
1339        if self.options.report_deprecated && def.deprecated {
1340            self.diag(
1341                Diagnostic::info(
1342                    Rule::Deprecated,
1343                    format!("deprecated attribute {}", def.name),
1344                )
1345                .with_attribute(def.name),
1346                pos,
1347            );
1348        }
1349
1350        // A compound is written inline, so it is recognised from the schema rather than
1351        // from `rdf:parseType`: producers do omit the attribute, and the nested content
1352        // is unambiguous either way.
1353        if let AttrKind::Compound(target) = def.kind {
1354            if self.attr(e, RDF_NS, "resource")?.is_some() {
1355                self.diag(
1356                    Diagnostic::error(
1357                        Rule::InvalidValue,
1358                        format!(
1359                            "{} holds a compound, which has no identity, but is written as \
1360                             a reference",
1361                            def.name
1362                        ),
1363                    )
1364                    .with_attribute(def.name)
1365                    .with_object(owner.clone()),
1366                    pos,
1367                );
1368                return Ok(Prop::Skip);
1369            }
1370            return Ok(Prop::Enter(attr, target));
1371        }
1372
1373        if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1374            let res = res.trim();
1375            return Ok(match self.resource_value(attr, res, owner, pos) {
1376                Some(v) => Prop::Value(attr, v),
1377                None => Prop::Skip,
1378            });
1379        }
1380        if self_closing {
1381            // An empty element means an empty string value.
1382            if matches!(def.kind, AttrKind::Primitive(Primitive::String)) {
1383                return Ok(Prop::Value(attr, Value::Text("".into())));
1384            }
1385            return Ok(Prop::Skip);
1386        }
1387        Ok(Prop::Text(attr))
1388    }
1389
1390    /// Determine an object's mRID from `rdf:ID` or `rdf:about`.
1391    fn object_identity(
1392        &mut self,
1393        e: &BytesStart<'_>,
1394        class: &'static str,
1395        pos: u64,
1396    ) -> Result<Mrid> {
1397        for (name, raw) in [
1398            ("rdf:ID", self.attr(e, RDF_NS, "ID")?),
1399            ("rdf:about", self.attr(e, RDF_NS, "about")?),
1400        ] {
1401            let Some(raw) = raw else { continue };
1402            let raw = raw.trim();
1403            let m = Mrid::parse(raw);
1404            // `rdf:ID` is an XML `NCName`, which cannot begin with a digit — the whole
1405            // reason 61970-552 writes an underscore before the UUID. A file omitting it is
1406            // invalid RDF/XML, and parsing strips that decoration, so the value survives
1407            // and nothing downstream can tell. Writing it back conforming is the only
1408            // option (D18), which makes it a repair.
1409            let unwritable_id = name == "rdf:ID" && !crate::xml::is_ncname(raw);
1410            // The form report is opt-in, because published files deviate constantly and
1411            // harmlessly. A repair is not that: the output differs from the input, so it is
1412            // reported whether or not the caller asked about form (D56).
1413            if unwritable_id || (self.options.report_non_conforming_mrids && !m.is_conforming()) {
1414                let complaint = if unwritable_id {
1415                    format!(
1416                        "is not an XML NCName and so cannot be written back as one; repaired to {:?}",
1417                        m.to_rdf_id()
1418                    )
1419                } else if m.is_uuid() {
1420                    // A UUID written without hyphens: the value is recoverable and the
1421                    // reference joins, so this is about the file's form, not its meaning.
1422                    format!(
1423                        "is a UUID written without hyphens; IEC 61970-552 requires {:?}",
1424                        m.canonical()
1425                    )
1426                } else {
1427                    "is not a UUID as IEC 61970-552 requires".to_owned()
1428                };
1429                self.diag(
1430                    Diagnostic::warning(
1431                        Rule::NonConformingMrid,
1432                        format!("{name} {raw:?} {complaint}"),
1433                    )
1434                    .with_class(class),
1435                    pos,
1436                );
1437            }
1438            return Ok(m);
1439        }
1440        // An object with no identifier at all still has to be *an* object. Giving them all
1441        // the same empty identifier merged them into one — the second overwriting the
1442        // first's values under a class it may not even share — so the document position
1443        // stands in, which is unique within a file and distinct from any UUID. The value is
1444        // deliberately opaque rather than a synthesized UUID: inventing a conforming
1445        // identifier would hide the defect from every later check.
1446        let placeholder = match &self.source {
1447            Some(src) => format!("no-identifier-{src}-{pos}"),
1448            None => format!("no-identifier-{pos}"),
1449        };
1450        self.diag(
1451            Diagnostic::error(
1452                Rule::Structure,
1453                format!("<{class}> has neither rdf:ID nor rdf:about; kept as {placeholder:?}"),
1454            )
1455            .with_class(class),
1456            pos,
1457        );
1458        Ok(Mrid::parse(&placeholder))
1459    }
1460
1461    /// Turn an `rdf:resource` IRI into a value for `attr`.
1462    fn resource_value(&mut self, attr: AttrId, res: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1463        let def = self.schema.attr(attr);
1464        let AttrKind::Enumeration(_) = def.kind else {
1465            return Some(Value::Reference(Mrid::parse(res)));
1466        };
1467        // Enumeration literals are absolute IRIs: `<ns>#Enum.literal`.
1468        let Some((ns, local)) = res.rsplit_once('#') else {
1469            self.diag(
1470                Diagnostic::error(
1471                    Rule::InvalidValue,
1472                    format!("enumeration value {res:?} is not an IRI"),
1473                )
1474                .with_attribute(def.name),
1475                pos,
1476            );
1477            return None;
1478        };
1479        if let Some(v) = self.schema.find_enum_value(&format!("{ns}#"), local) {
1480            return Some(Value::Enum(v));
1481        }
1482        // The qualified name is unambiguous even when the namespace is wrong, so recover
1483        // the value and report the mismatch rather than drop data.
1484        match self.schema.find_enum_value_any_ns(local) {
1485            Some(v) => {
1486                let correct = self.schema.namespace(self.schema.enum_value(v).ns).iri;
1487                self.diag(
1488                    Diagnostic::warning(
1489                        Rule::InvalidValue,
1490                        format!(
1491                            "enumeration literal {local} is written in namespace {ns}# but is \
1492                             declared in {correct}; value recovered"
1493                        ),
1494                    )
1495                    .with_attribute(def.name)
1496                    .with_object(owner.clone()),
1497                    pos,
1498                );
1499                Some(Value::Enum(v))
1500            }
1501            None => {
1502                self.diag(
1503                    Diagnostic::error(
1504                        Rule::InvalidValue,
1505                        format!("unknown enumeration literal {res:?}"),
1506                    )
1507                    .with_attribute(def.name)
1508                    .with_object(owner.clone()),
1509                    pos,
1510                );
1511                None
1512            }
1513        }
1514    }
1515
1516    /// Commit an accumulated text value.
1517    fn finish_text(&mut self, mut p: PendingText, st: &mut State, pos: u64) {
1518        // A character XML 1.0 cannot represent has no escaped form, so a value carrying
1519        // one cannot be written back at all: the document this crate would produce is
1520        // refused by every conforming parser at that byte. `quick-xml` does not enforce
1521        // the `Char` production in either direction, so this is where a character arriving
1522        // from a mis-encoded or corrupted source file is caught. It is dropped — the only
1523        // alternative to unreadable output — and the loss is reported rather than silent.
1524        if let Some((offset, c)) = crate::xml::find_illegal(&p.text) {
1525            self.diag(
1526                Diagnostic::warning(
1527                    Rule::IllegalXmlCharacter,
1528                    format!(
1529                        "value holds {}, which XML 1.0 cannot represent in any form; \
1530                         removed (first at byte {offset} of the value)",
1531                        crate::xml::describe_char(c)
1532                    ),
1533                ),
1534                pos,
1535            );
1536            p.text = crate::xml::strip_illegal(&p.text).into_owned();
1537        }
1538        match p.target {
1539            TextTarget::Attr(attr) => {
1540                let Some(obj) = st.object.as_ref() else {
1541                    return;
1542                };
1543                if let Some(v) = self.parse_text(attr, &p.text, obj.mrid(), pos) {
1544                    let obj = st.object.as_mut().expect("object present");
1545                    if self.schema.attr(attr).mult.is_many() {
1546                        obj.push_in(st.profile_mask, attr, v);
1547                    } else {
1548                        obj.set_in(st.profile_mask, attr, v);
1549                    }
1550                }
1551            }
1552            TextTarget::Compound(attr) => {
1553                let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1554                if let Some(v) = self.parse_text(attr, &p.text, mrid, pos)
1555                    && let Some((_, top)) = st.compounds.last_mut()
1556                {
1557                    if self.schema.attr(attr).mult.is_many() {
1558                        top.push(attr, v);
1559                    } else {
1560                        top.set(attr, v);
1561                    }
1562                }
1563            }
1564            TextTarget::Header { prefix, ns, local } => {
1565                apply_header_text(&mut st.header, &prefix, &ns, &local, p.text);
1566            }
1567            TextTarget::Statement {
1568                subject,
1569                class,
1570                defines_subject,
1571                ns,
1572                local,
1573                set,
1574            } => push_statement(
1575                &mut st.difference,
1576                set,
1577                Statement {
1578                    subject,
1579                    class,
1580                    defines_subject,
1581                    predicate_ns: ns,
1582                    predicate: local,
1583                    value: StatementValue::Literal(p.text),
1584                },
1585            ),
1586        }
1587    }
1588
1589    fn parse_text(&mut self, attr: AttrId, text: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1590        let def = self.schema.attr(attr);
1591        let prim = match def.kind {
1592            AttrKind::Primitive(prim) => prim,
1593            AttrKind::Datatype(dt) => self.schema.datatype(dt).value,
1594            // An enumeration, association or compound written as text is malformed; keep
1595            // the text so nothing is silently lost.
1596            AttrKind::Enumeration(_) | AttrKind::Association { .. } | AttrKind::Compound(_) => {
1597                Primitive::String
1598            }
1599        };
1600        match Value::parse_primitive(prim, text) {
1601            Ok(v) => Some(v),
1602            Err(e) => {
1603                let name = def.name;
1604                self.diag(
1605                    Diagnostic::error(Rule::InvalidValue, e.to_string())
1606                        .with_attribute(name)
1607                        .with_object(owner.clone()),
1608                    pos,
1609                );
1610                None
1611            }
1612        }
1613    }
1614
1615    /// Record the namespace bindings declared on an element.
1616    ///
1617    /// Bindings are kept in one flat map rather than a scope stack: CIM/XML declares
1618    /// everything on `rdf:RDF`, and a document that *rebinds* a prefix deeper down — as
1619    /// opposed to adding one — is beyond what IEC 61970-552 describes. Adding a binding
1620    /// found deeper is strictly better than leaving every element below it unresolvable.
1621    fn collect_namespaces(&mut self, e: &BytesStart<'_>) -> Result<()> {
1622        for attr in e.attributes().with_checks(false) {
1623            let attr = attr?;
1624            let key = attr.key.as_ref();
1625            let value = self.attr_value(&attr)?.into_owned();
1626            if let Some(prefix) = key.strip_prefix("xmlns:") {
1627                self.ns.insert(prefix.as_bytes().to_vec(), value);
1628            } else if key == "xmlns" {
1629                self.ns.insert(Vec::new(), value);
1630            }
1631        }
1632        Ok(())
1633    }
1634
1635    /// Read an attribute by namespace and local name, expanding its prefix.
1636    ///
1637    /// Borrows from the element where XML escaping allows, so the common case — one
1638    /// `rdf:ID` or `rdf:resource` per element, repeated hundreds of thousands of times —
1639    /// does not allocate.
1640    fn attr<'e>(
1641        &self,
1642        e: &'e BytesStart<'_>,
1643        ns: &str,
1644        local: &str,
1645    ) -> Result<Option<Cow<'e, str>>> {
1646        for attr in e.attributes().with_checks(false) {
1647            let attr = attr?;
1648            let key = attr.key.as_ref();
1649            let Some((prefix, name)) = key.split_once(':') else {
1650                continue;
1651            };
1652            if name != local {
1653                continue;
1654            }
1655            if self.ns.get(prefix.as_bytes()).map(String::as_str) != Some(ns) {
1656                continue;
1657            }
1658            return Ok(Some(self.attr_value(&attr)?));
1659        }
1660        Ok(None)
1661    }
1662}
1663
1664/// A parser failure as this crate's error: a failure to *read* stays an I/O error — the
1665/// input stopped, or an archive refused to hand out more than it declared — rather than
1666/// being reported as malformed XML, which it is not.
1667fn parse_error(e: quick_xml::Error) -> Error {
1668    match e {
1669        quick_xml::Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
1670        other => Error::Xml(other.to_string()),
1671    }
1672}
1673
1674/// The diagnostic for an entity reference this reader keeps as text.
1675fn undefined_entity(name: &str) -> Diagnostic {
1676    Diagnostic::warning(
1677        Rule::InvalidValue,
1678        format!(
1679            "undefined entity &{name}; kept as text: CIM/XML documents declare no DTD, so \
1680             only the five predefined entities and character references are expanded"
1681        ),
1682    )
1683}
1684
1685/// `raw` with every `&name;` that is neither predefined nor a character reference turned
1686/// into `&amp;name;`, so that normalizing it keeps the reference as text; and the names.
1687fn escape_undefined_entities(raw: &str) -> (String, Vec<String>) {
1688    let mut out = String::with_capacity(raw.len() + 8);
1689    let mut names = Vec::new();
1690    let mut rest = raw;
1691    while let Some(at) = rest.find('&') {
1692        out.push_str(&rest[..at]);
1693        let after = &rest[at + 1..];
1694        let name = after.split_once(';').map(|(n, _)| n);
1695        match name {
1696            Some(n)
1697                if !n.starts_with('#')
1698                    && quick_xml::escape::resolve_predefined_entity(n).is_none() =>
1699            {
1700                out.push_str("&amp;");
1701                names.push(n.to_owned());
1702            }
1703            _ => out.push('&'),
1704        }
1705        rest = after;
1706    }
1707    out.push_str(rest);
1708    (out, names)
1709}
1710
1711/// Whether an element carries an `xmlns` declaration, without parsing its attributes.
1712fn declares_namespace(e: &BytesStart<'_>) -> bool {
1713    e.as_ref().contains("xmlns")
1714}
1715
1716/// The prefix an element was written with, e.g. `md` for `md:Model.created`.
1717fn prefix_of(qname: &str) -> String {
1718    match qname.split_once(':') {
1719        Some((prefix, _)) => prefix.to_owned(),
1720        None => String::new(),
1721    }
1722}
1723
1724/// A header property given as `rdf:resource`.
1725fn apply_header_resource(
1726    header: &mut Option<ModelHeader>,
1727    prefix: &str,
1728    ns: &str,
1729    local: &str,
1730    res: String,
1731) {
1732    let Some(h) = header.as_mut() else { return };
1733    match (ns, local) {
1734        (MD_NS, "Model.DependentOn") => h.dependent_on.push(Mrid::parse(&res)),
1735        (MD_NS, "Model.Supersedes") => h.supersedes.push(Mrid::parse(&res)),
1736        (MD_NS, "Model.profile") => h.profiles.push(res),
1737        _ => h
1738            .extra
1739            .push(HeaderProperty::resource(prefix, ns, local, res)),
1740    }
1741}
1742
1743/// A header property given as element text.
1744fn apply_header_text(
1745    header: &mut Option<ModelHeader>,
1746    prefix: &str,
1747    ns: &str,
1748    local: &str,
1749    text: String,
1750) {
1751    let Some(h) = header.as_mut() else { return };
1752    if ns != MD_NS {
1753        h.extra.push(HeaderProperty::text(prefix, ns, local, text));
1754        return;
1755    }
1756    match local {
1757        "Model.created" => h.created = Some(text),
1758        "Model.scenarioTime" => h.scenario_time = Some(text),
1759        "Model.description" => h.description = Some(text),
1760        "Model.version" => h.version = Some(text),
1761        "Model.modelingAuthoritySet" => h.modeling_authority_set = Some(text),
1762        "Model.profile" => h.profiles.push(text),
1763        "Model.DependentOn" => h.dependent_on.push(Mrid::parse(&text)),
1764        "Model.Supersedes" => h.supersedes.push(Mrid::parse(&text)),
1765        _ => h.extra.push(HeaderProperty::text(prefix, ns, local, text)),
1766    }
1767}
1768
1769/// The three statement sets of a `dm:DifferenceModel`.
1770#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1771enum DiffSet {
1772    Preconditions,
1773    #[default]
1774    Reverse,
1775    Forward,
1776}
1777
1778fn push_statement(difference: &mut Option<DifferenceModel>, set: DiffSet, s: Statement) {
1779    let d = difference.get_or_insert_with(DifferenceModel::default);
1780    match set {
1781        DiffSet::Preconditions => d.preconditions.push(s),
1782        DiffSet::Reverse => d.reverse.push(s),
1783        DiffSet::Forward => d.forward.push(s),
1784    }
1785}
1786
1787struct PendingText {
1788    target: TextTarget,
1789    text: String,
1790}
1791
1792enum TextTarget {
1793    /// An attribute of the object under construction.
1794    Attr(AttrId),
1795    /// A field of the innermost compound under construction.
1796    Compound(AttrId),
1797    /// A header property, by prefix, namespace and local name.
1798    Header {
1799        prefix: String,
1800        ns: String,
1801        local: String,
1802    },
1803    /// A difference-model statement.
1804    Statement {
1805        subject: Mrid,
1806        class: Option<QualifiedName>,
1807        defines_subject: bool,
1808        ns: String,
1809        local: String,
1810        set: DiffSet,
1811    },
1812}