fhirconnect 0.2.3

The FHIRconnect mapping language for Rust: the mapping file model and its validation, context resolution into an immutable program, and the bidirectional interpreter between openEHR compositions and FHIR resources
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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The `hierarchy.split` groups, each run with its axes pinned.

use openehr_mapping_core::composition::FlatIndex;
use openehr_mapping_core::composition::PositionError;
use openehr_mapping_core::composition::RmPosition;
use openehr_mapping_core::index::paths::FlatId;

use crate::engine::outcome::Loss;
use crate::engine::outcome::SkipReason;
use crate::engine::outcome::Warning;
use crate::model::ast::keyword::Direction;
use crate::resolve::program::hierarchy::Create;
use crate::resolve::program::hierarchy::Hierarchy;
use crate::resolve::program::hierarchy::Split;
use crate::resolve::program::mapping::Mapping;
use crate::resolve::program::target::OpenehrTarget;
use crate::resolve::program::target::Target;
use crate::tree::Occurrence;

use crate::tree::element::Table;
use crate::tree::read::read;

use crate::engine::traverse::Binding;
use crate::engine::traverse::Run;
use crate::engine::traverse::error::EngineError;
use crate::engine::traverse::error::SplitRefusal;
use crate::engine::traverse::place::fhir_axes;
use crate::engine::traverse::tail::attribute_at;
use crate::engine::traverse::tail::lexical;
use crate::engine::traverse::tail::scalar;

impl<T: Table + ?Sized> Run<'_, T> {
    /// Runs a list of mappings, split by the hierarchy of the file they came
    /// from when it splits the direction's output.
    ///
    /// `split.fhir` creates FHIR resources, so it runs going out of openEHR,
    /// and `split.openehr` creates openEHR elements, so it runs going into
    /// openEHR (`types-of-mappings/concept-type/HierarchyMappings.adoc`,
    /// §split).
    pub(super) fn split_or_run(
        &mut self,
        mappings: &[Mapping],
        hierarchy: Option<&Hierarchy>,
        model: &str,
        parent: &Binding,
    ) -> Result<(), EngineError> {
        let Some(hierarchy) = hierarchy else {
            return self.mappings(mappings, parent);
        };
        match self.direction {
            Direction::OpenehrToFhir => match hierarchy.split_fhir() {
                Some(split) => self.split_resources(mappings, hierarchy, split, model, parent),
                None => self.mappings(mappings, parent),
            },
            Direction::FhirToOpenehr => match hierarchy.split_openehr() {
                Some(split) => self.split_elements(mappings, hierarchy, split, model, parent),
                None => self.mappings(mappings, parent),
            },
        }
    }

    /// Creates one FHIR resource per occurrence of the split's openEHR path
    /// and distinct `unique` tuple.
    ///
    /// "For each occurrence of `$archetype/data[at0001]/events[at0002]`, the
    /// `split` is executed", and "one could imagine this process as cloning
    /// the composition with one event each"
    /// (`types-of-mappings/concept-type/HierarchyMappings.adoc`, §split): the
    /// whole mapping set runs once per group with the split node pinned to
    /// the group's occurrence, so content outside the node reaches every
    /// resource. The first group fills the run's own resource and every
    /// further one is a created resource with an id from the identity sink.
    /// A split with no `unique` key makes every occurrence its own group.
    fn split_resources(
        &mut self,
        mappings: &[Mapping],
        hierarchy: &Hierarchy,
        split: &Split,
        model: &str,
        parent: &Binding,
    ) -> Result<(), EngineError> {
        let refuse = |reason: SplitRefusal| EngineError::Split {
            model: String::from(model),
            reason,
        };
        match split.create() {
            Some(Create::Resource) => {}
            Some(create) => return Err(refuse(SplitRefusal::WrongSide { create })),
            None => return Err(refuse(SplitRefusal::NoCreate)),
        }
        if split.path().is_some() {
            return Err(refuse(SplitRefusal::ResourcePath));
        }
        let with = hierarchy
            .openehr()
            .ok_or_else(|| refuse(SplitRefusal::NoWith))?;
        let mut groups: Vec<(Vec<String>, Vec<Vec<RmPosition>>)> = Vec::new();
        for positions in self.instances(model, with, parent)? {
            let tuple = self.unique_openehr(model, split.unique(), &positions)?;
            match groups
                .iter_mut()
                .find(|group| !split.unique().is_empty() && group.0 == tuple)
            {
                Some(group) => group.1.push(positions),
                None => groups.push((tuple, vec![positions])),
            }
        }
        if groups.is_empty() {
            return self.mappings(mappings, parent);
        }
        let base = self.fhir.clone();
        let start = self.warnings.len();
        for (index, (tuple, members)) in groups.into_iter().enumerate() {
            if index == 0 {
                self.run_pinned(mappings, parent, with, &members)?;
                continue;
            }
            let outer = core::mem::replace(&mut self.fhir, base.clone());
            let counters = core::mem::take(&mut self.counters);
            let ran = self.run_pinned(mappings, parent, with, &members);
            self.counters = counters;
            let mut created = core::mem::replace(&mut self.fhir, outer);
            ran?;
            let occurrence = members
                .first()
                .map(|positions| positions.iter().map(|position| position.get()).collect())
                .unwrap_or_default();
            let request = self
                .identity_request(self.program.resource().as_str(), model)
                .with_occurrence(occurrence)
                .with_unique(tuple);
            self.identify(model, &mut created, &request)?;
            self.created.push(created);
        }
        self.settle_split_warnings(start);
        Ok(())
    }

    /// Runs a mapping set once per member, with the split node pinned to it.
    fn run_pinned(
        &mut self,
        mappings: &[Mapping],
        parent: &Binding,
        with: &OpenehrTarget,
        members: &[Vec<RmPosition>],
    ) -> Result<(), EngineError> {
        for positions in members {
            let pins: Vec<(FlatId, RmPosition)> = with
                .occurrences()
                .iter()
                .cloned()
                .zip(positions.iter().copied())
                .collect();
            let held = core::mem::replace(&mut self.pins, pins);
            let ran = self.mappings(mappings, parent);
            self.pins = held;
            ran?;
        }
        Ok(())
    }

    /// Creates one openEHR element per occurrence of the split's FHIR path
    /// and distinct `unique` tuple.
    ///
    /// "For each `dosage` with a different `route` and/or `timing.event`,
    /// create a new `EVENT` in openEHR" (`HierarchyMappings.adoc`, §Hierarchy
    /// and unique values): each group pins the FHIR path to its occurrences
    /// and the created node to a fresh instance, so every mapping under the
    /// node writes into the group's own element.
    fn split_elements(
        &mut self,
        mappings: &[Mapping],
        hierarchy: &Hierarchy,
        split: &Split,
        model: &str,
        parent: &Binding,
    ) -> Result<(), EngineError> {
        let refuse = |reason: SplitRefusal| EngineError::Split {
            model: String::from(model),
            reason,
        };
        match split.create() {
            Some(Create::Event | Create::Archetype) => {}
            Some(create) => return Err(refuse(SplitRefusal::WrongSide { create })),
            None => return Err(refuse(SplitRefusal::NoCreate)),
        }
        let with = hierarchy
            .fhir()
            .ok_or_else(|| refuse(SplitRefusal::NoWith))?;
        let node = match split.path() {
            Some(Target::Openehr(target)) => target.as_ref(),
            Some(Target::Fhir(_)) | None => hierarchy
                .openehr()
                .ok_or_else(|| refuse(SplitRefusal::NoWith))?,
        };
        let axes = node.occurrences();
        if axes.last() != Some(node.node().flat_id()) {
            return Err(refuse(SplitRefusal::NotRepeating {
                node: String::from(node.node().aql_path().as_str()),
            }));
        }
        let parent_scope = self.scoped(Some(with), parent);
        let matches =
            read(self.table, self.document_for(with), with.expression()).map_err(|source| {
                EngineError::Read {
                    mapping: String::from(model),
                    expression: String::from(with.expression().as_str()),
                    source: Box::new(source),
                }
            })?;
        let mut groups: Vec<(Vec<String>, Vec<Occurrence>)> = Vec::new();
        for matched in matches {
            if !matched
                .occurrence()
                .indices()
                .starts_with(parent_scope.fhir.indices())
            {
                continue;
            }
            let occurrence = matched.occurrence().clone();
            let tuple = self.unique_fhir(model, split.unique(), &occurrence)?;
            match groups
                .iter_mut()
                .find(|group| !split.unique().is_empty() && group.0 == tuple)
            {
                Some(group) => group.1.push(occurrence),
                None => groups.push((tuple, vec![occurrence])),
            }
        }
        if groups.is_empty() {
            return self.mappings(mappings, parent);
        }
        let with_axes = fhir_axes(with);
        let start = self.warnings.len();
        for (_tuple, members) in groups {
            // NOTE: HierarchyMappings.adoc §split, each group creates an element, so the split node
            // takes the next free instance under the instances its ancestors are bound to.
            let mut positions = self.bound_positions(node, parent);
            positions.pop();
            let mut prefix = Vec::with_capacity(positions.len());
            for position in &positions {
                prefix.push(usize::try_from(FlatIndex::from(*position).get()).map_err(
                    |_refused| EngineError::Position {
                        mapping: String::from(model),
                        source: PositionError::Overflow,
                    },
                )?);
            }
            let split_axis = node.node().flat_id();
            let index = self.next_index(with.level(), split_axis.as_str(), &prefix);
            let instance = u32::try_from(index)
                .ok()
                .and_then(|index| RmPosition::try_from(FlatIndex::new(index)).ok())
                .ok_or(EngineError::Position {
                    mapping: String::from(model),
                    source: PositionError::Overflow,
                })?;
            positions.push(instance);
            let pins: Vec<(FlatId, RmPosition)> = axes.iter().cloned().zip(positions).collect();
            for occurrence in members {
                let held = core::mem::replace(&mut self.pins, pins.clone());
                let held_fhir = self
                    .pin_at(with.level())
                    .replace((with_axes.clone(), occurrence));
                let ran = self.mappings(mappings, parent);
                self.pins = held;
                *self.pin_at(with.level()) = held_fhir;
                ran?;
            }
        }
        self.settle_split_warnings(start);
        Ok(())
    }

    /// Keeps one of each warning a split's groups declared alike when the
    /// warning does not depend on the group.
    ///
    /// A mapping skipped for its `unidirectional` marker is skipped for every
    /// group the same way, so the split declares that loss once; a warning
    /// that depends on the group's data (a dropped occurrence, a one-way row,
    /// an unresolved reference) stays once per group. No specification governs
    /// this: our own design.
    fn settle_split_warnings(&mut self, start: usize) {
        settle(&mut self.warnings, start);
    }

    /// Returns the `unique` tuple one openEHR occurrence carries.
    ///
    /// "The path in the `unique:` key relates to the `with:` method"
    /// (`HierarchyMappings.adoc`), so each value is read at the occurrence's
    /// own instance, and an absent value is the empty text.
    fn unique_openehr(
        &self,
        model: &str,
        unique: &[Target],
        positions: &[RmPosition],
    ) -> Result<Vec<String>, EngineError> {
        let Some(composition) = self.composition else {
            return Ok(Vec::new());
        };
        let mut tuple = Vec::with_capacity(unique.len());
        for target in unique {
            let Target::Openehr(ref target) = *target else {
                tuple.push(String::new());
                continue;
            };
            let depth = target.occurrences().len();
            let mut at: Vec<RmPosition> = positions.iter().take(depth).copied().collect();
            at.resize(depth, RmPosition::first());
            let read = self
                .index
                .read(composition, target.node(), &at)
                .map_err(|source| EngineError::Template {
                    mapping: String::from(model),
                    node: String::from(target.node().aql_path().as_str()),
                    source: Box::new(source),
                })?;
            // NOTE: no specification governs this: our own design, a data value
            // compares by the text of its `value`, which is what a reader of
            // the element sees, and any other structure by its JSON.
            let text = read
                .as_ref()
                .and_then(|value| attribute_at(value, target, &[]))
                .map(|value| {
                    scalar(value)
                        .or_else(|| value.get("value").and_then(scalar))
                        .unwrap_or_else(|| value.to_string())
                })
                .unwrap_or_default();
            tuple.push(text);
        }
        Ok(tuple)
    }

    /// Returns the `unique` tuple one FHIR occurrence carries.
    fn unique_fhir(
        &self,
        model: &str,
        unique: &[Target],
        occurrence: &Occurrence,
    ) -> Result<Vec<String>, EngineError> {
        let mut tuple = Vec::with_capacity(unique.len());
        for target in unique {
            let Target::Fhir(ref target) = *target else {
                tuple.push(String::new());
                continue;
            };
            let matches = read(self.table, self.document_for(target), target.expression())
                .map_err(|source| EngineError::Read {
                    mapping: String::from(model),
                    expression: String::from(target.expression().as_str()),
                    source: Box::new(source),
                })?;
            let mut texts = Vec::new();
            for matched in &matches {
                if !matched
                    .occurrence()
                    .indices()
                    .starts_with(occurrence.indices())
                {
                    continue;
                }
                if let Some(value) = matched.value() {
                    texts.push(lexical(value));
                }
            }
            tuple.push(texts.join("|"));
        }
        Ok(tuple)
    }

    /// Returns the openEHR pin of one axis, by its flat id.
    ///
    /// Only an openEHR axis takes a pin; a FHIR output axis is a FHIR path,
    /// which no flat id equals.
    pub(super) fn pin(&self, axis: &str) -> Option<RmPosition> {
        self.pins
            .iter()
            .find(|pinned| pinned.0.as_str() == axis)
            .map(|pinned| pinned.1)
    }
}

/// Drops each group-independent warning declared from `start` on whose loss
/// an earlier warning from `start` on already declares.
///
/// The loss decides, so the declaration kept is the first group's, at the
/// location the first group gave it.
fn settle(warnings: &mut Vec<Warning>, start: usize) {
    let start = start.min(warnings.len());
    let declared = warnings.split_off(start);
    for warning in declared {
        let alike = matches!(
            *warning.loss(),
            Loss::Skipped {
                reason: SkipReason::Unidirectional,
                ..
            }
        );
        let seen = warnings
            .get(start..)
            .is_some_and(|kept| kept.iter().any(|held| held.loss() == warning.loss()));
        if alike && seen {
            continue;
        }
        warnings.push(warning);
    }
}

#[cfg(test)]
mod tests {
    use super::settle;
    use crate::engine::outcome::Location;
    use crate::engine::outcome::Loss;
    use crate::engine::outcome::SkipReason;
    use crate::engine::outcome::Warning;

    /// Returns a unidirectional skip of `subject` located at `fhir`.
    fn skip_at(fhir: &str) -> Warning {
        Warning::new(
            Loss::Skipped {
                mapping: String::from("subject"),
                reason: SkipReason::Unidirectional,
            },
            Location::default().with_fhir(fhir),
        )
    }

    #[test]
    fn a_skip_declared_once_keeps_the_first_groups_location() {
        let mut warnings = vec![
            skip_at("Encounter.location[0]"),
            skip_at("Encounter.location[1]"),
        ];
        settle(&mut warnings, 0);
        assert_eq!(warnings, [skip_at("Encounter.location[0]")]);
    }

    #[test]
    fn a_split_declares_a_group_independent_skip_once_and_keeps_the_rest() {
        let skip = skip_at("Encounter.subject");
        let dropped = Warning::new(
            Loss::LastOfMany {
                path: String::from("/content"),
                dropped: 1,
            },
            Location::default().with_openehr("/content"),
        );
        let before = Warning::new(
            Loss::Defaulted {
                field: String::from("/composer"),
            },
            Location::default().with_openehr("/composer"),
        );
        let mut warnings = vec![
            before.clone(),
            skip.clone(),
            dropped.clone(),
            skip.clone(),
            dropped.clone(),
        ];
        settle(&mut warnings, 1);
        assert_eq!(warnings, [before, skip, dropped.clone(), dropped]);
    }
}