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;
17use crate::error::{Diagnostic, Error, Report, Result, Rule};
18use crate::header::{
19 DM_NS, DifferenceModel, HeaderProperty, MD_NS, ModelHeader, ModelKind, QualifiedName,
20 Statement, StatementValue,
21};
22use crate::mrid::Mrid;
23use crate::object::{Compound, Object};
24use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileId, ProfileMask, Schema};
25use crate::value::Value;
26
27const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
28
29static UNKNOWN_MRID: Mrid = Mrid::nil();
31
32#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
34pub enum Strictness {
35 #[default]
39 Lenient,
40 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,
61 pub max_input_bytes: u64,
69}
70
71impl Default for ReadOptions {
72 fn default() -> Self {
73 ReadOptions {
74 strictness: Strictness::Lenient,
75 assume_profile: None,
76 report_deprecated: false,
77 report_non_conforming_mrids: false,
78 max_diagnostics: ReadOptions::DEFAULT_MAX_DIAGNOSTICS,
79 max_input_bytes: ReadOptions::DEFAULT_MAX_INPUT_BYTES,
80 }
81 }
82}
83
84impl ReadOptions {
85 pub const DEFAULT_MAX_DIAGNOSTICS: usize = 10_000;
87
88 pub const DEFAULT_MAX_INPUT_BYTES: u64 = 8 << 30;
93
94 pub fn lenient() -> ReadOptions {
96 ReadOptions::default()
97 }
98
99 pub fn strict() -> ReadOptions {
101 ReadOptions {
102 strictness: Strictness::Strict,
103 report_deprecated: true,
104 report_non_conforming_mrids: true,
105 ..ReadOptions::default()
106 }
107 }
108
109 pub fn with_profile(mut self, profile: ProfileId) -> Self {
110 self.assume_profile = Some(profile);
111 self
112 }
113
114 pub fn with_max_diagnostics(mut self, max: usize) -> Self {
116 self.max_diagnostics = max;
117 self
118 }
119
120 pub fn with_max_input_bytes(mut self, max: u64) -> Self {
122 self.max_input_bytes = max;
123 self
124 }
125}
126
127#[derive(Debug)]
132pub(crate) struct Budget {
133 limit: u64,
134 used: Cell<u64>,
135 tripped: Cell<bool>,
136}
137
138impl Budget {
139 pub(crate) fn new(options: &ReadOptions) -> Budget {
140 Budget {
141 limit: options.max_input_bytes,
142 used: Cell::new(0),
143 tripped: Cell::new(false),
144 }
145 }
146
147 pub(crate) fn meter<R: BufRead>(&self, input: R) -> Metered<'_, R> {
149 Metered {
150 inner: input,
151 used: self.used.get(),
152 limit: if self.limit == 0 {
154 u64::MAX
155 } else {
156 self.limit
157 },
158 budget: self,
159 }
160 }
161
162 pub(crate) fn check<T>(&self, result: Result<T>, source: Option<&str>) -> Result<T> {
167 match result {
168 Err(_) if self.tripped.get() => Err(Error::InputTooLarge {
169 limit: self.limit,
170 read: self.used.get(),
171 source: source.map(str::to_owned),
172 }),
173 other => other,
174 }
175 }
176
177 pub(crate) fn tripped(&self) -> bool {
178 self.tripped.get()
179 }
180}
181
182pub(crate) struct Metered<'a, R> {
187 inner: R,
188 used: u64,
189 limit: u64,
190 budget: &'a Budget,
191}
192
193impl<R> Drop for Metered<'_, R> {
194 fn drop(&mut self) {
195 self.budget.used.set(self.used);
196 }
197}
198
199impl<R: BufRead> Read for Metered<'_, R> {
200 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
201 let available = self.fill_buf()?;
202 let n = available.len().min(out.len());
203 out[..n].copy_from_slice(&available[..n]);
204 self.consume(n);
205 Ok(n)
206 }
207}
208
209impl<R: BufRead> BufRead for Metered<'_, R> {
210 #[inline]
211 fn fill_buf(&mut self) -> io::Result<&[u8]> {
212 if self.used > self.limit {
213 self.budget.tripped.set(true);
214 self.budget.used.set(self.used);
215 return Err(io::Error::other("input budget exceeded"));
216 }
217 let room = self.limit - self.used;
220 let buf = self.inner.fill_buf()?;
221 Ok(match usize::try_from(room) {
222 Ok(room) if room < buf.len() => &buf[..=room],
223 _ => buf,
224 })
225 }
226
227 #[inline]
228 fn consume(&mut self, amt: usize) {
229 self.used = self.used.saturating_add(amt as u64);
230 self.inner.consume(amt);
231 }
232}
233
234const SNIFF_PREFIX: u64 = 1 << 20;
236
237#[derive(Debug)]
239pub struct ReadOutcome {
240 pub header: Option<ModelHeader>,
241 pub difference: Option<DifferenceModel>,
243 pub report: Report,
244 pub objects_read: usize,
246}
247
248pub fn read_into<R: BufRead>(
260 dataset: &mut Dataset,
261 input: R,
262 source: Option<&str>,
263 options: &ReadOptions,
264) -> Result<ReadOutcome> {
265 let budget = Budget::new(options);
266 read_into_within(dataset, input, source, options, &budget)
267}
268
269pub(crate) fn read_into_within<R: BufRead>(
271 dataset: &mut Dataset,
272 input: R,
273 source: Option<&str>,
274 options: &ReadOptions,
275 budget: &Budget,
276) -> Result<ReadOutcome> {
277 let schema = dataset.schema();
278 let mut parser = Parser::new(schema, source, options, false);
279 let outcome = parser.run(budget.meter(input), Some(dataset));
280 budget.check(outcome, source)
281}
282
283pub fn read_header<R: BufRead>(
287 schema: &'static Schema,
288 input: R,
289 source: Option<&str>,
290) -> Result<Option<ModelHeader>> {
291 let options = ReadOptions::default();
292 let budget = Budget::new(&options);
293 let mut parser = Parser::new(schema, source, &options, true);
294 let outcome = parser.run(budget.meter(input), None);
295 Ok(budget.check(outcome, source)?.header)
296}
297
298pub fn sniff<R: BufRead>(input: R) -> Result<Option<&'static Schema>> {
315 let mut reader = Reader::from_reader(input.take(SNIFF_PREFIX));
316 reader.config_mut().check_end_names = false;
317 let mut buf = Vec::new();
318 loop {
319 let ev = match reader.read_event_into(&mut buf) {
320 Ok(ev) => ev,
321 Err(_) if reader.get_ref().limit() == 0 => return Ok(None),
324 Err(e) => {
325 return Err(Error::xml(shown(&e.to_string())).locate(None, reader.error_position()));
326 }
327 };
328 let e = match ev {
329 Event::Eof => return Ok(None),
330 Event::Start(e) | Event::Empty(e) => e,
331 _ => {
332 buf.clear();
333 continue;
334 }
335 };
336 let mut iris: Vec<String> = Vec::new();
339 for attr in e.attributes().with_checks(false) {
340 let attr = attr?;
341 let key = attr.key.as_ref();
342 if key == "xmlns" || key.starts_with("xmlns:") {
343 iris.push(attr.value.into_owned());
344 }
345 }
346 if let Some(schema) = Schema::detect(iris.iter().map(String::as_str)) {
347 return Ok(Some(schema));
348 }
349 buf.clear();
350 }
351}
352
353pub fn read_difference<R: BufRead>(
355 schema: &'static Schema,
356 input: R,
357 source: Option<&str>,
358 options: &ReadOptions,
359) -> Result<Option<DifferenceModel>> {
360 let budget = Budget::new(options);
361 let mut parser = Parser::new(schema, source, options, false);
362 let outcome = parser.run(budget.meter(input), None);
363 Ok(budget.check(outcome, source)?.difference)
364}
365
366#[derive(Clone, Copy)]
372enum Resolved {
373 Class(ClassId),
374 Attr(AttrId),
375 Unknown,
377}
378
379#[derive(Clone, Copy, PartialEq, Eq, Debug)]
381enum Ctx {
382 Outside,
384 Body,
386 Header,
388 Object,
390 Compound,
392 DiffSet,
394 DiffSubject,
396 Text,
401 Skip,
403}
404
405enum Prop {
407 Value(AttrId, Value),
409 Enter(AttrId, ClassId),
411 Text(AttrId),
413 Skip,
415}
416
417#[derive(Default)]
419struct State {
420 saw_root: bool,
421 header: Option<ModelHeader>,
422 difference: Option<DifferenceModel>,
423 staged: Vec<(Object, u64)>,
426 object: Option<Object>,
428 object_start: u64,
429 seen: Vec<(AttrId, u64)>,
431 compounds: Vec<Frame>,
434 pending: Option<PendingText>,
436 profile_mask: ProfileMask,
438 diff_subject: Option<(Mrid, Option<QualifiedName>, bool)>,
441 diff_set: DiffSet,
443}
444
445struct Frame {
448 attr: AttrId,
449 compound: Compound,
450 start: u64,
451 seen: Vec<(AttrId, u64)>,
452}
453
454impl Frame {
455 fn new(attr: AttrId, class: ClassId, start: u64) -> Frame {
456 Frame {
457 attr,
458 compound: Compound::new(class),
459 start,
460 seen: Vec::new(),
461 }
462 }
463}
464
465#[derive(Default)]
468struct OpenElements {
469 names: String,
470 open: Vec<(usize, u64)>,
471}
472
473impl OpenElements {
474 fn push(&mut self, qname: &str, start: u64) {
475 self.open.push((self.names.len(), start));
476 self.names.push_str(qname);
477 }
478
479 fn pop(&mut self) {
480 if let Some((at, _)) = self.open.pop() {
481 self.names.truncate(at);
482 }
483 }
484
485 fn innermost(&self) -> Option<(String, u64)> {
487 let &(at, start) = self.open.last()?;
488 Some((shown(&self.names[at..]).into_owned(), start))
489 }
490}
491
492struct Parser<'a> {
493 schema: &'static Schema,
494 options: &'a ReadOptions,
495 source: Option<String>,
496 report: Report,
497 header_only: bool,
498 truncated: bool,
500 ns: HashMap<Vec<u8>, String>,
502 cache: HashMap<Vec<u8>, Resolved>,
505 undefined_entities: RefCell<Vec<String>>,
509}
510
511impl<'a> Parser<'a> {
512 fn new(
513 schema: &'static Schema,
514 source: Option<&str>,
515 options: &'a ReadOptions,
516 header_only: bool,
517 ) -> Parser<'a> {
518 Parser {
519 schema,
520 options,
521 source: source.map(str::to_owned),
522 report: Report::default(),
523 header_only,
524 truncated: false,
525 ns: HashMap::new(),
526 cache: HashMap::new(),
527 undefined_entities: RefCell::new(Vec::new()),
528 }
529 }
530
531 #[inline]
534 fn flush_undefined_entities(&mut self, pos: u64) {
535 if !self.undefined_entities.get_mut().is_empty() {
536 self.report_undefined_entities(pos);
537 }
538 }
539
540 #[cold]
541 #[inline(never)]
542 fn report_undefined_entities(&mut self, pos: u64) {
543 let names = std::mem::take(self.undefined_entities.get_mut());
544 for name in names {
545 self.diag(undefined_entity(&name), pos);
546 }
547 }
548
549 fn attr_value<'e>(
552 &self,
553 attr: &quick_xml::events::attributes::Attribute<'e>,
554 ) -> Result<Cow<'e, str>> {
555 use quick_xml::escape::EscapeError;
556 match attr.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
557 Ok(v) => Ok(v),
558 Err(quick_xml::Error::Escape(EscapeError::UnrecognizedEntity(..))) => {
559 let (escaped, names) = escape_undefined_entities(&attr.value);
560 self.undefined_entities.borrow_mut().extend(names);
561 let rewritten = quick_xml::events::attributes::Attribute {
562 key: attr.key,
563 value: Cow::Owned(escaped),
564 };
565 let value = rewritten
566 .normalized_value(quick_xml::XmlVersion::Explicit1_0)
567 .map_err(|e| Error::xml(e.to_string()))?;
568 Ok(Cow::Owned(value.into_owned()))
569 }
570 Err(e) => Err(Error::xml(e.to_string())),
571 }
572 }
573
574 fn diag(&mut self, d: Diagnostic, pos: u64) {
575 let max = self.options.max_diagnostics;
576 if max != 0 && self.report.len() >= max {
577 if !self.truncated {
578 self.truncated = true;
579 self.report.push(Diagnostic::warning(
580 Rule::Structure,
581 format!(
582 "stopped recording after {max} diagnostics; reading continued \
583 (raise ReadOptions::max_diagnostics to see the rest)"
584 ),
585 ));
586 }
587 return;
588 }
589 let mut d = d.with_position(pos);
590 if let Some(s) = &self.source {
591 d = d.with_source(s.clone());
592 }
593 self.report.push(d);
594 }
595
596 fn expand<'q>(&self, qname: &'q str) -> Option<(&str, &'q str)> {
598 let (prefix, local) = match qname.split_once(':') {
599 Some((prefix, local)) => (prefix, local),
600 None => ("", qname),
601 };
602 let ns = self.ns.get(prefix.as_bytes())?;
603 Some((ns.as_str(), local))
604 }
605
606 fn resolve(&mut self, qname: &str) -> Resolved {
607 if let Some(r) = self.cache.get(qname.as_bytes()) {
608 return *r;
609 }
610 let resolved = match self.expand(qname) {
611 Some((ns, local)) if local.contains('.') => match self.schema.find_attr(ns, local) {
613 Some(a) => Resolved::Attr(a),
614 None => Resolved::Unknown,
615 },
616 Some((ns, local)) => match self.schema.find_class(ns, local) {
617 Some(c) => Resolved::Class(c),
618 None => Resolved::Unknown,
619 },
620 None => Resolved::Unknown,
621 };
622 self.cache.insert(qname.as_bytes().to_vec(), resolved);
623 resolved
624 }
625
626 fn run<R: BufRead>(&mut self, input: R, dataset: Option<&mut Dataset>) -> Result<ReadOutcome> {
627 let mut reader = Reader::from_reader(input);
628 reader.config_mut().trim_text(false);
629 reader.config_mut().expand_empty_elements = false;
630 reader.config_mut().check_end_names = true;
631
632 let source = self.source.clone();
633 let mut buf = Vec::new();
634 let mut ctx = Ctx::Outside;
635 let mut stack: Vec<Ctx> = Vec::with_capacity(8);
637 let mut open = OpenElements::default();
638 let mut root_closed = false;
639
640 let mut st = State {
641 profile_mask: self.options.assume_profile.map_or(0, |p| p.mask()),
642 ..Default::default()
643 };
644
645 loop {
646 let pos = reader.buffer_position();
648 let ev = match reader.read_event_into(&mut buf) {
649 Ok(ev) => ev,
650 Err(e) => {
651 let at_end = reader.get_mut().fill_buf().is_ok_and(<[u8]>::is_empty);
654 return Err(parse_error(
655 e,
656 reader.error_position(),
657 at_end,
658 &open,
659 &source,
660 ));
661 }
662 };
663 if stack.is_empty()
664 && let Some(problem) = outside_document(&ev, root_closed)
665 {
666 return Err(Error::xml(problem).locate(source.as_deref(), pos));
667 }
668
669 match ev {
670 Event::Eof => break,
671
672 Event::Start(e) => {
673 let next = self
674 .on_open(&e, false, ctx, &mut st, pos)
675 .map_err(|err| err.locate(source.as_deref(), pos))?;
676 self.flush_undefined_entities(pos);
677 open.push(e.name().as_ref(), pos);
678 stack.push(ctx);
679 ctx = next;
680 }
681
682 Event::Empty(e) => {
683 let saved = ctx;
686 let entered = self
687 .on_open(&e, true, ctx, &mut st, pos)
688 .map_err(|err| err.locate(source.as_deref(), pos))?;
689 self.flush_undefined_entities(pos);
690 match entered {
691 Ctx::Object => self.stage(&mut st),
694 Ctx::Compound => self.close_compound(&mut st),
696 Ctx::DiffSubject => st.diff_subject = None,
697 Ctx::Header => self.adopt_header(&mut st),
699 _ => {}
700 }
701 ctx = saved;
702 root_closed |= stack.is_empty();
703 }
704
705 Event::Text(t) if ctx == Ctx::Text => {
707 if let Some(p) = st.pending.as_mut() {
708 let text = t.xml10_content();
711 p.text.push_str(&text);
712 }
713 }
714
715 Event::GeneralRef(r) if ctx == Ctx::Text => {
718 let mut undefined = None;
719 if let Some(p) = st.pending.as_mut() {
720 match r.resolve_char_ref() {
721 Ok(Some(c)) => p.text.push(c),
723 Ok(None) | Err(_) => {
726 let name = r.as_ref();
727 match quick_xml::escape::resolve_predefined_entity(name) {
728 Some(text) => p.text.push_str(text),
729 None => {
730 p.text.push('&');
731 p.text.push_str(name);
732 p.text.push(';');
733 undefined = Some(name.to_owned());
734 }
735 }
736 }
737 }
738 }
739 if let Some(name) = undefined {
740 self.diag(undefined_entity(&name), pos);
741 }
742 }
743
744 Event::CData(t) if ctx == Ctx::Text => {
745 if let Some(p) = st.pending.as_mut() {
746 p.text.push_str(&t);
747 }
748 }
749
750 Event::End(_) => {
751 match ctx {
752 Ctx::Header => self.adopt_header(&mut st),
754 Ctx::Text => {
756 if let Some(p) = st.pending.take() {
757 self.finish_text(p, &mut st);
758 }
759 }
760 Ctx::Object => self.stage(&mut st),
761 Ctx::Compound => self.close_compound(&mut st),
762 Ctx::DiffSubject => st.diff_subject = None,
763 _ => {}
764 }
765 ctx = stack.pop().unwrap_or(Ctx::Outside);
766 open.pop();
767 root_closed |= stack.is_empty();
768 }
769
770 _ => {}
771 }
772 buf.clear();
773
774 if self.header_only && st.header.is_some() && ctx == Ctx::Body {
776 break;
777 }
778 }
779
780 if !self.header_only
782 && let Some((name, start)) = open.innermost()
783 {
784 return Err(Error::Truncated {
785 open: Some(name),
786 source,
787 position: start,
788 });
789 }
790 if !st.saw_root {
791 return Err(Error::NotCimXml {
792 message: "no rdf:RDF root element found".to_owned(),
793 source,
794 position: None,
795 });
796 }
797
798 let mut header = st.header;
799 let mut difference = st.difference;
800 if let Some(d) = difference.as_mut()
801 && let Some(h) = header.clone()
802 {
803 d.header = h;
804 }
805 if let Some(h) = header.as_mut()
806 && h.source.is_none()
807 {
808 h.source = self.source.clone();
809 }
810
811 let objects_read = st.staged.len();
814 if let Some(ds) = dataset {
815 let slot = ds.push_header(self.slot_header(header.as_ref()));
817 for (object, pos) in st.staged {
818 self.commit(object, slot, ds, pos);
819 }
820 if let Some(d) = difference.as_ref() {
823 ds.push_difference(d.clone());
824 }
825 }
826
827 Ok(ReadOutcome {
828 header,
829 difference,
830 report: std::mem::take(&mut self.report),
831 objects_read,
832 })
833 }
834
835 fn check_vintage(&mut self, pos: u64) {
838 let declared: Vec<&str> = self.ns.values().map(String::as_str).collect();
839 let Some(actual) = Schema::detect(declared.iter().copied()) else {
841 return;
842 };
843 if std::ptr::eq(actual, self.schema) {
844 return;
845 }
846 self.diag(
847 Diagnostic::error(
848 Rule::WrongVintage,
849 format!(
850 "this document is {} and is being read as {}; nothing in it will \
851 resolve. Use `{}::SCHEMA`, or `reader::sniff` to detect it",
852 actual.vintage, self.schema.vintage, actual.vintage
853 ),
854 ),
855 pos,
856 );
857 }
858
859 fn slot_header(&self, header: Option<&ModelHeader>) -> ModelHeader {
863 let mut h = header.cloned().unwrap_or_else(|| {
864 let mut h = ModelHeader::new(ModelKind::Full);
865 h.source = self.source.clone();
866 h
867 });
868 if h.profiles.is_empty()
869 && let Some(p) = self.options.assume_profile
870 {
871 h.profiles
872 .push(self.schema.profile(p).version_iri.to_owned());
873 }
874 h
875 }
876
877 fn adopt_header(&mut self, st: &mut State) {
879 let Some(h) = st.header.as_ref() else { return };
880 let declared = h
881 .profiles
882 .iter()
883 .filter_map(|iri| self.schema.profile_by_iri(iri))
884 .fold(0, |acc, p| acc | p.mask());
885 if declared != 0 {
886 st.profile_mask = declared;
887 }
888 }
889
890 fn stage(&mut self, st: &mut State) {
892 if let Some(mut o) = st.object.take() {
893 o.mark_profile(st.profile_mask);
894 st.staged.push((o, st.object_start));
895 }
896 }
897
898 fn close_compound(&mut self, st: &mut State) {
900 let Some(frame) = st.compounds.pop() else {
901 return;
902 };
903 let value = Value::Compound(Box::new(frame.compound));
904 self.store(st, frame.attr, value, frame.start);
905 }
906
907 fn store(&mut self, st: &mut State, attr: AttrId, value: Value, pos: u64) {
913 let many = self.schema.attr(attr).mult.is_many();
914 if !many {
915 let seen = match st.compounds.last_mut() {
916 Some(frame) => &mut frame.seen,
917 None => &mut st.seen,
918 };
919 match seen.iter().find(|(a, _)| *a == attr) {
920 Some(&(_, first)) => self.report_repeat(st, attr, &value, first, pos),
921 None => seen.push((attr, pos)),
922 }
923 }
924 let mask = st.profile_mask;
925 match st.compounds.last_mut() {
926 Some(frame) if many => frame.compound.push(attr, value),
927 Some(frame) => frame.compound.set(attr, value),
928 None => {
929 if let Some(obj) = st.object.as_mut() {
930 if many {
931 obj.push_in(mask, attr, value);
932 } else {
933 obj.set_in(mask, attr, value);
934 }
935 }
936 }
937 }
938 }
939
940 #[cold]
941 fn report_repeat(&mut self, st: &State, attr: AttrId, value: &Value, first: u64, pos: u64) {
942 let earlier = match st.compounds.last() {
943 Some(frame) => frame.compound.get(attr),
944 None => st.object.as_ref().and_then(|o| o.get(attr)),
945 };
946 let Some(earlier) = earlier else { return };
947 let schema = self.schema;
948 let def = schema.attr(attr);
949 let d = if earlier == value {
950 Diagnostic::warning(
951 Rule::CardinalityExceeded,
952 format!(
953 "{} is given again with the same value {}, first at byte {first}; it \
954 permits one",
955 def.name,
956 crate::value::display_value(schema, value)
957 ),
958 )
959 } else {
960 Diagnostic::error(
961 Rule::ConflictingValue,
962 format!(
963 "{} is given twice: {} at byte {first}, then {}; the later is kept",
964 def.name,
965 crate::value::display_value(schema, earlier),
966 crate::value::display_value(schema, value)
967 ),
968 )
969 };
970 let mut d = d.with_attribute(def.name).with_related_position(first);
971 if let Some(o) = st.object.as_ref() {
972 d = d
973 .with_class(schema.class(o.class()).name)
974 .with_object(o.mrid().clone());
975 }
976 self.diag(d, pos);
977 }
978
979 fn commit(&mut self, mut object: Object, slot: usize, ds: &mut Dataset, pos: u64) {
984 object.from_file = true;
985 object.shrink_for_load();
986 if let Some(existing) = ds.by_mrid(object.mrid()) {
987 let incoming = object.class();
988 let held = existing.class();
989 if !self.schema.is_a(incoming, held) && !self.schema.is_a(held, incoming) {
990 let d = Diagnostic::error(
991 Rule::DuplicateMrid,
992 format!(
993 "identifier {} is used by both {} and {}, which are unrelated classes",
994 object.mrid().canonical(),
995 self.schema.class(held).name,
996 self.schema.class(incoming).name
997 ),
998 )
999 .with_class(self.schema.class(incoming).name)
1000 .with_object(object.mrid().clone());
1001 self.diag(d, pos);
1002 }
1003 }
1004 let id = ds.insert(object);
1005 ds.record_source(slot, id);
1006 }
1007
1008 fn on_open(
1010 &mut self,
1011 e: &BytesStart<'_>,
1012 self_closing: bool,
1013 ctx: Ctx,
1014 st: &mut State,
1015 pos: u64,
1016 ) -> Result<Ctx> {
1017 let qname = e.name();
1018 let qname = qname.as_ref();
1019
1020 if !st.saw_root || declares_namespace(e) {
1023 self.collect_namespaces(e)?;
1024 }
1025 if !st.saw_root {
1026 if let Some((ns, local)) = self.expand(qname)
1027 && ns == RDF_NS
1028 && local == "RDF"
1029 {
1030 st.saw_root = true;
1031 self.check_vintage(pos);
1032 return Ok(Ctx::Body);
1033 }
1034 return Ok(ctx);
1036 }
1037
1038 match ctx {
1039 Ctx::Body => self.open_in_body(e, qname, st, pos),
1040 Ctx::Object => {
1041 let Some(obj) = st.object.as_ref() else {
1042 return Ok(Ctx::Skip);
1043 };
1044 let (class, mrid) = (obj.class(), obj.mrid());
1046 match self.property(e, self_closing, class, mrid, pos)? {
1047 Prop::Value(attr, value) => {
1048 self.store(st, attr, value, pos);
1049 Ok(Ctx::Skip)
1050 }
1051 Prop::Enter(attr, class) => {
1052 st.compounds.push(Frame::new(attr, class, pos));
1053 Ok(Ctx::Compound)
1054 }
1055 Prop::Text(attr) => {
1056 st.pending = Some(PendingText {
1057 target: TextTarget::Attr(attr),
1058 text: String::new(),
1059 start: pos,
1060 });
1061 Ok(Ctx::Text)
1062 }
1063 Prop::Skip => Ok(Ctx::Skip),
1064 }
1065 }
1066 Ctx::Compound => {
1067 let Some(top) = st.compounds.last() else {
1068 return Ok(Ctx::Skip);
1069 };
1070 let class = top.compound.class();
1071 let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1072 match self.property(e, self_closing, class, mrid, pos)? {
1073 Prop::Value(attr, value) => {
1074 self.store(st, attr, value, pos);
1075 Ok(Ctx::Skip)
1076 }
1077 Prop::Enter(attr, class) => {
1078 st.compounds.push(Frame::new(attr, class, pos));
1079 Ok(Ctx::Compound)
1080 }
1081 Prop::Text(attr) => {
1082 st.pending = Some(PendingText {
1083 target: TextTarget::Compound(attr),
1084 text: String::new(),
1085 start: pos,
1086 });
1087 Ok(Ctx::Text)
1088 }
1089 Prop::Skip => Ok(Ctx::Skip),
1090 }
1091 }
1092 Ctx::Header => self.open_in_header(e, qname, self_closing, st, pos),
1093 Ctx::DiffSet => {
1094 let about = self.attr(e, RDF_NS, "about")?;
1097 let defines = about.is_none();
1098 if let Some(raw) = about.or(self.attr(e, RDF_NS, "ID")?) {
1099 let class = self.expand(qname).and_then(|(ns, local)| {
1100 (!(ns == RDF_NS && local == "Description")).then(|| QualifiedName {
1101 ns: ns.to_owned(),
1102 local: local.to_owned(),
1103 })
1104 });
1105 st.diff_subject = Some((Mrid::parse(raw.trim()), class, defines));
1106 return Ok(Ctx::DiffSubject);
1107 }
1108 Ok(Ctx::Skip)
1109 }
1110 Ctx::DiffSubject => {
1111 let Some((ns, local)) = self
1112 .expand(qname)
1113 .map(|(n, l)| (n.to_owned(), l.to_owned()))
1114 else {
1115 return Ok(Ctx::Skip);
1116 };
1117 let Some((subject, class, defines_subject)) = st.diff_subject.clone() else {
1118 return Ok(Ctx::Skip);
1119 };
1120 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1121 let res = res.trim().to_owned();
1122 push_statement(
1123 &mut st.difference,
1124 st.diff_set,
1125 Statement {
1126 subject,
1127 class,
1128 defines_subject,
1129 predicate_ns: ns,
1130 predicate: local,
1131 value: StatementValue::Resource(res),
1132 },
1133 );
1134 return Ok(Ctx::Skip);
1135 }
1136 if self_closing {
1137 return Ok(Ctx::Skip);
1138 }
1139 st.pending = Some(PendingText {
1140 target: TextTarget::Statement {
1141 subject,
1142 class,
1143 defines_subject,
1144 ns,
1145 local,
1146 set: st.diff_set,
1147 },
1148 text: String::new(),
1149 start: pos,
1150 });
1151 Ok(Ctx::Text)
1152 }
1153 Ctx::Text => {
1155 let name = shown(qname);
1156 self.diag(
1157 Diagnostic::warning(
1158 Rule::Structure,
1159 format!("unexpected element <{name}> inside a value; skipped"),
1160 ),
1161 pos,
1162 );
1163 Ok(Ctx::Skip)
1164 }
1165 Ctx::Skip | Ctx::Outside => Ok(Ctx::Skip),
1166 }
1167 }
1168
1169 fn open_in_body(
1171 &mut self,
1172 e: &BytesStart<'_>,
1173 qname: &str,
1174 st: &mut State,
1175 pos: u64,
1176 ) -> Result<Ctx> {
1177 if let Some((ns, local)) = self.expand(qname)
1178 && ((ns == MD_NS && local == "FullModel")
1179 || (ns == DM_NS && local == "DifferenceModel"))
1180 {
1181 let kind = if ns == DM_NS {
1182 ModelKind::Difference
1183 } else {
1184 ModelKind::Full
1185 };
1186 let mut h = ModelHeader::new(kind);
1187 h.id = self
1188 .attr(e, RDF_NS, "about")?
1189 .map(|s| Mrid::parse(s.trim()));
1190 h.source = self.source.clone();
1191 st.header = Some(h);
1192 if kind == ModelKind::Difference {
1193 st.difference = Some(DifferenceModel::default());
1194 }
1195 return Ok(Ctx::Header);
1196 }
1197
1198 if self.header_only {
1199 return Ok(Ctx::Skip);
1200 }
1201
1202 match self.resolve(qname) {
1203 Resolved::Class(class) => {
1204 let def = self.schema.class(class);
1205 if def.compound {
1207 self.diag(
1208 Diagnostic::error(
1209 Rule::Structure,
1210 format!(
1211 "compound type {} has no identity and cannot be a top-level object",
1212 def.name
1213 ),
1214 )
1215 .with_class(def.name),
1216 pos,
1217 );
1218 return Ok(Ctx::Skip);
1219 }
1220 if !def.concrete {
1221 self.diag(
1222 Diagnostic::error(
1223 Rule::AbstractInstantiated,
1224 format!("abstract class {} instantiated", def.name),
1225 )
1226 .with_class(def.name),
1227 pos,
1228 );
1229 }
1230 if self.options.report_deprecated && def.deprecated {
1231 self.diag(
1232 Diagnostic::info(
1233 Rule::Deprecated,
1234 format!("deprecated class {}", def.name),
1235 )
1236 .with_class(def.name),
1237 pos,
1238 );
1239 }
1240 let mrid = self.object_identity(e, def.name, pos)?;
1241 let mut o = Object::new(class, mrid);
1242 o.mark_profile(st.profile_mask);
1243 st.object = Some(o);
1244 st.object_start = pos;
1245 st.seen.clear();
1246 Ok(Ctx::Object)
1247 }
1248 Resolved::Attr(_) | Resolved::Unknown => {
1249 let name = shown(qname);
1250 if self.options.strictness == Strictness::Strict {
1251 return Err(Error::not_cim(format!("unknown class element <{name}>")));
1252 }
1253 self.diag(
1254 Diagnostic::warning(
1255 Rule::UnknownClass,
1256 format!("unknown class element <{name}>, skipped"),
1257 ),
1258 pos,
1259 );
1260 Ok(Ctx::Skip)
1261 }
1262 }
1263 }
1264
1265 fn open_in_header(
1267 &mut self,
1268 e: &BytesStart<'_>,
1269 qname: &str,
1270 self_closing: bool,
1271 st: &mut State,
1272 pos: u64,
1273 ) -> Result<Ctx> {
1274 let Some((ns, local)) = self
1275 .expand(qname)
1276 .map(|(n, l)| (n.to_owned(), l.to_owned()))
1277 else {
1278 return Ok(Ctx::Skip);
1279 };
1280 let set = match (ns == DM_NS, local.as_str()) {
1282 (true, "forwardDifferences") => Some(DiffSet::Forward),
1283 (true, "reverseDifferences") => Some(DiffSet::Reverse),
1284 (true, "preconditions") => Some(DiffSet::Preconditions),
1285 _ => None,
1286 };
1287 if let Some(set) = set {
1288 st.diff_set = set;
1289 if st.difference.is_none() {
1290 st.difference = Some(DifferenceModel::default());
1291 }
1292 return Ok(Ctx::DiffSet);
1293 }
1294 let prefix = prefix_of(qname);
1295 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1296 let res = res.trim().to_owned();
1297 apply_header_resource(&mut st.header, &prefix, &ns, &local, res);
1298 return Ok(Ctx::Skip);
1299 }
1300 if self_closing {
1301 return Ok(Ctx::Skip);
1302 }
1303 st.pending = Some(PendingText {
1304 target: TextTarget::Header { prefix, ns, local },
1305 text: String::new(),
1306 start: pos,
1307 });
1308 Ok(Ctx::Text)
1309 }
1310
1311 fn property(
1313 &mut self,
1314 e: &BytesStart<'_>,
1315 self_closing: bool,
1316 class: ClassId,
1317 owner: &Mrid,
1318 pos: u64,
1319 ) -> Result<Prop> {
1320 let qname = e.name();
1321 let qname = qname.as_ref();
1322 let Resolved::Attr(attr) = self.resolve(qname) else {
1323 let name = shown(qname);
1324 if self.options.strictness == Strictness::Strict {
1325 return Err(Error::not_cim(format!("unknown property element <{name}>")));
1326 }
1327 self.diag(
1328 Diagnostic::warning(
1329 Rule::UnknownAttribute,
1330 format!("unknown property <{name}>, skipped"),
1331 )
1332 .with_object(owner.clone()),
1333 pos,
1334 );
1335 return Ok(Prop::Skip);
1336 };
1337
1338 let def = self.schema.attr(attr);
1339 if !self.schema.is_a(class, def.owner) {
1341 self.diag(
1342 Diagnostic::warning(
1343 Rule::UnknownAttribute,
1344 format!(
1345 "{} does not apply to class {}",
1346 def.name,
1347 self.schema.class(class).name
1348 ),
1349 )
1350 .with_attribute(def.name)
1351 .with_object(owner.clone()),
1352 pos,
1353 );
1354 return Ok(Prop::Skip);
1355 }
1356 if self.options.report_deprecated && def.deprecated {
1357 self.diag(
1358 Diagnostic::info(
1359 Rule::Deprecated,
1360 format!("deprecated attribute {}", def.name),
1361 )
1362 .with_attribute(def.name),
1363 pos,
1364 );
1365 }
1366
1367 if let AttrKind::Compound(target) = def.kind {
1369 if self.attr(e, RDF_NS, "resource")?.is_some() {
1370 self.diag(
1371 Diagnostic::error(
1372 Rule::InvalidValue,
1373 format!(
1374 "{} holds a compound, which has no identity, but is written as \
1375 a reference",
1376 def.name
1377 ),
1378 )
1379 .with_attribute(def.name)
1380 .with_object(owner.clone()),
1381 pos,
1382 );
1383 return Ok(Prop::Skip);
1384 }
1385 return Ok(Prop::Enter(attr, target));
1386 }
1387
1388 if let Some(res) = self.attr(e, RDF_NS, "resource")? {
1389 let res = res.trim();
1390 return Ok(match self.resource_value(attr, res, owner, pos) {
1391 Some(v) => Prop::Value(attr, v),
1392 None => Prop::Skip,
1393 });
1394 }
1395 if self_closing {
1396 if matches!(def.kind, AttrKind::Primitive(Primitive::String)) {
1398 return Ok(Prop::Value(attr, Value::Text("".into())));
1399 }
1400 return Ok(Prop::Skip);
1401 }
1402 Ok(Prop::Text(attr))
1403 }
1404
1405 fn object_identity(
1407 &mut self,
1408 e: &BytesStart<'_>,
1409 class: &'static str,
1410 pos: u64,
1411 ) -> Result<Mrid> {
1412 for (name, raw) in [
1413 ("rdf:ID", self.attr(e, RDF_NS, "ID")?),
1414 ("rdf:about", self.attr(e, RDF_NS, "about")?),
1415 ] {
1416 let Some(raw) = raw else { continue };
1417 let raw = raw.trim();
1418 let m = Mrid::parse(raw);
1419 let unwritable_id = name == "rdf:ID" && !crate::xml::is_ncname(raw);
1422 if unwritable_id || (self.options.report_non_conforming_mrids && !m.is_conforming()) {
1425 let complaint = if unwritable_id {
1426 format!(
1427 "is not an XML NCName and so cannot be written back as one; repaired to {:?}",
1428 m.to_rdf_id()
1429 )
1430 } else if m.is_uuid() {
1431 format!(
1433 "is a UUID written without hyphens; IEC 61970-552 requires {:?}",
1434 m.canonical()
1435 )
1436 } else {
1437 "is not a UUID as IEC 61970-552 requires".to_owned()
1438 };
1439 self.diag(
1440 Diagnostic::warning(
1441 Rule::NonConformingMrid,
1442 format!("{name} {raw:?} {complaint}"),
1443 )
1444 .with_class(class),
1445 pos,
1446 );
1447 }
1448 return Ok(m);
1449 }
1450 let placeholder = match &self.source {
1453 Some(src) => format!("no-identifier-{src}-{pos}"),
1454 None => format!("no-identifier-{pos}"),
1455 };
1456 self.diag(
1457 Diagnostic::error(
1458 Rule::Structure,
1459 format!("<{class}> has neither rdf:ID nor rdf:about; kept as {placeholder:?}"),
1460 )
1461 .with_class(class),
1462 pos,
1463 );
1464 Ok(Mrid::parse(&placeholder))
1465 }
1466
1467 fn resource_value(&mut self, attr: AttrId, res: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1469 let def = self.schema.attr(attr);
1470 let AttrKind::Enumeration(_) = def.kind else {
1471 return Some(Value::Reference(Mrid::parse(res)));
1472 };
1473 let Some((ns, local)) = res.rsplit_once('#') else {
1475 self.diag(
1476 Diagnostic::error(
1477 Rule::InvalidValue,
1478 format!("enumeration value {res:?} is not an IRI"),
1479 )
1480 .with_attribute(def.name),
1481 pos,
1482 );
1483 return None;
1484 };
1485 if let Some(v) = self.schema.find_enum_value(&format!("{ns}#"), local) {
1486 return Some(Value::Enum(v));
1487 }
1488 match self.schema.find_enum_value_any_ns(local) {
1491 Some(v) => {
1492 let correct = self.schema.namespace(self.schema.enum_value(v).ns).iri;
1493 self.diag(
1494 Diagnostic::warning(
1495 Rule::InvalidValue,
1496 format!(
1497 "enumeration literal {local} is written in namespace {ns}# but is \
1498 declared in {correct}; value recovered"
1499 ),
1500 )
1501 .with_attribute(def.name)
1502 .with_object(owner.clone()),
1503 pos,
1504 );
1505 Some(Value::Enum(v))
1506 }
1507 None => {
1508 self.diag(
1509 Diagnostic::error(
1510 Rule::InvalidValue,
1511 format!("unknown enumeration literal {res:?}"),
1512 )
1513 .with_attribute(def.name)
1514 .with_object(owner.clone()),
1515 pos,
1516 );
1517 None
1518 }
1519 }
1520 }
1521
1522 fn finish_text(&mut self, mut p: PendingText, st: &mut State) {
1524 let pos = p.start;
1525 if let Some((offset, c)) = crate::xml::find_illegal(&p.text) {
1528 self.diag(
1529 Diagnostic::warning(
1530 Rule::IllegalXmlCharacter,
1531 format!(
1532 "value holds {}, which XML 1.0 cannot represent in any form; \
1533 removed (first at byte {offset} of the value)",
1534 crate::xml::describe_char(c)
1535 ),
1536 ),
1537 pos,
1538 );
1539 p.text = crate::xml::strip_illegal(&p.text).into_owned();
1540 }
1541 match p.target {
1542 TextTarget::Attr(attr) => {
1543 let Some(obj) = st.object.as_ref() else {
1544 return;
1545 };
1546 if let Some(v) = self.parse_text(attr, &p.text, obj.mrid(), pos) {
1547 self.store(st, attr, v, pos);
1548 }
1549 }
1550 TextTarget::Compound(attr) => {
1551 let mrid = st.object.as_ref().map_or(&UNKNOWN_MRID, |o| o.mrid());
1552 if let Some(v) = self.parse_text(attr, &p.text, mrid, pos)
1553 && !st.compounds.is_empty()
1554 {
1555 self.store(st, attr, v, pos);
1556 }
1557 }
1558 TextTarget::Header { prefix, ns, local } => {
1559 apply_header_text(&mut st.header, &prefix, &ns, &local, p.text);
1560 }
1561 TextTarget::Statement {
1562 subject,
1563 class,
1564 defines_subject,
1565 ns,
1566 local,
1567 set,
1568 } => push_statement(
1569 &mut st.difference,
1570 set,
1571 Statement {
1572 subject,
1573 class,
1574 defines_subject,
1575 predicate_ns: ns,
1576 predicate: local,
1577 value: StatementValue::Literal(p.text),
1578 },
1579 ),
1580 }
1581 }
1582
1583 fn parse_text(&mut self, attr: AttrId, text: &str, owner: &Mrid, pos: u64) -> Option<Value> {
1584 let def = self.schema.attr(attr);
1585 let prim = match def.kind {
1586 AttrKind::Primitive(prim) => prim,
1587 AttrKind::Datatype(dt) => self.schema.datatype(dt).value,
1588 AttrKind::Enumeration(_) | AttrKind::Association { .. } | AttrKind::Compound(_) => {
1591 Primitive::String
1592 }
1593 };
1594 match Value::parse_primitive(prim, text) {
1595 Ok(v) => Some(v),
1596 Err(e) => {
1597 let name = def.name;
1598 self.diag(
1599 Diagnostic::error(Rule::InvalidValue, e.to_string())
1600 .with_attribute(name)
1601 .with_object(owner.clone()),
1602 pos,
1603 );
1604 None
1605 }
1606 }
1607 }
1608
1609 fn collect_namespaces(&mut self, e: &BytesStart<'_>) -> Result<()> {
1614 for attr in e.attributes().with_checks(false) {
1615 let attr = attr?;
1616 let key = attr.key.as_ref();
1617 let value = self.attr_value(&attr)?.into_owned();
1618 if let Some(prefix) = key.strip_prefix("xmlns:") {
1619 self.ns.insert(prefix.as_bytes().to_vec(), value);
1620 } else if key == "xmlns" {
1621 self.ns.insert(Vec::new(), value);
1622 }
1623 }
1624 Ok(())
1625 }
1626
1627 fn attr<'e>(
1631 &self,
1632 e: &'e BytesStart<'_>,
1633 ns: &str,
1634 local: &str,
1635 ) -> Result<Option<Cow<'e, str>>> {
1636 for attr in e.attributes().with_checks(false) {
1637 let attr = attr?;
1638 let key = attr.key.as_ref();
1639 let Some((prefix, name)) = key.split_once(':') else {
1640 continue;
1641 };
1642 if name != local {
1643 continue;
1644 }
1645 if self.ns.get(prefix.as_bytes()).map(String::as_str) != Some(ns) {
1646 continue;
1647 }
1648 return Ok(Some(self.attr_value(&attr)?));
1649 }
1650 Ok(None)
1651 }
1652}
1653
1654fn parse_error(
1660 e: quick_xml::Error,
1661 at: u64,
1662 at_end: bool,
1663 open: &OpenElements,
1664 source: &Option<String>,
1665) -> Error {
1666 use quick_xml::errors::{IllFormedError, SyntaxError};
1667 match e {
1668 quick_xml::Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
1669 quick_xml::Error::Syntax(s) if !matches!(s, SyntaxError::InvalidBangMarkup) => {
1670 Error::Truncated {
1671 open: open.innermost().map(|(name, _)| name),
1672 source: source.clone(),
1673 position: at,
1674 }
1675 }
1676 quick_xml::Error::IllFormed(IllFormedError::UnclosedReference) if at_end => {
1677 Error::Truncated {
1678 open: open.innermost().map(|(name, _)| name),
1679 source: source.clone(),
1680 position: at,
1681 }
1682 }
1683 quick_xml::Error::IllFormed(IllFormedError::UnclosedReference) => Error::xml(
1684 "a `&` that starts no entity or character reference; a literal ampersand is \
1685 written `&`",
1686 )
1687 .locate(source.as_deref(), at),
1688 quick_xml::Error::IllFormed(e) => {
1691 Error::xml(shown(&e.to_string())).locate(source.as_deref(), at)
1692 }
1693 other => Error::xml(shown(&other.to_string())).locate(source.as_deref(), at),
1694 }
1695}
1696
1697fn outside_document(ev: &Event<'_>, root_closed: bool) -> Option<&'static str> {
1700 match ev {
1701 Event::Start(_) | Event::Empty(_) if root_closed => {
1702 Some("a second document element; XML allows exactly one")
1703 }
1704 Event::Text(t)
1705 if !t
1706 .as_ref()
1707 .bytes()
1708 .all(|b| matches!(b, b' ' | b'\t' | b'\r' | b'\n')) =>
1709 {
1710 Some("text outside the document element")
1711 }
1712 Event::CData(_) | Event::GeneralRef(_) => Some("text outside the document element"),
1713 _ => None,
1714 }
1715}
1716
1717fn shown(text: &str) -> Cow<'_, str> {
1721 if text.chars().any(char::is_control) {
1722 Cow::Owned(
1723 text.chars()
1724 .map(|c| {
1725 if c.is_control() {
1726 c.escape_default().to_string()
1727 } else {
1728 c.to_string()
1729 }
1730 })
1731 .collect(),
1732 )
1733 } else {
1734 Cow::Borrowed(text)
1735 }
1736}
1737
1738fn undefined_entity(name: &str) -> Diagnostic {
1740 Diagnostic::warning(
1741 Rule::InvalidValue,
1742 format!(
1743 "undefined entity &{name}; kept as text: CIM/XML documents declare no DTD, so \
1744 only the five predefined entities and character references are expanded"
1745 ),
1746 )
1747}
1748
1749fn escape_undefined_entities(raw: &str) -> (String, Vec<String>) {
1752 let mut out = String::with_capacity(raw.len() + 8);
1753 let mut names = Vec::new();
1754 let mut rest = raw;
1755 while let Some(at) = rest.find('&') {
1756 out.push_str(&rest[..at]);
1757 let after = &rest[at + 1..];
1758 let name = after.split_once(';').map(|(n, _)| n);
1759 match name {
1760 Some(n)
1761 if !n.starts_with('#')
1762 && quick_xml::escape::resolve_predefined_entity(n).is_none() =>
1763 {
1764 out.push_str("&");
1765 names.push(n.to_owned());
1766 }
1767 _ => out.push('&'),
1768 }
1769 rest = after;
1770 }
1771 out.push_str(rest);
1772 (out, names)
1773}
1774
1775fn declares_namespace(e: &BytesStart<'_>) -> bool {
1777 e.as_ref().contains("xmlns")
1778}
1779
1780fn prefix_of(qname: &str) -> String {
1782 match qname.split_once(':') {
1783 Some((prefix, _)) => prefix.to_owned(),
1784 None => String::new(),
1785 }
1786}
1787
1788fn apply_header_resource(
1790 header: &mut Option<ModelHeader>,
1791 prefix: &str,
1792 ns: &str,
1793 local: &str,
1794 res: String,
1795) {
1796 let Some(h) = header.as_mut() else { return };
1797 match (ns, local) {
1798 (MD_NS, "Model.DependentOn") => h.dependent_on.push(Mrid::parse(&res)),
1799 (MD_NS, "Model.Supersedes") => h.supersedes.push(Mrid::parse(&res)),
1800 (MD_NS, "Model.profile") => h.profiles.push(res),
1801 _ => h
1802 .extra
1803 .push(HeaderProperty::resource(prefix, ns, local, res)),
1804 }
1805}
1806
1807fn apply_header_text(
1809 header: &mut Option<ModelHeader>,
1810 prefix: &str,
1811 ns: &str,
1812 local: &str,
1813 text: String,
1814) {
1815 let Some(h) = header.as_mut() else { return };
1816 if ns != MD_NS {
1817 h.extra.push(HeaderProperty::text(prefix, ns, local, text));
1818 return;
1819 }
1820 match local {
1821 "Model.created" => h.created = Some(text),
1822 "Model.scenarioTime" => h.scenario_time = Some(text),
1823 "Model.description" => h.description = Some(text),
1824 "Model.version" => h.version = Some(text),
1825 "Model.modelingAuthoritySet" => h.modeling_authority_set = Some(text),
1826 "Model.profile" => h.profiles.push(text),
1827 "Model.DependentOn" => h.dependent_on.push(Mrid::parse(&text)),
1828 "Model.Supersedes" => h.supersedes.push(Mrid::parse(&text)),
1829 _ => h.extra.push(HeaderProperty::text(prefix, ns, local, text)),
1830 }
1831}
1832
1833#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1835enum DiffSet {
1836 Preconditions,
1837 #[default]
1838 Reverse,
1839 Forward,
1840}
1841
1842fn push_statement(difference: &mut Option<DifferenceModel>, set: DiffSet, s: Statement) {
1843 let d = difference.get_or_insert_with(DifferenceModel::default);
1844 match set {
1845 DiffSet::Preconditions => d.preconditions.push(s),
1846 DiffSet::Reverse => d.reverse.push(s),
1847 DiffSet::Forward => d.forward.push(s),
1848 }
1849}
1850
1851struct PendingText {
1852 target: TextTarget,
1853 text: String,
1854 start: u64,
1856}
1857
1858enum TextTarget {
1859 Attr(AttrId),
1861 Compound(AttrId),
1863 Header {
1865 prefix: String,
1866 ns: String,
1867 local: String,
1868 },
1869 Statement {
1871 subject: Mrid,
1872 class: Option<QualifiedName>,
1873 defines_subject: bool,
1874 ns: String,
1875 local: String,
1876 set: DiffSet,
1877 },
1878}