fhirconnect 0.2.4

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
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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! A value read and written below the template's deepest node, one tail
//! attribute at a time.

use fhir_types::codec::Value;
use openehr_mapping_core::composition::NodeValue;
use openehr_mapping_core::composition::RmPosition;
use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::index::paths::FlatId;
use openehr_rm::v1_2::model;
use openehr_rm::v1_2::paths::PathSegment;
use openehr_rm::v1_2::paths::Predicate;
use openehr_rm::v1_2::paths::RmPath;
use openehr_rm::v1_2::paths::item_at_path;
use openehr_rm::v1_2::paths::items_at_path;
use openehr_rm::v1_2::paths::write::SetPathError;
use openehr_rm::v1_2::paths::write::set_at_path;
use openehr_rm::v1_2::typing::RmType;
use openehr_sdt::flat::path::Segment;

use crate::engine::cell;
use crate::engine::family;
use crate::engine::fhir::FhirValue;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::null_flavour::NullFlavourLens;
use crate::engine::lens::scalar::IntegerLens;
use crate::engine::lens::scalar::RealLens;
use crate::engine::outcome::Warning;
use crate::engine::rm;
use crate::engine::rm::RmError;
use crate::engine::rm::RmValue;
use crate::engine::rm::carried::Carried;
use crate::model::ast::keyword::Direction;
use crate::resolve::program::mapping::Mapping;
use crate::resolve::program::target::FhirTarget;
use crate::resolve::program::target::ListAxis;
use crate::resolve::program::target::OpenehrTarget;

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

use crate::engine::traverse::Binding;
use crate::engine::traverse::Held;
use crate::engine::traverse::Run;
use crate::engine::traverse::Written;
use crate::engine::traverse::demographic::Shape;
use crate::engine::traverse::error::EngineError;

/// The class of a tail the [`crate::engine::lens::party_ref::PartyRefLens`]
/// carries through the demographics endpoint.
pub(super) const PARTY_REF: &str = "PARTY_REF";

/// The class of a history's origin.
const DV_DATE_TIME: &str = "DV_DATE_TIME";

impl<T: Table + ?Sized> Run<'_, T> {
    /// Writes one FHIR element as the `_`-prefixed family a tail names below a
    /// structural node: a `PARTY_IDENTIFIED` as `family::provider` spells it,
    /// a `DV_DATE_TIME` as `family::end_time` does.
    fn convert_family(
        &mut self,
        owner: &str,
        mapping: &Mapping,
        target: &FhirTarget,
        openehr: &OpenehrTarget,
        view: &FhirValue,
        binding: &Binding,
    ) -> Result<(), EngineError> {
        let node = openehr.node();
        let segments = tail_segments(openehr);
        if openehr.on_element() && segments == [rm::null_flavour::NULL_FLAVOUR] {
            let refuse = |source: LensError| EngineError::Cell {
                mapping: String::from(mapping.name()),
                element: String::from(target.expression().as_str()),
                source: Box::new(source),
            };
            let FhirValue::String(ref code) = *view else {
                return Err(refuse(LensError::NoCell {
                    rm_type: String::from("ELEMENT.null_flavour"),
                    kind: view.kind().as_str(),
                    direction: Direction::FhirToOpenehr,
                }));
            };
            let flavour = NullFlavourLens.put(code, None).map_err(refuse)?;
            self.families
                .extend(family::null_flavour(node, &binding.openehr, &flavour));
            return Ok(());
        }
        let leaf = openehr
            .leaf_class()
            .ok_or_else(|| unsupported_tail(mapping, openehr))?;
        let produced = cell::put(view, leaf, None, self.binding_of(node).as_deref(), &[]).map_err(
            |source| EngineError::Cell {
                mapping: String::from(mapping.name()),
                element: String::from(target.expression().as_str()),
                source: Box::new(source),
            },
        )?;
        for taken in &produced.fallbacks {
            self.warnings.push(Warning::fallback(
                taken,
                self.locate(mapping, &binding.fhir),
            ));
        }
        let value = self.identified(mapping, view, produced.value, Shape::Identifier)?;
        let under =
            rm::family_of(owner, &segments).ok_or_else(|| unsupported_tail(mapping, openehr))?;
        match value {
            RmValue::Party(ref party) => {
                if under
                    .iter()
                    .any(|segment| segment.name == family::HEALTH_CARE_FACILITY)
                {
                    self.facility_written = true;
                }
                self.families
                    .extend(family::provider(node, &binding.openehr, &under, party));
            }
            RmValue::DateTime(ref date_time) => {
                self.families.push(family::end_time(
                    node,
                    &binding.openehr,
                    &under,
                    &date_time.value,
                ));
            }
            _ => {
                return Err(EngineError::Rm {
                    mapping: String::from(mapping.name()),
                    node: String::from(node.aql_path().as_str()),
                    source: Box::new(RmError::UnknownClass {
                        rm_type: String::from(value.rm_type()),
                    }),
                });
            }
        }
        Ok(())
    }

    /// Writes one FHIR element into the attribute a tail names below a node.
    ///
    /// The tail's leaf class selects the cell when the leaf is a data value,
    /// and a scalar leaf takes the text of the FHIR element. The attribute is
    /// merged into what the place already holds, so several mappings that
    /// name attributes of one value build that one value, and the whole value
    /// is read as its class when the composition is built.
    pub(super) fn convert_tail(
        &mut self,
        mapping: &Mapping,
        target: &FhirTarget,
        openehr: &OpenehrTarget,
        view: &FhirValue,
        binding: &Binding,
    ) -> Result<(), EngineError> {
        let node = openehr.node();
        let segments = tail_segments(openehr);
        let (class, carried) = rm::carried::carried(openehr.tail_class(), &segments)
            .ok_or_else(|| unsupported_tail(mapping, openehr))?;
        let refuse_rm = |source: RmError| EngineError::Rm {
            mapping: String::from(mapping.name()),
            node: String::from(node.aql_path().as_str()),
            source: Box::new(source),
        };
        if carried == Carried::EntryTime {
            let key = rm::entry_time_key(class, &segments.join("/"))
                .ok_or_else(|| unsupported_tail(mapping, openehr))?;
            return self.entry_time(mapping, target, node, view, binding, key);
        }
        if carried == Carried::Family {
            return self.convert_family(class, mapping, target, openehr, view, binding);
        }
        let object = self
            .held_object(&binding.openehr, node.flat_id())
            .map_err(refuse_rm)?;
        let written = if carried == Carried::Value && openehr.leaf_class() == Some(PARTY_REF) {
            self.party_ref_of(mapping, target, view)?
                .to_canonical()
                .map_err(refuse_rm)?
        } else if carried == Carried::Value {
            let leaf = openehr
                .leaf_class()
                .ok_or_else(|| unsupported_tail(mapping, openehr))?;
            // NOTE: no specification governs this: our own design, a held
            // sub-value still being written attribute by attribute is no whole
            // value yet, so it carries nothing over and the cell starts fresh.
            let held = serde_json::Value::Object(object.clone());
            let existing = attribute_at(&held, openehr, &binding.elements).and_then(|found| {
                RmValue::from_canonical(leaf, node.aql_path().as_str(), found).ok()
            });
            let produced = cell::put(
                view,
                leaf,
                existing.as_ref(),
                self.binding_of(node).as_deref(),
                &[],
            )
            .map_err(|source| EngineError::Cell {
                mapping: String::from(mapping.name()),
                element: String::from(target.expression().as_str()),
                source: Box::new(source),
            })?;
            for taken in &produced.fallbacks {
                self.warnings.push(Warning::fallback(
                    taken,
                    self.locate(mapping, &binding.fhir),
                ));
            }
            self.identified(mapping, view, produced.value, Shape::Identifier)?
                .to_canonical()
                .map_err(refuse_rm)?
        } else {
            self.scalar_written(mapping, target, binding, view, (carried, class, node))?
        };
        if openehr.lists().len() > binding.elements.len() {
            return Err(unsupported_tail(mapping, openehr));
        }
        let mut whole = serde_json::Value::Object(object);
        set_at_path(
            &mut whole,
            &RmType::simple(class),
            &positioned(openehr, &binding.elements),
            written,
        )
        .map_err(|source| EngineError::TailWrite {
            mapping: String::from(mapping.name()),
            node: String::from(node.aql_path().as_str()),
            source: Box::new(source),
        })?;
        let serde_json::Value::Object(mut object) = whole else {
            return Err(unsupported_tail(mapping, openehr));
        };
        let kept = object
            .get("_type")
            .and_then(serde_json::Value::as_str)
            .filter(|held| *held == class || model::is_a(held, class))
            .map(String::from);
        object.insert(
            String::from("_type"),
            serde_json::Value::String(kept.unwrap_or_else(|| String::from(class))),
        );
        self.store(Written {
            flat_id: node.flat_id().clone(),
            positions: binding.openehr.clone(),
            value: Held::Partial(object),
        });
        Ok(())
    }

    /// Returns the JSON a FHIR value writes into one scalar attribute of
    /// `class` below `node`.
    ///
    /// A `Coding`, `Identifier` or `Reference` written into a text attribute
    /// runs the `String.adoc` cells; every other element writes its own
    /// lexical form.
    fn scalar_written(
        &mut self,
        mapping: &Mapping,
        target: &FhirTarget,
        binding: &Binding,
        view: &FhirValue,
        (carried, class, node): (Carried, &str, &ResolvedNode),
    ) -> Result<serde_json::Value, EngineError> {
        if let (Carried::Text, Some(produced)) = (carried, cell::put_string(view)) {
            let produced = produced.map_err(|source| EngineError::Cell {
                mapping: String::from(mapping.name()),
                element: String::from(target.expression().as_str()),
                source: Box::new(source),
            })?;
            for taken in &produced.fallbacks {
                self.warnings.push(Warning::fallback(
                    taken,
                    self.locate(mapping, &binding.fhir),
                ));
            }
            return Ok(serde_json::Value::String(produced.value));
        }
        let number = match (carried, view) {
            (Carried::Integer, FhirValue::Integer(integer)) => Some(
                IntegerLens
                    .put(integer, None)
                    .map(|number| serde_json::Value::Number(number.into())),
            ),
            (Carried::Real, FhirValue::Decimal(decimal)) => {
                Some(RealLens.put(decimal, None).map(serde_json::Value::Number))
            }
            _ => None,
        };
        if let Some(number) = number {
            return number.map_err(|source| EngineError::Cell {
                mapping: String::from(mapping.name()),
                element: String::from(target.expression().as_str()),
                source: Box::new(source),
            });
        }
        let element = String::from(target.resolved().leaf());
        let text = view.write(&element).map_err(|source| EngineError::Fhir {
            mapping: String::from(mapping.name()),
            element: element.clone(),
            source: Box::new(source),
        })?;
        scalar_json(carried, class, node, &text).map_err(|source| EngineError::Rm {
            mapping: String::from(mapping.name()),
            node: String::from(node.aql_path().as_str()),
            source: Box::new(source),
        })
    }

    /// Writes a date-time attribute of an entry, an observation's history origin
    /// or an action's time, as the FLAT attribute `key` of the entry's node.
    ///
    /// Simplified Formats sets the origin "to the time of the earliest event
    /// if not explicitly set" (master05 §OBSERVATION) and an action's time from
    /// the context default (master06), so a mapping that names either sets it
    /// explicitly; the FLAT form carries the time alone.
    fn entry_time(
        &mut self,
        mapping: &Mapping,
        target: &FhirTarget,
        node: &ResolvedNode,
        view: &FhirValue,
        binding: &Binding,
        key: &str,
    ) -> Result<(), EngineError> {
        let produced =
            cell::put(view, DV_DATE_TIME, None, None, &[]).map_err(|source| EngineError::Cell {
                mapping: String::from(mapping.name()),
                element: String::from(target.expression().as_str()),
                source: Box::new(source),
            })?;
        for taken in &produced.fallbacks {
            self.warnings.push(Warning::fallback(
                taken,
                self.locate(mapping, &binding.fhir),
            ));
        }
        let RmValue::DateTime(ref time) = produced.value else {
            return Err(EngineError::Rm {
                mapping: String::from(mapping.name()),
                node: String::from(node.aql_path().as_str()),
                source: Box::new(RmError::UnknownClass {
                    rm_type: String::from(produced.value.rm_type()),
                }),
            });
        };
        self.families.push(
            NodeValue::new(node, serde_json::Value::String(time.value.clone()))
                .with_occurrences(binding.openehr.clone())
                .under(vec![Segment {
                    name: String::from(key),
                    index: None,
                }]),
        );
        Ok(())
    }

    /// Returns the canonical JSON the run holds at one place, empty when it
    /// holds nothing there.
    fn held_object(
        &self,
        positions: &[RmPosition],
        flat_id: &FlatId,
    ) -> Result<serde_json::Map<String, serde_json::Value>, RmError> {
        let Some(written) = self
            .written
            .iter()
            .find(|written| written.flat_id == *flat_id && written.positions == positions)
        else {
            return Ok(serde_json::Map::new());
        };
        match written.value {
            Held::Partial(ref object) | Held::Canonical(serde_json::Value::Object(ref object)) => {
                Ok(object.clone())
            }
            Held::Canonical(_) => Ok(serde_json::Map::new()),
            Held::Value(ref value) => match value.to_canonical()? {
                serde_json::Value::Object(object) => Ok(object),
                _ => Ok(serde_json::Map::new()),
            },
        }
    }
}

/// Returns the value a target's tail names below its node, in the element
/// `elements` names of each `List` the tail steps through.
///
/// A Web Template node is as deep as the template constrains, and a target
/// may name an attribute below it, so the tail is read from the canonical
/// JSON of the node with `PATHABLE.item_at_path` of `openehr-rm`. A list the
/// positions do not reach is read whole, so its first element answers.
pub(super) fn attribute_at<'value>(
    value: &'value serde_json::Value,
    target: &OpenehrTarget,
    elements: &[RmPosition],
) -> Option<&'value serde_json::Value> {
    item_at_path(value, &positioned(target, elements))
}

/// Returns a target's tail with the position of each `List` element
/// `elements` names, as the positional predicate openEHR BASE Release 1.2.0
/// §Paths and Locators writes (`other_reference_ranges[2]`).
pub(super) fn positioned(target: &OpenehrTarget, elements: &[RmPosition]) -> RmPath {
    let mut tail = target.tail().clone();
    for (axis, position) in target.lists().iter().zip(elements) {
        if let Some(segment) = tail.segments.get_mut(axis.depth()) {
            segment.predicate.position = usize::try_from(position.get()).ok();
        }
    }
    tail
}

/// Returns the number of elements the list `axis` of `target` holds in
/// `value`, in the elements `outer` names of the lists above it.
pub(super) fn list_length(
    value: &serde_json::Value,
    target: &OpenehrTarget,
    axis: &ListAxis,
    outer: &[RmPosition],
) -> usize {
    let mut path = positioned(target, outer);
    path.segments.truncate(axis.depth().saturating_add(1));
    items_at_path(value, &path).len()
}

/// Returns the text one FHIR value is compared by, for a `unique` tuple.
pub(super) fn lexical(value: &Value) -> String {
    match *value {
        Value::Null => String::new(),
        Value::Bool(flag) => String::from(if flag { "true" } else { "false" }),
        Value::Number(ref number) => String::from(number.as_str()),
        Value::String(ref text) => text.clone(),
        Value::Array(ref items) => items.iter().map(lexical).collect::<Vec<String>>().join(","),
        Value::Object(ref object) => object
            .iter()
            .map(|(key, member)| format!("{key}={}", lexical(member)))
            .collect::<Vec<String>>()
            .join(";"),
    }
}

/// Returns the attribute names a target's tail walks, outermost first.
pub(super) fn tail_segments(target: &OpenehrTarget) -> Vec<&str> {
    target
        .tail()
        .segments
        .iter()
        .map(|segment| segment.attribute.as_str())
        .collect()
}

/// Returns the refusal of a tail no FLAT part of the node's class carries.
pub(super) fn unsupported_tail(mapping: &Mapping, target: &OpenehrTarget) -> EngineError {
    EngineError::UnsupportedTail {
        mapping: String::from(mapping.name()),
        node: String::from(target.node().aql_path().as_str()),
        tail: target.tail().to_string(),
    }
}

/// Returns the canonical JSON of one scalar tail attribute, from the FHIR
/// element's JSON.
///
/// The attribute's type comes from the RM attribute model, so a text that
/// does not read as it is a refusal naming the class.
fn scalar_json(
    carried: Carried,
    class: &str,
    node: &ResolvedNode,
    written: &Value,
) -> Result<serde_json::Value, RmError> {
    let text = match *written {
        Value::String(ref text) => text.clone(),
        Value::Number(ref number) => String::from(number.as_str()),
        Value::Bool(flag) => String::from(if flag { "true" } else { "false" }),
        Value::Null | Value::Array(_) | Value::Object(_) => String::new(),
    };
    let refuse = |expected: &'static str| RmError::Scalar {
        node: String::from(node.aql_path().as_str()),
        rm_type: String::from(class),
        text: text.clone(),
        expected,
    };
    match carried {
        Carried::Text if written.as_str().is_some() => Ok(serde_json::Value::String(text)),
        Carried::Text | Carried::Value | Carried::Family | Carried::EntryTime => {
            Err(refuse("text"))
        }
        Carried::Real => serde_json::from_str::<serde_json::Number>(&text)
            .map(serde_json::Value::Number)
            .map_err(|_refused| refuse("a real number")),
        Carried::Integer => text
            .parse::<i64>()
            .map(|number| serde_json::Value::Number(number.into()))
            .map_err(|_refused| refuse("an integer")),
        Carried::Boolean => match text.as_str() {
            "true" => Ok(serde_json::Value::Bool(true)),
            "false" => Ok(serde_json::Value::Bool(false)),
            _ => Err(refuse("a boolean")),
        },
    }
}

/// Returns the text a scalar carries, `None` for a structure.
pub(super) fn scalar(value: &serde_json::Value) -> Option<String> {
    match *value {
        serde_json::Value::String(ref text) => Some(text.clone()),
        serde_json::Value::Bool(flag) => Some(String::from(if flag { "true" } else { "false" })),
        serde_json::Value::Number(ref number) => Some(number.to_string()),
        serde_json::Value::Null | serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
            None
        }
    }
}

/// Writes one manual path's text into the object the entry builds for a node
/// of `class`, through `openehr_rm::v1_2::paths::set_at_path`, so paths that
/// share a prefix merge into one data element.
pub(super) fn merge(
    object: &mut serde_json::Map<String, serde_json::Value>,
    class: &str,
    segments: &[&str],
    value: &str,
) -> Result<(), SetPathError> {
    let path = RmPath {
        absolute: false,
        segments: segments
            .iter()
            .map(|attribute| PathSegment {
                attribute: String::from(*attribute),
                predicate: Predicate::default(),
                descendant: false,
            })
            .collect(),
    };
    let mut whole = serde_json::Value::Object(core::mem::take(object));
    let written = set_at_path(
        &mut whole,
        &RmType::simple(class),
        &path,
        serde_json::Value::String(String::from(value)),
    );
    if let serde_json::Value::Object(held) = whole {
        *object = held;
    }
    written.map(drop)
}

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

    #[test]
    fn manual_paths_that_share_a_prefix_merge_into_one_element() {
        // manual.adoc: "`defining_code/terminology_id/value` and
        // `defining_code/code_string` are merged together in the same data
        // element and do not overwrite".
        let mut object = serde_json::Map::new();
        let class = "DV_CODED_TEXT";
        merge(
            &mut object,
            class,
            &["defining_code", "terminology_id", "value"],
            "openehr",
        )
        .expect("the terminology should be written");
        merge(&mut object, class, &["defining_code", "code_string"], "524")
            .expect("the code should merge beside the terminology");
        merge(&mut object, class, &["value"], "Initial").expect("the text should be written");
        assert_eq!(
            serde_json::Value::Object(object),
            serde_json::json!({
                "defining_code": {"terminology_id": {"value": "openehr"}, "code_string": "524"},
                "value": "Initial"
            })
        );
    }
}