1use 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
28static UNKNOWN_MRID: Mrid = Mrid::nil();
30
31#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
33pub enum Strictness {
34 #[default]
38 Lenient,
39 Strict,
41}
42
43#[derive(Clone, Debug)]
45pub struct ReadOptions {
46 pub strictness: Strictness,
47 pub assume_profile: Option<ProfileId>,
49 pub report_deprecated: bool,
51 pub report_non_conforming_mrids: bool,
53 pub max_diagnostics: usize,
58 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 pub const DEFAULT_MAX_DIAGNOSTICS: usize = 10_000;
84
85 pub const DEFAULT_MAX_INPUT_BYTES: u64 = 2 << 30;
90
91 pub fn lenient() -> ReadOptions {
93 ReadOptions::default()
94 }
95
96 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 pub fn with_max_diagnostics(mut self, max: usize) -> Self {
113 self.max_diagnostics = max;
114 self
115 }
116
117 pub fn with_max_input_bytes(mut self, max: u64) -> Self {
119 self.max_input_bytes = max;
120 self
121 }
122}
123
124#[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 pub(crate) fn meter<R: BufRead>(&self, input: R) -> Metered<'_, R> {
146 Metered {
147 inner: input,
148 used: self.used.get(),
149 limit: if self.limit == 0 {
151 u64::MAX
152 } else {
153 self.limit
154 },
155 budget: self,
156 }
157 }
158
159 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
179pub(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 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
231const SNIFF_PREFIX: u64 = 1 << 20;
233
234#[derive(Debug)]
236pub struct ReadOutcome {
237 pub header: Option<ModelHeader>,
238 pub difference: Option<DifferenceModel>,
240 pub report: Report,
241 pub objects_read: usize,
243}
244
245pub 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
256pub(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
270pub 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
285pub 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 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 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
338pub 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#[derive(Clone, Copy)]
357enum Resolved {
358 Class(ClassId),
359 Attr(AttrId),
360 Unknown,
362}
363
364#[derive(Clone, Copy, PartialEq, Eq, Debug)]
366enum Ctx {
367 Outside,
369 Body,
371 Header,
373 Object,
375 Compound,
377 DiffSet,
379 DiffSubject,
381 Text,
386 Skip,
388}
389
390enum Prop {
392 Value(AttrId, Value),
394 Enter(AttrId, ClassId),
396 Text(AttrId),
398 Skip,
400}
401
402#[derive(Default)]
404struct State {
405 saw_root: bool,
406 header: Option<ModelHeader>,
407 difference: Option<DifferenceModel>,
408 objects_read: usize,
409 object: Option<Object>,
411 compounds: Vec<(AttrId, Compound)>,
414 pending: Option<PendingText>,
416 profile_mask: ProfileMask,
418 diff_subject: Option<(Mrid, Option<QualifiedName>, bool)>,
421 diff_set: DiffSet,
423 source: Option<usize>,
426 header_registered: bool,
428 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 truncated: bool,
441 ns: HashMap<Vec<u8>, String>,
443 cache: HashMap<Vec<u8>, Resolved>,
446 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 #[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 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 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 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 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 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 Ctx::Compound => self.close_compound(&mut st),
618 Ctx::DiffSubject => st.diff_subject = None,
619 Ctx::Header => self.register_header(&mut st, &mut dataset),
622 _ => {}
623 }
624 ctx = saved;
625 }
626
627 Event::Text(t) if ctx == Ctx::Text => {
629 if let Some(p) = st.pending.as_mut() {
630 let text = t.xml10_content();
633 p.text.push_str(&text);
634 }
635 }
636
637 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 Ok(Some(c)) => p.text.push(c),
645 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 if ctx == Ctx::Header {
676 self.register_header(&mut st, &mut dataset);
677 }
678 match ctx {
679 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 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 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 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 fn check_vintage(&mut self, pos: u64) {
750 let declared: Vec<&str> = self.ns.values().map(String::as_str).collect();
751 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let unwritable_id = name == "rdf:ID" && !crate::xml::is_ncname(raw);
1329 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 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 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 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 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 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 fn finish_text(&mut self, mut p: PendingText, st: &mut State, pos: u64) {
1431 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 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 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 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
1569fn 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
1578fn 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
1589fn 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("&");
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
1615fn declares_namespace(e: &BytesStart<'_>) -> bool {
1617 e.as_ref().contains("xmlns")
1618}
1619
1620fn prefix_of(qname: &str) -> String {
1622 match qname.split_once(':') {
1623 Some((prefix, _)) => prefix.to_owned(),
1624 None => String::new(),
1625 }
1626}
1627
1628fn 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
1647fn 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#[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 Attr(AttrId),
1699 Compound(AttrId),
1701 Header {
1703 prefix: String,
1704 ns: String,
1705 local: String,
1706 },
1707 Statement {
1709 subject: Mrid,
1710 class: Option<QualifiedName>,
1711 defines_subject: bool,
1712 ns: String,
1713 local: String,
1714 set: DiffSet,
1715 },
1716}