1use std::path::Path;
2
3use quick_xml::events::{BytesStart, Event};
4use quick_xml::Reader;
5
6use crate::base::{intern, AttrDef, AttrKind, ClassDef, Element, FastMap, FastSet, FieldValue, TypeRegistry};
7use crate::difference::{Block, Differences};
8use crate::registry;
9
10pub fn is_cim(text: &str) -> bool {
16 let mut end = text.len().min(8192);
17 while !text.is_char_boundary(end) {
18 end -= 1;
19 }
20 let head = &text[..end];
21 ["http://iec.ch/TC57/", "https://cim.ucaiug.io/ns#", "https://ap.cim4.eu/", "https://energy.referencedata.eu/"]
22 .iter()
23 .any(|marker| head.contains(marker))
24}
25
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
30pub struct FieldForm {
31 pub ns: Option<&'static str>,
36 pub datatype: Option<&'static str>,
39 pub resource_ns: Option<&'static str>,
44}
45
46impl FieldForm {
47 fn fill_from(&mut self, other: FieldForm) {
48 self.ns = self.ns.or(other.ns);
49 self.datatype = self.datatype.or(other.datatype);
50 self.resource_ns = self.resource_ns.or(other.resource_ns);
51 }
52}
53
54#[derive(Clone)]
55pub struct CimDataset {
56 pub entries: FastMap<String, Element>,
57 pub by_type: FastMap<String, Vec<String>>,
59 pub field_forms: FastMap<(&'static str, &'static str), FieldForm>,
66 pub type_ns: FastMap<String, &'static str>,
71 pub prefixes: FastMap<&'static str, &'static str>,
75 pub foreign: FastMap<String, Element>,
83 pub differences: Vec<Differences>,
89}
90
91impl Default for CimDataset {
92 fn default() -> Self {
93 Self::new()
94 }
95}
96
97impl CimDataset {
98 pub fn new() -> Self {
99 Self {
100 entries: FastMap::default(),
101 by_type: FastMap::default(),
102 field_forms: FastMap::default(),
103 type_ns: FastMap::default(),
104 prefixes: FastMap::default(),
105 foreign: FastMap::default(),
106 differences: Vec::new(),
107 }
108 }
109
110 pub fn decode_str(content: &str) -> Result<Self, Box<dyn std::error::Error>> {
112 let mut ds = Self::new();
113 parse_rdf(content, registry::type_registry(), &mut ds)?;
114 Ok(ds)
115 }
116
117 pub fn decode_file(path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
119 Self::decode_str(&std::fs::read_to_string(path)?)
120 }
121
122 pub fn decode_files(paths: &[&Path]) -> Result<Self, Box<dyn std::error::Error>> {
124 let mut combined = Self::new();
125 for path in paths {
126 let file_ds = Self::decode_file(path)?;
127 combined.merge(file_ds);
128 }
129 Ok(combined)
130 }
131
132 pub fn decode_files_parallel_separate(paths: &[&Path]) -> Result<Vec<Self>, Box<dyn std::error::Error>> {
136 if paths.len() <= 1 || cfg!(target_family = "wasm") {
138 return paths.iter().map(|p| Self::decode_file(p)).collect();
139 }
140 let results: Vec<Result<Self, String>> = std::thread::scope(|s| {
141 paths
142 .iter()
143 .map(|p| s.spawn(|| Self::decode_file(p).map_err(|e| e.to_string())))
144 .collect::<Vec<_>>()
145 .into_iter()
146 .map(|h| h.join().expect("decode thread panicked"))
147 .collect()
148 });
149 results
150 .into_iter()
151 .collect::<Result<_, String>>()
152 .map_err(|e| e.into())
153 }
154
155 pub fn decode_files_parallel(paths: &[&Path]) -> Result<Self, Box<dyn std::error::Error>> {
157 let datasets = Self::decode_files_parallel_separate(paths)?;
158 Ok(datasets
159 .into_iter()
160 .reduce(|mut a, b| {
161 a.merge(b);
162 a
163 })
164 .unwrap_or_default())
165 }
166
167 pub fn merge(&mut self, other: CimDataset) {
177 self.differences.extend(other.differences);
178 for (key, form) in other.field_forms {
179 self.field_forms.entry(key).or_default().fill_from(form);
180 }
181 for (mrid, ns) in other.type_ns {
182 self.type_ns.entry(mrid).or_insert(ns);
183 }
184 for (ns, prefix) in other.prefixes {
185 self.prefixes.entry(ns).or_insert(prefix);
186 }
187 for (id, incoming) in other.foreign {
188 match self.foreign.get_mut(&id) {
189 Some(existing) => existing.merge_from(&incoming),
190 None => {
191 self.foreign.insert(id, incoming);
192 }
193 }
194 }
195 let reg = registry::type_registry();
196 let mut moved: FastMap<&'static str, FastSet<String>> = FastMap::default();
197 for (mrid, incoming) in other.entries {
198 if let Some(existing) = self.entries.get_mut(&mrid) {
199 existing.merge_from(&incoming);
200 let old = existing.class();
201 let mut changed = false;
202 for t in incoming.types() {
203 changed |= existing.add_type(t, reg);
204 }
205 if changed {
206 moved.entry(old.qualified).or_default().insert(mrid.clone());
207 self.by_type.entry(existing.type_name().to_string()).or_default().push(mrid);
208 }
209 } else {
210 let type_name = incoming.type_name().to_string();
211 self.by_type.entry(type_name).or_default().push(mrid.clone());
212 self.entries.insert(mrid, incoming);
213 }
214 }
215 for (old, mrids) in moved {
217 if let Some(bucket) = self.by_type.get_mut(old) {
218 bucket.retain(|m| !mrids.contains(m));
219 }
220 }
221 }
222
223 pub fn element_from_json(&self, class: &'static ClassDef, value: &serde_json::Value) -> Result<Element, String> {
231 let reg = registry::type_registry();
232 let mut element = Element::from_json(class, reg, value)?;
233 let keys: Vec<&'static str> = element.fields().keys().copied().collect();
234 for key in keys {
235 if let Some(reference) = self.held_as_reference(class.qualified, key) {
236 element.retype(key, reference);
237 }
238 }
239 Ok(element)
240 }
241
242 fn held_as_reference(&self, type_name: &str, key: &str) -> Option<bool> {
246 self.by_type
247 .get(type_name)
248 .into_iter()
249 .flatten()
250 .filter_map(|m| self.entries.get(m))
251 .find_map(|e| match e.get(key)? {
252 FieldValue::Resource(_) | FieldValue::ResourceList(_) => Some(true),
253 FieldValue::Text(_) | FieldValue::TextList(_) => Some(false),
254 })
255 .or_else(|| self.field_forms.get(&(type_name, key)).and_then(|f| f.resource_ns).map(|_| true))
256 }
257
258 pub fn set(&mut self, mrid: String, element: Element) {
261 let new_type = element.type_name().to_string();
262 if let Some(old) = self.entries.get(&mrid) {
263 let old_type = old.type_name();
264 if old_type != new_type
265 && let Some(v) = self.by_type.get_mut(old_type) {
266 v.retain(|m| m != &mrid);
267 }
268 }
269 let already_indexed = self
270 .by_type
271 .get(&new_type)
272 .is_some_and(|v| v.contains(&mrid));
273 if !already_indexed {
274 self.by_type.entry(new_type).or_default().push(mrid.clone());
275 }
276 self.entries.insert(mrid, element);
277 }
278
279 pub fn remove(&mut self, mrid: &str) -> Option<Element> {
282 let removed = self.entries.remove(mrid)?;
283 if let Some(v) = self.by_type.get_mut(removed.type_name()) {
284 v.retain(|m| m != mrid);
285 }
286 Some(removed)
287 }
288
289 pub fn type_conflicts(&self) -> Vec<(&str, Vec<&'static str>)> {
295 let reg = registry::type_registry();
296 let related = |a: &ClassDef, b: &ClassDef| {
297 reg.chain(a).iter().any(|c| c.qualified == b.qualified)
298 || reg.chain(b).iter().any(|c| c.qualified == a.qualified)
299 };
300 let mut out: Vec<(&str, Vec<&'static str>)> = self
301 .entries
302 .iter()
303 .filter_map(|(mrid, e)| {
304 let types: Vec<&'static ClassDef> = e.types().collect();
305 let conflict = types.iter().enumerate().any(|(i, a)| types[i + 1..].iter().any(|b| !related(a, b)));
306 conflict.then(|| (mrid.as_str(), types.iter().map(|c| c.qualified).collect()))
307 })
308 .collect();
309 out.sort_unstable();
310 out
311 }
312}
313
314fn index(by_type: &mut FastMap<String, Vec<String>>, type_name: &'static str, mrid: String) {
319 if let Some(bucket) = by_type.get_mut(type_name) {
320 bucket.push(mrid);
321 } else {
322 by_type.insert(type_name.to_string(), vec![mrid]);
323 }
324}
325
326type Table = FastMap<&'static str, &'static ClassDef>;
327
328#[derive(Default, Clone)]
334struct Scope {
335 prefixes: Vec<(Vec<u8>, &'static str, Option<&'static Table>)>,
337 default: Option<&'static Table>,
338 default_ns: &'static str,
339}
340
341impl Scope {
342 fn absorb(&mut self, e: &BytesStart, reg: &'static TypeRegistry) {
344 for attr in e.attributes().flatten() {
345 let key = attr.key.as_ref();
346 let Some(rest) = key.strip_prefix(b"xmlns".as_slice()) else {
347 continue;
348 };
349 let Ok(ns) = std::str::from_utf8(&attr.value) else {
350 continue;
351 };
352 let table = reg.ns_table(ns).or_else(|| {
354 if ns.ends_with('#') || ns.ends_with('/') {
355 None
356 } else {
357 reg.ns_table(&format!("{ns}#"))
358 }
359 });
360 let ns = intern(ns);
361 match rest.strip_prefix(b":".as_slice()) {
362 Some(prefix) => {
363 let prefix = prefix.to_vec();
364 match self.prefixes.iter_mut().find(|(k, _, _)| *k == prefix) {
365 Some(slot) => (slot.1, slot.2) = (ns, table),
366 None => self.prefixes.push((prefix, ns, table)),
367 }
368 }
369 None if rest.is_empty() => (self.default, self.default_ns) = (table, ns),
370 None => {}
371 }
372 }
373 }
374
375 fn table(&self, prefix: Option<&[u8]>) -> Option<&'static Table> {
376 match prefix {
377 None => self.default,
378 Some(p) => self
379 .prefixes
380 .iter()
381 .find(|(k, _, _)| k.as_slice() == p)
382 .and_then(|(_, _, t)| *t),
383 }
384 }
385
386 fn ns(&self, prefix: Option<&[u8]>) -> &'static str {
388 match prefix {
389 None => self.default_ns,
390 Some(p) => self.prefixes.iter().find(|(k, _, _)| k.as_slice() == p).map_or("", |(_, ns, _)| ns),
391 }
392 }
393
394}
395
396struct Subject {
398 mrid: String,
401 id: String,
404 described: bool,
406 has_xmlns: bool,
407}
408
409fn scan_attrs(e: &BytesStart) -> Result<Subject, Box<dyn std::error::Error>> {
413 let mut subject = Subject { mrid: String::new(), id: String::new(), described: false, has_xmlns: false };
414 let mut defined = false;
415 for attr in e.attributes().flatten() {
416 let key = attr.key.as_ref();
417 if key == b"rdf:about" || key == b"rdf:ID" {
418 let value = std::str::from_utf8(&attr.value)?;
419 subject.mrid = strip_fragment(value);
420 subject.id = value.strip_prefix('#').unwrap_or(value).to_string();
421 subject.described |= key == b"rdf:about";
422 defined |= key == b"rdf:ID";
423 } else if key == b"rdf:nodeID" {
424 subject.mrid = format!("_:{}", std::str::from_utf8(&attr.value)?);
425 subject.id = subject.mrid.clone();
426 } else if key.starts_with(b"xmlns") {
427 subject.has_xmlns = true;
428 }
429 }
430 subject.described &= !defined;
431 Ok(subject)
432}
433
434fn object(
439 scope: &Scope,
440 reg: &'static TypeRegistry,
441 e: &BytesStart,
442 subject: Subject,
443) -> Result<Option<(Element, bool, Option<&'static str>)>, Box<dyn std::error::Error>> {
444 if subject.id.is_empty() {
445 return Ok(None);
446 }
447 let name = e.name();
448 let (prefix, local) = split_qname(name.as_ref());
449 let ns = scope.ns(prefix);
450 let (mut element, foreign) = match resolve(scope, reg, name.as_ref())? {
451 Some(class) => (Element::new(class, subject.mrid), false),
452 None => (Element::new(crate::base::foreign_class(ns, std::str::from_utf8(local)?), subject.id), true),
453 };
454 if subject.described {
455 element.mark_described();
456 }
457 let written = (!ns.is_empty() && !same_ns(element.type_ns(), ns)).then_some(ns);
458 Ok(Some((element, foreign, written)))
459}
460
461fn same_ns(a: &str, b: &str) -> bool {
464 a == b || a.strip_suffix('#') == Some(b) || b.strip_suffix('#') == Some(a)
465}
466
467fn store(ds: &mut CimDataset, element: Element, foreign: bool, written: Option<&'static str>) {
469 if let Some(ns) = written
470 && !foreign
471 && !element.mrid().is_empty()
472 {
473 ds.type_ns.entry(element.mrid().to_string()).or_insert(ns);
474 }
475 if foreign {
476 ds.foreign.insert(element.mrid().to_string(), element);
477 } else if !element.mrid().is_empty() {
478 index(&mut ds.by_type, element.type_name(), element.mrid().to_string());
479 ds.entries.insert(element.mrid().to_string(), element);
480 }
481}
482
483fn split_qname(raw: &[u8]) -> (Option<&[u8]>, &[u8]) {
485 match raw.iter().position(|b| *b == b':') {
486 Some(i) => (Some(&raw[..i]), &raw[i + 1..]),
487 None => (None, raw),
488 }
489}
490
491fn resolve(
501 scope: &Scope,
502 reg: &'static TypeRegistry,
503 raw: &[u8],
504) -> Result<Option<&'static ClassDef>, Box<dyn std::error::Error>> {
505 let (prefix, local_bytes) = split_qname(raw);
506 let local = std::str::from_utf8(local_bytes)?;
507 if let Some(class) = scope.table(prefix).and_then(|t| t.get(local)) {
508 return Ok(Some(*class));
509 }
510 Ok(reg.bare().get(local).copied())
511}
512
513fn parse_rdf(
515 content: &str,
516 reg: &'static TypeRegistry,
517 ds: &mut CimDataset,
518) -> Result<(), Box<dyn std::error::Error>> {
519 let mut reader = Reader::from_str(content);
520 parse_events(&mut reader, reg, ds, Scope::default(), false)
521}
522
523fn block_of(key: &str) -> Option<Block> {
526 match key.rsplit('.').next()? {
527 "forwardDifferences" | "forwardDifference" => Some(Block::Forward),
528 "reverseDifferences" | "reverseDifference" => Some(Block::Reverse),
529 "preconditions" => Some(Block::Preconditions),
530 _ => None,
531 }
532}
533
534fn parse_events(
540 reader: &mut Reader<&[u8]>,
541 reg: &'static TypeRegistry,
542 ds: &mut CimDataset,
543 mut scope: Scope,
544 block: bool,
545) -> Result<(), Box<dyn std::error::Error>> {
546 let mut buf = Vec::new();
547
548 let mut depth: u32 = u32::from(block);
549 let mut differences: Option<Differences> = None;
551 let mut nested: Option<Scope> = None;
553 let mut current: Option<Element> = None;
556 let mut current_foreign = false;
558 let mut current_ns: Option<&'static str> = None;
560 let mut declared: Option<&'static FastMap<&'static str, &'static AttrDef>> = None;
562 let mut pending_key: Option<&'static str> = None;
563 let mut pending_lang: Option<String> = None;
565 let mut pending_text = String::new();
569 let field = |declared: Option<&'static FastMap<&'static str, &'static AttrDef>>,
575 class: &'static str,
576 e: &BytesStart,
577 scope: &Scope,
578 forms: &mut FastMap<(&'static str, &'static str), FieldForm>|
579 -> Result<(&'static str, FieldAttrs), Box<dyn std::error::Error>> {
580 let name = e.name();
581 let (prefix, local_bytes) = split_qname(name.as_ref());
582 let local = std::str::from_utf8(local_bytes)?;
583 let attr = declared.and_then(|d| d.get(local));
584 let key = attr.map_or_else(|| intern(local), |a| a.id);
585 let attrs = field_attrs(e.attributes())?;
586 let ns = scope.ns(prefix);
587 let undeclared_ns = (!ns.is_empty() && attr.is_none_or(|a| !same_ns(a.ns, ns))).then_some(ns);
588 let resource_ns = attrs.resource_ns.filter(|_| attr.is_none_or(|a| a.kind != AttrKind::Enum));
589 if undeclared_ns.is_some() || attrs.datatype.is_some() || resource_ns.is_some() {
590 forms.entry((class, key)).or_default().fill_from(FieldForm {
591 ns: undeclared_ns,
592 datatype: attrs.datatype,
593 resource_ns,
594 });
595 }
596 Ok((key, attrs))
597 };
598
599 loop {
600 match reader.read_event_into(&mut buf) {
601 Ok(Event::Start(ref e)) => {
602 depth += 1;
603
604 match depth {
605 1 => {
606 scope.absorb(e, reg);
607 for (prefix, ns, _) in &scope.prefixes {
608 if let Ok(prefix) = std::str::from_utf8(prefix) {
609 ds.prefixes.entry(ns).or_insert_with(|| intern(prefix));
610 }
611 }
612 }
613 2 => {
614 let subject = scan_attrs(e)?;
619 if subject.has_xmlns {
620 let mut inner = Scope {
621 prefixes: scope.prefixes.clone(),
622 default: scope.default,
623 default_ns: scope.default_ns,
624 };
625 inner.absorb(e, reg);
626 nested = Some(std::mem::replace(&mut scope, inner));
627 }
628
629 (current, current_foreign, current_ns) = match object(&scope, reg, e, subject)? {
630 Some((element, foreign, written)) => (Some(element), foreign, written),
631 None => (None, false, None),
632 };
633 declared = current.as_ref().and_then(|c| reg.declared(c.class()));
634 }
635 3 => {
636 if let Some(element) = current.as_mut() {
637 let (key, attrs) = field(declared, element.type_name(), e, &scope, &mut ds.field_forms)?;
638 if attrs.nodes
639 && let Some(which) = block_of(key)
640 {
641 let found = differences.get_or_insert_with(|| Differences::new(element.mrid()));
644 parse_events(reader, reg, found.block_mut(which), scope.clone(), true)?;
645 depth -= 1;
646 buf.clear();
647 continue;
648 }
649 if let Some(res) = attrs.resource {
650 element.add_field(key, FieldValue::Resource(res));
651 } else if !attrs.nodes {
652 pending_key = Some(key);
653 pending_lang = attrs.lang;
654 pending_text.clear();
655 }
656 }
657 }
658 _ => pending_key = None,
661 }
662 }
663
664 Ok(Event::Empty(ref e)) => {
665 match depth {
666 1 => {
667 let subject = scan_attrs(e)?;
672 let local_scope = if subject.has_xmlns {
673 let mut inner = Scope {
674 prefixes: scope.prefixes.clone(),
675 default: scope.default,
676 default_ns: scope.default_ns,
677 };
678 inner.absorb(e, reg);
679 Some(inner)
680 } else {
681 None
682 };
683 let active = local_scope.as_ref().unwrap_or(&scope);
684 if let Some((element, foreign, written)) = object(active, reg, e, subject)? {
685 store(ds, element, foreign, written);
686 }
687 }
688 2 => {
689 if let Some(element) = current.as_mut() {
692 let (key, attrs) = field(declared, element.type_name(), e, &scope, &mut ds.field_forms)?;
693 if attrs.nodes
694 && let Some(which) = block_of(key)
695 {
696 differences.get_or_insert_with(|| Differences::new(element.mrid())).block_mut(which);
698 } else if let Some(res) = attrs.resource {
699 element.add_field(key, FieldValue::Resource(res));
700 } else if !attrs.nodes {
701 element.add_field(key, FieldValue::Text(String::new()));
702 if let Some(lang) = attrs.lang {
703 element.add_lang(key, &lang);
704 }
705 }
706 }
707 }
708 _ => pending_key = None,
709 }
710 }
711
712 Ok(Event::Text(ref e)) if depth == 3 && pending_key.is_some() => {
713 pending_text.push_str(&e.unescape()?);
714 }
715
716 Ok(Event::CData(ref e)) if depth == 3 && pending_key.is_some() => {
717 pending_text.push_str(std::str::from_utf8(e)?);
718 }
719
720 Ok(Event::End(_)) => {
721 if depth == 3
722 && let (Some(element), Some(key)) = (current.as_mut(), pending_key.take()) {
723 element.add_field(key, FieldValue::Text(std::mem::take(&mut pending_text)));
724 if let Some(lang) = pending_lang.take() {
725 element.add_lang(key, &lang);
726 }
727 }
728 if depth == 2 {
729 pending_key = None;
730 pending_lang = None;
731 if let Some(element) = current.take() {
732 store(ds, element, current_foreign, current_ns.take());
733 }
734 if let Some(found) = differences.take() {
735 ds.differences.push(found);
736 }
737 if let Some(outer) = nested.take() {
738 scope = outer;
739 }
740 }
741 depth = depth.saturating_sub(1);
742 if block && depth == 0 {
744 break;
745 }
746 }
747
748 Ok(Event::Eof) if block => return Err("a difference block is not closed".into()),
749 Ok(Event::Eof) => break,
750 Err(e) => return Err(Box::new(e)),
751 _ => {}
752 }
753 buf.clear();
754 }
755
756 Ok(())
757}
758
759fn strip_fragment(s: &str) -> String {
769 match s.rfind('#') {
770 Some(i) if i + 1 == s.len() && i > 0 => s.to_string(),
771 Some(i) => s[i + 1..].to_string(),
772 None => s.to_string(),
773 }
774}
775
776
777struct FieldAttrs {
779 resource: Option<String>,
781 resource_ns: Option<&'static str>,
784 lang: Option<String>,
785 datatype: Option<&'static str>,
786 nodes: bool,
790}
791
792fn field_attrs(attrs: quick_xml::events::attributes::Attributes<'_>) -> Result<FieldAttrs, Box<dyn std::error::Error>> {
794 let mut out = FieldAttrs { resource: None, resource_ns: None, lang: None, datatype: None, nodes: false };
795 for attr in attrs.flatten() {
796 match attr.key.as_ref() {
797 b"rdf:resource" => {
798 let iri = std::str::from_utf8(&attr.value)?;
799 let kept = strip_fragment(iri);
800 if kept.len() < iri.len() && kept.len() + 1 < iri.len() {
801 out.resource_ns = Some(intern(&iri[..iri.len() - kept.len()]));
802 }
803 out.resource = Some(kept);
804 }
805 b"rdf:nodeID" => out.resource = Some(format!("_:{}", std::str::from_utf8(&attr.value)?)),
806 b"xml:lang" => out.lang = Some(std::str::from_utf8(&attr.value)?.to_string()),
807 b"rdf:datatype" => out.datatype = Some(intern(std::str::from_utf8(&attr.value)?)),
808 b"rdf:parseType" => out.nodes = attr.value.as_ref() != b"Literal",
809 _ => {}
810 }
811 }
812 Ok(out)
813}