1use std::borrow::Cow;
10use std::cell::{Cell, RefCell};
11use std::collections::HashMap;
12use std::io::{self, BufRead, Read};
13
14use quick_xml::Reader;
15use quick_xml::events::{BytesStart, Event};
16
17use crate::dataset::Dataset;
18use crate::error::{Diagnostic, Error, Report, Result, Rule};
19use crate::header::{
20 DM_NS, DifferenceModel, HeaderProperty, MD_NS, ModelHeader, ModelKind, QualifiedName,
21 Statement, StatementValue,
22};
23use crate::mrid::Mrid;
24use crate::object::{Compound, Object};
25use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileId, ProfileMask, Schema};
26use crate::value::Value;
27
28const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
29
30static UNKNOWN_MRID: Mrid = Mrid::nil();
32
33#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
35pub enum Strictness {
36 #[default]
41 Lenient,
42 Strict,
44}
45
46#[derive(Clone, Debug)]
48pub struct ReadOptions {
49 pub strictness: Strictness,
50 pub assume_profile: Option<ProfileId>,
52 pub report_deprecated: bool,
54 pub report_non_conforming_mrids: bool,
56 pub max_diagnostics: usize,
66 pub max_input_bytes: u64,
77}
78
79impl Default for ReadOptions {
80 fn default() -> Self {
81 ReadOptions {
82 strictness: Strictness::Lenient,
83 assume_profile: None,
84 report_deprecated: false,
85 report_non_conforming_mrids: false,
86 max_diagnostics: ReadOptions::DEFAULT_MAX_DIAGNOSTICS,
87 max_input_bytes: ReadOptions::DEFAULT_MAX_INPUT_BYTES,
88 }
89 }
90}
91
92impl ReadOptions {
93 pub const DEFAULT_MAX_DIAGNOSTICS: usize = 10_000;
95
96 pub const DEFAULT_MAX_INPUT_BYTES: u64 = 2 << 30;
103
104 pub fn lenient() -> ReadOptions {
106 ReadOptions::default()
107 }
108
109 pub fn strict() -> ReadOptions {
111 ReadOptions {
112 strictness: Strictness::Strict,
113 report_deprecated: true,
114 report_non_conforming_mrids: true,
115 ..ReadOptions::default()
116 }
117 }
118
119 pub fn with_profile(mut self, profile: ProfileId) -> Self {
120 self.assume_profile = Some(profile);
121 self
122 }
123
124 pub fn with_max_diagnostics(mut self, max: usize) -> Self {
126 self.max_diagnostics = max;
127 self
128 }
129
130 pub fn with_max_input_bytes(mut self, max: u64) -> Self {
132 self.max_input_bytes = max;
133 self
134 }
135}
136
137#[derive(Debug)]
143pub(crate) struct Budget {
144 limit: u64,
145 used: Cell<u64>,
146 tripped: Cell<bool>,
147}
148
149impl Budget {
150 pub(crate) fn new(options: &ReadOptions) -> Budget {
151 Budget {
152 limit: options.max_input_bytes,
153 used: Cell::new(0),
154 tripped: Cell::new(false),
155 }
156 }
157
158 pub(crate) fn meter<R: BufRead>(&self, input: R) -> Metered<'_, R> {
160 Metered {
161 inner: input,
162 used: self.used.get(),
163 limit: if self.limit == 0 {
165 u64::MAX
166 } else {
167 self.limit
168 },
169 budget: self,
170 }
171 }
172
173 pub(crate) fn check<T>(&self, result: Result<T>, source: Option<&str>) -> Result<T> {
180 match result {
181 Err(_) if self.tripped.get() => Err(Error::InputTooLarge {
182 limit: self.limit,
183 read: self.used.get(),
184 source: source.map(str::to_owned),
185 }),
186 other => other,
187 }
188 }
189
190 pub(crate) fn tripped(&self) -> bool {
191 self.tripped.get()
192 }
193}
194
195pub(crate) struct Metered<'a, R> {
201 inner: R,
202 used: u64,
203 limit: u64,
204 budget: &'a Budget,
205}
206
207impl<R> Drop for Metered<'_, R> {
208 fn drop(&mut self) {
209 self.budget.used.set(self.used);
210 }
211}
212
213impl<R: BufRead> Read for Metered<'_, R> {
214 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
215 let available = self.fill_buf()?;
216 let n = available.len().min(out.len());
217 out[..n].copy_from_slice(&available[..n]);
218 self.consume(n);
219 Ok(n)
220 }
221}
222
223impl<R: BufRead> BufRead for Metered<'_, R> {
224 #[inline]
225 fn fill_buf(&mut self) -> io::Result<&[u8]> {
226 if self.used > self.limit {
227 self.budget.tripped.set(true);
228 self.budget.used.set(self.used);
229 return Err(io::Error::other("input budget exceeded"));
230 }
231 let room = self.limit - self.used;
235 let buf = self.inner.fill_buf()?;
236 Ok(match usize::try_from(room) {
237 Ok(room) if room < buf.len() => &buf[..=room],
238 _ => buf,
239 })
240 }
241
242 #[inline]
243 fn consume(&mut self, amt: usize) {
244 self.used = self.used.saturating_add(amt as u64);
245 self.inner.consume(amt);
246 }
247}
248
249const SNIFF_PREFIX: u64 = 1 << 20;
251
252#[derive(Debug)]
254pub struct ReadOutcome {
255 pub header: Option<ModelHeader>,
256 pub difference: Option<DifferenceModel>,
258 pub report: Report,
259 pub objects_read: usize,
261}
262
263pub fn read_into<R: BufRead>(
265 dataset: &mut Dataset,
266 input: R,
267 source: Option<&str>,
268 options: &ReadOptions,
269) -> Result<ReadOutcome> {
270 let budget = Budget::new(options);
271 read_into_within(dataset, input, source, options, &budget)
272}
273
274pub(crate) fn read_into_within<R: BufRead>(
276 dataset: &mut Dataset,
277 input: R,
278 source: Option<&str>,
279 options: &ReadOptions,
280 budget: &Budget,
281) -> Result<ReadOutcome> {
282 let schema = dataset.schema();
283 let mut parser = Parser::new(schema, source, options, false);
284 let outcome = parser.run(budget.meter(input), Some(dataset));
285 budget.check(outcome, source)
286}
287
288pub fn read_header<R: BufRead>(
292 schema: &'static Schema,
293 input: R,
294 source: Option<&str>,
295) -> Result<Option<ModelHeader>> {
296 let options = ReadOptions::default();
297 let budget = Budget::new(&options);
298 let mut parser = Parser::new(schema, source, &options, true);
299 let outcome = parser.run(budget.meter(input), None);
300 Ok(budget.check(outcome, source)?.header)
301}
302
303pub fn sniff<R: BufRead>(input: R) -> Result<Option<&'static Schema>> {
321 let mut reader = Reader::from_reader(input.take(SNIFF_PREFIX));
322 reader.config_mut().check_end_names = false;
323 let mut buf = Vec::new();
324 loop {
325 let ev = match reader.read_event_into(&mut buf) {
326 Ok(ev) => ev,
327 Err(_) if reader.get_ref().limit() == 0 => return Ok(None),
330 Err(e) => return Err(Error::Xml(e.to_string())),
331 };
332 let e = match ev {
333 Event::Eof => return Ok(None),
334 Event::Start(e) | Event::Empty(e) => e,
335 _ => {
336 buf.clear();
337 continue;
338 }
339 };
340 let mut iris: Vec<String> = Vec::new();
343 for attr in e.attributes().with_checks(false) {
344 let attr = attr?;
345 let key = attr.key.as_ref();
346 if key == "xmlns" || key.starts_with("xmlns:") {
347 iris.push(attr.value.into_owned());
348 }
349 }
350 if let Some(schema) = Schema::detect(iris.iter().map(String::as_str)) {
351 return Ok(Some(schema));
352 }
353 buf.clear();
354 }
355}
356
357pub fn read_difference<R: BufRead>(
362 schema: &'static Schema,
363 input: R,
364 source: Option<&str>,
365 options: &ReadOptions,
366) -> Result<Option<DifferenceModel>> {
367 let budget = Budget::new(options);
368 let mut parser = Parser::new(schema, source, options, false);
369 let outcome = parser.run(budget.meter(input), None);
370 Ok(budget.check(outcome, source)?.difference)
371}
372
373#[derive(Clone, Copy)]
379enum Resolved {
380 Class(ClassId),
381 Attr(AttrId),
382 Unknown,
384}
385
386#[derive(Clone, Copy, PartialEq, Eq, Debug)]
388enum Ctx {
389 Outside,
391 Body,
393 Header,
395 Object,
397 Compound,
399 DiffSet,
401 DiffSubject,
403 Text,
411 Skip,
413}
414
415enum Prop {
417 Value(AttrId, Value),
419 Enter(AttrId, ClassId),
421 Text(AttrId),
423 Skip,
425}
426
427#[derive(Default)]
432struct State {
433 saw_root: bool,
434 header: Option<ModelHeader>,
435 difference: Option<DifferenceModel>,
436 objects_read: usize,
437 object: Option<Object>,
439 compounds: Vec<(AttrId, Compound)>,
442 pending: Option<PendingText>,
444 profile_mask: ProfileMask,
446 diff_subject: Option<(Mrid, Option<QualifiedName>, bool)>,
449 diff_set: DiffSet,
451 source: Option<usize>,
454 header_registered: bool,
456 placeholder_slot: Option<usize>,
459}
460
461struct Parser<'a> {
462 schema: &'static Schema,
463 options: &'a ReadOptions,
464 source: Option<String>,
465 report: Report,
466 header_only: bool,
467 truncated: bool,
469 ns: HashMap<Vec<u8>, String>,
471 cache: HashMap<Vec<u8>, Resolved>,
474 undefined_entities: RefCell<Vec<String>>,
478}
479
480impl<'a> Parser<'a> {
481 fn new(
482 schema: &'static Schema,
483 source: Option<&str>,
484 options: &'a ReadOptions,
485 header_only: bool,
486 ) -> Parser<'a> {
487 Parser {
488 schema,
489 options,
490 source: source.map(str::to_owned),
491 report: Report::default(),
492 header_only,
493 truncated: false,
494 ns: HashMap::new(),
495 cache: HashMap::new(),
496 undefined_entities: RefCell::new(Vec::new()),
497 }
498 }
499
500 #[inline]
505 fn flush_undefined_entities(&mut self, pos: u64) {
506 if !self.undefined_entities.get_mut().is_empty() {
507 self.report_undefined_entities(pos);
508 }
509 }
510
511 #[cold]
512 #[inline(never)]
513 fn report_undefined_entities(&mut self, pos: u64) {
514 let names = std::mem::take(self.undefined_entities.get_mut());
515 for name in names {
516 self.diag(undefined_entity(&name), pos);
517 }
518 }
519
520 fn attr_value<'e>(
527 &self,
528 attr: &quick_xml::events::attributes::Attribute<'e>,
529 ) -> Result<Cow<'e, str>> {
530 use quick_xml::escape::EscapeError;
531 match attr.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
532 Ok(v) => Ok(v),
533 Err(quick_xml::Error::Escape(EscapeError::UnrecognizedEntity(..))) => {
534 let (escaped, names) = escape_undefined_entities(&attr.value);
535 self.undefined_entities.borrow_mut().extend(names);
536 let rewritten = quick_xml::events::attributes::Attribute {
537 key: attr.key,
538 value: Cow::Owned(escaped),
539 };
540 let value = rewritten
541 .normalized_value(quick_xml::XmlVersion::Explicit1_0)
542 .map_err(|e| Error::Xml(e.to_string()))?;
543 Ok(Cow::Owned(value.into_owned()))
544 }
545 Err(e) => Err(Error::Xml(e.to_string())),
546 }
547 }
548
549 fn diag(&mut self, d: Diagnostic, pos: u64) {
550 let max = self.options.max_diagnostics;
551 if max != 0 && self.report.len() >= max {
552 if !self.truncated {
553 self.truncated = true;
554 self.report.push(Diagnostic::warning(
555 Rule::Structure,
556 format!(
557 "stopped recording after {max} diagnostics; reading continued \
558 (raise ReadOptions::max_diagnostics to see the rest)"
559 ),
560 ));
561 }
562 return;
563 }
564 let mut d = d.with_position(pos);
565 if let Some(s) = &self.source {
566 d = d.with_source(s.clone());
567 }
568 self.report.push(d);
569 }
570
571 fn expand<'q>(&self, qname: &'q str) -> Option<(&str, &'q str)> {
573 let (prefix, local) = match qname.split_once(':') {
574 Some((prefix, local)) => (prefix, local),
575 None => ("", qname),
576 };
577 let ns = self.ns.get(prefix.as_bytes())?;
578 Some((ns.as_str(), local))
579 }
580
581 fn resolve(&mut self, qname: &str) -> Resolved {
582 if let Some(r) = self.cache.get(qname.as_bytes()) {
583 return *r;
584 }
585 let resolved = match self.expand(qname) {
586 Some((ns, local)) if local.contains('.') => match self.schema.find_attr(ns, local) {
588 Some(a) => Resolved::Attr(a),
589 None => Resolved::Unknown,
590 },
591 Some((ns, local)) => match self.schema.find_class(ns, local) {
592 Some(c) => Resolved::Class(c),
593 None => Resolved::Unknown,
594 },
595 None => Resolved::Unknown,
596 };
597 self.cache.insert(qname.as_bytes().to_vec(), resolved);
598 resolved
599 }
600
601 fn run<R: BufRead>(
602 &mut self,
603 input: R,
604 mut dataset: Option<&mut Dataset>,
605 ) -> Result<ReadOutcome> {
606 let mut reader = Reader::from_reader(input);
607 reader.config_mut().trim_text(false);
608 reader.config_mut().expand_empty_elements = false;
609 reader.config_mut().check_end_names = false;
610
611 let mut buf = Vec::new();
612 let mut ctx = Ctx::Outside;
613 let mut stack: Vec<Ctx> = Vec::with_capacity(8);
614
615 let mut st = State {
616 profile_mask: self.options.assume_profile.map_or(0, |p| p.mask()),
617 ..Default::default()
618 };
619
620 loop {
621 let ev = reader.read_event_into(&mut buf).map_err(parse_error)?;
622 let pos = reader.buffer_position();
623
624 match ev {
625 Event::Eof => break,
626
627 Event::Start(e) => {
628 let next = self.on_open(&e, false, ctx, &mut st, pos)?;
629 self.flush_undefined_entities(pos);
630 stack.push(ctx);
631 ctx = next;
632 }
633
634 Event::Empty(e) => {
635 let saved = ctx;
638 let entered = self.on_open(&e, true, ctx, &mut st, pos)?;
639 self.flush_undefined_entities(pos);
640 match entered {
641 Ctx::Object => {
645 if let Some(o) = st.object.take() {
646 self.ensure_source(&mut st, &mut dataset);
647 self.commit(o, &st, &mut dataset, pos);
648 st.objects_read += 1;
649 }
650 }
651 Ctx::Compound => self.close_compound(&mut st),
653 Ctx::DiffSubject => st.diff_subject = None,
654 Ctx::Header => self.register_header(&mut st, &mut dataset),
659 _ => {}
660 }
661 ctx = saved;
662 }
663
664 Event::Text(t) if ctx == Ctx::Text => {
668 if let Some(p) = st.pending.as_mut() {
669 let text = t.xml10_content();
674 p.text.push_str(&text);
675 }
676 }
677
678 Event::GeneralRef(r) if ctx == Ctx::Text => {
683 let mut undefined = None;
684 if let Some(p) = st.pending.as_mut() {
685 match r.resolve_char_ref() {
686 Ok(Some(c)) => p.text.push(c),
688 Ok(None) | Err(_) => {
692 let name = r.as_ref();
693 match quick_xml::escape::resolve_predefined_entity(name) {
694 Some(text) => p.text.push_str(text),
695 None => {
696 p.text.push('&');
697 p.text.push_str(name);
698 p.text.push(';');
699 undefined = Some(name.to_owned());
700 }
701 }
702 }
703 }
704 }
705 if let Some(name) = undefined {
708 self.diag(undefined_entity(&name), pos);
709 }
710 }
711
712 Event::CData(t) if ctx == Ctx::Text => {
713 if let Some(p) = st.pending.as_mut() {
714 p.text.push_str(&t);
715 }
716 }
717
718 Event::End(_) => {
719 if ctx == Ctx::Header {
723 self.register_header(&mut st, &mut dataset);
724 }
725 match ctx {
726 Ctx::Text => {
728 if let Some(p) = st.pending.take() {
729 self.finish_text(p, &mut st, pos);
730 }
731 }
732 Ctx::Object => {
733 if let Some(o) = st.object.take() {
734 self.ensure_source(&mut st, &mut dataset);
735 self.commit(o, &st, &mut dataset, pos);
736 st.objects_read += 1;
737 }
738 }
739 Ctx::Compound => self.close_compound(&mut st),
740 Ctx::DiffSubject => st.diff_subject = None,
741 _ => {}
742 }
743 ctx = stack.pop().unwrap_or(Ctx::Outside);
744 }
745
746 _ => {}
747 }
748 buf.clear();
749
750 if self.header_only && st.header.is_some() && ctx == Ctx::Body {
752 break;
753 }
754 }
755
756 if !st.saw_root {
757 return Err(Error::NotCimXml("no rdf:RDF root element found".to_owned()));
758 }
759
760 if !st.header_registered
764 && let Some(ds) = dataset.as_mut()
765 {
766 ds.push_header(self.placeholder_header());
767 }
768
769 let mut header = st.header;
770 let mut difference = st.difference;
771 if let Some(d) = difference.as_mut()
772 && let Some(h) = header.clone()
773 {
774 d.header = h;
775 }
776 if let Some(h) = header.as_mut()
777 && h.source.is_none()
778 {
779 h.source = self.source.clone();
780 }
781 if let (Some(d), Some(ds)) = (difference.as_ref(), dataset.as_mut()) {
784 ds.push_difference(d.clone());
785 }
786
787 Ok(ReadOutcome {
788 header,
789 difference,
790 report: std::mem::take(&mut self.report),
791 objects_read: st.objects_read,
792 })
793 }
794
795 fn check_vintage(&mut self, pos: u64) {
801 let declared: Vec<&str> = self.ns.values().map(String::as_str).collect();
802 let Some(actual) = Schema::detect(declared.iter().copied()) else {
806 return;
807 };
808 if std::ptr::eq(actual, self.schema) {
809 return;
810 }
811 self.diag(
812 Diagnostic::error(
813 Rule::WrongVintage,
814 format!(
815 "this document is {} and is being read as {}; nothing in it will \
816 resolve. Use `{}::SCHEMA`, or `reader::sniff` to detect it",
817 actual.vintage, self.schema.vintage, actual.vintage
818 ),
819 ),
820 pos,
821 );
822 }
823
824 fn placeholder_header(&self) -> ModelHeader {
831 let mut h = ModelHeader::new(ModelKind::Full);
832 h.source = self.source.clone();
833 if let Some(p) = self.options.assume_profile {
834 h.profiles
835 .push(self.schema.profile(p).version_iri.to_owned());
836 }
837 h
838 }
839
840 fn ensure_source(&mut self, st: &mut State, dataset: &mut Option<&mut Dataset>) {
846 if st.header_registered || st.source.is_some() {
847 return;
848 }
849 st.header_registered = true;
850 if let Some(ds) = dataset.as_mut() {
851 let slot = ds.push_header(self.placeholder_header());
852 st.placeholder_slot = Some(slot);
853 st.source = Some(slot);
854 }
855 }
856
857 fn register_header(&mut self, st: &mut State, dataset: &mut Option<&mut Dataset>) {
859 let Some(h) = st.header.as_ref() else { return };
860 let declared = h
861 .profiles
862 .iter()
863 .filter_map(|iri| self.schema.profile_by_iri(iri))
864 .fold(0, |acc, p| acc | p.mask());
865 if declared != 0 {
866 st.profile_mask = declared;
867 }
868 if let Some(slot) = st.placeholder_slot.take()
871 && let Some(ds) = dataset.as_mut()
872 {
873 let mut h = h.clone();
874 if h.source.is_none() {
875 h.source = self.source.clone();
876 }
877 ds.set_header(slot, h);
878 return;
879 }
880 if st.header_registered {
881 return;
882 }
883 st.header_registered = true;
884 if let Some(ds) = dataset.as_mut() {
885 let mut h = h.clone();
886 if h.source.is_none() {
887 h.source = self.source.clone();
888 }
889 if h.profiles.is_empty()
894 && let Some(p) = self.options.assume_profile
895 {
896 h.profiles
897 .push(self.schema.profile(p).version_iri.to_owned());
898 }
899 st.source = Some(ds.push_header(h));
900 }
901 }
902
903 fn close_compound(&mut self, st: &mut State) {
905 let Some((attr, compound)) = st.compounds.pop() else {
906 return;
907 };
908 let value = Value::Compound(Box::new(compound));
909 let many = self.schema.attr(attr).mult.is_many();
910 match st.compounds.last_mut() {
911 Some((_, parent)) => {
912 if many {
913 parent.push(attr, value)
914 } else {
915 parent.set(attr, value)
916 }
917 }
918 None => {
919 if let Some(obj) = st.object.as_mut() {
920 if many {
921 obj.push_in(st.profile_mask, attr, value);
922 } else {
923 obj.set_in(st.profile_mask, attr, value);
924 }
925 }
926 }
927 }
928 }
929
930 fn commit(
936 &mut self,
937 mut object: Object,
938 st: &State,
939 dataset: &mut Option<&mut Dataset>,
940 pos: u64,
941 ) {
942 object.mark_profile(st.profile_mask);
943 object.from_file = true;
944 object.shrink_for_load();
945 let Some(ds) = dataset.as_mut() else { return };
946
947 if let Some(existing) = ds.by_mrid(object.mrid()) {
948 let incoming = object.class();
949 let held = existing.class();
950 if !self.schema.is_a(incoming, held) && !self.schema.is_a(held, incoming) {
951 let d = Diagnostic::error(
952 Rule::DuplicateMrid,
953 format!(
954 "identifier {} is used by both {} and {}, which are unrelated classes",
955 object.mrid().canonical(),
956 self.schema.class(held).name,
957 self.schema.class(incoming).name
958 ),
959 )
960 .with_class(self.schema.class(incoming).name)
961 .with_object(object.mrid().clone());
962 self.diag(d, pos);
963 }
964 }
965 if let Some(ds) = dataset.as_mut() {
967 let id = ds.insert(object);
968 if let Some(source) = st.source {
969 ds.record_source(source, id);
970 }
971 }
972 }
973
974 fn on_open(
976 &mut self,
977 e: &BytesStart<'_>,
978 self_closing: bool,
979 ctx: Ctx,
980 st: &mut State,
981 pos: u64,
982 ) -> Result<Ctx> {
983 let qname = e.name();
984 let qname = qname.as_ref();
985
986 if !st.saw_root || declares_namespace(e) {
992 self.collect_namespaces(e)?;
993 }
994 if !st.saw_root {
995 if let Some((ns, local)) = self.expand(qname)
996 && ns == RDF_NS
997 && local == "RDF"
998 {
999 st.saw_root = true;
1000 self.check_vintage(pos);
1001 return Ok(Ctx::Body);
1002 }
1003 return Ok(ctx);
1005 }
1006
1007 match ctx {
1008 Ctx::Body => self.open_in_body(e, qname, st, pos),
1009 Ctx::Object => {
1010 let Some(obj) = st.object.as_ref() else {
1011 return Ok(Ctx::Skip);
1012 };
1013 let (class, mrid) = (obj.class(), obj.mrid());
1016 match self.property(e, self_closing, class, mrid, pos)? {
1017 Prop::Value(attr, value) => {
1018 let obj = st.object.as_mut().expect("object present");
1019 if self.schema.attr(attr).mult.is_many() {
1020 obj.push_in(st.profile_mask, attr, value);
1021 } else {
1022 obj.set_in(st.profile_mask, attr, value);
1023 }
1024 Ok(Ctx::Skip)
1025 }
1026 Prop::Enter(attr, class) => {
1027 st.compounds.push((attr, Compound::new(class)));
1028 Ok(Ctx::Compound)
1029 }
1030 Prop::Text(attr) => {
1031 st.pending = Some(PendingText {
1032 target: TextTarget::Attr(attr),
1033 text: String::new(),
1034 });
1035 Ok(Ctx::Text)
1036 }
1037 Prop::Skip => Ok(Ctx::Skip),
1038 }
1039 }
1040 Ctx::Compound => {
1041 let Some((_, top)) = st.compounds.last() else {
1042 return Ok(Ctx::Skip);
1043 };
1044 let class = top.class();
1045 let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1046 match self.property(e, self_closing, class, mrid, pos)? {
1047 Prop::Value(attr, value) => {
1048 let (_, top) = st.compounds.last_mut().expect("compound present");
1049 if self.schema.attr(attr).mult.is_many() {
1050 top.push(attr, value);
1051 } else {
1052 top.set(attr, value);
1053 }
1054 Ok(Ctx::Skip)
1055 }
1056 Prop::Enter(attr, class) => {
1057 st.compounds.push((attr, Compound::new(class)));
1058 Ok(Ctx::Compound)
1059 }
1060 Prop::Text(attr) => {
1061 st.pending = Some(PendingText {
1062 target: TextTarget::Compound(attr),
1063 text: String::new(),
1064 });
1065 Ok(Ctx::Text)
1066 }
1067 Prop::Skip => Ok(Ctx::Skip),
1068 }
1069 }
1070 Ctx::Header => self.open_in_header(e, qname, self_closing, st),
1071 Ctx::DiffSet => {
1072 let about = self.attr(e, RDF_NS, "about")?;
1076 let defines = about.is_none();
1077 if let Some(raw) = about.or(self.attr(e, RDF_NS, "ID")?) {
1078 let class = self.expand(qname).and_then(|(ns, local)| {
1079 (!(ns == RDF_NS && local == "Description")).then(|| QualifiedName {
1080 ns: ns.to_owned(),
1081 local: local.to_owned(),
1082 })
1083 });
1084 st.diff_subject = Some((Mrid::parse(raw.trim()), class, defines));
1085 return Ok(Ctx::DiffSubject);
1086 }
1087 Ok(Ctx::Skip)
1088 }
1089 Ctx::DiffSubject => {
1090 let Some((ns, local)) = self
1091 .expand(qname)
1092 .map(|(n, l)| (n.to_owned(), l.to_owned()))
1093 else {
1094 return Ok(Ctx::Skip);
1095 };
1096 let Some((subject, class, defines_subject)) = st.diff_subject.clone() else {
1097 return Ok(Ctx::Skip);
1098 };
1099 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1100 let res = res.trim().to_owned();
1101 push_statement(
1102 &mut st.difference,
1103 st.diff_set,
1104 Statement {
1105 subject,
1106 class,
1107 defines_subject,
1108 predicate_ns: ns,
1109 predicate: local,
1110 value: StatementValue::Resource(res),
1111 },
1112 );
1113 return Ok(Ctx::Skip);
1114 }
1115 if self_closing {
1116 return Ok(Ctx::Skip);
1117 }
1118 st.pending = Some(PendingText {
1119 target: TextTarget::Statement {
1120 subject,
1121 class,
1122 defines_subject,
1123 ns,
1124 local,
1125 set: st.diff_set,
1126 },
1127 text: String::new(),
1128 });
1129 Ok(Ctx::Text)
1130 }
1131 Ctx::Text => {
1136 let name = qname.to_owned();
1137 self.diag(
1138 Diagnostic::warning(
1139 Rule::Structure,
1140 format!("unexpected element <{name}> inside a value; skipped"),
1141 ),
1142 pos,
1143 );
1144 Ok(Ctx::Skip)
1145 }
1146 Ctx::Skip | Ctx::Outside => Ok(Ctx::Skip),
1147 }
1148 }
1149
1150 fn open_in_body(
1152 &mut self,
1153 e: &BytesStart<'_>,
1154 qname: &str,
1155 st: &mut State,
1156 pos: u64,
1157 ) -> Result<Ctx> {
1158 if let Some((ns, local)) = self.expand(qname)
1159 && ((ns == MD_NS && local == "FullModel")
1160 || (ns == DM_NS && local == "DifferenceModel"))
1161 {
1162 let kind = if ns == DM_NS {
1163 ModelKind::Difference
1164 } else {
1165 ModelKind::Full
1166 };
1167 let mut h = ModelHeader::new(kind);
1168 h.id = self
1169 .attr(e, RDF_NS, "about")?
1170 .map(|s| Mrid::parse(s.trim()));
1171 h.source = self.source.clone();
1172 st.header = Some(h);
1173 if kind == ModelKind::Difference {
1174 st.difference = Some(DifferenceModel::default());
1175 }
1176 return Ok(Ctx::Header);
1177 }
1178
1179 if self.header_only {
1180 return Ok(Ctx::Skip);
1181 }
1182
1183 match self.resolve(qname) {
1184 Resolved::Class(class) => {
1185 let def = self.schema.class(class);
1186 if def.compound {
1189 self.diag(
1190 Diagnostic::error(
1191 Rule::Structure,
1192 format!(
1193 "compound type {} has no identity and cannot be a top-level object",
1194 def.name
1195 ),
1196 )
1197 .with_class(def.name),
1198 pos,
1199 );
1200 return Ok(Ctx::Skip);
1201 }
1202 if !def.concrete {
1203 self.diag(
1204 Diagnostic::error(
1205 Rule::AbstractInstantiated,
1206 format!("abstract class {} instantiated", def.name),
1207 )
1208 .with_class(def.name),
1209 pos,
1210 );
1211 }
1212 if self.options.report_deprecated && def.deprecated {
1213 self.diag(
1214 Diagnostic::info(
1215 Rule::Deprecated,
1216 format!("deprecated class {}", def.name),
1217 )
1218 .with_class(def.name),
1219 pos,
1220 );
1221 }
1222 let mrid = self.object_identity(e, def.name, pos)?;
1223 let mut o = Object::new(class, mrid);
1224 o.mark_profile(st.profile_mask);
1225 st.object = Some(o);
1226 Ok(Ctx::Object)
1227 }
1228 Resolved::Attr(_) | Resolved::Unknown => {
1229 let name = qname.to_owned();
1230 if self.options.strictness == Strictness::Strict {
1231 return Err(Error::NotCimXml(format!("unknown class element <{name}>")));
1232 }
1233 self.diag(
1234 Diagnostic::warning(
1235 Rule::UnknownClass,
1236 format!("unknown class element <{name}>, skipped"),
1237 ),
1238 pos,
1239 );
1240 Ok(Ctx::Skip)
1241 }
1242 }
1243 }
1244
1245 fn open_in_header(
1247 &mut self,
1248 e: &BytesStart<'_>,
1249 qname: &str,
1250 self_closing: bool,
1251 st: &mut State,
1252 ) -> Result<Ctx> {
1253 let Some((ns, local)) = self
1254 .expand(qname)
1255 .map(|(n, l)| (n.to_owned(), l.to_owned()))
1256 else {
1257 return Ok(Ctx::Skip);
1258 };
1259 let set = match (ns == DM_NS, local.as_str()) {
1261 (true, "forwardDifferences") => Some(DiffSet::Forward),
1262 (true, "reverseDifferences") => Some(DiffSet::Reverse),
1263 (true, "preconditions") => Some(DiffSet::Preconditions),
1267 _ => None,
1268 };
1269 if let Some(set) = set {
1270 st.diff_set = set;
1271 if st.difference.is_none() {
1272 st.difference = Some(DifferenceModel::default());
1273 }
1274 return Ok(Ctx::DiffSet);
1275 }
1276 let prefix = prefix_of(qname);
1277 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1278 let res = res.trim().to_owned();
1279 apply_header_resource(&mut st.header, &prefix, &ns, &local, res);
1280 return Ok(Ctx::Skip);
1281 }
1282 if self_closing {
1283 return Ok(Ctx::Skip);
1284 }
1285 st.pending = Some(PendingText {
1286 target: TextTarget::Header { prefix, ns, local },
1287 text: String::new(),
1288 });
1289 Ok(Ctx::Text)
1290 }
1291
1292 fn property(
1294 &mut self,
1295 e: &BytesStart<'_>,
1296 self_closing: bool,
1297 class: ClassId,
1298 owner: &Mrid,
1299 pos: u64,
1300 ) -> Result<Prop> {
1301 let qname = e.name();
1302 let qname = qname.as_ref();
1303 let Resolved::Attr(attr) = self.resolve(qname) else {
1304 let name = qname.to_owned();
1305 if self.options.strictness == Strictness::Strict {
1306 return Err(Error::NotCimXml(format!(
1307 "unknown property element <{name}>"
1308 )));
1309 }
1310 self.diag(
1311 Diagnostic::warning(
1312 Rule::UnknownAttribute,
1313 format!("unknown property <{name}>, skipped"),
1314 )
1315 .with_object(owner.clone()),
1316 pos,
1317 );
1318 return Ok(Prop::Skip);
1319 };
1320
1321 let def = self.schema.attr(attr);
1322 if !self.schema.is_a(class, def.owner) {
1324 self.diag(
1325 Diagnostic::warning(
1326 Rule::UnknownAttribute,
1327 format!(
1328 "{} does not apply to class {}",
1329 def.name,
1330 self.schema.class(class).name
1331 ),
1332 )
1333 .with_attribute(def.name)
1334 .with_object(owner.clone()),
1335 pos,
1336 );
1337 return Ok(Prop::Skip);
1338 }
1339 if self.options.report_deprecated && def.deprecated {
1340 self.diag(
1341 Diagnostic::info(
1342 Rule::Deprecated,
1343 format!("deprecated attribute {}", def.name),
1344 )
1345 .with_attribute(def.name),
1346 pos,
1347 );
1348 }
1349
1350 if let AttrKind::Compound(target) = def.kind {
1354 if self.attr(e, RDF_NS, "resource")?.is_some() {
1355 self.diag(
1356 Diagnostic::error(
1357 Rule::InvalidValue,
1358 format!(
1359 "{} holds a compound, which has no identity, but is written as \
1360 a reference",
1361 def.name
1362 ),
1363 )
1364 .with_attribute(def.name)
1365 .with_object(owner.clone()),
1366 pos,
1367 );
1368 return Ok(Prop::Skip);
1369 }
1370 return Ok(Prop::Enter(attr, target));
1371 }
1372
1373 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1374 let res = res.trim();
1375 return Ok(match self.resource_value(attr, res, owner, pos) {
1376 Some(v) => Prop::Value(attr, v),
1377 None => Prop::Skip,
1378 });
1379 }
1380 if self_closing {
1381 if matches!(def.kind, AttrKind::Primitive(Primitive::String)) {
1383 return Ok(Prop::Value(attr, Value::Text("".into())));
1384 }
1385 return Ok(Prop::Skip);
1386 }
1387 Ok(Prop::Text(attr))
1388 }
1389
1390 fn object_identity(
1392 &mut self,
1393 e: &BytesStart<'_>,
1394 class: &'static str,
1395 pos: u64,
1396 ) -> Result<Mrid> {
1397 for (name, raw) in [
1398 ("rdf:ID", self.attr(e, RDF_NS, "ID")?),
1399 ("rdf:about", self.attr(e, RDF_NS, "about")?),
1400 ] {
1401 let Some(raw) = raw else { continue };
1402 let raw = raw.trim();
1403 let m = Mrid::parse(raw);
1404 let unwritable_id = name == "rdf:ID" && !crate::xml::is_ncname(raw);
1410 if unwritable_id || (self.options.report_non_conforming_mrids && !m.is_conforming()) {
1414 let complaint = if unwritable_id {
1415 format!(
1416 "is not an XML NCName and so cannot be written back as one; repaired to {:?}",
1417 m.to_rdf_id()
1418 )
1419 } else if m.is_uuid() {
1420 format!(
1423 "is a UUID written without hyphens; IEC 61970-552 requires {:?}",
1424 m.canonical()
1425 )
1426 } else {
1427 "is not a UUID as IEC 61970-552 requires".to_owned()
1428 };
1429 self.diag(
1430 Diagnostic::warning(
1431 Rule::NonConformingMrid,
1432 format!("{name} {raw:?} {complaint}"),
1433 )
1434 .with_class(class),
1435 pos,
1436 );
1437 }
1438 return Ok(m);
1439 }
1440 let placeholder = match &self.source {
1447 Some(src) => format!("no-identifier-{src}-{pos}"),
1448 None => format!("no-identifier-{pos}"),
1449 };
1450 self.diag(
1451 Diagnostic::error(
1452 Rule::Structure,
1453 format!("<{class}> has neither rdf:ID nor rdf:about; kept as {placeholder:?}"),
1454 )
1455 .with_class(class),
1456 pos,
1457 );
1458 Ok(Mrid::parse(&placeholder))
1459 }
1460
1461 fn resource_value(&mut self, attr: AttrId, res: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1463 let def = self.schema.attr(attr);
1464 let AttrKind::Enumeration(_) = def.kind else {
1465 return Some(Value::Reference(Mrid::parse(res)));
1466 };
1467 let Some((ns, local)) = res.rsplit_once('#') else {
1469 self.diag(
1470 Diagnostic::error(
1471 Rule::InvalidValue,
1472 format!("enumeration value {res:?} is not an IRI"),
1473 )
1474 .with_attribute(def.name),
1475 pos,
1476 );
1477 return None;
1478 };
1479 if let Some(v) = self.schema.find_enum_value(&format!("{ns}#"), local) {
1480 return Some(Value::Enum(v));
1481 }
1482 match self.schema.find_enum_value_any_ns(local) {
1485 Some(v) => {
1486 let correct = self.schema.namespace(self.schema.enum_value(v).ns).iri;
1487 self.diag(
1488 Diagnostic::warning(
1489 Rule::InvalidValue,
1490 format!(
1491 "enumeration literal {local} is written in namespace {ns}# but is \
1492 declared in {correct}; value recovered"
1493 ),
1494 )
1495 .with_attribute(def.name)
1496 .with_object(owner.clone()),
1497 pos,
1498 );
1499 Some(Value::Enum(v))
1500 }
1501 None => {
1502 self.diag(
1503 Diagnostic::error(
1504 Rule::InvalidValue,
1505 format!("unknown enumeration literal {res:?}"),
1506 )
1507 .with_attribute(def.name)
1508 .with_object(owner.clone()),
1509 pos,
1510 );
1511 None
1512 }
1513 }
1514 }
1515
1516 fn finish_text(&mut self, mut p: PendingText, st: &mut State, pos: u64) {
1518 if let Some((offset, c)) = crate::xml::find_illegal(&p.text) {
1525 self.diag(
1526 Diagnostic::warning(
1527 Rule::IllegalXmlCharacter,
1528 format!(
1529 "value holds {}, which XML 1.0 cannot represent in any form; \
1530 removed (first at byte {offset} of the value)",
1531 crate::xml::describe_char(c)
1532 ),
1533 ),
1534 pos,
1535 );
1536 p.text = crate::xml::strip_illegal(&p.text).into_owned();
1537 }
1538 match p.target {
1539 TextTarget::Attr(attr) => {
1540 let Some(obj) = st.object.as_ref() else {
1541 return;
1542 };
1543 if let Some(v) = self.parse_text(attr, &p.text, obj.mrid(), pos) {
1544 let obj = st.object.as_mut().expect("object present");
1545 if self.schema.attr(attr).mult.is_many() {
1546 obj.push_in(st.profile_mask, attr, v);
1547 } else {
1548 obj.set_in(st.profile_mask, attr, v);
1549 }
1550 }
1551 }
1552 TextTarget::Compound(attr) => {
1553 let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1554 if let Some(v) = self.parse_text(attr, &p.text, mrid, pos)
1555 && let Some((_, top)) = st.compounds.last_mut()
1556 {
1557 if self.schema.attr(attr).mult.is_many() {
1558 top.push(attr, v);
1559 } else {
1560 top.set(attr, v);
1561 }
1562 }
1563 }
1564 TextTarget::Header { prefix, ns, local } => {
1565 apply_header_text(&mut st.header, &prefix, &ns, &local, p.text);
1566 }
1567 TextTarget::Statement {
1568 subject,
1569 class,
1570 defines_subject,
1571 ns,
1572 local,
1573 set,
1574 } => push_statement(
1575 &mut st.difference,
1576 set,
1577 Statement {
1578 subject,
1579 class,
1580 defines_subject,
1581 predicate_ns: ns,
1582 predicate: local,
1583 value: StatementValue::Literal(p.text),
1584 },
1585 ),
1586 }
1587 }
1588
1589 fn parse_text(&mut self, attr: AttrId, text: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1590 let def = self.schema.attr(attr);
1591 let prim = match def.kind {
1592 AttrKind::Primitive(prim) => prim,
1593 AttrKind::Datatype(dt) => self.schema.datatype(dt).value,
1594 AttrKind::Enumeration(_) | AttrKind::Association { .. } | AttrKind::Compound(_) => {
1597 Primitive::String
1598 }
1599 };
1600 match Value::parse_primitive(prim, text) {
1601 Ok(v) => Some(v),
1602 Err(e) => {
1603 let name = def.name;
1604 self.diag(
1605 Diagnostic::error(Rule::InvalidValue, e.to_string())
1606 .with_attribute(name)
1607 .with_object(owner.clone()),
1608 pos,
1609 );
1610 None
1611 }
1612 }
1613 }
1614
1615 fn collect_namespaces(&mut self, e: &BytesStart<'_>) -> Result<()> {
1622 for attr in e.attributes().with_checks(false) {
1623 let attr = attr?;
1624 let key = attr.key.as_ref();
1625 let value = self.attr_value(&attr)?.into_owned();
1626 if let Some(prefix) = key.strip_prefix("xmlns:") {
1627 self.ns.insert(prefix.as_bytes().to_vec(), value);
1628 } else if key == "xmlns" {
1629 self.ns.insert(Vec::new(), value);
1630 }
1631 }
1632 Ok(())
1633 }
1634
1635 fn attr<'e>(
1641 &self,
1642 e: &'e BytesStart<'_>,
1643 ns: &str,
1644 local: &str,
1645 ) -> Result<Option<Cow<'e, str>>> {
1646 for attr in e.attributes().with_checks(false) {
1647 let attr = attr?;
1648 let key = attr.key.as_ref();
1649 let Some((prefix, name)) = key.split_once(':') else {
1650 continue;
1651 };
1652 if name != local {
1653 continue;
1654 }
1655 if self.ns.get(prefix.as_bytes()).map(String::as_str) != Some(ns) {
1656 continue;
1657 }
1658 return Ok(Some(self.attr_value(&attr)?));
1659 }
1660 Ok(None)
1661 }
1662}
1663
1664fn parse_error(e: quick_xml::Error) -> Error {
1668 match e {
1669 quick_xml::Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
1670 other => Error::Xml(other.to_string()),
1671 }
1672}
1673
1674fn undefined_entity(name: &str) -> Diagnostic {
1676 Diagnostic::warning(
1677 Rule::InvalidValue,
1678 format!(
1679 "undefined entity &{name}; kept as text: CIM/XML documents declare no DTD, so \
1680 only the five predefined entities and character references are expanded"
1681 ),
1682 )
1683}
1684
1685fn escape_undefined_entities(raw: &str) -> (String, Vec<String>) {
1688 let mut out = String::with_capacity(raw.len() + 8);
1689 let mut names = Vec::new();
1690 let mut rest = raw;
1691 while let Some(at) = rest.find('&') {
1692 out.push_str(&rest[..at]);
1693 let after = &rest[at + 1..];
1694 let name = after.split_once(';').map(|(n, _)| n);
1695 match name {
1696 Some(n)
1697 if !n.starts_with('#')
1698 && quick_xml::escape::resolve_predefined_entity(n).is_none() =>
1699 {
1700 out.push_str("&");
1701 names.push(n.to_owned());
1702 }
1703 _ => out.push('&'),
1704 }
1705 rest = after;
1706 }
1707 out.push_str(rest);
1708 (out, names)
1709}
1710
1711fn declares_namespace(e: &BytesStart<'_>) -> bool {
1713 e.as_ref().contains("xmlns")
1714}
1715
1716fn prefix_of(qname: &str) -> String {
1718 match qname.split_once(':') {
1719 Some((prefix, _)) => prefix.to_owned(),
1720 None => String::new(),
1721 }
1722}
1723
1724fn apply_header_resource(
1726 header: &mut Option<ModelHeader>,
1727 prefix: &str,
1728 ns: &str,
1729 local: &str,
1730 res: String,
1731) {
1732 let Some(h) = header.as_mut() else { return };
1733 match (ns, local) {
1734 (MD_NS, "Model.DependentOn") => h.dependent_on.push(Mrid::parse(&res)),
1735 (MD_NS, "Model.Supersedes") => h.supersedes.push(Mrid::parse(&res)),
1736 (MD_NS, "Model.profile") => h.profiles.push(res),
1737 _ => h
1738 .extra
1739 .push(HeaderProperty::resource(prefix, ns, local, res)),
1740 }
1741}
1742
1743fn apply_header_text(
1745 header: &mut Option<ModelHeader>,
1746 prefix: &str,
1747 ns: &str,
1748 local: &str,
1749 text: String,
1750) {
1751 let Some(h) = header.as_mut() else { return };
1752 if ns != MD_NS {
1753 h.extra.push(HeaderProperty::text(prefix, ns, local, text));
1754 return;
1755 }
1756 match local {
1757 "Model.created" => h.created = Some(text),
1758 "Model.scenarioTime" => h.scenario_time = Some(text),
1759 "Model.description" => h.description = Some(text),
1760 "Model.version" => h.version = Some(text),
1761 "Model.modelingAuthoritySet" => h.modeling_authority_set = Some(text),
1762 "Model.profile" => h.profiles.push(text),
1763 "Model.DependentOn" => h.dependent_on.push(Mrid::parse(&text)),
1764 "Model.Supersedes" => h.supersedes.push(Mrid::parse(&text)),
1765 _ => h.extra.push(HeaderProperty::text(prefix, ns, local, text)),
1766 }
1767}
1768
1769#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1771enum DiffSet {
1772 Preconditions,
1773 #[default]
1774 Reverse,
1775 Forward,
1776}
1777
1778fn push_statement(difference: &mut Option<DifferenceModel>, set: DiffSet, s: Statement) {
1779 let d = difference.get_or_insert_with(DifferenceModel::default);
1780 match set {
1781 DiffSet::Preconditions => d.preconditions.push(s),
1782 DiffSet::Reverse => d.reverse.push(s),
1783 DiffSet::Forward => d.forward.push(s),
1784 }
1785}
1786
1787struct PendingText {
1788 target: TextTarget,
1789 text: String,
1790}
1791
1792enum TextTarget {
1793 Attr(AttrId),
1795 Compound(AttrId),
1797 Header {
1799 prefix: String,
1800 ns: String,
1801 local: String,
1802 },
1803 Statement {
1805 subject: Mrid,
1806 class: Option<QualifiedName>,
1807 defines_subject: bool,
1808 ns: String,
1809 local: String,
1810 set: DiffSet,
1811 },
1812}