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

//! The data-type cell of one mapping, run over its input values.

use core::str::FromStr;
use std::borrow::Cow;

use fhir_types::codec::Value;
use openehr_mapping_core::composition::RmPosition;
use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;

use crate::engine::cell;
use crate::engine::fhir::FhirKind;
use crate::engine::fhir::FhirValue;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::null_flavour;
use crate::engine::lens::null_flavour::NullFlavour;
use crate::engine::lens::null_flavour::NullFlavourLens;
use crate::engine::lens::scalar;
use crate::engine::lens::scalar::IntegerLens;
use crate::engine::lens::scalar::RealLens;
use crate::engine::lens::term_mapping::Withheld;
use crate::engine::outcome::Loss;
use crate::engine::outcome::SkipReason;
use crate::engine::outcome::Warning;
use crate::engine::rm;
use crate::engine::rm::RmValue;
use crate::engine::rm::carried::Carried;
use crate::model::ast::keyword::Direction;
use crate::resolve::program::manual::Manual;
use crate::resolve::program::manual::ManualValue;
use crate::resolve::program::mapping::Derived;
use crate::resolve::program::mapping::Mapping;
use crate::resolve::program::target::FhirTarget;
use crate::resolve::program::target::OpenehrTarget;
use crate::tree::Occurrence;

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

use crate::engine::traverse::Binding;
use crate::engine::traverse::Leaf;
use crate::engine::traverse::Run;
use crate::engine::traverse::Written;
use crate::engine::traverse::demographic::Shape;
use crate::engine::traverse::error::EngineError;
use crate::engine::traverse::place::rm_positions;
use crate::engine::traverse::tail::tail_segments;
use crate::engine::traverse::tail::unsupported_tail;
use crate::engine::traverse::translate::Output;

impl<T: Table + ?Sized> Run<'_, T> {
    /// Returns the text a `manual` path writes.
    ///
    /// A `$context` member is a per-call value the caller supplies, so a
    /// member this run does not carry is a refusal rather than an invented
    /// value (`basics/Variables.adoc`, §`$context`).
    pub(super) fn manual_text<'run>(
        &'run self,
        mapping: &Mapping,
        entry: &Manual,
        value: &'run ManualValue,
    ) -> Result<&'run str, EngineError> {
        match *value {
            ManualValue::Literal(ref text) => Ok(text.as_str()),
            ManualValue::Context(ref member) => {
                self.context
                    .member(member)
                    .ok_or_else(|| EngineError::ContextMember {
                        mapping: format!("{}.{}", mapping.name(), entry.name()),
                        member: member.clone(),
                    })
            }
        }
    }

    /// Runs the data-type cell of a plain `with` mapping, or only binds.
    pub(super) fn values(
        &mut self,
        mapping: &Mapping,
        parent: &Binding,
        inputs: &[Occurrence],
    ) -> Result<Vec<Binding>, EngineError> {
        let inputs = self.held_inputs(mapping, inputs)?;
        let inputs = inputs.as_ref();
        let bindings = self.bindings(mapping, parent, inputs)?;
        if !mapping.manual().is_empty() {
            for entry in mapping.manual() {
                for binding in &bindings {
                    self.manual(mapping, entry, binding)?;
                }
            }
            return Ok(bindings);
        }
        // NOTE: PopulatingAnEntry.adoc writes `type: NONE` on the parent whose
        // `followedBy` children carry every value, so the parent anchors them
        // and transforms nothing of its own (recorded as a silence in #185).
        if mapping.data_type() == Some(crate::model::ast::keyword::DataType::None)
            || matches!(mapping.derived(), Some(Derived::Anchor))
        {
            return Ok(bindings);
        }
        let (Some(_fhir), Some(_openehr)) = (mapping.fhir(), mapping.openehr()) else {
            return Ok(bindings);
        };
        // NOTE: no specification governs this: our own design, a list holds no single value,
        // so a cell aimed at one refuses whether or not the run meets an element of it.
        if let Some(openehr) = converted(mapping).filter(|target| target.ends_on_list()) {
            return Err(unsupported_tail(mapping, openehr));
        }
        for (input, binding) in inputs.iter().zip(bindings.iter()) {
            self.convert(mapping, input, binding)?;
            if self.direction == Direction::FhirToOpenehr {
                self.reads.push(self.locate(mapping, input));
            }
        }
        Ok(bindings)
    }

    /// Returns the inputs of a mapping out of openEHR that hold a value.
    ///
    /// A leaf cell out of openEHR whose node holds no value writes nothing
    /// and has no child to anchor, so it takes no output instance: a later
    /// mapping onto the same repeating element then writes its first one.
    /// Every other mapping keeps every input, since its binding anchors its
    /// children or a `manual` writes without a source value.
    fn held_inputs<'inputs>(
        &self,
        mapping: &Mapping,
        inputs: &'inputs [Occurrence],
    ) -> Result<Cow<'inputs, [Occurrence]>, EngineError> {
        let leaf = self.direction == Direction::OpenehrToFhir
            && mapping.manual().is_empty()
            && mapping.followed_by().is_empty()
            && mapping.data_type() != Some(crate::model::ast::keyword::DataType::None)
            && !matches!(mapping.derived(), Some(Derived::Anchor | Derived::Event(_)))
            && converted(mapping).is_some_and(|target| !target.ends_on_list());
        let Some(target) = mapping.fhir().filter(|_| leaf) else {
            return Ok(Cow::Borrowed(inputs));
        };
        let mut held = Vec::with_capacity(inputs.len());
        for input in inputs {
            if self.output_source(mapping, target, input)?.is_some() {
                held.push(input.clone());
            }
        }
        Ok(Cow::Owned(held))
    }

    /// Returns the FHIR value one openEHR value reads as, with what the cell
    /// withheld, a party's minted identity read back as its reference.
    fn read_value(
        &self,
        value: &RmValue,
        kind: FhirKind,
        terminology: Option<&str>,
    ) -> Result<(FhirValue, Dropped), LensError> {
        let (value, reference) = self.minted(value);
        let dropped = Dropped {
            code: cell::withheld::uncarried_code(&value, kind).cloned(),
            mappings: cell::withheld::withheld(&value, kind, terminology),
            reason: false,
        };
        let mut view = cell::get(&value, kind, terminology)?;
        if let (Some(reference), FhirValue::Reference(held)) = (reference, &mut view) {
            held.reference = Some(fhir_types::r4::primitives::String::from(reference));
        }
        Ok((view, dropped))
    }

    /// Runs one occurrence of a mapping through its data-type cell.
    fn convert(
        &mut self,
        mapping: &Mapping,
        input: &Occurrence,
        binding: &Binding,
    ) -> Result<(), EngineError> {
        if let Some(Derived::Event(event)) = mapping.derived() {
            return match self.direction {
                Direction::FhirToOpenehr => self.event_in(mapping, event, input, binding),
                Direction::OpenehrToFhir => self.event_out(mapping, event, input, binding),
            };
        }
        match self.direction {
            Direction::FhirToOpenehr => self.convert_in(mapping, input, binding),
            Direction::OpenehrToFhir => self.convert_out(mapping, input, binding),
        }
    }

    /// Runs one occurrence of a mapping from FHIR into openEHR.
    fn convert_in(
        &mut self,
        mapping: &Mapping,
        input: &Occurrence,
        binding: &Binding,
    ) -> Result<(), EngineError> {
        let Some(target) = mapping.fhir() else {
            return Ok(());
        };
        let found = match mapping.derived() {
            Some(Derived::Polymorphic { read, pairings }) => {
                self.polymorphic_in(mapping, read, pairings, input)?
            }
            _ => match converted(mapping) {
                Some(openehr) => self
                    .input_value(mapping, target, openehr, input)?
                    .map(|view| (openehr, view)),
                None => None,
            },
        };
        let Some((openehr, view)) = found else {
            return Ok(());
        };
        let node = openehr.node();
        let Some(view) = self.translated(mapping, view, Output::openehr(openehr, input))? else {
            return Ok(());
        };
        if !openehr.tail().segments.is_empty() {
            return self.convert_tail(mapping, target, openehr, &view, binding);
        }
        let held = self.held(&binding.openehr, node.flat_id());
        let mut produced = cell::put(
            &view,
            node.rm_type(),
            held.as_ref(),
            self.binding_of(node).as_deref(),
            self.index.ordinal_options(node).unwrap_or_default(),
        )
        .map_err(|source| EngineError::Cell {
            mapping: String::from(mapping.name()),
            element: String::from(target.expression().as_str()),
            source: Box::new(source),
        })?;
        self.resolve_display(mapping, &view, &mut produced)?;
        for taken in &produced.fallbacks {
            self.warnings
                .push(Warning::fallback(taken, self.locate(mapping, input)));
        }
        let value = self.identified(mapping, &view, produced.value, Shape::at(node))?;
        self.put_openehr_at(openehr, binding, value);
        Ok(())
    }

    /// Runs one occurrence of a mapping from openEHR out to FHIR.
    fn convert_out(
        &mut self,
        mapping: &Mapping,
        input: &Occurrence,
        binding: &Binding,
    ) -> Result<(), EngineError> {
        let Some(target) = mapping.fhir() else {
            return Ok(());
        };
        let Some((openehr, source, target, kind)) = self.output_source(mapping, target, input)?
        else {
            return Ok(());
        };
        let refuse = |source: LensError| EngineError::Cell {
            mapping: String::from(mapping.name()),
            element: String::from(target.expression().as_str()),
            source: Box::new(source),
        };
        let (view, dropped) = match source {
            Leaf::Value(ref value) if let RmValue::PartyRef(ref party) = **value => (
                self.reference_of_party(mapping, target, party)?,
                Dropped::default(),
            ),
            Leaf::Value(ref value) => {
                let terminology = self.binding_of(openehr.node());
                self.read_value(value, kind, terminology.as_deref())
                    .map_err(refuse)?
            }
            Leaf::Scalar(ref text) => (
                Self::read_scalar(mapping, target, openehr, kind, text)?,
                Dropped::default(),
            ),
            Leaf::NullFlavour(ref flavour) => (
                read_null_flavour(flavour, kind).map_err(refuse)?,
                Dropped {
                    reason: null_flavour::uncarried_reason(flavour).is_some(),
                    ..Dropped::default()
                },
            ),
        };
        let output = Output::fhir(target, &binding.fhir);
        let Some(view) = self.translated(mapping, view, output)? else {
            return Ok(());
        };
        self.put_fhir_at(mapping, target, binding, &view)?;
        self.record_dropped(mapping, binding, &dropped);
        Ok(())
    }

    /// Returns the openEHR node one occurrence reads out of, what it holds
    /// there, and the FHIR target and kind it writes, `None` when the node
    /// holds nothing.
    ///
    /// A [`Derived::Polymorphic`] mapping reads the first value node, in the
    /// order of its pairs, that holds a value of its own class, and writes the
    /// alternative that node's first pair names. A polymorphic `ELEMENT` that
    /// holds a value no pair reads refuses, and so does a [`Derived::Value`]
    /// mapping whose `ELEMENT` holds another alternative than its own.
    fn output_source<'mapping>(
        &self,
        mapping: &'mapping Mapping,
        target: &'mapping FhirTarget,
        input: &Occurrence,
    ) -> Result<Option<OutSource<'mapping>>, EngineError> {
        if let Some(Derived::Polymorphic { pairings, .. }) = mapping.derived() {
            // NOTE: openEHR RM data_structures §ELEMENT: the value alternatives share
            // the `value` attribute, so the class the instance carries picks the pair.
            let Some(first) = pairings.first() else {
                return Ok(None);
            };
            let positions = Self::positions_of(mapping, input, first.target())?;
            for pairing in pairings {
                let openehr = pairing.target();
                let Some(source) = self.value_at(mapping, openehr, &positions)? else {
                    continue;
                };
                let written = pairing.alternative();
                let kind = FhirKind::of_code(written.code()).ok_or_else(|| {
                    EngineError::UnknownElement {
                        mapping: String::from(mapping.name()),
                        element: String::from(written.target().resolved().leaf()),
                    }
                })?;
                return Ok(Some((openehr, source, written.target(), kind)));
            }
            if self.node_held(mapping.name(), first.target(), &positions)? {
                return Err(other_alternative(mapping, target, first.target()));
            }
            return Ok(None);
        }
        let Some(openehr) = converted(mapping) else {
            return Ok(None);
        };
        let positions = Self::positions_of(mapping, input, openehr)?;
        let Some(source) = self.value_at(mapping, openehr, &positions)? else {
            if matches!(mapping.derived(), Some(Derived::Value { .. }))
                && self.node_held(mapping.name(), openehr, &positions)?
            {
                return Err(other_alternative(mapping, target, openehr));
            }
            return Ok(None);
        };
        let (target, kind) = Self::output_target(mapping, target)?;
        Ok(Some((openehr, source, target, kind)))
    }

    /// Reads the text a scalar leaf holds as the FHIR element `kind` names.
    fn read_scalar(
        mapping: &Mapping,
        target: &FhirTarget,
        openehr: &OpenehrTarget,
        kind: FhirKind,
        text: &str,
    ) -> Result<FhirValue, EngineError> {
        let refuse = |source: LensError| EngineError::Cell {
            mapping: String::from(mapping.name()),
            element: String::from(target.expression().as_str()),
            source: Box::new(source),
        };
        // NOTE: a scalar leaf carries text, so only an element that travels as
        // text, or one `String.adoc` writes as text, takes it; no specification
        // governs the rest: our own design.
        match kind {
            FhirKind::Coding | FhirKind::Identifier | FhirKind::Reference
                if openehr.leaf_class() == Some(cell::STRING) =>
            {
                cell::get_string(text, kind).map_err(refuse)
            }
            FhirKind::Integer | FhirKind::Decimal
                if let Some(read) = scalar_number(openehr, kind, text) =>
            {
                read.map_err(refuse)
            }
            FhirKind::String
            | FhirKind::Date
            | FhirKind::DateTime
            | FhirKind::Instant
            | FhirKind::Time
            | FhirKind::Url => {
                let element = target.resolved().leaf();
                FhirValue::read(kind, element, &Value::String(String::from(text))).map_err(
                    |source| EngineError::Fhir {
                        mapping: String::from(mapping.name()),
                        element: String::from(element),
                        source: Box::new(source),
                    },
                )
            }
            FhirKind::Boolean
            | FhirKind::Coding
            | FhirKind::CodeableConcept
            | FhirKind::Period
            | FhirKind::Reference
            | FhirKind::Identifier
            | FhirKind::Quantity
            | FhirKind::Integer
            | FhirKind::UnsignedInt
            | FhirKind::PositiveInt
            | FhirKind::Decimal
            | FhirKind::Count
            | FhirKind::Duration
            | FhirKind::Attachment
            | FhirKind::Range => Err(refuse(LensError::NoCell {
                rm_type: String::from(openehr.leaf_class().unwrap_or(cell::STRING)),
                kind: kind.as_str(),
                direction: Direction::OpenehrToFhir,
            })),
        }
    }

    /// Records the defining code and each term mapping a cell of `mapping`
    /// left out of the FHIR element it wrote under `binding`.
    fn record_dropped(&mut self, mapping: &Mapping, binding: &Binding, dropped: &Dropped) {
        if dropped.code.is_none() && dropped.mappings.is_empty() && !dropped.reason {
            return;
        }
        let location = self.locate(mapping, &binding.fhir);
        // NOTE: no specification governs this: our own design, each loss
        // concerns one attribute of the value, so the openEHR side names that
        // attribute below the node's path.
        let below = |attribute: &str| match location.openehr() {
            Some(path) => location.clone().with_openehr(format!("{path}/{attribute}")),
            None => location.clone(),
        };
        if let Some(ref code) = dropped.code {
            self.warnings.push(Warning::uncarried_code(
                mapping.name(),
                code,
                below("defining_code"),
            ));
        }
        let mappings = below("mappings");
        for taken in &dropped.mappings {
            self.warnings
                .push(Warning::withheld(mapping.name(), taken, mappings.clone()));
        }
        if dropped.reason {
            self.warnings.push(Warning::new(
                Loss::Skipped {
                    mapping: String::from(mapping.name()),
                    reason: SkipReason::NullReasonUncarried,
                },
                location.clone(),
            ));
        }
    }

    /// Reads the FHIR element one input occurrence names, as the conversion
    /// the compiler derived or the `type` key names.
    fn input_value(
        &self,
        mapping: &Mapping,
        target: &FhirTarget,
        openehr: &OpenehrTarget,
        input: &Occurrence,
    ) -> Result<Option<FhirValue>, EngineError> {
        match mapping.derived() {
            Some(Derived::Choice { read, .. } | Derived::Polymorphic { read, .. }) => {
                self.choice_at(mapping, read, openehr, input)
            }
            Some(Derived::Declared(declared)) => {
                let kind = Self::kind(mapping, declared.target())?;
                self.element_at(mapping, declared.target(), input, kind)
            }
            Some(
                Derived::Element(_) | Derived::Anchor | Derived::Value { .. } | Derived::Event(_),
            )
            | None => {
                let kind = Self::kind(mapping, target)?;
                self.element_at(mapping, target, input, kind)
            }
        }
    }

    /// Returns the target a mapping writes FHIR through, with the element
    /// kind it writes.
    fn output_target<'mapping>(
        mapping: &'mapping Mapping,
        target: &'mapping FhirTarget,
    ) -> Result<(&'mapping FhirTarget, FhirKind), EngineError> {
        match mapping.derived() {
            Some(Derived::Choice {
                write: Some(written),
                ..
            }) => {
                let kind = FhirKind::of_code(written.code()).ok_or_else(|| {
                    EngineError::UnknownElement {
                        mapping: String::from(mapping.name()),
                        element: String::from(written.target().resolved().leaf()),
                    }
                })?;
                Ok((written.target(), kind))
            }
            Some(Derived::Declared(declared)) => {
                Ok((declared.target(), Self::kind(mapping, declared.target())?))
            }
            Some(Derived::Choice { write: None, .. } | Derived::Polymorphic { .. }) => {
                Err(EngineError::UnknownElement {
                    mapping: String::from(mapping.name()),
                    element: String::from(target.resolved().leaf()),
                })
            }
            Some(
                Derived::Element(_) | Derived::Anchor | Derived::Value { .. } | Derived::Event(_),
            )
            | None => Ok((target, Self::kind(mapping, target)?)),
        }
    }

    /// Stores one written value, overwriting what the same place holds.
    pub(super) fn store(&mut self, written: Written) {
        if let Some(slot) = self
            .written
            .iter_mut()
            .find(|held| held.flat_id == written.flat_id && held.positions == written.positions)
        {
            *slot = written;
        } else {
            self.written.push(written);
        }
    }

    /// Returns the positions one input occurrence names for an openEHR node,
    /// followed by the element of each `List` axis below it.
    pub(super) fn positions_of(
        mapping: &Mapping,
        input: &Occurrence,
        target: &OpenehrTarget,
    ) -> Result<Vec<RmPosition>, EngineError> {
        let depth = target
            .occurrences()
            .len()
            .saturating_add(target.lists().len());
        let taken = input.indices().get(..depth).unwrap_or(input.indices());
        let mut positions = rm_positions(mapping.name(), taken)?;
        positions.resize(depth, RmPosition::first());
        Ok(positions)
    }
}

/// Returns the openEHR node a mapping's data-type cell reads and writes.
///
/// A polymorphic `ELEMENT` converts into the value alternative the compiler
/// chose (`Derived::Value`); every other mapping converts at its own node.
fn converted(mapping: &Mapping) -> Option<&OpenehrTarget> {
    match mapping.derived() {
        Some(Derived::Value { target, .. }) => Some(target),
        _ => mapping.openehr(),
    }
}

/// Reads the number a scalar `Integer` or `Real` leaf holds as a FHIR
/// `integer` or `decimal`, `None` when the leaf and the kind are no such
/// pair.
fn scalar_number(
    openehr: &OpenehrTarget,
    kind: FhirKind,
    text: &str,
) -> Option<Result<FhirValue, LensError>> {
    let carried = rm::carried::carried(openehr.tail_class(), &tail_segments(openehr))
        .map(|(_, carried)| carried);
    let unreadable = |cell: &'static str, attribute: &'static str| LensError::Shape {
        cell,
        attribute,
        found: String::from(text),
        reason: "the composition holds no number there",
        direction: Direction::OpenehrToFhir,
    };
    match (carried, kind) {
        (Some(Carried::Integer), FhirKind::Integer) => Some(
            text.parse::<i64>()
                .map_err(|_refused| unreadable(scalar::INTEGER_CELL, "Integer"))
                .and_then(|number| IntegerLens.get(&number))
                .map(FhirValue::Integer),
        ),
        (Some(Carried::Real), FhirKind::Decimal) => Some(
            serde_json::Number::from_str(text)
                .map_err(|_refused| unreadable(scalar::REAL_CELL, "Real"))
                .and_then(|number| RealLens.get(&number))
                .map(FhirValue::Decimal),
        ),
        _ => None,
    }
}

/// Returns the refusal of a polymorphic `ELEMENT` that holds a value of an
/// alternative the mapping does not read.
fn other_alternative(mapping: &Mapping, target: &FhirTarget, node: &OpenehrTarget) -> EngineError {
    EngineError::UnknownElement {
        mapping: String::from(mapping.name()),
        element: format!(
            "{} from another value alternative at `{}`",
            target.resolved().leaf(),
            node.node().aql_path().as_str()
        ),
    }
}

/// Reads an `ELEMENT`'s null flavour as the `code` of a `data-absent-reason`
/// extension.
///
/// The extension's value is a `code`
/// (<https://hl7.org/fhir/R4/extension-data-absent-reason.html>), which
/// travels as text, so the cell pairs only with a FHIR element that does.
fn read_null_flavour(flavour: &NullFlavour, kind: FhirKind) -> Result<FhirValue, LensError> {
    match kind {
        FhirKind::String => NullFlavourLens.get(flavour).map(FhirValue::String),
        other => Err(LensError::NoCell {
            rm_type: String::from("ELEMENT.null_flavour"),
            kind: other.as_str(),
            direction: Direction::OpenehrToFhir,
        }),
    }
}

/// What a cell read out of openEHR left out of the FHIR element it wrote.
#[derive(Debug, Default)]
struct Dropped {
    /// The `defining_code` a `string` cannot carry.
    code: Option<CodePhrase>,
    /// The term mappings the element cannot carry.
    mappings: Vec<Withheld>,
    /// Whether a `null_reason` that names no code was left out.
    reason: bool,
}

/// The node an occurrence reads out of, what it holds, and the FHIR target
/// and kind it writes.
type OutSource<'mapping> = (
    &'mapping OpenehrTarget,
    Leaf,
    &'mapping FhirTarget,
    FhirKind,
);

#[cfg(test)]
mod tests {
    use super::read_null_flavour;
    use crate::engine::fhir::FhirKind;
    use crate::engine::lens::Lens;
    use crate::engine::lens::null_flavour::NullFlavourLens;

    #[test]
    fn a_null_flavour_pairs_only_with_an_element_that_travels_as_text() {
        // R4 extension-data-absent-reason: the value is a `code`.
        let flavour = NullFlavourLens
            .put(&fhir_types::r4::primitives::String::from("masked"), None)
            .expect("masked is in the value set");
        assert!(read_null_flavour(&flavour, FhirKind::String).is_ok());
        let error = read_null_flavour(&flavour, FhirKind::Coding)
            .expect_err("no cell pairs a null flavour with a Coding");
        assert!(error.to_string().contains("null_flavour"), "{error}");
    }
}