1use std::borrow::Cow;
9use std::cell::{Cell, RefCell};
10use std::collections::HashMap;
11use std::io::{self, BufRead, Read};
12
13use quick_xml::Reader;
14use quick_xml::events::{BytesStart, Event};
15
16use crate::dataset::{Dataset, ObjectId};
17use crate::error::{Diagnostic, Error, Report, Result, Rule};
18use crate::header::{
19 DM_NS, DifferenceModel, HeaderProperty, MD_NS, ModelHeader, ModelKind, QualifiedName,
20 Statement, StatementValue,
21};
22use crate::mrid::Mrid;
23use crate::object::{Compound, Object};
24use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileId, ProfileMask, Schema};
25use crate::value::Value;
26
27const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
28const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
30const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
32
33static UNKNOWN_MRID: Mrid = Mrid::nil();
35
36#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
38pub enum Strictness {
39 #[default]
43 Lenient,
44 Strict,
48}
49
50#[derive(Clone, Debug)]
52pub struct ReadOptions {
53 pub strictness: Strictness,
54 pub assume_profile: Option<ProfileId>,
56 pub report_deprecated: bool,
58 pub report_non_conforming_mrids: bool,
60 pub max_diagnostics: usize,
65 pub max_input_bytes: u64,
73 pub single_description: bool,
79}
80
81impl Default for ReadOptions {
82 fn default() -> Self {
83 ReadOptions {
84 strictness: Strictness::Lenient,
85 assume_profile: None,
86 report_deprecated: false,
87 report_non_conforming_mrids: false,
88 max_diagnostics: ReadOptions::DEFAULT_MAX_DIAGNOSTICS,
89 max_input_bytes: ReadOptions::DEFAULT_MAX_INPUT_BYTES,
90 single_description: false,
91 }
92 }
93}
94
95impl ReadOptions {
96 pub const DEFAULT_MAX_DIAGNOSTICS: usize = 10_000;
98
99 pub const DEFAULT_MAX_INPUT_BYTES: u64 = 8 << 30;
104
105 pub fn lenient() -> ReadOptions {
107 ReadOptions::default()
108 }
109
110 pub fn strict() -> ReadOptions {
112 ReadOptions {
113 strictness: Strictness::Strict,
114 report_deprecated: true,
115 report_non_conforming_mrids: true,
116 ..ReadOptions::default()
117 }
118 }
119
120 pub fn with_profile(mut self, profile: ProfileId) -> Self {
121 self.assume_profile = Some(profile);
122 self
123 }
124
125 pub fn with_max_diagnostics(mut self, max: usize) -> Self {
127 self.max_diagnostics = max;
128 self
129 }
130
131 pub fn with_max_input_bytes(mut self, max: u64) -> Self {
133 self.max_input_bytes = max;
134 self
135 }
136
137 pub fn with_single_description(mut self, on: bool) -> Self {
140 self.single_description = on;
141 self
142 }
143}
144
145#[derive(Debug)]
150pub(crate) struct Budget {
151 limit: u64,
152 used: Cell<u64>,
153 tripped: Cell<bool>,
154}
155
156impl Budget {
157 pub(crate) fn new(options: &ReadOptions) -> Budget {
158 Budget {
159 limit: options.max_input_bytes,
160 used: Cell::new(0),
161 tripped: Cell::new(false),
162 }
163 }
164
165 pub(crate) fn meter<R: BufRead>(&self, input: R) -> Metered<'_, R> {
167 Metered {
168 inner: input,
169 used: self.used.get(),
170 limit: if self.limit == 0 {
172 u64::MAX
173 } else {
174 self.limit
175 },
176 budget: self,
177 }
178 }
179
180 pub(crate) fn check<T>(&self, result: Result<T>, source: Option<&str>) -> Result<T> {
185 match result {
186 Err(_) if self.tripped.get() => Err(Error::InputTooLarge {
187 limit: self.limit,
188 read: self.used.get(),
189 source: source.map(str::to_owned),
190 }),
191 other => other,
192 }
193 }
194
195 pub(crate) fn tripped(&self) -> bool {
196 self.tripped.get()
197 }
198}
199
200pub(crate) struct Metered<'a, R> {
205 inner: R,
206 used: u64,
207 limit: u64,
208 budget: &'a Budget,
209}
210
211impl<R> Drop for Metered<'_, R> {
212 fn drop(&mut self) {
213 self.budget.used.set(self.used);
214 }
215}
216
217impl<R: BufRead> Read for Metered<'_, R> {
218 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
219 let available = self.fill_buf()?;
220 let n = available.len().min(out.len());
221 out[..n].copy_from_slice(&available[..n]);
222 self.consume(n);
223 Ok(n)
224 }
225}
226
227impl<R: BufRead> BufRead for Metered<'_, R> {
228 #[inline]
229 fn fill_buf(&mut self) -> io::Result<&[u8]> {
230 if self.used > self.limit {
231 self.budget.tripped.set(true);
232 self.budget.used.set(self.used);
233 return Err(io::Error::other("input budget exceeded"));
234 }
235 let room = self.limit - self.used;
238 let buf = self.inner.fill_buf()?;
239 Ok(match usize::try_from(room) {
240 Ok(room) if room < buf.len() => &buf[..=room],
241 _ => buf,
242 })
243 }
244
245 #[inline]
246 fn consume(&mut self, amt: usize) {
247 self.used = self.used.saturating_add(amt as u64);
248 self.inner.consume(amt);
249 }
250}
251
252const SNIFF_PREFIX: u64 = 1 << 20;
254
255#[derive(Debug)]
257pub struct ReadOutcome {
258 pub header: Option<ModelHeader>,
259 pub difference: Option<DifferenceModel>,
261 pub report: Report,
262 pub objects_read: usize,
264}
265
266pub fn read_into<R: BufRead>(
278 dataset: &mut Dataset,
279 input: R,
280 source: Option<&str>,
281 options: &ReadOptions,
282) -> Result<ReadOutcome> {
283 let budget = Budget::new(options);
284 read_into_within(dataset, input, source, options, &budget)
285}
286
287pub(crate) fn read_into_within<R: BufRead>(
289 dataset: &mut Dataset,
290 input: R,
291 source: Option<&str>,
292 options: &ReadOptions,
293 budget: &Budget,
294) -> Result<ReadOutcome> {
295 let schema = dataset.schema();
296 let mut parser = Parser::new(schema, source, options, false);
297 let outcome = parser.run(budget.meter(input), Some(dataset));
298 budget.check(outcome, source)
299}
300
301pub fn read_header<R: BufRead>(
305 schema: &'static Schema,
306 input: R,
307 source: Option<&str>,
308) -> Result<Option<ModelHeader>> {
309 let options = ReadOptions::default();
310 let budget = Budget::new(&options);
311 let mut parser = Parser::new(schema, source, &options, true);
312 let outcome = parser.run(budget.meter(input), None);
313 Ok(budget.check(outcome, source)?.header)
314}
315
316pub fn sniff<R: BufRead>(input: R) -> Result<Option<&'static Schema>> {
333 let mut reader = Reader::from_reader(input.take(SNIFF_PREFIX));
334 reader.config_mut().check_end_names = false;
335 let mut buf = Vec::new();
336 loop {
337 let ev = match reader.read_event_into(&mut buf) {
338 Ok(ev) => ev,
339 Err(_) if reader.get_ref().limit() == 0 => return Ok(None),
342 Err(e) => {
343 return Err(Error::xml(shown(&e.to_string())).locate(None, reader.error_position()));
344 }
345 };
346 let e = match ev {
347 Event::Eof => return Ok(None),
348 Event::Start(e) | Event::Empty(e) => e,
349 _ => {
350 buf.clear();
351 continue;
352 }
353 };
354 let mut iris: Vec<String> = Vec::new();
357 for attr in e.attributes().with_checks(false) {
358 let attr = attr?;
359 let key = attr.key.as_ref();
360 if key == "xmlns" || key.starts_with("xmlns:") {
361 iris.push(attr.value.into_owned());
362 }
363 }
364 if let Some(schema) = Schema::detect(iris.iter().map(String::as_str)) {
365 return Ok(Some(schema));
366 }
367 buf.clear();
368 }
369}
370
371pub fn read_difference<R: BufRead>(
373 schema: &'static Schema,
374 input: R,
375 source: Option<&str>,
376 options: &ReadOptions,
377) -> Result<Option<DifferenceModel>> {
378 let budget = Budget::new(options);
379 let mut parser = Parser::new(schema, source, options, false);
380 let outcome = parser.run(budget.meter(input), None);
381 Ok(budget.check(outcome, source)?.difference)
382}
383
384#[derive(Clone, Copy)]
390enum Resolved {
391 Class(ClassId),
392 Attr(AttrId),
393 Unknown,
395}
396
397#[derive(Clone, Copy, PartialEq, Eq, Debug)]
399enum Ctx {
400 Outside,
402 Body,
404 Header,
406 Object,
408 Compound,
410 DiffSet,
412 DiffSubject,
414 Text,
419 Skip,
421}
422
423enum Prop {
425 Value(AttrId, Value),
427 Enter(AttrId, ClassId),
429 Text(AttrId),
431 Skip,
433}
434
435#[derive(Default)]
437struct State {
438 saw_root: bool,
439 header: Option<ModelHeader>,
440 difference: Option<DifferenceModel>,
441 staged: Vec<Staged>,
444 staged_seen: Vec<(AttrId, u64)>,
447 object: Option<Object>,
449 object_start: u64,
450 object_defined: bool,
451 seen: Vec<(AttrId, u64)>,
453 compounds: Vec<Frame>,
456 pending: Option<PendingText>,
458 profile_mask: ProfileMask,
460 diff_subject: Option<(Mrid, Option<QualifiedName>, bool)>,
463 diff_set: DiffSet,
465}
466
467struct Staged {
469 object: Object,
470 start: u64,
472 defined: bool,
474 seen: std::ops::Range<u32>,
476}
477
478struct Described {
481 start: u64,
482 defined: bool,
483 seen: std::ops::Range<u32>,
486 more: Vec<(AttrId, u64)>,
487}
488
489impl Described {
490 fn new(s: &Staged) -> Described {
491 Described {
492 start: s.start,
493 defined: s.defined,
494 seen: s.seen.clone(),
495 more: Vec::new(),
496 }
497 }
498}
499
500struct DocumentObjects {
503 base: usize,
504 created: Vec<Described>,
505 merged: HashMap<u32, Described>,
506}
507
508impl DocumentObjects {
509 fn get_mut(&mut self, id: ObjectId) -> Option<&mut Described> {
510 match id.index().checked_sub(self.base) {
511 Some(i) => self.created.get_mut(i),
512 None => self.merged.get_mut(&(id.index() as u32)),
513 }
514 }
515}
516
517struct Frame {
520 attr: AttrId,
521 compound: Compound,
522 start: u64,
523 seen: Vec<(AttrId, u64)>,
524}
525
526impl Frame {
527 fn new(attr: AttrId, class: ClassId, start: u64) -> Frame {
528 Frame {
529 attr,
530 compound: Compound::new(class),
531 start,
532 seen: Vec::new(),
533 }
534 }
535}
536
537#[derive(Default)]
540struct OpenElements {
541 names: String,
542 open: Vec<(usize, u64)>,
543}
544
545impl OpenElements {
546 fn push(&mut self, qname: &str, start: u64) {
547 self.open.push((self.names.len(), start));
548 self.names.push_str(qname);
549 }
550
551 fn pop(&mut self) {
552 if let Some((at, _)) = self.open.pop() {
553 self.names.truncate(at);
554 }
555 }
556
557 fn innermost(&self) -> Option<(String, u64)> {
559 let &(at, start) = self.open.last()?;
560 Some((shown(&self.names[at..]).into_owned(), start))
561 }
562}
563
564struct Parser<'a> {
565 schema: &'static Schema,
566 options: &'a ReadOptions,
567 source: Option<String>,
568 report: Report,
569 header_only: bool,
570 truncated: bool,
572 ns: Vec<(usize, Box<str>, String)>,
576 rdf_spans: Cell<[(u32, u32); 3]>,
580 cache: HashMap<Vec<u8>, Resolved>,
583 undefined_entities: RefCell<Vec<String>>,
587 illegal_in_attribute: Cell<Option<char>>,
590}
591
592impl<'a> Parser<'a> {
593 fn new(
594 schema: &'static Schema,
595 source: Option<&str>,
596 options: &'a ReadOptions,
597 header_only: bool,
598 ) -> Parser<'a> {
599 Parser {
600 schema,
601 options,
602 source: source.map(str::to_owned),
603 report: Report::default(),
604 header_only,
605 truncated: false,
606 ns: Vec::new(),
607 rdf_spans: Cell::new([(0, 0); 3]),
608 cache: HashMap::new(),
609 undefined_entities: RefCell::new(Vec::new()),
610 illegal_in_attribute: Cell::new(None),
611 }
612 }
613
614 #[inline]
617 fn flush_attribute_findings(&mut self, pos: u64) {
618 if !self.undefined_entities.get_mut().is_empty()
619 || self.illegal_in_attribute.get().is_some()
620 {
621 self.report_attribute_findings(pos);
622 }
623 }
624
625 #[cold]
626 #[inline(never)]
627 fn report_attribute_findings(&mut self, pos: u64) {
628 let names = std::mem::take(self.undefined_entities.get_mut());
629 for name in names {
630 self.diag(undefined_entity(&name), pos);
631 }
632 if let Some(c) = self.illegal_in_attribute.take() {
633 self.diag(
634 Diagnostic::warning(
635 Rule::IllegalXmlCharacter,
636 format!(
637 "an attribute value holds {}, which XML 1.0 cannot represent in any \
638 form; removed",
639 crate::xml::describe_char(c)
640 ),
641 ),
642 pos,
643 );
644 }
645 }
646
647 fn attr_value<'e>(
652 &self,
653 attr: &quick_xml::events::attributes::Attribute<'e>,
654 ) -> Result<Cow<'e, str>> {
655 let value = self.normalized_attr_value(attr)?;
656 match crate::xml::find_illegal(&value) {
657 None => Ok(value),
658 Some((_, c)) => {
659 if self.illegal_in_attribute.get().is_none() {
660 self.illegal_in_attribute.set(Some(c));
661 }
662 Ok(Cow::Owned(crate::xml::strip_illegal(&value).into_owned()))
663 }
664 }
665 }
666
667 fn normalized_attr_value<'e>(
668 &self,
669 attr: &quick_xml::events::attributes::Attribute<'e>,
670 ) -> Result<Cow<'e, str>> {
671 use quick_xml::escape::EscapeError;
672 match attr.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
673 Ok(v) => Ok(v),
674 Err(quick_xml::Error::Escape(EscapeError::UnrecognizedEntity(..))) => {
675 let (escaped, names) = escape_undefined_entities(&attr.value);
676 self.undefined_entities.borrow_mut().extend(names);
677 let rewritten = quick_xml::events::attributes::Attribute {
678 key: attr.key,
679 value: Cow::Owned(escaped),
680 };
681 let value = rewritten
682 .normalized_value(quick_xml::XmlVersion::Explicit1_0)
683 .map_err(|e| Error::xml(e.to_string()))?;
684 Ok(Cow::Owned(value.into_owned()))
685 }
686 Err(e) => Err(Error::xml(e.to_string())),
687 }
688 }
689
690 fn diag(&mut self, d: Diagnostic, pos: u64) {
691 let max = self.options.max_diagnostics;
692 if max != 0 && self.report.len() >= max {
693 if !self.truncated {
694 self.truncated = true;
695 self.report.push(Diagnostic::warning(
696 Rule::Structure,
697 format!(
698 "stopped recording after {max} diagnostics; reading continued \
699 (raise ReadOptions::max_diagnostics to see the rest)"
700 ),
701 ));
702 }
703 return;
704 }
705 let mut d = d.with_position(pos);
706 if let Some(s) = &self.source {
707 d = d.with_source(s.clone());
708 }
709 self.report.push(d);
710 }
711
712 fn expand<'q>(&self, qname: &'q str) -> Option<(&str, &'q str)> {
714 let (prefix, local) = match qname.split_once(':') {
715 Some((prefix, local)) => (prefix, local),
716 None => ("", qname),
717 };
718 Some((self.namespace(prefix)?, local))
719 }
720
721 fn resolve(&mut self, qname: &str) -> Result<Resolved> {
725 if let Some(r) = self.cache.get(qname.as_bytes()) {
726 return Ok(*r);
727 }
728 let resolved = match self.expand(qname) {
729 Some((ns, local)) if local.contains('.') => match self.schema.find_attr(ns, local) {
731 Some(a) => Resolved::Attr(a),
732 None => Resolved::Unknown,
733 },
734 Some((ns, local)) => match self.schema.find_class(ns, local) {
735 Some(c) => Resolved::Class(c),
736 None => Resolved::Unknown,
737 },
738 None => {
740 self.check_prefix(qname, qname)?;
741 Resolved::Unknown
742 }
743 };
744 self.cache.insert(qname.as_bytes().to_vec(), resolved);
745 Ok(resolved)
746 }
747
748 fn run<R: BufRead>(&mut self, input: R, dataset: Option<&mut Dataset>) -> Result<ReadOutcome> {
749 let mut reader = Reader::from_reader(input);
750 reader.config_mut().trim_text(false);
751 reader.config_mut().expand_empty_elements = false;
752 reader.config_mut().check_end_names = true;
753
754 let source = self.source.clone();
755 let mut buf = Vec::new();
756 let mut ctx = Ctx::Outside;
757 let mut stack: Vec<Ctx> = Vec::with_capacity(8);
759 let mut open = OpenElements::default();
760 let mut root_closed = false;
761
762 let mut st = State {
763 profile_mask: self.options.assume_profile.map_or(0, |p| p.mask()),
764 ..Default::default()
765 };
766
767 loop {
768 let pos = reader.buffer_position();
770 let ev = match reader.read_event_into(&mut buf) {
771 Ok(ev) => ev,
772 Err(e) => {
773 let at_end = reader.get_mut().fill_buf().is_ok_and(<[u8]>::is_empty);
776 return Err(parse_error(
777 e,
778 reader.error_position(),
779 at_end,
780 &open,
781 &source,
782 ));
783 }
784 };
785 if stack.is_empty()
786 && let Some(problem) = outside_document(&ev, root_closed)
787 {
788 return Err(Error::xml(problem).locate(source.as_deref(), pos));
789 }
790
791 match ev {
792 Event::Eof => break,
793
794 Event::Start(e) => {
795 let next = self
796 .on_open(&e, false, ctx, &mut st, pos, stack.len())
797 .map_err(|err| err.locate(source.as_deref(), pos))?;
798 self.flush_attribute_findings(pos);
799 open.push(e.name().as_ref(), pos);
800 stack.push(ctx);
801 ctx = next;
802 }
803
804 Event::Empty(e) => {
805 let saved = ctx;
808 let entered = self
809 .on_open(&e, true, ctx, &mut st, pos, stack.len())
810 .map_err(|err| err.locate(source.as_deref(), pos))?;
811 self.flush_attribute_findings(pos);
812 self.close_scope(stack.len());
813 match entered {
814 Ctx::Object => self.stage(&mut st),
817 Ctx::Compound => self.close_compound(&mut st),
819 Ctx::DiffSubject => st.diff_subject = None,
820 Ctx::Header => self.adopt_header(&mut st),
822 _ => {}
823 }
824 ctx = saved;
825 root_closed |= stack.is_empty();
826 }
827
828 Event::Text(t) if ctx == Ctx::Text => {
830 if let Some(p) = st.pending.as_mut() {
831 let text = t.xml10_content();
834 p.text.push_str(&text);
835 }
836 }
837
838 Event::GeneralRef(r) if ctx == Ctx::Text => {
841 let mut undefined = None;
842 if let Some(p) = st.pending.as_mut() {
843 match r.resolve_char_ref() {
844 Ok(Some(c)) => p.text.push(c),
846 Ok(None) | Err(_) => {
849 let name = r.as_ref();
850 match quick_xml::escape::resolve_predefined_entity(name) {
851 Some(text) => p.text.push_str(text),
852 None => {
853 p.text.push('&');
854 p.text.push_str(name);
855 p.text.push(';');
856 undefined = Some(name.to_owned());
857 }
858 }
859 }
860 }
861 }
862 if let Some(name) = undefined {
863 self.diag(undefined_entity(&name), pos);
864 }
865 }
866
867 Event::CData(t) if ctx == Ctx::Text => {
868 if let Some(p) = st.pending.as_mut() {
869 p.text.push_str(&t);
870 }
871 }
872
873 Event::End(_) => {
874 match ctx {
875 Ctx::Header => self.adopt_header(&mut st),
877 Ctx::Text => {
879 if let Some(p) = st.pending.take() {
880 self.finish_text(p, &mut st);
881 }
882 }
883 Ctx::Object => self.stage(&mut st),
884 Ctx::Compound => self.close_compound(&mut st),
885 Ctx::DiffSubject => st.diff_subject = None,
886 _ => {}
887 }
888 ctx = stack.pop().unwrap_or(Ctx::Outside);
889 self.close_scope(stack.len());
890 open.pop();
891 root_closed |= stack.is_empty();
892 }
893
894 _ => {}
895 }
896 buf.clear();
897
898 if self.header_only && st.header.is_some() && ctx == Ctx::Body {
900 break;
901 }
902 }
903
904 if !self.header_only
906 && let Some((name, start)) = open.innermost()
907 {
908 return Err(Error::Truncated {
909 open: Some(name),
910 source,
911 position: start,
912 });
913 }
914 if !st.saw_root {
915 return Err(Error::NotCimXml {
916 message: "no rdf:RDF root element found".to_owned(),
917 source,
918 position: None,
919 });
920 }
921
922 let mut header = st.header;
923 let mut difference = st.difference;
924 if let Some(d) = difference.as_mut()
925 && let Some(h) = header.clone()
926 {
927 d.header = h;
928 }
929 if let Some(h) = header.as_mut()
930 && h.source.is_none()
931 {
932 h.source = self.source.clone();
933 }
934
935 let objects_read = st.staged.len();
938 if let Some(ds) = dataset {
939 let slot = ds.push_header(self.slot_header(header.as_ref()));
941 let mut doc = DocumentObjects {
942 base: ds.slot_count(),
943 created: Vec::with_capacity(st.staged.len()),
944 merged: HashMap::new(),
945 };
946 for s in st.staged {
947 self.commit(s, &mut st.staged_seen, &mut doc, slot, ds);
948 }
949 if let Some(d) = difference.as_ref() {
952 ds.push_difference(d.clone());
953 }
954 }
955
956 Ok(ReadOutcome {
957 header,
958 difference,
959 report: std::mem::take(&mut self.report),
960 objects_read,
961 })
962 }
963
964 fn check_vintage(&mut self, pos: u64) {
967 let declared: Vec<&str> = self.ns.iter().map(|(.., iri)| iri.as_str()).collect();
968 let Some(actual) = Schema::detect(declared.iter().copied()) else {
970 return;
971 };
972 if std::ptr::eq(actual, self.schema) {
973 return;
974 }
975 self.diag(
976 Diagnostic::error(
977 Rule::WrongVintage,
978 format!(
979 "this document is {} and is being read as {}; nothing in it will \
980 resolve. Use `{}::SCHEMA`, or `reader::sniff` to detect it",
981 actual.vintage, self.schema.vintage, actual.vintage
982 ),
983 ),
984 pos,
985 );
986 }
987
988 fn slot_header(&self, header: Option<&ModelHeader>) -> ModelHeader {
992 let mut h = header.cloned().unwrap_or_else(|| {
993 let mut h = ModelHeader::new(ModelKind::Full);
994 h.source = self.source.clone();
995 h
996 });
997 if h.profiles.is_empty()
998 && let Some(p) = self.options.assume_profile
999 {
1000 h.profiles
1001 .push(self.schema.profile(p).version_iri.to_owned());
1002 }
1003 h
1004 }
1005
1006 fn adopt_header(&mut self, st: &mut State) {
1008 let Some(h) = st.header.as_ref() else { return };
1009 let declared = h
1010 .profiles
1011 .iter()
1012 .filter_map(|iri| self.schema.profile_by_iri(iri))
1013 .fold(0, |acc, p| acc | p.mask());
1014 if declared != 0 {
1015 st.profile_mask = declared;
1016 }
1017 }
1018
1019 fn stage(&mut self, st: &mut State) {
1021 let Some(mut object) = st.object.take() else {
1022 return;
1023 };
1024 object.mark_profile(st.profile_mask);
1025 let from = st.staged_seen.len() as u32;
1026 st.staged_seen.extend_from_slice(&st.seen);
1027 st.staged.push(Staged {
1028 object,
1029 start: st.object_start,
1030 defined: st.object_defined,
1031 seen: from..st.staged_seen.len() as u32,
1032 });
1033 }
1034
1035 fn close_compound(&mut self, st: &mut State) {
1037 let Some(frame) = st.compounds.pop() else {
1038 return;
1039 };
1040 let value = Value::Compound(Box::new(frame.compound));
1041 self.store(st, frame.attr, value, frame.start);
1042 }
1043
1044 fn store(&mut self, st: &mut State, attr: AttrId, value: Value, pos: u64) {
1050 let many = self.schema.attr(attr).mult.is_many();
1051 if !many {
1052 let seen = match st.compounds.last_mut() {
1053 Some(frame) => &mut frame.seen,
1054 None => &mut st.seen,
1055 };
1056 match seen.iter().find(|(a, _)| *a == attr) {
1057 Some(&(_, first)) => self.report_repeat(st, attr, &value, first, pos),
1058 None => seen.push((attr, pos)),
1059 }
1060 }
1061 let mask = st.profile_mask;
1062 match st.compounds.last_mut() {
1063 Some(frame) if many => frame.compound.push(attr, value),
1064 Some(frame) => frame.compound.set(attr, value),
1065 None => {
1066 if let Some(obj) = st.object.as_mut() {
1067 if many {
1068 obj.push_in(mask, attr, value);
1069 } else {
1070 obj.set_in(mask, attr, value);
1071 }
1072 }
1073 }
1074 }
1075 }
1076
1077 #[cold]
1078 fn report_repeat(&mut self, st: &State, attr: AttrId, value: &Value, first: u64, pos: u64) {
1079 let earlier = match st.compounds.last() {
1080 Some(frame) => frame.compound.get(attr),
1081 None => st.object.as_ref().and_then(|o| o.get(attr)),
1082 };
1083 let Some(earlier) = earlier else { return };
1084 let schema = self.schema;
1085 let mut d = repeat_finding(schema, attr, earlier, value, first);
1086 if let Some(o) = st.object.as_ref() {
1087 d = d
1088 .with_class(schema.class(o.class()).name)
1089 .with_object(o.mrid().clone());
1090 }
1091 self.diag(d, pos);
1092 }
1093
1094 fn commit(
1100 &mut self,
1101 s: Staged,
1102 seen: &mut [(AttrId, u64)],
1103 doc: &mut DocumentObjects,
1104 slot: usize,
1105 ds: &mut Dataset,
1106 ) {
1107 let Some(id) = ds.find(s.object.mrid()) else {
1108 doc.created.push(Described::new(&s));
1109 let mut object = s.object;
1110 object.from_file = true;
1111 object.shrink_for_load();
1112 let id = ds.insert_new(object);
1113 ds.record_source(slot, id);
1114 return;
1115 };
1116 if let Some(held) = doc.get_mut(id) {
1117 self.redescribe(ds, id, held, s, seen);
1118 return;
1119 }
1120 let described = Described::new(&s);
1121 let mut object = s.object;
1122 object.from_file = true;
1123 object.shrink_for_load();
1124 if let Some(existing) = ds.get(id) {
1125 let (incoming, held) = (object.class(), existing.class());
1126 if !self.schema.is_a(incoming, held) && !self.schema.is_a(held, incoming) {
1127 let d = Diagnostic::error(
1128 Rule::DuplicateMrid,
1129 format!(
1130 "identifier {} is used by both {} and {}, which are unrelated classes",
1131 object.mrid().canonical(),
1132 self.schema.class(held).name,
1133 self.schema.class(incoming).name
1134 ),
1135 )
1136 .with_class(self.schema.class(incoming).name)
1137 .with_object(object.mrid().clone());
1138 self.diag(d, s.start);
1139 }
1140 }
1141 for c in ds.absorb(id, object) {
1142 ds.record_conflict(c);
1143 }
1144 doc.merged.insert(id.index() as u32, described);
1145 ds.record_source(slot, id);
1146 }
1147
1148 #[cold]
1152 fn redescribe(
1153 &mut self,
1154 ds: &mut Dataset,
1155 id: ObjectId,
1156 held: &mut Described,
1157 s: Staged,
1158 seen: &mut [(AttrId, u64)],
1159 ) {
1160 let schema = self.schema;
1161 let Some(current) = ds.get(id) else { return };
1162 let (held_class, class) = (current.class(), s.object.class());
1163 let name = schema.class(class).name;
1164 let mrid = s.object.mrid();
1165 let first = held.start;
1166 let twice = if s.defined && held.defined {
1167 Some(format!(
1168 "{} is defined again with rdf:ID; first defined at byte {first}",
1169 mrid.canonical()
1170 ))
1171 } else if !schema.is_a(class, held_class) && !schema.is_a(held_class, class) {
1172 Some(format!(
1173 "{} is described as {} at byte {first} and again as {name}, which are \
1174 unrelated classes",
1175 mrid.canonical(),
1176 schema.class(held_class).name
1177 ))
1178 } else if self.options.single_description {
1179 Some(format!(
1180 "{} is described again; first described at byte {first}",
1181 mrid.canonical()
1182 ))
1183 } else {
1184 None
1185 };
1186 if let Some(message) = twice {
1187 let d = Diagnostic::error(Rule::DuplicateMrid, message)
1188 .with_class(name)
1189 .with_object(mrid.clone())
1190 .with_related_position(first);
1191 self.diag(d, s.start);
1192 }
1193 let mut reported = Vec::new();
1196 for k in s.seen.clone() {
1197 let (attr, pos) = seen[k as usize];
1198 let (first_seen, more) = (
1199 &mut seen[held.seen.start as usize..held.seen.end as usize],
1200 &mut held.more,
1201 );
1202 let Some(entry) = first_seen
1203 .iter_mut()
1204 .chain(more.iter_mut())
1205 .find(|(a, _)| *a == attr)
1206 else {
1207 held.more.push((attr, pos));
1208 continue;
1209 };
1210 if let (Some(earlier), Some(later)) = (current.get(attr), s.object.get(attr)) {
1211 let d = repeat_finding(schema, attr, earlier, later, entry.1)
1212 .with_class(name)
1213 .with_object(mrid.clone());
1214 self.diag(d, pos);
1215 reported.push(attr);
1216 }
1217 entry.1 = pos;
1218 }
1219 held.defined |= s.defined;
1220 for c in ds.absorb(id, s.object) {
1222 if !reported.contains(&c.attr) {
1223 ds.record_conflict(c);
1224 }
1225 }
1226 }
1227
1228 fn on_open(
1230 &mut self,
1231 e: &BytesStart<'_>,
1232 self_closing: bool,
1233 ctx: Ctx,
1234 st: &mut State,
1235 pos: u64,
1236 depth: usize,
1237 ) -> Result<Ctx> {
1238 let qname = e.name();
1239 let qname = qname.as_ref();
1240
1241 if !st.saw_root || declares_namespace(e) {
1244 self.collect_namespaces(e, depth)?;
1245 }
1246 let resolves = st.saw_root
1248 && !self.header_only
1249 && match ctx {
1250 Ctx::Body => true,
1251 Ctx::Object => st.object.is_some(),
1252 Ctx::Compound => !st.compounds.is_empty(),
1253 _ => false,
1254 };
1255 if !resolves {
1256 self.check_prefix(qname, qname)?;
1257 }
1258 self.check_attribute_prefixes(e, qname)?;
1259 if !st.saw_root {
1260 if let Some((ns, local)) = self.expand(qname)
1261 && ns == RDF_NS
1262 && local == "RDF"
1263 {
1264 st.saw_root = true;
1265 self.check_vintage(pos);
1266 return Ok(Ctx::Body);
1267 }
1268 return Ok(ctx);
1270 }
1271
1272 match ctx {
1273 Ctx::Body => self.open_in_body(e, qname, st, pos),
1274 Ctx::Object => {
1275 let Some(obj) = st.object.as_ref() else {
1276 return Ok(Ctx::Skip);
1277 };
1278 let (class, mrid) = (obj.class(), obj.mrid());
1280 match self.property(e, self_closing, class, mrid, pos)? {
1281 Prop::Value(attr, value) => {
1282 self.store(st, attr, value, pos);
1283 Ok(Ctx::Skip)
1284 }
1285 Prop::Enter(attr, class) => {
1286 st.compounds.push(Frame::new(attr, class, pos));
1287 Ok(Ctx::Compound)
1288 }
1289 Prop::Text(attr) => {
1290 st.pending = Some(PendingText {
1291 target: TextTarget::Attr(attr),
1292 text: String::new(),
1293 start: pos,
1294 });
1295 Ok(Ctx::Text)
1296 }
1297 Prop::Skip => Ok(Ctx::Skip),
1298 }
1299 }
1300 Ctx::Compound => {
1301 let Some(top) = st.compounds.last() else {
1302 return Ok(Ctx::Skip);
1303 };
1304 let class = top.compound.class();
1305 let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1306 match self.property(e, self_closing, class, mrid, pos)? {
1307 Prop::Value(attr, value) => {
1308 self.store(st, attr, value, pos);
1309 Ok(Ctx::Skip)
1310 }
1311 Prop::Enter(attr, class) => {
1312 st.compounds.push(Frame::new(attr, class, pos));
1313 Ok(Ctx::Compound)
1314 }
1315 Prop::Text(attr) => {
1316 st.pending = Some(PendingText {
1317 target: TextTarget::Compound(attr),
1318 text: String::new(),
1319 start: pos,
1320 });
1321 Ok(Ctx::Text)
1322 }
1323 Prop::Skip => Ok(Ctx::Skip),
1324 }
1325 }
1326 Ctx::Header => self.open_in_header(e, qname, self_closing, st, pos),
1327 Ctx::DiffSet => {
1328 let about = self.attr(e, RDF_NS, "about")?;
1331 let defines = about.is_none();
1332 if let Some(raw) = about.or(self.attr(e, RDF_NS, "ID")?) {
1333 let class = self.expand(qname).and_then(|(ns, local)| {
1334 (!(ns == RDF_NS && local == "Description")).then(|| QualifiedName {
1335 ns: ns.to_owned(),
1336 local: local.to_owned(),
1337 })
1338 });
1339 st.diff_subject = Some((Mrid::parse(raw.trim()), class, defines));
1340 return Ok(Ctx::DiffSubject);
1341 }
1342 Ok(Ctx::Skip)
1343 }
1344 Ctx::DiffSubject => {
1345 let Some((ns, local)) = self
1346 .expand(qname)
1347 .map(|(n, l)| (n.to_owned(), l.to_owned()))
1348 else {
1349 return Ok(Ctx::Skip);
1350 };
1351 let Some((subject, class, defines_subject)) = st.diff_subject.clone() else {
1352 return Ok(Ctx::Skip);
1353 };
1354 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1355 let res = res.trim().to_owned();
1356 push_statement(
1357 &mut st.difference,
1358 st.diff_set,
1359 Statement {
1360 subject,
1361 class,
1362 defines_subject,
1363 predicate_ns: ns,
1364 predicate: local,
1365 value: StatementValue::Resource(res),
1366 },
1367 );
1368 return Ok(Ctx::Skip);
1369 }
1370 if self_closing {
1371 return Ok(Ctx::Skip);
1372 }
1373 st.pending = Some(PendingText {
1374 target: TextTarget::Statement {
1375 subject,
1376 class,
1377 defines_subject,
1378 ns,
1379 local,
1380 set: st.diff_set,
1381 },
1382 text: String::new(),
1383 start: pos,
1384 });
1385 Ok(Ctx::Text)
1386 }
1387 Ctx::Text => {
1389 let name = shown(qname);
1390 self.diag(
1391 Diagnostic::warning(
1392 Rule::Structure,
1393 format!("unexpected element <{name}> inside a value; skipped"),
1394 ),
1395 pos,
1396 );
1397 Ok(Ctx::Skip)
1398 }
1399 Ctx::Skip | Ctx::Outside => Ok(Ctx::Skip),
1400 }
1401 }
1402
1403 fn open_in_body(
1405 &mut self,
1406 e: &BytesStart<'_>,
1407 qname: &str,
1408 st: &mut State,
1409 pos: u64,
1410 ) -> Result<Ctx> {
1411 if let Some((ns, local)) = self.expand(qname)
1412 && ((ns == MD_NS && local == "FullModel")
1413 || (ns == DM_NS && local == "DifferenceModel"))
1414 {
1415 let kind = if ns == DM_NS {
1416 ModelKind::Difference
1417 } else {
1418 ModelKind::Full
1419 };
1420 let mut h = ModelHeader::new(kind);
1421 h.id = self
1422 .attr(e, RDF_NS, "about")?
1423 .map(|s| Mrid::parse(s.trim()));
1424 h.source = self.source.clone();
1425 st.header = Some(h);
1426 if kind == ModelKind::Difference {
1427 st.difference = Some(DifferenceModel::default());
1428 }
1429 return Ok(Ctx::Header);
1430 }
1431
1432 if self.header_only {
1433 return Ok(Ctx::Skip);
1434 }
1435
1436 match self.resolve(qname)? {
1437 Resolved::Class(class) => {
1438 let def = self.schema.class(class);
1439 if def.compound {
1441 self.diag(
1442 Diagnostic::error(
1443 Rule::Structure,
1444 format!(
1445 "compound type {} has no identity and cannot be a top-level object",
1446 def.name
1447 ),
1448 )
1449 .with_class(def.name),
1450 pos,
1451 );
1452 return Ok(Ctx::Skip);
1453 }
1454 if !def.concrete {
1455 self.diag(
1456 Diagnostic::error(
1457 Rule::AbstractInstantiated,
1458 format!("abstract class {} instantiated", def.name),
1459 )
1460 .with_class(def.name),
1461 pos,
1462 );
1463 }
1464 if self.options.report_deprecated && def.deprecated {
1465 self.diag(
1466 Diagnostic::info(
1467 Rule::Deprecated,
1468 format!("deprecated class {}", def.name),
1469 )
1470 .with_class(def.name),
1471 pos,
1472 );
1473 }
1474 let (mrid, defined) = self.object_identity(e, def.name, pos)?;
1475 let mut o = Object::new(class, mrid);
1476 o.mark_profile(st.profile_mask);
1477 st.object = Some(o);
1478 st.object_start = pos;
1479 st.object_defined = defined;
1480 st.seen.clear();
1481 Ok(Ctx::Object)
1482 }
1483 Resolved::Attr(_) | Resolved::Unknown => {
1484 let name = shown(qname);
1485 if self.options.strictness == Strictness::Strict {
1486 return Err(Error::not_cim(format!("unknown class element <{name}>")));
1487 }
1488 self.diag(
1489 Diagnostic::warning(
1490 Rule::UnknownClass,
1491 format!("unknown class element <{name}>, skipped"),
1492 ),
1493 pos,
1494 );
1495 Ok(Ctx::Skip)
1496 }
1497 }
1498 }
1499
1500 fn open_in_header(
1502 &mut self,
1503 e: &BytesStart<'_>,
1504 qname: &str,
1505 self_closing: bool,
1506 st: &mut State,
1507 pos: u64,
1508 ) -> Result<Ctx> {
1509 let Some((ns, local)) = self
1510 .expand(qname)
1511 .map(|(n, l)| (n.to_owned(), l.to_owned()))
1512 else {
1513 return Ok(Ctx::Skip);
1514 };
1515 let set = match (ns == DM_NS, local.as_str()) {
1517 (true, "forwardDifferences") => Some(DiffSet::Forward),
1518 (true, "reverseDifferences") => Some(DiffSet::Reverse),
1519 (true, "preconditions") => Some(DiffSet::Preconditions),
1520 _ => None,
1521 };
1522 if let Some(set) = set {
1523 st.diff_set = set;
1524 if st.difference.is_none() {
1525 st.difference = Some(DifferenceModel::default());
1526 }
1527 return Ok(Ctx::DiffSet);
1528 }
1529 let prefix = prefix_of(qname);
1530 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1531 let res = res.trim().to_owned();
1532 apply_header_resource(&mut st.header, &prefix, &ns, &local, res);
1533 return Ok(Ctx::Skip);
1534 }
1535 if self_closing {
1536 return Ok(Ctx::Skip);
1537 }
1538 st.pending = Some(PendingText {
1539 target: TextTarget::Header { prefix, ns, local },
1540 text: String::new(),
1541 start: pos,
1542 });
1543 Ok(Ctx::Text)
1544 }
1545
1546 fn property(
1548 &mut self,
1549 e: &BytesStart<'_>,
1550 self_closing: bool,
1551 class: ClassId,
1552 owner: &Mrid,
1553 pos: u64,
1554 ) -> Result<Prop> {
1555 let qname = e.name();
1556 let qname = qname.as_ref();
1557 let Resolved::Attr(attr) = self.resolve(qname)? else {
1558 let name = shown(qname);
1559 if self.options.strictness == Strictness::Strict {
1560 return Err(Error::not_cim(format!("unknown property element <{name}>")));
1561 }
1562 self.diag(
1563 Diagnostic::warning(
1564 Rule::UnknownAttribute,
1565 format!("unknown property <{name}>, skipped"),
1566 )
1567 .with_object(owner.clone()),
1568 pos,
1569 );
1570 return Ok(Prop::Skip);
1571 };
1572
1573 let def = self.schema.attr(attr);
1574 if !self.schema.is_a(class, def.owner) {
1576 self.diag(
1577 Diagnostic::warning(
1578 Rule::UnknownAttribute,
1579 format!(
1580 "{} does not apply to class {}",
1581 def.name,
1582 self.schema.class(class).name
1583 ),
1584 )
1585 .with_attribute(def.name)
1586 .with_object(owner.clone()),
1587 pos,
1588 );
1589 return Ok(Prop::Skip);
1590 }
1591 if self.options.report_deprecated && def.deprecated {
1592 self.diag(
1593 Diagnostic::info(
1594 Rule::Deprecated,
1595 format!("deprecated attribute {}", def.name),
1596 )
1597 .with_attribute(def.name),
1598 pos,
1599 );
1600 }
1601
1602 if let AttrKind::Compound(target) = def.kind {
1604 if self.attr(e, RDF_NS, "resource")?.is_some() {
1605 self.diag(
1606 Diagnostic::error(
1607 Rule::InvalidValue,
1608 format!(
1609 "{} holds a compound, which has no identity, but is written as \
1610 a reference",
1611 def.name
1612 ),
1613 )
1614 .with_attribute(def.name)
1615 .with_object(owner.clone()),
1616 pos,
1617 );
1618 return Ok(Prop::Skip);
1619 }
1620 return Ok(Prop::Enter(attr, target));
1621 }
1622
1623 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1624 let res = res.trim();
1625 return Ok(match self.resource_value(attr, res, owner, pos) {
1626 Some(v) => Prop::Value(attr, v),
1627 None => Prop::Skip,
1628 });
1629 }
1630 if self_closing {
1631 if matches!(def.kind, AttrKind::Primitive(Primitive::String)) {
1633 return Ok(Prop::Value(attr, Value::Text("".into())));
1634 }
1635 return Ok(Prop::Skip);
1636 }
1637 Ok(Prop::Text(attr))
1638 }
1639
1640 fn object_identity(
1643 &mut self,
1644 e: &BytesStart<'_>,
1645 class: &'static str,
1646 pos: u64,
1647 ) -> Result<(Mrid, bool)> {
1648 for (name, raw) in [
1649 ("rdf:ID", self.attr(e, RDF_NS, "ID")?),
1650 ("rdf:about", self.attr(e, RDF_NS, "about")?),
1651 ] {
1652 let Some(raw) = raw else { continue };
1653 let raw = raw.trim();
1654 let m = Mrid::parse(raw);
1655 let unwritable_id = name == "rdf:ID" && !crate::xml::is_ncname(raw);
1658 if unwritable_id || (self.options.report_non_conforming_mrids && !m.is_conforming()) {
1661 let complaint = if unwritable_id {
1662 format!(
1663 "is not an XML NCName and so cannot be written back as one; repaired to {:?}",
1664 m.to_rdf_id()
1665 )
1666 } else if m.is_uuid() {
1667 format!(
1669 "is a UUID written without hyphens; IEC 61970-552 requires {:?}",
1670 m.canonical()
1671 )
1672 } else {
1673 "is not a UUID as IEC 61970-552 requires".to_owned()
1674 };
1675 self.diag(
1676 Diagnostic::warning(
1677 Rule::NonConformingMrid,
1678 format!("{name} {raw:?} {complaint}"),
1679 )
1680 .with_class(class),
1681 pos,
1682 );
1683 }
1684 return Ok((m, name == "rdf:ID"));
1685 }
1686 let placeholder = match &self.source {
1689 Some(src) => format!("no-identifier-{src}-{pos}"),
1690 None => format!("no-identifier-{pos}"),
1691 };
1692 self.diag(
1693 Diagnostic::error(
1694 Rule::Structure,
1695 format!("<{class}> has neither rdf:ID nor rdf:about; kept as {placeholder:?}"),
1696 )
1697 .with_class(class),
1698 pos,
1699 );
1700 Ok((Mrid::parse(&placeholder), false))
1701 }
1702
1703 fn resource_value(&mut self, attr: AttrId, res: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1705 let def = self.schema.attr(attr);
1706 let AttrKind::Enumeration(_) = def.kind else {
1707 return Some(Value::Reference(Mrid::parse(res)));
1708 };
1709 let Some((ns, local)) = res.rsplit_once('#') else {
1711 self.diag(
1712 Diagnostic::error(
1713 Rule::InvalidValue,
1714 format!("enumeration value {res:?} is not an IRI"),
1715 )
1716 .with_attribute(def.name),
1717 pos,
1718 );
1719 return None;
1720 };
1721 if let Some(v) = self.schema.find_enum_value(&format!("{ns}#"), local) {
1722 return Some(Value::Enum(v));
1723 }
1724 match self.schema.find_enum_value_any_ns(local) {
1727 Some(v) => {
1728 let correct = self.schema.namespace(self.schema.enum_value(v).ns).iri;
1729 self.diag(
1730 Diagnostic::warning(
1731 Rule::InvalidValue,
1732 format!(
1733 "enumeration literal {local} is written in namespace {ns}# but is \
1734 declared in {correct}; value recovered"
1735 ),
1736 )
1737 .with_attribute(def.name)
1738 .with_object(owner.clone()),
1739 pos,
1740 );
1741 Some(Value::Enum(v))
1742 }
1743 None => {
1744 self.diag(
1745 Diagnostic::error(
1746 Rule::InvalidValue,
1747 format!("unknown enumeration literal {res:?}"),
1748 )
1749 .with_attribute(def.name)
1750 .with_object(owner.clone()),
1751 pos,
1752 );
1753 None
1754 }
1755 }
1756 }
1757
1758 fn finish_text(&mut self, mut p: PendingText, st: &mut State) {
1760 let pos = p.start;
1761 if let Some((offset, c)) = crate::xml::find_illegal(&p.text) {
1764 self.diag(
1765 Diagnostic::warning(
1766 Rule::IllegalXmlCharacter,
1767 format!(
1768 "value holds {}, which XML 1.0 cannot represent in any form; \
1769 removed (first at byte {offset} of the value)",
1770 crate::xml::describe_char(c)
1771 ),
1772 ),
1773 pos,
1774 );
1775 p.text = crate::xml::strip_illegal(&p.text).into_owned();
1776 }
1777 match p.target {
1778 TextTarget::Attr(attr) => {
1779 let Some(obj) = st.object.as_ref() else {
1780 return;
1781 };
1782 if let Some(v) = self.parse_text(attr, &p.text, obj.mrid(), pos) {
1783 self.store(st, attr, v, pos);
1784 }
1785 }
1786 TextTarget::Compound(attr) => {
1787 let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1788 if let Some(v) = self.parse_text(attr, &p.text, mrid, pos)
1789 && !st.compounds.is_empty()
1790 {
1791 self.store(st, attr, v, pos);
1792 }
1793 }
1794 TextTarget::Header { prefix, ns, local } => {
1795 apply_header_text(&mut st.header, &prefix, &ns, &local, p.text);
1796 }
1797 TextTarget::Statement {
1798 subject,
1799 class,
1800 defines_subject,
1801 ns,
1802 local,
1803 set,
1804 } => push_statement(
1805 &mut st.difference,
1806 set,
1807 Statement {
1808 subject,
1809 class,
1810 defines_subject,
1811 predicate_ns: ns,
1812 predicate: local,
1813 value: StatementValue::Literal(p.text),
1814 },
1815 ),
1816 }
1817 }
1818
1819 fn parse_text(&mut self, attr: AttrId, text: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1820 let def = self.schema.attr(attr);
1821 let prim = match def.kind {
1822 AttrKind::Primitive(prim) => prim,
1823 AttrKind::Datatype(dt) => self.schema.datatype(dt).value,
1824 AttrKind::Enumeration(_) | AttrKind::Association { .. } | AttrKind::Compound(_) => {
1827 Primitive::String
1828 }
1829 };
1830 match Value::parse_primitive(prim, text) {
1831 Ok(v) => Some(v),
1832 Err(e) => {
1833 let name = def.name;
1834 self.diag(
1835 Diagnostic::error(Rule::InvalidValue, e.to_string())
1836 .with_attribute(name)
1837 .with_object(owner.clone()),
1838 pos,
1839 );
1840 None
1841 }
1842 }
1843 }
1844
1845 #[inline]
1847 fn namespace(&self, prefix: &str) -> Option<&str> {
1848 match self.ns.iter().rev().find(|(_, p, _)| **p == *prefix) {
1849 Some((.., iri)) => Some(iri),
1850 None => (prefix == "xml").then_some(XML_NS),
1851 }
1852 }
1853
1854 fn collect_namespaces(&mut self, e: &BytesStart<'_>, depth: usize) -> Result<()> {
1859 for attr in e.attributes().with_checks(false) {
1860 let attr = attr?;
1861 let key = attr.key.as_ref();
1862 let prefix = match key.strip_prefix("xmlns:") {
1863 Some(prefix) => prefix,
1864 None if key == "xmlns" => "",
1865 None => continue,
1866 };
1867 let value = self.attr_value(&attr)?.into_owned();
1868 check_binding(prefix, &value)?;
1869 self.ns.push((depth, prefix.into(), value));
1870 self.cache.clear();
1872 }
1873 Ok(())
1874 }
1875
1876 #[inline]
1878 fn close_scope(&mut self, depth: usize) {
1879 if self.ns.last().is_some_and(|(d, ..)| *d >= depth) {
1880 self.end_scope(depth);
1881 }
1882 }
1883
1884 #[cold]
1885 fn end_scope(&mut self, depth: usize) {
1886 let keep = self.ns.partition_point(|(d, ..)| *d < depth);
1887 self.ns.truncate(keep);
1888 self.cache.clear();
1889 }
1890
1891 #[inline]
1894 fn check_attribute_prefixes(&self, e: &BytesStart<'_>, qname: &str) -> Result<()> {
1895 let tag: &str = e;
1896 let mut spans = [(0, 0); 3];
1897 for attr in e.attributes().with_checks(false) {
1898 let attr = attr?;
1899 let key = attr.key.as_ref();
1900 let Some((prefix, local)) = key.split_once(':') else {
1901 continue;
1902 };
1903 if prefix == "xmlns" {
1904 continue;
1905 }
1906 match self.namespace(prefix) {
1907 Some(RDF_NS) => {
1908 if let (Some(i), Cow::Borrowed(value)) = (rdf_slot(local), &attr.value) {
1909 if spans[i] == (0, 0) {
1911 let at = value.as_ptr() as usize - tag.as_ptr() as usize;
1912 spans[i] = (at as u32, (at + value.len()) as u32 + 1);
1913 }
1914 }
1915 }
1916 Some(_) => {}
1917 None => return Err(unbound_prefix(prefix, key, qname)),
1918 }
1919 }
1920 self.rdf_spans.set(spans);
1921 Ok(())
1922 }
1923
1924 #[inline]
1927 fn check_prefix(&self, name: &str, element: &str) -> Result<()> {
1928 match name.split_once(':') {
1929 Some((prefix, _)) if self.namespace(prefix).is_none() => {
1930 Err(unbound_prefix(prefix, name, element))
1931 }
1932 _ => Ok(()),
1933 }
1934 }
1935
1936 fn attr<'e>(
1940 &self,
1941 e: &'e BytesStart<'_>,
1942 ns: &str,
1943 local: &str,
1944 ) -> Result<Option<Cow<'e, str>>> {
1945 if ns == RDF_NS
1946 && let Some(i) = rdf_slot(local)
1947 {
1948 let (start, end) = self.rdf_spans.get()[i];
1949 if end == 0 {
1950 return Ok(None);
1951 }
1952 let tag: &'e str = e;
1953 let attr = quick_xml::events::attributes::Attribute {
1954 key: quick_xml::name::QName(["rdf:ID", "rdf:about", "rdf:resource"][i]),
1955 value: Cow::Borrowed(&tag[start as usize..end as usize - 1]),
1956 };
1957 return self.attr_value(&attr).map(Some);
1958 }
1959 for attr in e.attributes().with_checks(false) {
1960 let attr = attr?;
1961 let key = attr.key.as_ref();
1962 let Some((prefix, name)) = key.split_once(':') else {
1963 continue;
1964 };
1965 if name != local {
1966 continue;
1967 }
1968 if self.namespace(prefix) != Some(ns) {
1969 continue;
1970 }
1971 return Ok(Some(self.attr_value(&attr)?));
1972 }
1973 Ok(None)
1974 }
1975}
1976
1977fn parse_error(
1983 e: quick_xml::Error,
1984 at: u64,
1985 at_end: bool,
1986 open: &OpenElements,
1987 source: &Option<String>,
1988) -> Error {
1989 use quick_xml::errors::{IllFormedError, SyntaxError};
1990 match e {
1991 quick_xml::Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
1992 quick_xml::Error::Syntax(s) if !matches!(s, SyntaxError::InvalidBangMarkup) => {
1993 Error::Truncated {
1994 open: open.innermost().map(|(name, _)| name),
1995 source: source.clone(),
1996 position: at,
1997 }
1998 }
1999 quick_xml::Error::IllFormed(IllFormedError::UnclosedReference) if at_end => {
2000 Error::Truncated {
2001 open: open.innermost().map(|(name, _)| name),
2002 source: source.clone(),
2003 position: at,
2004 }
2005 }
2006 quick_xml::Error::IllFormed(IllFormedError::UnclosedReference) => Error::xml(
2007 "a `&` that starts no entity or character reference; a literal ampersand is \
2008 written `&`",
2009 )
2010 .locate(source.as_deref(), at),
2011 quick_xml::Error::IllFormed(e) => {
2014 Error::xml(shown(&e.to_string())).locate(source.as_deref(), at)
2015 }
2016 other => Error::xml(shown(&other.to_string())).locate(source.as_deref(), at),
2017 }
2018}
2019
2020fn outside_document(ev: &Event<'_>, root_closed: bool) -> Option<&'static str> {
2023 match ev {
2024 Event::Start(_) | Event::Empty(_) if root_closed => {
2025 Some("a second document element; XML allows exactly one")
2026 }
2027 Event::Text(t)
2028 if !t
2029 .as_ref()
2030 .bytes()
2031 .all(|b| matches!(b, b' ' | b'\t' | b'\r' | b'\n')) =>
2032 {
2033 Some("text outside the document element")
2034 }
2035 Event::CData(_) | Event::GeneralRef(_) => Some("text outside the document element"),
2036 _ => None,
2037 }
2038}
2039
2040fn shown(text: &str) -> Cow<'_, str> {
2044 if text.chars().any(char::is_control) {
2045 Cow::Owned(
2046 text.chars()
2047 .map(|c| {
2048 if c.is_control() {
2049 c.escape_default().to_string()
2050 } else {
2051 c.to_string()
2052 }
2053 })
2054 .collect(),
2055 )
2056 } else {
2057 Cow::Borrowed(text)
2058 }
2059}
2060
2061fn undefined_entity(name: &str) -> Diagnostic {
2063 Diagnostic::warning(
2064 Rule::InvalidValue,
2065 format!(
2066 "undefined entity &{name}; kept as text: CIM/XML documents declare no DTD, so \
2067 only the five predefined entities and character references are expanded"
2068 ),
2069 )
2070}
2071
2072fn escape_undefined_entities(raw: &str) -> (String, Vec<String>) {
2075 let mut out = String::with_capacity(raw.len() + 8);
2076 let mut names = Vec::new();
2077 let mut rest = raw;
2078 while let Some(at) = rest.find('&') {
2079 out.push_str(&rest[..at]);
2080 let after = &rest[at + 1..];
2081 let name = after.split_once(';').map(|(n, _)| n);
2082 match name {
2083 Some(n)
2084 if !n.starts_with('#')
2085 && quick_xml::escape::resolve_predefined_entity(n).is_none() =>
2086 {
2087 out.push_str("&");
2088 names.push(n.to_owned());
2089 }
2090 _ => out.push('&'),
2091 }
2092 rest = after;
2093 }
2094 out.push_str(rest);
2095 (out, names)
2096}
2097
2098#[inline]
2100fn rdf_slot(local: &str) -> Option<usize> {
2101 match local {
2102 "ID" => Some(0),
2103 "about" => Some(1),
2104 "resource" => Some(2),
2105 _ => None,
2106 }
2107}
2108
2109#[cold]
2110fn unbound_prefix(prefix: &str, name: &str, element: &str) -> Error {
2111 let what = if name == element {
2112 String::new()
2113 } else {
2114 format!(" of attribute {}", shown(name))
2115 };
2116 Error::xml(format!(
2117 "prefix {}{what} on <{}> is not declared",
2118 shown(prefix),
2119 shown(element)
2120 ))
2121}
2122
2123fn check_binding(prefix: &str, iri: &str) -> Result<()> {
2126 let problem = if prefix == "xmlns" {
2127 "the prefix xmlns cannot be declared"
2128 } else if prefix == "xml" && iri != XML_NS {
2129 "the prefix xml cannot be bound to another namespace"
2130 } else if prefix != "xml" && iri == XML_NS {
2131 "only the prefix xml can be bound to the XML namespace"
2132 } else if iri == XMLNS_NS {
2133 "the xmlns namespace cannot be bound"
2134 } else if !prefix.is_empty() && iri.is_empty() {
2135 "a prefixed namespace declaration cannot be empty"
2136 } else {
2137 return Ok(());
2138 };
2139 let attr = if prefix.is_empty() {
2140 "xmlns".to_owned()
2141 } else {
2142 format!("xmlns:{}", shown(prefix))
2143 };
2144 Err(Error::xml(format!("{attr}: {problem}")))
2145}
2146
2147fn repeat_finding(
2150 schema: &Schema,
2151 attr: AttrId,
2152 earlier: &Value,
2153 later: &Value,
2154 first: u64,
2155) -> Diagnostic {
2156 let def = schema.attr(attr);
2157 let shown = |v| crate::value::display_value(schema, v);
2158 let d = if earlier == later {
2159 Diagnostic::warning(
2160 Rule::CardinalityExceeded,
2161 format!(
2162 "{} is given again with the same value {}, first at byte {first}; it permits one",
2163 def.name,
2164 shown(later)
2165 ),
2166 )
2167 } else {
2168 Diagnostic::error(
2169 Rule::ConflictingValue,
2170 format!(
2171 "{} is given twice: {} at byte {first}, then {}; the later is kept",
2172 def.name,
2173 shown(earlier),
2174 shown(later)
2175 ),
2176 )
2177 };
2178 d.with_attribute(def.name).with_related_position(first)
2179}
2180
2181fn declares_namespace(e: &BytesStart<'_>) -> bool {
2183 e.as_ref().contains("xmlns")
2184}
2185
2186fn prefix_of(qname: &str) -> String {
2188 match qname.split_once(':') {
2189 Some((prefix, _)) => prefix.to_owned(),
2190 None => String::new(),
2191 }
2192}
2193
2194fn apply_header_resource(
2196 header: &mut Option<ModelHeader>,
2197 prefix: &str,
2198 ns: &str,
2199 local: &str,
2200 res: String,
2201) {
2202 let Some(h) = header.as_mut() else { return };
2203 match (ns, local) {
2204 (MD_NS, "Model.DependentOn") => h.dependent_on.push(Mrid::parse(&res)),
2205 (MD_NS, "Model.Supersedes") => h.supersedes.push(Mrid::parse(&res)),
2206 (MD_NS, "Model.profile") => h.profiles.push(res),
2207 _ => h
2208 .extra
2209 .push(HeaderProperty::resource(prefix, ns, local, res)),
2210 }
2211}
2212
2213fn apply_header_text(
2215 header: &mut Option<ModelHeader>,
2216 prefix: &str,
2217 ns: &str,
2218 local: &str,
2219 text: String,
2220) {
2221 let Some(h) = header.as_mut() else { return };
2222 if ns != MD_NS {
2223 h.extra.push(HeaderProperty::text(prefix, ns, local, text));
2224 return;
2225 }
2226 match local {
2227 "Model.created" => h.created = Some(text),
2228 "Model.scenarioTime" => h.scenario_time = Some(text),
2229 "Model.description" => h.description = Some(text),
2230 "Model.version" => h.version = Some(text),
2231 "Model.modelingAuthoritySet" => h.modeling_authority_set = Some(text),
2232 "Model.profile" => h.profiles.push(text),
2233 "Model.DependentOn" => h.dependent_on.push(Mrid::parse(&text)),
2234 "Model.Supersedes" => h.supersedes.push(Mrid::parse(&text)),
2235 _ => h.extra.push(HeaderProperty::text(prefix, ns, local, text)),
2236 }
2237}
2238
2239#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2241enum DiffSet {
2242 Preconditions,
2243 #[default]
2244 Reverse,
2245 Forward,
2246}
2247
2248fn push_statement(difference: &mut Option<DifferenceModel>, set: DiffSet, s: Statement) {
2249 let d = difference.get_or_insert_with(DifferenceModel::default);
2250 match set {
2251 DiffSet::Preconditions => d.preconditions.push(s),
2252 DiffSet::Reverse => d.reverse.push(s),
2253 DiffSet::Forward => d.forward.push(s),
2254 }
2255}
2256
2257struct PendingText {
2258 target: TextTarget,
2259 text: String,
2260 start: u64,
2262}
2263
2264enum TextTarget {
2265 Attr(AttrId),
2267 Compound(AttrId),
2269 Header {
2271 prefix: String,
2272 ns: String,
2273 local: String,
2274 },
2275 Statement {
2277 subject: Mrid,
2278 class: Option<QualifiedName>,
2279 defines_subject: bool,
2280 ns: String,
2281 local: String,
2282 set: DiffSet,
2283 },
2284}