1use std::path::Path;
2
3use quick_xml::Reader;
4use quick_xml::events::{BytesStart, Event};
5
6use crate::base::{
7 AttrDef, AttrKind, ClassDef, Element, FastMap, FastSet, FieldValue, TypeRegistry, intern,
8};
9use crate::difference::{Block, Differences};
10use crate::registry;
11
12pub fn is_cim(text: &str) -> bool {
18 let mut end = text.len().min(8192);
19 while !text.is_char_boundary(end) {
20 end -= 1;
21 }
22 let head = &text[..end];
23 [
24 "http://iec.ch/TC57/",
25 "https://cim.ucaiug.io/ns#",
26 "https://ap.cim4.eu/",
27 "https://energy.referencedata.eu/",
28 ]
29 .iter()
30 .any(|marker| head.contains(marker))
31}
32
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
37pub struct FieldForm {
38 pub ns: Option<&'static str>,
43 pub datatype: Option<&'static str>,
46 pub resource_ns: Option<&'static str>,
51}
52
53impl FieldForm {
54 fn fill_from(&mut self, other: FieldForm) {
55 self.ns = self.ns.or(other.ns);
56 self.datatype = self.datatype.or(other.datatype);
57 self.resource_ns = self.resource_ns.or(other.resource_ns);
58 }
59}
60
61#[derive(Clone)]
62pub struct CimDataset {
63 pub entries: FastMap<String, Element>,
64 pub by_type: FastMap<String, Vec<String>>,
66 pub field_forms: FastMap<(&'static str, &'static str), FieldForm>,
73 pub type_ns: FastMap<String, &'static str>,
78 pub prefixes: FastMap<&'static str, &'static str>,
82 pub foreign: FastMap<String, Element>,
90 pub differences: Vec<Differences>,
96}
97
98impl Default for CimDataset {
99 fn default() -> Self {
100 Self::new()
101 }
102}
103
104impl CimDataset {
105 pub fn new() -> Self {
106 Self {
107 entries: FastMap::default(),
108 by_type: FastMap::default(),
109 field_forms: FastMap::default(),
110 type_ns: FastMap::default(),
111 prefixes: FastMap::default(),
112 foreign: FastMap::default(),
113 differences: Vec::new(),
114 }
115 }
116
117 pub fn decode_str(content: &str) -> Result<Self, Box<dyn std::error::Error>> {
119 let mut ds = Self::new();
120 parse_rdf(content, registry::type_registry(), &mut ds)?;
121 Ok(ds)
122 }
123
124 pub fn decode_file(path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
126 Self::decode_str(&std::fs::read_to_string(path)?)
127 }
128
129 pub fn decode_files(paths: &[&Path]) -> Result<Self, Box<dyn std::error::Error>> {
131 let mut combined = Self::new();
132 for path in paths {
133 let file_ds = Self::decode_file(path)?;
134 combined.merge(file_ds);
135 }
136 Ok(combined)
137 }
138
139 pub fn decode_files_parallel_separate(
143 paths: &[&Path],
144 ) -> Result<Vec<Self>, Box<dyn std::error::Error>> {
145 if paths.len() <= 1 || cfg!(target_family = "wasm") {
147 return paths.iter().map(|p| Self::decode_file(p)).collect();
148 }
149 let results: Vec<Result<Self, String>> = std::thread::scope(|s| {
150 paths
151 .iter()
152 .map(|p| s.spawn(|| Self::decode_file(p).map_err(|e| e.to_string())))
153 .collect::<Vec<_>>()
154 .into_iter()
155 .map(|h| h.join().expect("decode thread panicked"))
156 .collect()
157 });
158 results
159 .into_iter()
160 .collect::<Result<_, String>>()
161 .map_err(|e| e.into())
162 }
163
164 pub fn decode_files_parallel(paths: &[&Path]) -> Result<Self, Box<dyn std::error::Error>> {
166 let datasets = Self::decode_files_parallel_separate(paths)?;
167 Ok(datasets
168 .into_iter()
169 .reduce(|mut a, b| {
170 a.merge(b);
171 a
172 })
173 .unwrap_or_default())
174 }
175
176 pub fn merge(&mut self, other: CimDataset) {
186 self.differences.extend(other.differences);
187 for (key, form) in other.field_forms {
188 self.field_forms.entry(key).or_default().fill_from(form);
189 }
190 for (mrid, ns) in other.type_ns {
191 self.type_ns.entry(mrid).or_insert(ns);
192 }
193 for (ns, prefix) in other.prefixes {
194 self.prefixes.entry(ns).or_insert(prefix);
195 }
196 for (id, incoming) in other.foreign {
197 match self.foreign.get_mut(&id) {
198 Some(existing) => existing.merge_from(&incoming),
199 None => {
200 self.foreign.insert(id, incoming);
201 }
202 }
203 }
204 let reg = registry::type_registry();
205 let mut moved: FastMap<&'static str, FastSet<String>> = FastMap::default();
206 for (mrid, incoming) in other.entries {
207 if let Some(existing) = self.entries.get_mut(&mrid) {
208 existing.merge_from(&incoming);
209 let old = existing.class();
210 let mut changed = false;
211 for t in incoming.types() {
212 changed |= existing.add_type(t, reg);
213 }
214 if changed {
215 moved.entry(old.qualified).or_default().insert(mrid.clone());
216 self.by_type
217 .entry(existing.type_name().to_string())
218 .or_default()
219 .push(mrid);
220 }
221 } else {
222 let type_name = incoming.type_name().to_string();
223 self.by_type
224 .entry(type_name)
225 .or_default()
226 .push(mrid.clone());
227 self.entries.insert(mrid, incoming);
228 }
229 }
230 for (old, mrids) in moved {
232 if let Some(bucket) = self.by_type.get_mut(old) {
233 bucket.retain(|m| !mrids.contains(m));
234 }
235 }
236 }
237
238 pub fn element_from_json(
246 &self,
247 class: &'static ClassDef,
248 value: &serde_json::Value,
249 ) -> Result<Element, String> {
250 let reg = registry::type_registry();
251 let mut element = Element::from_json(class, reg, value)?;
252 let keys: Vec<&'static str> = element.fields().keys().copied().collect();
253 for key in keys {
254 if let Some(reference) = self.held_as_reference(class.qualified, key) {
255 element.retype(key, reference);
256 }
257 }
258 Ok(element)
259 }
260
261 fn held_as_reference(&self, type_name: &str, key: &str) -> Option<bool> {
265 self.by_type
266 .get(type_name)
267 .into_iter()
268 .flatten()
269 .filter_map(|m| self.entries.get(m))
270 .find_map(|e| match e.get(key)? {
271 FieldValue::Resource(_) | FieldValue::ResourceList(_) => Some(true),
272 FieldValue::Text(_) | FieldValue::TextList(_) => Some(false),
273 })
274 .or_else(|| {
275 self.field_forms
276 .get(&(type_name, key))
277 .and_then(|f| f.resource_ns)
278 .map(|_| true)
279 })
280 }
281
282 pub fn set(&mut self, mrid: String, element: Element) {
285 let new_type = element.type_name().to_string();
286 if let Some(old) = self.entries.get(&mrid) {
287 let old_type = old.type_name();
288 if old_type != new_type
289 && let Some(v) = self.by_type.get_mut(old_type)
290 {
291 v.retain(|m| m != &mrid);
292 }
293 }
294 let already_indexed = self
295 .by_type
296 .get(&new_type)
297 .is_some_and(|v| v.contains(&mrid));
298 if !already_indexed {
299 self.by_type.entry(new_type).or_default().push(mrid.clone());
300 }
301 self.entries.insert(mrid, element);
302 }
303
304 pub fn remove(&mut self, mrid: &str) -> Option<Element> {
307 let removed = self.entries.remove(mrid)?;
308 if let Some(v) = self.by_type.get_mut(removed.type_name()) {
309 v.retain(|m| m != mrid);
310 }
311 Some(removed)
312 }
313
314 pub fn type_conflicts(&self) -> Vec<(&str, Vec<&'static str>)> {
320 let reg = registry::type_registry();
321 let related = |a: &ClassDef, b: &ClassDef| {
322 reg.chain(a).iter().any(|c| c.qualified == b.qualified)
323 || reg.chain(b).iter().any(|c| c.qualified == a.qualified)
324 };
325 let mut out: Vec<(&str, Vec<&'static str>)> = self
326 .entries
327 .iter()
328 .filter_map(|(mrid, e)| {
329 let types: Vec<&'static ClassDef> = e.types().collect();
330 let conflict = types
331 .iter()
332 .enumerate()
333 .any(|(i, a)| types[i + 1..].iter().any(|b| !related(a, b)));
334 conflict.then(|| (mrid.as_str(), types.iter().map(|c| c.qualified).collect()))
335 })
336 .collect();
337 out.sort_unstable();
338 out
339 }
340}
341
342fn index(by_type: &mut FastMap<String, Vec<String>>, type_name: &'static str, mrid: String) {
347 if let Some(bucket) = by_type.get_mut(type_name) {
348 bucket.push(mrid);
349 } else {
350 by_type.insert(type_name.to_string(), vec![mrid]);
351 }
352}
353
354type Table = FastMap<&'static str, &'static ClassDef>;
355
356#[derive(Default, Clone)]
362struct Scope {
363 prefixes: Vec<(Vec<u8>, &'static str, Option<&'static Table>)>,
365 default: Option<&'static Table>,
366 default_ns: &'static str,
367}
368
369impl Scope {
370 fn absorb(&mut self, e: &BytesStart, reg: &'static TypeRegistry) {
372 for attr in e.attributes().flatten() {
373 let key = attr.key.as_ref();
374 let Some(rest) = key.strip_prefix(b"xmlns".as_slice()) else {
375 continue;
376 };
377 let Ok(ns) = std::str::from_utf8(&attr.value) else {
378 continue;
379 };
380 let table = reg.ns_table(ns).or_else(|| {
382 if ns.ends_with('#') || ns.ends_with('/') {
383 None
384 } else {
385 reg.ns_table(&format!("{ns}#"))
386 }
387 });
388 let ns = intern(ns);
389 match rest.strip_prefix(b":".as_slice()) {
390 Some(prefix) => {
391 let prefix = prefix.to_vec();
392 match self.prefixes.iter_mut().find(|(k, _, _)| *k == prefix) {
393 Some(slot) => (slot.1, slot.2) = (ns, table),
394 None => self.prefixes.push((prefix, ns, table)),
395 }
396 }
397 None if rest.is_empty() => (self.default, self.default_ns) = (table, ns),
398 None => {}
399 }
400 }
401 }
402
403 fn table(&self, prefix: Option<&[u8]>) -> Option<&'static Table> {
404 match prefix {
405 None => self.default,
406 Some(p) => self
407 .prefixes
408 .iter()
409 .find(|(k, _, _)| k.as_slice() == p)
410 .and_then(|(_, _, t)| *t),
411 }
412 }
413
414 fn ns(&self, prefix: Option<&[u8]>) -> &'static str {
416 match prefix {
417 None => self.default_ns,
418 Some(p) => self
419 .prefixes
420 .iter()
421 .find(|(k, _, _)| k.as_slice() == p)
422 .map_or("", |(_, ns, _)| ns),
423 }
424 }
425}
426
427struct Subject {
429 mrid: String,
432 id: String,
435 described: bool,
437 has_xmlns: bool,
438}
439
440fn scan_attrs(e: &BytesStart) -> Result<Subject, Box<dyn std::error::Error>> {
444 let mut subject = Subject {
445 mrid: String::new(),
446 id: String::new(),
447 described: false,
448 has_xmlns: false,
449 };
450 let mut defined = false;
451 for attr in e.attributes().flatten() {
452 let key = attr.key.as_ref();
453 if key == b"rdf:about" || key == b"rdf:ID" {
454 let value = std::str::from_utf8(&attr.value)?;
455 subject.mrid = strip_fragment(value);
456 subject.id = value.strip_prefix('#').unwrap_or(value).to_string();
457 subject.described |= key == b"rdf:about";
458 defined |= key == b"rdf:ID";
459 } else if key == b"rdf:nodeID" {
460 subject.mrid = format!("_:{}", std::str::from_utf8(&attr.value)?);
461 subject.id = subject.mrid.clone();
462 } else if key.starts_with(b"xmlns") {
463 subject.has_xmlns = true;
464 }
465 }
466 subject.described &= !defined;
467 Ok(subject)
468}
469
470fn object(
475 scope: &Scope,
476 reg: &'static TypeRegistry,
477 e: &BytesStart,
478 subject: Subject,
479) -> Result<Option<(Element, bool, Option<&'static str>)>, Box<dyn std::error::Error>> {
480 if subject.id.is_empty() {
481 return Ok(None);
482 }
483 let name = e.name();
484 let (prefix, local) = split_qname(name.as_ref());
485 let ns = scope.ns(prefix);
486 let (mut element, foreign) = match resolve(scope, reg, name.as_ref())? {
487 Some(class) => (Element::new(class, subject.mrid), false),
488 None => (
489 Element::new(
490 crate::base::foreign_class(ns, std::str::from_utf8(local)?),
491 subject.id,
492 ),
493 true,
494 ),
495 };
496 if subject.described {
497 element.mark_described();
498 }
499 let written = (!ns.is_empty() && !same_ns(element.type_ns(), ns)).then_some(ns);
500 Ok(Some((element, foreign, written)))
501}
502
503fn same_ns(a: &str, b: &str) -> bool {
506 a == b || a.strip_suffix('#') == Some(b) || b.strip_suffix('#') == Some(a)
507}
508
509fn store(ds: &mut CimDataset, element: Element, foreign: bool, written: Option<&'static str>) {
511 if let Some(ns) = written
512 && !foreign
513 && !element.mrid().is_empty()
514 {
515 ds.type_ns.entry(element.mrid().to_string()).or_insert(ns);
516 }
517 if foreign {
518 ds.foreign.insert(element.mrid().to_string(), element);
519 } else if !element.mrid().is_empty() {
520 index(
521 &mut ds.by_type,
522 element.type_name(),
523 element.mrid().to_string(),
524 );
525 ds.entries.insert(element.mrid().to_string(), element);
526 }
527}
528
529fn split_qname(raw: &[u8]) -> (Option<&[u8]>, &[u8]) {
531 match raw.iter().position(|b| *b == b':') {
532 Some(i) => (Some(&raw[..i]), &raw[i + 1..]),
533 None => (None, raw),
534 }
535}
536
537fn resolve(
547 scope: &Scope,
548 reg: &'static TypeRegistry,
549 raw: &[u8],
550) -> Result<Option<&'static ClassDef>, Box<dyn std::error::Error>> {
551 let (prefix, local_bytes) = split_qname(raw);
552 let local = std::str::from_utf8(local_bytes)?;
553 if let Some(class) = scope.table(prefix).and_then(|t| t.get(local)) {
554 return Ok(Some(*class));
555 }
556 Ok(reg.bare().get(local).copied())
557}
558
559fn parse_rdf(
561 content: &str,
562 reg: &'static TypeRegistry,
563 ds: &mut CimDataset,
564) -> Result<(), Box<dyn std::error::Error>> {
565 let mut reader = Reader::from_str(content);
566 parse_events(&mut reader, reg, ds, Scope::default(), false)
567}
568
569fn block_of(key: &str) -> Option<Block> {
572 match key.rsplit('.').next()? {
573 "forwardDifferences" | "forwardDifference" => Some(Block::Forward),
574 "reverseDifferences" | "reverseDifference" => Some(Block::Reverse),
575 "preconditions" => Some(Block::Preconditions),
576 _ => None,
577 }
578}
579
580fn parse_events(
586 reader: &mut Reader<&[u8]>,
587 reg: &'static TypeRegistry,
588 ds: &mut CimDataset,
589 mut scope: Scope,
590 block: bool,
591) -> Result<(), Box<dyn std::error::Error>> {
592 let mut buf = Vec::new();
593
594 let mut depth: u32 = u32::from(block);
595 let mut differences: Option<Differences> = None;
597 let mut nested: Option<Scope> = None;
599 let mut current: Option<Element> = None;
602 let mut current_foreign = false;
604 let mut current_ns: Option<&'static str> = None;
606 let mut declared: Option<&'static FastMap<&'static str, &'static AttrDef>> = None;
608 let mut pending_key: Option<&'static str> = None;
609 let mut pending_lang: Option<String> = None;
611 let mut pending_text = String::new();
615 let field = |declared: Option<&'static FastMap<&'static str, &'static AttrDef>>,
621 class: &'static str,
622 e: &BytesStart,
623 scope: &Scope,
624 forms: &mut FastMap<(&'static str, &'static str), FieldForm>|
625 -> Result<(&'static str, FieldAttrs), Box<dyn std::error::Error>> {
626 let name = e.name();
627 let (prefix, local_bytes) = split_qname(name.as_ref());
628 let local = std::str::from_utf8(local_bytes)?;
629 let attr = declared.and_then(|d| d.get(local));
630 let key = attr.map_or_else(|| intern(local), |a| a.id);
631 let attrs = field_attrs(e.attributes())?;
632 let ns = scope.ns(prefix);
633 let undeclared_ns =
634 (!ns.is_empty() && attr.is_none_or(|a| !same_ns(a.ns, ns))).then_some(ns);
635 let resource_ns = attrs
636 .resource_ns
637 .filter(|_| attr.is_none_or(|a| a.kind != AttrKind::Enum));
638 if undeclared_ns.is_some() || attrs.datatype.is_some() || resource_ns.is_some() {
639 forms.entry((class, key)).or_default().fill_from(FieldForm {
640 ns: undeclared_ns,
641 datatype: attrs.datatype,
642 resource_ns,
643 });
644 }
645 Ok((key, attrs))
646 };
647
648 loop {
649 match reader.read_event_into(&mut buf) {
650 Ok(Event::Start(ref e)) => {
651 depth += 1;
652
653 match depth {
654 1 => {
655 scope.absorb(e, reg);
656 for (prefix, ns, _) in &scope.prefixes {
657 if let Ok(prefix) = std::str::from_utf8(prefix) {
658 ds.prefixes.entry(ns).or_insert_with(|| intern(prefix));
659 }
660 }
661 }
662 2 => {
663 let subject = scan_attrs(e)?;
668 if subject.has_xmlns {
669 let mut inner = Scope {
670 prefixes: scope.prefixes.clone(),
671 default: scope.default,
672 default_ns: scope.default_ns,
673 };
674 inner.absorb(e, reg);
675 nested = Some(std::mem::replace(&mut scope, inner));
676 }
677
678 (current, current_foreign, current_ns) =
679 match object(&scope, reg, e, subject)? {
680 Some((element, foreign, written)) => {
681 (Some(element), foreign, written)
682 }
683 None => (None, false, None),
684 };
685 declared = current.as_ref().and_then(|c| reg.declared(c.class()));
686 }
687 3 => {
688 if let Some(element) = current.as_mut() {
689 let (key, attrs) = field(
690 declared,
691 element.type_name(),
692 e,
693 &scope,
694 &mut ds.field_forms,
695 )?;
696 if attrs.nodes
697 && let Some(which) = block_of(key)
698 {
699 let found = differences
702 .get_or_insert_with(|| Differences::new(element.mrid()));
703 parse_events(
704 reader,
705 reg,
706 found.block_mut(which),
707 scope.clone(),
708 true,
709 )?;
710 depth -= 1;
711 buf.clear();
712 continue;
713 }
714 if let Some(res) = attrs.resource {
715 element.add_field(key, FieldValue::Resource(res));
716 } else if !attrs.nodes {
717 pending_key = Some(key);
718 pending_lang = attrs.lang;
719 pending_text.clear();
720 }
721 }
722 }
723 _ => pending_key = None,
726 }
727 }
728
729 Ok(Event::Empty(ref e)) => {
730 match depth {
731 1 => {
732 let subject = scan_attrs(e)?;
737 let local_scope = if subject.has_xmlns {
738 let mut inner = Scope {
739 prefixes: scope.prefixes.clone(),
740 default: scope.default,
741 default_ns: scope.default_ns,
742 };
743 inner.absorb(e, reg);
744 Some(inner)
745 } else {
746 None
747 };
748 let active = local_scope.as_ref().unwrap_or(&scope);
749 if let Some((element, foreign, written)) = object(active, reg, e, subject)?
750 {
751 store(ds, element, foreign, written);
752 }
753 }
754 2 => {
755 if let Some(element) = current.as_mut() {
758 let (key, attrs) = field(
759 declared,
760 element.type_name(),
761 e,
762 &scope,
763 &mut ds.field_forms,
764 )?;
765 if attrs.nodes
766 && let Some(which) = block_of(key)
767 {
768 differences
770 .get_or_insert_with(|| Differences::new(element.mrid()))
771 .block_mut(which);
772 } else if let Some(res) = attrs.resource {
773 element.add_field(key, FieldValue::Resource(res));
774 } else if !attrs.nodes {
775 element.add_field(key, FieldValue::Text(String::new()));
776 if let Some(lang) = attrs.lang {
777 element.add_lang(key, &lang);
778 }
779 }
780 }
781 }
782 _ => pending_key = None,
783 }
784 }
785
786 Ok(Event::Text(ref e)) if depth == 3 && pending_key.is_some() => {
787 pending_text.push_str(&e.unescape()?);
788 }
789
790 Ok(Event::CData(ref e)) if depth == 3 && pending_key.is_some() => {
791 pending_text.push_str(std::str::from_utf8(e)?);
792 }
793
794 Ok(Event::End(_)) => {
795 if depth == 3
796 && let (Some(element), Some(key)) = (current.as_mut(), pending_key.take())
797 {
798 element.add_field(key, FieldValue::Text(std::mem::take(&mut pending_text)));
799 if let Some(lang) = pending_lang.take() {
800 element.add_lang(key, &lang);
801 }
802 }
803 if depth == 2 {
804 pending_key = None;
805 pending_lang = None;
806 if let Some(element) = current.take() {
807 store(ds, element, current_foreign, current_ns.take());
808 }
809 if let Some(found) = differences.take() {
810 ds.differences.push(found);
811 }
812 if let Some(outer) = nested.take() {
813 scope = outer;
814 }
815 }
816 depth = depth.saturating_sub(1);
817 if block && depth == 0 {
819 break;
820 }
821 }
822
823 Ok(Event::Eof) if block => return Err("a difference block is not closed".into()),
824 Ok(Event::Eof) => break,
825 Err(e) => return Err(Box::new(e)),
826 _ => {}
827 }
828 buf.clear();
829 }
830
831 Ok(())
832}
833
834fn strip_fragment(s: &str) -> String {
843 match s.rfind('#') {
844 Some(i) if i + 1 == s.len() && i > 0 => s.to_string(),
845 Some(i) => s[i + 1..].to_string(),
846 None => s.to_string(),
847 }
848}
849
850struct FieldAttrs {
852 resource: Option<String>,
854 resource_ns: Option<&'static str>,
857 lang: Option<String>,
858 datatype: Option<&'static str>,
859 nodes: bool,
863}
864
865fn field_attrs(
867 attrs: quick_xml::events::attributes::Attributes<'_>,
868) -> Result<FieldAttrs, Box<dyn std::error::Error>> {
869 let mut out = FieldAttrs {
870 resource: None,
871 resource_ns: None,
872 lang: None,
873 datatype: None,
874 nodes: false,
875 };
876 for attr in attrs.flatten() {
877 match attr.key.as_ref() {
878 b"rdf:resource" => {
879 let iri = std::str::from_utf8(&attr.value)?;
880 let kept = strip_fragment(iri);
881 if kept.len() < iri.len() && kept.len() + 1 < iri.len() {
882 out.resource_ns = Some(intern(&iri[..iri.len() - kept.len()]));
883 }
884 out.resource = Some(kept);
885 }
886 b"rdf:nodeID" => {
887 out.resource = Some(format!("_:{}", std::str::from_utf8(&attr.value)?))
888 }
889 b"xml:lang" => out.lang = Some(std::str::from_utf8(&attr.value)?.to_string()),
890 b"rdf:datatype" => out.datatype = Some(intern(std::str::from_utf8(&attr.value)?)),
891 b"rdf:parseType" => out.nodes = attr.value.as_ref() != b"Literal",
892 _ => {}
893 }
894 }
895 Ok(out)
896}