Skip to main content

cim_kit/
reader.rs

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