fhir-diff 0.1.2

Semantic diff of FHIR packages and profiles with a breaking-change gate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
//! Changes between two versions of a package, profile by profile and element by element, each
//! classified by what it does to existing data and implementations.
//!
//! **Breaking**: an instance valid against the old profile may be invalid against the new one,
//! or an implementer gains an obligation — a profile removed or replaced, `min` up, `max` down,
//! a type or reference target removed, a new mustSupport, a stronger binding, a new error
//! invariant, a new or changed fixed/pattern value, slicing closed, a required slice added.
//! **Warning**: may break, depending on content the diff does not see — a different value set
//! under a required or extensible binding, a changed invariant expression, a different base, a
//! changed modifier flag, a new warning invariant.
//! **Info**: relaxations and additions that keep old instances valid.

use std::collections::{BTreeMap, BTreeSet};

use serde::Serialize;

use crate::model::{Node, Pool, Profile, Strength, is_variant};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Info,
    Warning,
    Breaking,
}

impl Severity {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Breaking => "breaking",
        }
    }
}

/// Every rule, with its severity and what it means.
pub const RULES: &[(&str, Severity, &str)] = &[
    (
        "profile-removed",
        Severity::Breaking,
        "A profile or extension definition was removed",
    ),
    (
        "profile-added",
        Severity::Info,
        "A profile or extension definition was added",
    ),
    (
        "profile-replaced",
        Severity::Breaking,
        "A profile gave way to one with another canonical URL: each is the only one of its type removed or added",
    ),
    (
        "base-changed",
        Severity::Warning,
        "The profile is based on a different definition",
    ),
    (
        "min-increased",
        Severity::Breaking,
        "The minimum cardinality went up",
    ),
    (
        "min-decreased",
        Severity::Info,
        "The minimum cardinality went down",
    ),
    (
        "max-decreased",
        Severity::Breaking,
        "The maximum cardinality went down",
    ),
    (
        "max-increased",
        Severity::Info,
        "The maximum cardinality went up",
    ),
    (
        "type-removed",
        Severity::Breaking,
        "A type the element allowed is no longer allowed",
    ),
    (
        "type-added",
        Severity::Info,
        "The element allows another type",
    ),
    (
        "target-removed",
        Severity::Breaking,
        "A reference target type is no longer allowed",
    ),
    (
        "target-narrowed",
        Severity::Warning,
        "A reference target was narrowed to a profile of the same type",
    ),
    (
        "target-added",
        Severity::Info,
        "A reference may point to another profile",
    ),
    (
        "must-support-added",
        Severity::Breaking,
        "The element became mustSupport",
    ),
    (
        "must-support-removed",
        Severity::Info,
        "The element is no longer mustSupport",
    ),
    (
        "binding-stronger",
        Severity::Breaking,
        "The binding became extensible or required, or required from extensible",
    ),
    (
        "binding-stronger-advisory",
        Severity::Info,
        "The binding strength went up but stays advisory (example → preferred)",
    ),
    (
        "binding-weaker",
        Severity::Info,
        "The binding strength went down",
    ),
    (
        "binding-added",
        Severity::Breaking,
        "A required or extensible binding was added",
    ),
    (
        "value-set-changed",
        Severity::Warning,
        "A required or extensible binding names another value set",
    ),
    (
        "invariant-added",
        Severity::Breaking,
        "An error invariant was added",
    ),
    (
        "invariant-warning-added",
        Severity::Warning,
        "A warning invariant was added",
    ),
    (
        "invariant-changed",
        Severity::Warning,
        "An invariant's expression changed",
    ),
    (
        "invariant-moved",
        Severity::Info,
        "An invariant moved to another element and says the same from there",
    ),
    (
        "invariant-removed",
        Severity::Info,
        "An invariant was removed",
    ),
    (
        "fixed-added",
        Severity::Breaking,
        "A fixed or pattern value was added",
    ),
    (
        "fixed-changed",
        Severity::Breaking,
        "The fixed or pattern value changed",
    ),
    (
        "fixed-removed",
        Severity::Info,
        "The fixed or pattern value was removed",
    ),
    (
        "slicing-closed",
        Severity::Breaking,
        "Slicing became closed",
    ),
    ("slicing-opened", Severity::Info, "Slicing became open"),
    ("slice-added", Severity::Info, "An optional slice was added"),
    ("slice-removed", Severity::Warning, "A slice was removed"),
    (
        "modifier-changed",
        Severity::Warning,
        "The isModifier flag changed",
    ),
];

pub fn severity_of(rule: &str) -> Severity {
    RULES
        .iter()
        .find(|(id, _, _)| *id == rule)
        .map_or(Severity::Info, |(_, severity, _)| *severity)
}

/// One change.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Change {
    pub rule: &'static str,
    pub severity: Severity,
    /// Element path, slices written `:name` (`Patient.identifier:mrn.system`).
    pub path: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Added,
    Removed,
    Changed,
    Unchanged,
}

/// The changes of one profile.
#[derive(Debug, Clone, Serialize)]
pub struct ProfileDiff {
    pub url: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    pub type_name: String,
    pub status: Status,
    /// Canonical URL of the profile this one took over from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replaces: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_version: Option<String>,
    /// File in the new package (the old one for a removed profile).
    pub file: String,
    pub changes: Vec<Change>,
}

impl ProfileDiff {
    pub fn worst(&self) -> Option<Severity> {
        self.changes.iter().map(|c| c.severity).max()
    }
}

/// The diff of two packages.
#[derive(Debug, Clone, Serialize)]
pub struct Report {
    pub old: String,
    pub new: String,
    pub profiles: Vec<ProfileDiff>,
    /// Definitions that could not be read, and bases that were missing or taken from the other
    /// package.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<String>,
}

impl Report {
    pub fn count(&self, severity: Severity) -> usize {
        self.profiles
            .iter()
            .flat_map(|p| &p.changes)
            .filter(|c| c.severity == severity)
            .count()
    }

    pub fn worst(&self) -> Option<Severity> {
        self.profiles.iter().filter_map(ProfileDiff::worst).max()
    }
}

/// Which profiles to compare.
#[derive(Debug, Clone, Default)]
pub struct Filter {
    /// URLs or names; empty compares all.
    pub profiles: Vec<String>,
}

impl Filter {
    fn admits(&self, profile: &Profile) -> bool {
        self.profiles.is_empty()
            || self
                .profiles
                .iter()
                .any(|p| p == &profile.url || p == &profile.name)
    }
}

/// Compare the profiles of two pools.
pub fn diff(old_id: &str, old: &Pool, new_id: &str, new: &Pool, filter: &Filter) -> Report {
    let (old_all, new_all) = (old.profiles(), new.profiles());
    // A profile is chosen on either side: renamed between versions (US Core `USCoreLocation` →
    // `USCoreLocationProfile`), its canonical URL still pairs the two.
    let chosen: BTreeSet<String> = old_all
        .iter()
        .chain(&new_all)
        .filter(|p| filter.admits(p))
        .map(|p| p.url.clone())
        .collect();
    let keep = |profiles: Vec<Profile>| -> BTreeMap<String, Profile> {
        profiles
            .into_iter()
            .filter(|p| chosen.contains(&p.url))
            .map(|p| (p.url.clone(), p))
            .collect()
    };
    let (old_profiles, new_profiles) = (keep(old_all), keep(new_all));
    let urls: BTreeSet<&String> = old_profiles.keys().chain(new_profiles.keys()).collect();
    let replacements = replacements(&old_profiles, &new_profiles);
    let replaced: BTreeSet<&String> = replacements.values().collect();
    let mut profiles = Vec::new();
    for url in urls {
        if replaced.contains(url) {
            continue;
        }
        let predecessor = replacements
            .get(url)
            .and_then(|previous| old_profiles.get(previous));
        let entry = match (predecessor.or(old_profiles.get(url)), new_profiles.get(url)) {
            (Some(o), Some(n)) => {
                let mut changes = Vec::new();
                if o.url != n.url {
                    changes.push(change(
                        "profile-replaced",
                        &n.type_name,
                        &format!("Takes over from {}", o.url),
                        Some(o.url.clone()),
                        Some(n.url.clone()),
                    ));
                }
                if o.base != n.base {
                    changes.push(change(
                        "base-changed",
                        &n.type_name,
                        "The profile is based on another definition",
                        o.base.clone(),
                        n.base.clone(),
                    ));
                }
                let mut walker = Walker {
                    old,
                    new,
                    changes: &mut changes,
                    invariants_added: Vec::new(),
                    invariants_removed: Vec::new(),
                };
                walker.node(&n.type_name, &n.type_name, &o.tree, &n.tree);
                let (added, removed) = (walker.invariants_added, walker.invariants_removed);
                fold_moved_invariants(&mut changes, &added, &removed);
                ProfileDiff {
                    url: url.clone(),
                    name: n.name.clone(),
                    title: n.title.clone(),
                    type_name: n.type_name.clone(),
                    status: if changes.is_empty() {
                        Status::Unchanged
                    } else {
                        Status::Changed
                    },
                    replaces: (o.url != n.url).then(|| o.url.clone()),
                    old_version: o.version.clone(),
                    new_version: n.version.clone(),
                    file: n.file.clone(),
                    changes,
                }
            }
            (Some(o), None) => ProfileDiff {
                url: url.clone(),
                name: o.name.clone(),
                title: o.title.clone(),
                type_name: o.type_name.clone(),
                status: Status::Removed,
                replaces: None,
                old_version: o.version.clone(),
                new_version: None,
                file: o.file.clone(),
                changes: vec![change(
                    "profile-removed",
                    &o.type_name,
                    "The profile is not in the new package",
                    Some(url.clone()),
                    None,
                )],
            },
            (None, Some(n)) => ProfileDiff {
                url: url.clone(),
                name: n.name.clone(),
                title: n.title.clone(),
                type_name: n.type_name.clone(),
                status: Status::Added,
                replaces: None,
                old_version: None,
                new_version: n.version.clone(),
                file: n.file.clone(),
                changes: vec![change(
                    "profile-added",
                    &n.type_name,
                    "The profile is new",
                    None,
                    Some(url.clone()),
                )],
            },
            (None, None) => continue,
        };
        profiles.push(entry);
    }
    let notes = old
        .skipped
        .iter()
        .map(|(file, reason)| format!("{old_id}: {file}: {reason}"))
        .chain(
            new.skipped
                .iter()
                .map(|(file, reason)| format!("{new_id}: {file}: {reason}")),
        )
        .chain(old.missing.borrow().iter().map(|base| {
            format!("{old_id}: base {base} is in no loaded package; compared over the core type")
        }))
        .chain(new.missing.borrow().iter().map(|base| {
            format!("{new_id}: base {base} is in no loaded package; compared over the core type")
        }))
        .chain(old.borrowed.iter().map(|base| {
            format!("{old_id}: base {base} is in no listed dependency; taken from {new_id}'s")
        }))
        .chain(new.borrowed.iter().map(|base| {
            format!("{new_id}: base {base} is in no listed dependency; taken from {old_id}'s")
        }))
        .collect();
    Report {
        old: old_id.to_owned(),
        new: new_id.to_owned(),
        profiles,
        notes,
    }
}

/// Profiles that took over from another under a new canonical URL, new URL to old. A package
/// says nothing about this, so the pair is inferred, and only where it leaves no choice: the one
/// profile of a type removed and the one added. Extensions are left out, since two of them on
/// the same type say nothing about each other.
fn replacements(
    old: &BTreeMap<String, Profile>,
    new: &BTreeMap<String, Profile>,
) -> BTreeMap<String, String> {
    let only_here = |side: &'_ BTreeMap<String, Profile>, other: &BTreeMap<String, Profile>| {
        let mut by_type: BTreeMap<String, Vec<String>> = BTreeMap::new();
        for profile in side.values() {
            if !other.contains_key(&profile.url) && profile.type_name != "Extension" {
                by_type
                    .entry(profile.type_name.clone())
                    .or_default()
                    .push(profile.url.clone());
            }
        }
        by_type
    };
    let (removed, added) = (only_here(old, new), only_here(new, old));
    removed
        .iter()
        .filter_map(
            |(type_name, urls)| match (urls.as_slice(), added.get(type_name)?.as_slice()) {
                ([previous], [next]) => Some((next.clone(), previous.clone())),
                _ => None,
            },
        )
        .collect()
}

/// An invariant found on one element and gone from another.
struct InvariantSite {
    key: String,
    severity: String,
    /// Its change in the profile's list.
    index: usize,
}

/// An invariant that left one element and arrived on another is one change, not a removal and
/// an addition.
fn fold_moved_invariants(
    changes: &mut Vec<Change>,
    added: &[InvariantSite],
    removed: &[InvariantSite],
) {
    let mut folded = BTreeSet::new();
    for site in added {
        let Some(from) = removed
            .iter()
            .find(|r| r.key == site.key && !folded.contains(&r.index))
        else {
            continue;
        };
        let origin = changes[from.index].clone();
        let (old_expression, arrival) = (origin.old.unwrap_or_default(), &mut changes[site.index]);
        let new_expression = arrival.new.clone().unwrap_or_default();
        let same = from.severity == site.severity
            && same_after_move(
                &origin.path,
                &old_expression,
                &arrival.path,
                &new_expression,
            );
        let (rule, message) = if same {
            (
                "invariant-moved",
                format!("Invariant {} moved from {}", site.key, origin.path),
            )
        } else {
            (
                "invariant-changed",
                format!(
                    "Invariant {} moved from {} and changed",
                    site.key, origin.path
                ),
            )
        };
        arrival.rule = rule;
        arrival.severity = severity_of(rule);
        arrival.message = message;
        arrival.old = Some(old_expression);
        folded.insert(from.index);
    }
    let mut index = 0;
    changes.retain(|_| {
        index += 1;
        !folded.contains(&(index - 1))
    });
}

/// Whether two expressions say the same from their own elements: `value.ofType(Quantity)` on
/// `Observation` is `ofType(Quantity)` on `Observation.value`.
fn same_after_move(from: &str, old: &str, to: &str, new: &str) -> bool {
    match (to.strip_prefix(from), from.strip_prefix(to)) {
        (Some(tail), _) if tail.starts_with('.') => relative_to(old, &tail[1..]) == new,
        (_, Some(tail)) if tail.starts_with('.') => relative_to(new, &tail[1..]) == old,
        _ => old == new,
    }
}

/// `expression` with the leading `element.` taken off every path that starts with it.
fn relative_to(expression: &str, element: &str) -> String {
    let prefix = format!("{element}.");
    let mut result = String::new();
    let mut rest = expression;
    while let Some(at) = rest.find(&prefix) {
        result.push_str(&rest[..at]);
        let inside_a_path = result
            .chars()
            .next_back()
            .is_some_and(|c| c.is_alphanumeric() || c == '.' || c == '_');
        if inside_a_path {
            result.push_str(&prefix);
        }
        rest = &rest[at + prefix.len()..];
    }
    result.push_str(rest);
    result
}

fn change(
    rule: &'static str,
    path: &str,
    message: &str,
    old: Option<String>,
    new: Option<String>,
) -> Change {
    Change {
        rule,
        severity: severity_of(rule),
        path: path.to_owned(),
        message: message.to_owned(),
        old,
        new,
    }
}

fn cardinality(max: Option<u32>) -> String {
    max.map_or_else(|| "*".to_owned(), |m| m.to_string())
}

struct Walker<'a> {
    old: &'a Pool,
    new: &'a Pool,
    changes: &'a mut Vec<Change>,
    invariants_added: Vec<InvariantSite>,
    invariants_removed: Vec<InvariantSite>,
}

impl Walker<'_> {
    fn push(
        &mut self,
        rule: &'static str,
        path: &str,
        message: String,
        old: Option<String>,
        new: Option<String>,
    ) {
        self.changes.push(Change {
            rule,
            severity: severity_of(rule),
            path: path.to_owned(),
            message,
            old,
            new,
        });
    }

    /// Compare two versions of one element; `type_name` is the element's own type, for
    /// looking up children only one version constrains.
    fn node(&mut self, path: &str, type_name: &str, old: &Node, new: &Node) {
        self.element(path, type_name, old, new, false, &BTreeMap::new());
    }

    /// Compare an element; a choice `variant` (`valueQuantity`) repeats what its choice
    /// element says about cardinality, flags, invariants and type slices, so only its own
    /// binding, value and children are compared. `old_siblings` are the elements next to `old`,
    /// where a choice keeps its variants.
    fn element(
        &mut self,
        path: &str,
        type_name: &str,
        old: &Node,
        new: &Node,
        variant: bool,
        old_siblings: &BTreeMap<String, Node>,
    ) {
        if !variant {
            self.cardinality(path, old, new);
            self.types(path, old, new);
            self.flags(path, old, new);
            self.constraints(path, old, new);
            self.slicing(path, old, new);
        }
        self.binding(path, old, new);
        self.pattern(path, old, new);

        let names: BTreeSet<&String> = old.children.keys().chain(new.children.keys()).collect();
        for name in names {
            let child_path = format!("{path}.{name}");
            let (o, n) = (old.children.get(name), new.children.get(name));
            let child_type = n
                .or(o)
                .and_then(|c| (c.types.len() == 1).then(|| c.types.iter().next().cloned()))
                .flatten()
                .unwrap_or_default();
            let variant = is_variant(&new.children, name) || is_variant(&old.children, name);
            match (o, n) {
                (Some(o), Some(n)) => {
                    if variant && choice_settled(old, new, name) {
                        self.flags(&child_path, o, n);
                    }
                    self.element(&child_path, &child_type, o, n, variant, &old.children);
                }
                (Some(o), None) => {
                    let base = self.base(type_name, name, o);
                    self.element(&child_path, &child_type, o, &base, variant, &old.children);
                }
                (None, Some(n)) => {
                    let base = self.base(type_name, name, n);
                    self.element(&child_path, &child_type, &base, n, variant, &old.children);
                }
                (None, None) => {}
            }
        }

        if variant {
            return;
        }
        let slices: BTreeSet<&String> = old.slices.keys().chain(new.slices.keys()).collect();
        for slice in slices {
            let slice_path = format!("{path}:{slice}");
            match (old.slices.get(slice), new.slices.get(slice)) {
                (Some(o), Some(n)) => self.node(&slice_path, type_name, o, n),
                (Some(_), None) => self.push(
                    "slice-removed",
                    &slice_path,
                    format!("Slice {slice} was removed"),
                    Some(slice.clone()),
                    None,
                ),
                (None, Some(n)) => {
                    if n.min > 0 {
                        self.push(
                            "min-increased",
                            &slice_path,
                            format!("Required slice {slice} was added (min {})", n.min),
                            Some("0".into()),
                            Some(n.min.to_string()),
                        );
                    } else {
                        self.push(
                            "slice-added",
                            &slice_path,
                            format!("Optional slice {slice} was added"),
                            None,
                            Some(slice.clone()),
                        );
                    }
                    // A type slice of a choice asks for nothing new when that type already was
                    // mustSupport.
                    let supported = old_siblings.get(slice).is_some_and(|v| v.must_support);
                    if n.must_support && !supported {
                        self.push(
                            "must-support-added",
                            &slice_path,
                            format!("New slice {slice} is mustSupport"),
                            None,
                            Some("true".into()),
                        );
                    }
                }
                (None, None) => {}
            }
        }
    }

    /// What an element only one version constrains is in the other: its core definition,
    /// else the same element without constraints.
    fn base(&self, type_name: &str, name: &str, present: &Node) -> Node {
        let core = self
            .new
            .base_node(type_name, name)
            .or_else(|| self.old.base_node(type_name, name));
        match core {
            Some(mut base) => {
                // The core definition has no nested constraints of its own here.
                base.children.clear();
                base
            }
            // Not a core element (a backbone child, a logical model): compare the
            // constraints alone, keeping the element's shape.
            None => Node {
                types: present.types.clone(),
                max: present.max,
                targets: present.targets.clone(),
                ..Node::unconstrained()
            },
        }
    }

    fn cardinality(&mut self, path: &str, old: &Node, new: &Node) {
        if new.min > old.min {
            self.push(
                "min-increased",
                path,
                format!("min {} → {}", old.min, new.min),
                Some(old.min.to_string()),
                Some(new.min.to_string()),
            );
        } else if new.min < old.min {
            self.push(
                "min-decreased",
                path,
                format!("min {} → {}", old.min, new.min),
                Some(old.min.to_string()),
                Some(new.min.to_string()),
            );
        }
        let narrower = match (old.max, new.max) {
            (None, Some(_)) => Some(true),
            (Some(_), None) => Some(false),
            (Some(a), Some(b)) if b < a => Some(true),
            (Some(a), Some(b)) if b > a => Some(false),
            _ => None,
        };
        if let Some(narrower) = narrower {
            self.push(
                if narrower {
                    "max-decreased"
                } else {
                    "max-increased"
                },
                path,
                format!("max {} → {}", cardinality(old.max), cardinality(new.max)),
                Some(cardinality(old.max)),
                Some(cardinality(new.max)),
            );
        }
    }

    fn types(&mut self, path: &str, old: &Node, new: &Node) {
        // A node that names no type allows its base's types.
        if !old.types.is_empty() && !new.types.is_empty() {
            for removed in old.types.difference(&new.types) {
                self.push(
                    "type-removed",
                    path,
                    format!("Type {removed} is no longer allowed"),
                    Some(removed.clone()),
                    None,
                );
            }
            for added in new.types.difference(&old.types) {
                self.push(
                    "type-added",
                    path,
                    format!("Type {added} is allowed"),
                    None,
                    Some(added.clone()),
                );
            }
        }
        if old.targets.is_empty() && !new.targets.is_empty() {
            self.push(
                "target-removed",
                path,
                format!("References are restricted to {}", join(&new.targets)),
                None,
                Some(join(&new.targets)),
            );
        } else if !new.targets.is_empty() {
            let mut added: Vec<&String> = new.targets.difference(&old.targets).collect();
            for removed in old.targets.difference(&new.targets) {
                let removed_type = self.old.type_of(removed);
                // `Patient` → `us-core-patient`: the same type, now with a profile.
                let narrowed = added
                    .iter()
                    .position(|a| removed_type.is_some() && self.new.type_of(a) == removed_type);
                match narrowed {
                    Some(index) => {
                        let to = added.remove(index);
                        self.push(
                            "target-narrowed",
                            path,
                            format!("Target {removed} narrowed to {to}"),
                            Some(removed.clone()),
                            Some(to.clone()),
                        );
                    }
                    None => self.push(
                        "target-removed",
                        path,
                        format!("Target {removed} is no longer allowed"),
                        Some(removed.clone()),
                        None,
                    ),
                }
            }
            for added in added {
                self.push(
                    "target-added",
                    path,
                    format!("Target {added} is allowed"),
                    None,
                    Some(added.clone()),
                );
            }
        }
    }

    fn flags(&mut self, path: &str, old: &Node, new: &Node) {
        match (old.must_support, new.must_support) {
            (false, true) => self.push(
                "must-support-added",
                path,
                "Became mustSupport".into(),
                Some("false".into()),
                Some("true".into()),
            ),
            (true, false) => self.push(
                "must-support-removed",
                path,
                "No longer mustSupport".into(),
                Some("true".into()),
                Some("false".into()),
            ),
            _ => {}
        }
        // Profiles cannot change isModifier on an element; an extension definition can
        // (its root): compare it there only.
        if !path.contains('.') && old.is_modifier != new.is_modifier {
            self.push(
                "modifier-changed",
                path,
                format!("isModifier {} → {}", old.is_modifier, new.is_modifier),
                Some(old.is_modifier.to_string()),
                Some(new.is_modifier.to_string()),
            );
        }
    }

    fn binding(&mut self, path: &str, old: &Node, new: &Node) {
        let describe = |b: &crate::model::Binding| {
            format!(
                "{} {}",
                b.strength.as_str(),
                b.value_set.as_deref().unwrap_or("(no value set)")
            )
        };
        match (&old.binding, &new.binding) {
            (None, Some(n)) if n.strength >= Strength::Extensible => {
                self.push(
                    "binding-added",
                    path,
                    format!("Bound {}", describe(n)),
                    None,
                    Some(describe(n)),
                );
            }
            (Some(o), Some(n)) => {
                if n.strength > o.strength {
                    // Only an extensible or required binding can make existing data invalid.
                    let rule = if n.strength >= Strength::Extensible {
                        "binding-stronger"
                    } else {
                        "binding-stronger-advisory"
                    };
                    self.push(
                        rule,
                        path,
                        format!("{} → {}", o.strength.as_str(), n.strength.as_str()),
                        Some(describe(o)),
                        Some(describe(n)),
                    );
                } else if n.strength < o.strength {
                    self.push(
                        "binding-weaker",
                        path,
                        format!("{} → {}", o.strength.as_str(), n.strength.as_str()),
                        Some(describe(o)),
                        Some(describe(n)),
                    );
                }
                let plain = |vs: &Option<String>| {
                    vs.as_deref()
                        .map(|v| v.split('|').next().unwrap_or(v).to_owned())
                };
                if plain(&o.value_set) != plain(&n.value_set) && n.strength >= Strength::Extensible
                {
                    self.push(
                        "value-set-changed",
                        path,
                        format!(
                            "Value set {} → {}",
                            o.value_set.as_deref().unwrap_or("-"),
                            n.value_set.as_deref().unwrap_or("-")
                        ),
                        o.value_set.clone(),
                        n.value_set.clone(),
                    );
                }
            }
            _ => {}
        }
    }

    fn constraints(&mut self, path: &str, old: &Node, new: &Node) {
        for (key, constraint) in &new.constraints {
            match old.constraints.get(key) {
                None => {
                    let rule = if constraint.severity == "error" {
                        "invariant-added"
                    } else {
                        "invariant-warning-added"
                    };
                    self.invariants_added.push(InvariantSite {
                        key: key.clone(),
                        severity: constraint.severity.clone(),
                        index: self.changes.len(),
                    });
                    self.push(
                        rule,
                        path,
                        format!("Invariant {key}: {}", constraint.human),
                        None,
                        Some(constraint.expression.clone()),
                    );
                }
                Some(previous) if previous.expression != constraint.expression => {
                    self.push(
                        "invariant-changed",
                        path,
                        format!("Invariant {key} changed"),
                        Some(previous.expression.clone()),
                        Some(constraint.expression.clone()),
                    );
                }
                Some(_) => {}
            }
        }
        for (key, constraint) in &old.constraints {
            if !new.constraints.contains_key(key) {
                self.invariants_removed.push(InvariantSite {
                    key: key.clone(),
                    severity: constraint.severity.clone(),
                    index: self.changes.len(),
                });
                self.push(
                    "invariant-removed",
                    path,
                    format!("Invariant {key} was removed"),
                    Some(constraint.expression.clone()),
                    None,
                );
            }
        }
    }

    fn pattern(&mut self, path: &str, old: &Node, new: &Node) {
        let text = |v: &serde_json::Value| v.to_string();
        match (&old.pattern, &new.pattern) {
            (None, Some(n)) => self.push(
                "fixed-added",
                path,
                format!("Fixed/pattern {}", text(n)),
                None,
                Some(text(n)),
            ),
            (Some(o), None) => self.push(
                "fixed-removed",
                path,
                "Fixed/pattern value removed".into(),
                Some(text(o)),
                None,
            ),
            (Some(o), Some(n)) if o != n => self.push(
                "fixed-changed",
                path,
                "Fixed/pattern value changed".into(),
                Some(text(o)),
                Some(text(n)),
            ),
            _ => {}
        }
    }

    fn slicing(&mut self, path: &str, old: &Node, new: &Node) {
        let rules = |node: &Node| node.slicing.as_ref().map(|s| s.rules.clone());
        match (rules(old).as_deref(), rules(new).as_deref()) {
            (Some("closed"), Some(r)) if r != "closed" => self.push(
                "slicing-opened",
                path,
                format!("Slicing closed → {r}"),
                Some("closed".into()),
                Some(r.to_owned()),
            ),
            (o, Some("closed")) if o != Some("closed") => self.push(
                "slicing-closed",
                path,
                format!("Slicing {} → closed", o.unwrap_or("none")),
                o.map(str::to_owned),
                Some("closed".into()),
            ),
            _ => {}
        }
    }
}

/// A variant's own mustSupport means something only while its choice stays put: a choice whose
/// flag changed is reported itself, and one sliced by type speaks through its slices.
fn choice_settled(old: &Node, new: &Node, variant: &str) -> bool {
    let choice = |parent: &'_ Node| {
        parent
            .children
            .values()
            .find(|c| c.types.contains(variant))
            .map(|c| (c.must_support, c.slices.is_empty()))
    };
    matches!(
        (choice(old), choice(new)),
        (Some((before, true)), Some((after, true))) if before == after
    )
}

fn join(set: &BTreeSet<String>) -> String {
    set.iter().cloned().collect::<Vec<_>>().join(", ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_expression_reads_the_same_from_a_child_element() {
        let old = "value.ofType(Quantity).system.empty() or value.ofType(Quantity).system = 'u'";
        let new = "ofType(Quantity).system.empty() or ofType(Quantity).system = 'u'";
        assert!(same_after_move(
            "Observation",
            old,
            "Observation.value",
            new
        ));
        assert!(same_after_move(
            "Observation.value",
            new,
            "Observation",
            old
        ));
        // The same text on another element means something else.
        assert!(!same_after_move(
            "Observation",
            old,
            "Observation.value",
            old
        ));
    }

    #[test]
    fn only_paths_that_start_with_the_element_are_rewritten() {
        assert_eq!(
            relative_to("a.value.b or value.c", "value"),
            "a.value.b or c"
        );
        assert_eq!(relative_to("myvalue.x", "value"), "myvalue.x");
    }
}