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