1use std::error::Error;
16use std::fmt::Write;
17
18use crate::base::{ClassDef, Element, FastMap, FastSet, FieldValue, Value, foreign_class};
19use crate::convert_nc::Prefixes;
20use crate::decode::{CimDataset, FieldForm};
21use crate::registry::type_registry;
22
23const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
25pub(crate) const DM: &str = "http://iec.ch/TC57/61970-552/DifferenceModel/1#";
27pub(crate) const DCATCIM: &str = "https://cim4.eu/ns/dcatcim#";
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Block {
33 Forward,
35 Reverse,
37 Preconditions,
39}
40
41#[derive(Clone)]
43pub struct Differences {
44 pub header: String,
47 pub forward: CimDataset,
48 pub reverse: CimDataset,
49 pub preconditions: CimDataset,
50 pub blocks: Vec<Block>,
52}
53
54impl Differences {
55 pub(crate) fn new(header: &str) -> Self {
56 Self {
57 header: header.to_string(),
58 forward: CimDataset::new(),
59 reverse: CimDataset::new(),
60 preconditions: CimDataset::new(),
61 blocks: Vec::new(),
62 }
63 }
64
65 pub(crate) fn block_mut(&mut self, which: Block) -> &mut CimDataset {
67 if !self.blocks.contains(&which) {
68 self.blocks.push(which);
69 }
70 match which {
71 Block::Forward => &mut self.forward,
72 Block::Reverse => &mut self.reverse,
73 Block::Preconditions => &mut self.preconditions,
74 }
75 }
76
77 pub fn between(before: &CimDataset, after: &CimDataset) -> Self {
84 let mut d = Self::new("");
85 d.blocks = vec![Block::Reverse, Block::Forward];
86 let ids: FastSet<&str> = before
87 .entries
88 .keys()
89 .chain(before.foreign.keys())
90 .chain(after.entries.keys())
91 .chain(after.foreign.keys())
92 .map(String::as_str)
93 .collect();
94 let mut ids: Vec<&str> = ids.into_iter().collect();
95 ids.sort_unstable();
96 for id in ids {
97 let (was, now) = (lookup(before, id), lookup(after, id));
98 match (was, now) {
99 (Some((b, foreign)), None) => put(&mut d.reverse, b.clone(), foreign),
100 (None, Some((a, foreign))) => put(&mut d.forward, a.clone(), foreign),
101 (Some((b, foreign)), Some((a, _))) => {
102 let gone = without(b, a);
103 let came = without(a, b);
104 let types =
105 |e: &Element| e.types().map(|c| c.qualified).collect::<FastSet<_>>();
106 let (tb, ta) = (types(b), types(a));
107 let lost: Vec<&'static ClassDef> =
108 b.types().filter(|c| !ta.contains(c.qualified)).collect();
109 let gained: Vec<&'static ClassDef> =
110 a.types().filter(|c| !tb.contains(c.qualified)).collect();
111 if !gone.is_empty() || !lost.is_empty() {
112 put(&mut d.reverse, statements(id, &lost, gone), foreign);
113 named(&mut d.reverse, before, id, b);
114 }
115 if !came.is_empty() || !gained.is_empty() {
116 put(&mut d.forward, statements(id, &gained, came), foreign);
117 named(&mut d.forward, after, id, a);
118 }
119 }
120 (None, None) => {}
121 }
122 }
123 d
124 }
125}
126
127fn lookup<'a>(ds: &'a CimDataset, id: &str) -> Option<(&'a Element, bool)> {
131 ds.entries
132 .get(id)
133 .or_else(|| ds.entries.get(fragment(id)))
134 .map(|e| (e, false))
135 .or_else(|| ds.foreign.get(id).map(|e| (e, true)))
136}
137
138fn fragment(id: &str) -> &str {
140 id.rsplit_once('#')
141 .map_or(id, |(_, f)| if f.is_empty() { id } else { f })
142}
143
144fn put(ds: &mut CimDataset, element: Element, foreign: bool) {
147 let id = element.mrid().to_string();
148 if foreign || element.class().qualified.starts_with(RDF) {
149 ds.foreign.insert(id, element);
150 } else {
151 ds.set(id, element);
152 }
153}
154
155fn without(a: &Element, b: &Element) -> Vec<(&'static str, FieldValue)> {
157 let mut out = Vec::new();
158 let mut keys: Vec<&'static str> = a.fields().keys().copied().collect();
159 keys.sort_unstable();
160 for key in keys {
161 for v in a.fields()[key].values() {
162 if !b.has_value(key, &v.owned()) {
163 out.push((key, v.owned()));
164 }
165 }
166 }
167 out
168}
169
170fn statements(
175 id: &str,
176 types: &[&'static ClassDef],
177 values: Vec<(&'static str, FieldValue)>,
178) -> Element {
179 let mut e = Element::new(foreign_class(RDF, "Description"), id.to_string());
180 e.set_types(types);
181 e.mark_described();
182 for (key, value) in values {
183 e.add_field(key, value);
184 }
185 e
186}
187
188fn named(block: &mut CimDataset, from: &CimDataset, id: &str, like: &Element) {
192 let Some(e) = block.foreign.get(id).filter(|e| untyped(e)) else {
193 return;
194 };
195 let reg = type_registry();
196 let class = e.class().qualified;
197 for &key in e.fields().keys() {
198 let form = from
199 .field_forms
200 .get(&(like.type_name(), key))
201 .copied()
202 .unwrap_or_default();
203 let ns = form
204 .ns
205 .or_else(|| reg.attr_of(like.class(), key).map(|a| a.ns));
206 let resource_ns = form.resource_ns;
207 block.field_forms.insert(
208 (class, key),
209 FieldForm {
210 ns,
211 datatype: form.datatype,
212 resource_ns,
213 },
214 );
215 }
216}
217
218pub(crate) fn write_blocks(
223 out: &mut String,
224 prefixes: &mut Prefixes,
225 d: &Differences,
226 ns: &'static str,
227) -> Result<(), Box<dyn Error>> {
228 let nc = ns == DCATCIM;
229 let prefix = prefixes.of(ns);
230 for &which in &d.blocks {
231 let (name, ds) = match (which, nc) {
232 (Block::Forward, false) => ("forwardDifferences", &d.forward),
233 (Block::Forward, true) => ("forwardDifference", &d.forward),
234 (Block::Reverse, false) => ("reverseDifferences", &d.reverse),
235 (Block::Reverse, true) => ("reverseDifference", &d.reverse),
236 (Block::Preconditions, false) => ("preconditions", &d.preconditions),
237 (Block::Preconditions, true) => continue,
238 };
239 let mut inner = String::new();
240 crate::convert::write_objects(&mut inner, prefixes, ds)?;
241 if inner.is_empty() {
242 write!(out, "\n <{prefix}:{name} rdf:parseType=\"Statements\"/>")?;
243 } else {
244 write!(
245 out,
246 "\n <{prefix}:{name} rdf:parseType=\"Statements\">\n{inner} </{prefix}:{name}>"
247 )?;
248 }
249 }
250 Ok(())
251}
252
253fn sorted(ds: &CimDataset) -> Vec<(&String, &Element)> {
255 let mut all: Vec<(&String, &Element)> = ds.entries.iter().chain(&ds.foreign).collect();
256 all.sort_unstable_by_key(|(id, _)| id.as_str());
257 all
258}
259
260fn untyped(e: &Element) -> bool {
262 e.class().qualified == "http://www.w3.org/1999/02/22-rdf-syntax-ns#Description"
263}
264
265#[derive(Debug, Clone, PartialEq, Eq)]
267pub enum Statement {
268 Type(&'static str),
270 Value(&'static str, FieldValue),
272}
273
274#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct Unmatched {
279 pub block: Block,
280 pub subject: String,
281 pub statement: Statement,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
287pub struct FieldChange {
288 pub key: &'static str,
289 pub before: Option<FieldValue>,
290 pub after: Option<FieldValue>,
291}
292
293#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct Changed {
296 pub id: String,
297 pub retyped: Option<(&'static str, &'static str)>,
299 pub fields: Vec<FieldChange>,
300}
301
302#[derive(Debug, Default)]
305pub struct Applied {
306 pub added: Vec<String>,
308 pub removed: Vec<Element>,
310 pub changed: Vec<Changed>,
311 pub unmatched: Vec<Unmatched>,
313 pub untyped: Vec<String>,
316}
317
318impl CimDataset {
319 pub fn apply(&mut self, d: &Differences) -> Applied {
327 let mut applied = Applied::default();
328 let miss = |applied: &mut Applied, block, subject: &str, statement| {
329 applied.unmatched.push(Unmatched {
330 block,
331 subject: subject.to_string(),
332 statement,
333 });
334 };
335
336 for (id, e) in sorted(&d.preconditions) {
338 let held = lookup(self, id).map(|(o, _)| o);
339 if !untyped(e) {
340 for t in e.types() {
341 if !held.is_some_and(|o| o.types().any(|c| c.qualified == t.qualified)) {
342 miss(
343 &mut applied,
344 Block::Preconditions,
345 id,
346 Statement::Type(t.qualified),
347 );
348 }
349 }
350 }
351 for (key, fv) in e.fields() {
352 for v in fv.values() {
353 if !held.is_some_and(|o| o.has_value(key, &v.owned())) {
354 miss(
355 &mut applied,
356 Block::Preconditions,
357 id,
358 Statement::Value(key, v.owned()),
359 );
360 }
361 }
362 }
363 }
364
365 let mut touched: Vec<&str> = d
367 .reverse
368 .entries
369 .keys()
370 .chain(d.reverse.foreign.keys())
371 .chain(d.forward.entries.keys())
372 .chain(d.forward.foreign.keys())
373 .map(String::as_str)
374 .collect::<FastSet<&str>>()
375 .into_iter()
376 .collect();
377 touched.sort_unstable();
378 let mut was: FastMap<&str, Option<(Element, bool)>> = FastMap::default();
380 let mut types: FastMap<&str, Vec<&'static ClassDef>> = FastMap::default();
381 for &id in &touched {
382 let found = lookup(self, id).map(|(e, f)| (e.clone(), f));
383 types.insert(
384 id,
385 found
386 .as_ref()
387 .map_or_else(Vec::new, |(e, _)| e.types().collect()),
388 );
389 was.insert(id, found);
390 }
391
392 for (id, e) in sorted(&d.reverse) {
393 let id = id.as_str();
394 let Some(object) = self.object_mut(id) else {
395 if !untyped(e) {
396 for t in e.types() {
397 miss(
398 &mut applied,
399 Block::Reverse,
400 id,
401 Statement::Type(t.qualified),
402 );
403 }
404 }
405 for (key, fv) in e.fields() {
406 for v in fv.values() {
407 miss(
408 &mut applied,
409 Block::Reverse,
410 id,
411 Statement::Value(key, v.owned()),
412 );
413 }
414 }
415 continue;
416 };
417 let mut missed = Vec::new();
418 for (key, fv) in e.fields() {
419 for v in fv.values() {
420 if !object.remove_value(key, &v.owned()) {
421 missed.push(Statement::Value(key, v.owned()));
422 }
423 }
424 }
425 if !untyped(e) {
426 let held = types.get_mut(id).expect("touched");
427 for t in e.types() {
428 match held.iter().position(|c| c.qualified == t.qualified) {
429 Some(i) => {
430 held.remove(i);
431 }
432 None => missed.push(Statement::Type(t.qualified)),
433 }
434 }
435 }
436 for statement in missed {
437 miss(&mut applied, Block::Reverse, id, statement);
438 }
439 }
440
441 for (id, e) in sorted(&d.forward) {
442 let id = id.as_str();
443 let stated: Vec<&'static ClassDef> = if untyped(e) {
444 Vec::new()
445 } else {
446 e.types().collect()
447 };
448 let held = types.get_mut(id).expect("touched");
449 for t in &stated {
450 if !held.iter().any(|c| c.qualified == t.qualified) {
451 held.push(t);
452 }
453 }
454 if self.object_mut(id).is_none() {
455 let Some(&class) = stated.first() else {
456 for (key, fv) in e.fields() {
458 for v in fv.values() {
459 miss(
460 &mut applied,
461 Block::Forward,
462 id,
463 Statement::Value(key, v.owned()),
464 );
465 }
466 }
467 continue;
468 };
469 let mut created = Element::new(class, e.mrid().to_string());
470 if !e.defined() {
471 created.mark_described();
472 }
473 let foreign = d.forward.foreign.contains_key(id);
474 put(self, created, foreign);
475 }
476 let object = self.object_mut(id).expect("just made");
477 for (key, fv) in e.fields() {
478 for v in fv.values() {
479 let value = v.owned();
480 if !object.has_value(key, &value) {
481 object.add_field(key, value);
482 }
483 }
484 }
485 }
486
487 for &id in &touched {
489 let now_types = &types[id];
490 let Some((key, foreign)) = self.key_of(id) else {
491 continue;
492 };
493 match &was[id] {
494 None => applied.added.push(key),
495 Some((before, _)) => {
496 let object = if foreign {
497 &self.foreign[&key]
498 } else {
499 &self.entries[&key]
500 };
501 if now_types.is_empty() {
502 if object.fields().is_empty() {
503 let removed = if foreign {
504 self.foreign.remove(&key)
505 } else {
506 self.remove(&key)
507 };
508 applied.removed.extend(removed.map(|_| before.clone()));
509 } else {
510 applied.untyped.push(key.clone());
511 if let Some(c) = changes(&key, before, object) {
512 applied.changed.push(c);
513 }
514 }
515 continue;
516 }
517 let mut object = object.clone();
518 if !now_types
519 .iter()
520 .map(|c| c.qualified)
521 .eq(object.types().map(|c| c.qualified))
522 {
523 object.set_types(now_types);
524 }
525 if let Some(c) = changes(&key, before, &object) {
526 applied.changed.push(c);
527 }
528 if foreign {
529 self.foreign.insert(key, object);
530 } else {
531 self.set(key, object);
532 }
533 }
534 }
535 }
536 applied.added.sort_unstable();
537 applied.added.dedup();
538 applied
539 }
540
541 fn object_mut(&mut self, id: &str) -> Option<&mut Element> {
543 let (key, foreign) = self.key_of(id)?;
544 if foreign {
545 self.foreign.get_mut(&key)
546 } else {
547 self.entries.get_mut(&key)
548 }
549 }
550
551 fn key_of(&self, id: &str) -> Option<(String, bool)> {
553 if self.entries.contains_key(id) {
554 Some((id.to_string(), false))
555 } else if self.entries.contains_key(fragment(id)) {
556 Some((fragment(id).to_string(), false))
557 } else if self.foreign.contains_key(id) {
558 Some((id.to_string(), true))
559 } else {
560 None
561 }
562 }
563}
564
565fn changes(id: &str, before: &Element, after: &Element) -> Option<Changed> {
568 let retyped = (before.class().qualified != after.class().qualified)
569 .then(|| (before.class().qualified, after.class().qualified));
570 let mut keys: Vec<&'static str> = before
571 .fields()
572 .keys()
573 .chain(after.fields().keys())
574 .copied()
575 .collect::<FastSet<_>>()
576 .into_iter()
577 .collect();
578 keys.sort_unstable();
579 let same = |a: Option<&FieldValue>, b: Option<&FieldValue>| match (a, b) {
580 (None, None) => true,
581 (Some(a), Some(b)) => {
582 let mut x: Vec<Value> = a.values().collect();
583 let mut y: Vec<Value> = b.values().collect();
584 x.sort_unstable();
585 y.sort_unstable();
586 x == y
587 }
588 _ => false,
589 };
590 let fields: Vec<FieldChange> = keys
591 .into_iter()
592 .filter(|k| !same(before.fields().get(k), after.fields().get(k)))
593 .map(|k| FieldChange {
594 key: k,
595 before: before.fields().get(k).cloned(),
596 after: after.fields().get(k).cloned(),
597 })
598 .collect();
599 (retyped.is_some() || !fields.is_empty()).then(|| Changed {
600 id: id.to_string(),
601 retyped,
602 fields,
603 })
604}