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