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

//! The pair a mapping with no `type` converts through.

use core::str::FromStr;

use fhir_types::schema::Kind;
use fhir_types::schema::ValueKind;
use openehr_mapping_core::diagnostic::Diagnostic;
use openehr_mapping_core::diagnostic::ModelPath;
use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::position::Position;
use openehr_rm::v1_2::model;

use crate::model::ast::ModelMappingFile;
use crate::model::ast::keyword::Direction;
use crate::resolve::derive;
use crate::resolve::error::ResolveCode;
use crate::resolve::extensions::diagnostic;
use crate::resolve::program::mapping::Alternative;
use crate::resolve::program::mapping::Derived;
use crate::resolve::program::mapping::EventTime;
use crate::resolve::program::mapping::Pairing;
use crate::resolve::program::target::FhirTarget;
use crate::resolve::program::target::OpenehrTarget;
use crate::tree::element;
use crate::tree::element::Location;
use crate::tree::element::Move;
use crate::tree::path::FhirPath;

use crate::resolve::compile::Compiler;
use crate::resolve::compile::Derivation;

/// The two resolved sides of a mapping with no `type` key, as its conversion
/// is derived from them.
#[derive(Debug, Clone, Copy)]
struct Sides<'target> {
    fhir: &'target FhirTarget,
    openehr: &'target OpenehrTarget,
    direction: Option<Direction>,
    children: bool,
}

/// The FHIR type every extension is (<https://hl7.org/fhir/R4/extensibility.html>).
const EXTENSION_TYPE: &str = "Extension";

/// The element of an extension that carries its value, `Extension.value[x]`.
const EXTENSION_VALUE: &str = "value";

/// The reference-model class of a leaf of an item structure, whose `value`
/// holds one data value (openEHR RM, the data structures `ELEMENT` class).
const ELEMENT: &str = "ELEMENT";

/// The abstract class of an event of a history (openEHR RM, the data
/// structures `EVENT` class).
const EVENT: &str = "EVENT";

/// The event a point in time makes (RM data structures, `POINT_EVENT`).
const POINT_EVENT: &str = "POINT_EVENT";

/// The event a period makes (RM data structures, `INTERVAL_EVENT`).
const INTERVAL_EVENT: &str = "INTERVAL_EVENT";

/// The attribute of an event that carries its time (RM `EVENT.time`).
const TIME: &str = "time";

/// The FHIR type a `POINT_EVENT` is written as.
const DATE_TIME: &str = "dateTime";

/// The FHIR type an `INTERVAL_EVENT` is written as.
const PERIOD: &str = "Period";

/// The FHIR types `EVENT.adoc` pairs with a `POINT_EVENT` besides `dateTime`,
/// which go in and have no event class to come out as.
const POINT_CODES: &[&str] = &["instant", "date", "time"];

impl<'a> Compiler<'a> {
    /// Derives what the data-type cell of a mapping converts, when the
    /// mapping leaves it to the compiler.
    ///
    /// A plain value mapping with no `type` key derives its pair from its two
    /// sides, and a mapping whose `type` key names the type of a choice element
    /// no filter resolved takes that alternative. Every other mapping carries
    /// what it wrote.
    pub(super) fn derived_of(
        &mut self,
        file: &'a ModelMappingFile,
        derivation: &Derivation<'_>,
        position: Position,
        path: &ModelPath,
    ) -> Option<Derived> {
        let fhir = derivation.fhir?;
        match (derivation.openehr, derivation.data_type) {
            (Some(openehr), None) if derivation.plain => self.derive(
                file,
                Sides {
                    fhir,
                    openehr,
                    direction: derivation.direction,
                    children: derivation.children,
                },
                position,
                path,
            ),
            (_, Some(data_type))
                if derivation.plain
                    && matches!(*fhir.resolved().location(), Location::Choice(_)) =>
            {
                let code = derive::declared(data_type)?;
                self.declared_alternative(file, fhir, code, position, path)
            }
            _ => None,
        }
    }

    /// Derives the conversion of a mapping with no `type` key from its two
    /// resolved sides.
    ///
    /// A structural node anchors the children and converts nothing, as the
    /// `type: NONE` of `types-of-mappings/concept-type/FollowedBy.adoc` does,
    /// and one with no child writes nothing, which is refused. A choice
    /// element, and an `Extension` against a data value, read the alternative
    /// the document carries and write the first pair of the node's class the
    /// choice admits (`crate::resolve::derive`).
    fn derive(
        &mut self,
        file: &'a ModelMappingFile,
        sides: Sides<'_>,
        position: Position,
        path: &ModelPath,
    ) -> Option<Derived> {
        let owner = file.header().name().value();
        let Sides {
            fhir,
            openehr,
            direction,
            children,
        } = sides;
        let class = openehr.leaf_class().unwrap_or(openehr.node().rm_type());
        // NOTE: DV_QUANTITY.adoc §Range maps a range other than the normal one to the
        // `other_reference_ranges` List, whose elements only a mapping's children can fill.
        if openehr.ends_on_list() {
            return children.then_some(Derived::Anchor);
        }
        if model::is_a(class, derive::STRUCTURAL) {
            if let Some(event) = self.event_time(file, fhir, openehr, position, path) {
                return Some(event);
            }
            if let Some(polymorphic) = self.element_choice(file, fhir, openehr, position, path) {
                return Some(polymorphic);
            }
            if let Some(value) = self.element_value(fhir, openehr) {
                return Some(value);
            }
            if children {
                return Some(Derived::Anchor);
            }
            // NOTE: no specification governs this: our own design, the mapping is kept
            // with no derived pair so a run that carries its element refuses with no cell.
            self.diagnostics.push(
                Diagnostic::warning(
                    file.file().to_path_buf(),
                    ResolveCode::AnchorWithoutChildren.into(),
                    format!(
                        "`{}` names the {class} node `{}`, which holds other nodes, and no \
                         `type` or child says what to write into it, so a run that carries \
                         the element refuses",
                        fhir.expression(),
                        openehr.path()
                    ),
                )
                .with_position(position)
                .with_mapping_name(owner.clone())
                .with_model_path(path.clone()),
            );
            return None;
        }
        let read = match *fhir.resolved().location() {
            Location::Choice(_) => fhir.clone(),
            Location::Complex(schema)
                if schema.name == EXTENSION_TYPE && !derive::pairs(class).is_empty() =>
            {
                self.derived_target(file, fhir, EXTENSION_VALUE, position, path)?
            }
            Location::Complex(_) | Location::Primitive(_) | Location::Attribute => {
                return self.element_pair(file, sides, class, position, path);
            }
            Location::Resource
                if openehr.leaf_class().is_none() && !derive::pairs(class).is_empty() =>
            {
                let resource = fhir.resolved().leaf();
                self.unpaired(file, (fhir, openehr), class, resource, position, path);
                return None;
            }
            Location::PrimitiveElement | Location::Resource | Location::Deferred => return None,
        };
        if direction == Some(Direction::FhirToOpenehr) {
            return Some(Derived::Choice { read, write: None });
        }
        let variants = match read.resolved().moves().last() {
            Some(Move::Choice { schema, .. }) => match schema.kind {
                Kind::Choice(variants) => variants,
                _ => &[],
            },
            _ => &[],
        };
        let Some(suffix) = derive::alternative(class, variants) else {
            self.diagnostics.push(diagnostic(
                file.file(),
                owner,
                ResolveCode::UnderivedAlternative,
                position,
                path,
                format!(
                    "`{}` is written from the {class} node `{}`, and the choice admits none of \
                     the types {class} pairs with ({}); a `type` or an `as()` says which to write",
                    read.resolved().leaf(),
                    openehr.path(),
                    derive::pairs(class).join(", ")
                ),
            ));
            return None;
        };
        let written = self.derived_target(file, &read, &format!("as({suffix})"), position, path)?;
        let code = written.resolved().type_code().unwrap_or(suffix);
        Some(Derived::Choice {
            read,
            write: Some(Alternative::new(code, written)),
        })
    }

    /// Derives the pair of an element that is no choice and no extension,
    /// refusing one no page of the data-type chapter pairs with `class`.
    fn element_pair(
        &mut self,
        file: &'a ModelMappingFile,
        sides: Sides<'_>,
        class: &str,
        position: Position,
        path: &ModelPath,
    ) -> Option<Derived> {
        let Sides {
            fhir,
            openehr,
            direction,
            ..
        } = sides;
        let code = fhir.resolved().type_code()?;
        let text = matches!(
            *fhir.resolved().location(),
            Location::Primitive(ValueKind::Text) | Location::Attribute
        );
        let pair = derive::element(class, code, text);
        if openehr.leaf_class().is_none()
            && !derive::pairs(class).is_empty()
            && !derive::pairs_in(class, pair, direction)
        {
            self.unpaired(file, (fhir, openehr), class, code, position, path);
            return None;
        }
        Some(Derived::Element(pair))
    }

    /// Refuses a mapping whose openEHR `class` and FHIR `named` type no page
    /// of the data-type chapter pairs
    /// (`docs/specs/fhirconnect/modules/ROOT/pages/types-of-mappings/data-type/`),
    /// so it fails at load and never on the run that first carries it.
    fn unpaired(
        &mut self,
        file: &'a ModelMappingFile,
        (fhir, openehr): (&FhirTarget, &OpenehrTarget),
        class: &str,
        named: &str,
        position: Position,
        path: &ModelPath,
    ) {
        self.diagnostics.push(diagnostic(
            file.file(),
            file.header().name().value(),
            ResolveCode::UnpairedTypes,
            position,
            path,
            format!(
                "`{}` ({named}) is mapped onto the {class} node `{}`, and the data-type chapter \
                 pairs {class} only with {}; a `manual`, a `mappingCode` or a path to a paired \
                 element says how to carry it",
                fhir.expression(),
                openehr.path(),
                derive::pairs(class).join(", ")
            ),
        ));
    }

    /// Returns the value alternative of a polymorphic `ELEMENT` the FHIR
    /// element converts into, when the node is one and an alternative pairs.
    ///
    /// The Web Template gives each data type an `ELEMENT` admits a child node
    /// of its own, so the node holds other nodes; `FollowedBy.adoc` runs the
    /// children after the parent "has been executed", so the parent converts
    /// its own value first. A class that pairs with the FHIR type itself
    /// outranks one reached through the text fallback of [`derive::element`]:
    /// `types-of-mappings/data-type/DV_DATE_TIME.adoc` §`DateTime` pairs
    /// `dateTime` with `DV_DATE_TIME`, while `DV_TEXT.adoc` §`String` pairs only
    /// `string`. Among the rest the alternative is the one whose class pairs
    /// with the FHIR type earliest in [`derive::PAIRS`], the first in template
    /// order on a tie (no specification governs the tie-break: our own design).
    fn element_value(&self, fhir: &FhirTarget, openehr: &OpenehrTarget) -> Option<Derived> {
        if openehr.node().rm_type() != ELEMENT || !openehr.tail().segments.is_empty() {
            return None;
        }
        let location = fhir.resolved().location();
        let text = match *location {
            Location::Primitive(ValueKind::Text) | Location::Attribute => true,
            Location::Complex(_) | Location::Primitive(_) => false,
            Location::Choice(_)
            | Location::PrimitiveElement
            | Location::Resource
            | Location::Deferred => return None,
        };
        let code = fhir.resolved().type_code()?;
        let mut chosen: Option<((bool, usize), &ResolvedNode, &'static str)> = None;
        for flat_id in openehr.node().children() {
            let Ok(child) = self.template.node_by_flat_id(flat_id) else {
                continue;
            };
            let class = child.rm_type();
            let pair = derive::element(class, code, text);
            let Some(rank) = derive::pairs(class)
                .iter()
                .position(|&paired| paired == pair)
            else {
                continue;
            };
            let key = (pair != code, rank);
            if chosen.is_none_or(|(best, _, _)| key < best) {
                chosen = Some((key, child, pair));
            }
        }
        let (_, child, pair) = chosen?;
        // NOTE: openEHR RM data_structures §ELEMENT: `value` holds one data value, so the
        // alternative repeats exactly where the `ELEMENT` does and takes its axes.
        let target = OpenehrTarget::new(
            child.rm_path().clone(),
            child.clone(),
            openehr.tail().clone(),
            openehr.occurrences().to_vec(),
        );
        Some(Derived::Value { code: pair, target })
    }

    /// Returns the event time a FHIR time maps onto an `EVENT` node as, when
    /// the node is one and the FHIR element is a time, a `Period` or a choice
    /// admitting either.
    ///
    /// `types-of-mappings/data-type/EVENT.adoc` §`POINT_EVENT` and
    /// `INTERVAL_EVENT` pairs `time`, `date`, `dateTime` and `instant` with a
    /// `POINT_EVENT` and `Period` with an `INTERVAL_EVENT`. Coming out a
    /// `POINT_EVENT` is written as `dateTime` and an `INTERVAL_EVENT` as
    /// `Period`, and a node the template narrows to one class takes only its
    /// own (no specification governs which alternative is written: our own
    /// design).
    fn event_time(
        &mut self,
        file: &'a ModelMappingFile,
        fhir: &FhirTarget,
        openehr: &OpenehrTarget,
        position: Position,
        path: &ModelPath,
    ) -> Option<Derived> {
        let class = openehr.node().rm_type();
        if !model::is_a(class, EVENT) || !openehr.tail().segments.is_empty() {
            return None;
        }
        let points = model::is_a(POINT_EVENT, class);
        let intervals = model::is_a(INTERVAL_EVENT, class);
        let time = self.event_time_node(openehr)?;
        let (point, interval) = match *fhir.resolved().location() {
            Location::Choice(_) => {
                let variants = match fhir.resolved().moves().last() {
                    Some(Move::Choice { schema, .. }) => match schema.kind {
                        Kind::Choice(variants) => variants,
                        _ => &[],
                    },
                    _ => &[],
                };
                let point = derive::suffix_of(DATE_TIME, variants).filter(|_| points);
                let interval = derive::suffix_of(PERIOD, variants).filter(|_| intervals);
                if point.is_none() && interval.is_none() {
                    return None;
                }
                let mut written = |suffix: Option<&str>| match suffix {
                    Some(suffix) => self
                        .derived_target(file, fhir, &format!("as({suffix})"), position, path)
                        .map(Some),
                    None => Some(None),
                };
                (written(point)?, written(interval)?)
            }
            Location::Complex(_) | Location::Primitive(_) => match fhir.resolved().type_code()? {
                PERIOD if intervals => (None, Some(fhir.clone())),
                DATE_TIME if points => (Some(fhir.clone()), None),
                code if points && POINT_CODES.contains(&code) => (None, None),
                _ => return None,
            },
            Location::Attribute
            | Location::PrimitiveElement
            | Location::Resource
            | Location::Deferred => return None,
        };
        Some(Derived::Event(Box::new(EventTime::new(
            fhir.clone(),
            time,
            point,
            interval,
        ))))
    }

    /// Returns the `time` node of an `EVENT` node, with the event's axes.
    ///
    /// `EVENT.time` is 1..1 (openEHR RM data structures, the `EVENT` class), so
    /// the node repeats exactly where the event does.
    fn event_time_node(&self, openehr: &OpenehrTarget) -> Option<OpenehrTarget> {
        let child = openehr.node().children().iter().find_map(|flat_id| {
            self.template.node_by_flat_id(flat_id).ok().filter(|child| {
                child
                    .rm_path()
                    .segments
                    .last()
                    .is_some_and(|segment| segment.attribute == TIME)
            })
        })?;
        Some(OpenehrTarget::new(
            child.rm_path().clone(),
            child.clone(),
            openehr.tail().clone(),
            openehr.occurrences().to_vec(),
        ))
    }

    /// Returns the pairs a choice element converts through against a
    /// polymorphic `ELEMENT`, when the node is one and an alternative pairs.
    ///
    /// The Web Template gives each data type an `ELEMENT` admits a child node,
    /// and the data-type chapter pairs each class with FHIR types
    /// ([`derive::PAIRS`]), so every alternative of the choice that pairs with
    /// a child's class is kept, child by child in template order and each
    /// child's pairs in its page's order (no specification governs the order:
    /// our own design). The document's alternative or the composition's value
    /// node picks one at run time.
    fn element_choice(
        &mut self,
        file: &'a ModelMappingFile,
        fhir: &FhirTarget,
        openehr: &OpenehrTarget,
        position: Position,
        path: &ModelPath,
    ) -> Option<Derived> {
        if openehr.node().rm_type() != ELEMENT
            || !openehr.tail().segments.is_empty()
            || !matches!(*fhir.resolved().location(), Location::Choice(_))
        {
            return None;
        }
        let variants = match fhir.resolved().moves().last() {
            Some(Move::Choice { schema, .. }) => match schema.kind {
                Kind::Choice(variants) => variants,
                _ => &[],
            },
            _ => &[],
        };
        let mut pairings = Vec::new();
        for flat_id in openehr.node().children() {
            let Ok(child) = self.template.node_by_flat_id(flat_id) else {
                continue;
            };
            // NOTE: openEHR RM data_structures §ELEMENT: `value` holds one data value, so
            // each value alternative repeats exactly where the `ELEMENT` does.
            let target = OpenehrTarget::new(
                child.rm_path().clone(),
                child.clone(),
                openehr.tail().clone(),
                openehr.occurrences().to_vec(),
            );
            for (rank, code) in derive::pairs(child.rm_type()).iter().enumerate() {
                let Some(suffix) = derive::suffix_of(code, variants) else {
                    continue;
                };
                let written =
                    self.derived_target(file, fhir, &format!("as({suffix})"), position, path)?;
                let code = written.resolved().type_code().unwrap_or(code);
                pairings.push(Pairing::new(
                    Alternative::new(code, written),
                    suffix,
                    rank,
                    target.clone(),
                ));
            }
        }
        (!pairings.is_empty()).then(|| Derived::Polymorphic {
            read: fhir.clone(),
            pairings,
        })
    }

    /// Resolves the alternative of a choice element the `type` key names.
    ///
    /// The key names the FHIR type of the element, the Type ID column of the
    /// table in `types-of-mappings/data-type/data-mappings.adoc` §Deprecated, so
    /// on a choice it fixes the alternative both directions read and write.
    fn declared_alternative(
        &mut self,
        file: &'a ModelMappingFile,
        fhir: &FhirTarget,
        code: &'static str,
        position: Position,
        path: &ModelPath,
    ) -> Option<Derived> {
        let variants = match fhir.resolved().moves().last() {
            Some(Move::Choice { schema, .. }) => match schema.kind {
                Kind::Choice(variants) => variants,
                _ => &[],
            },
            _ => &[],
        };
        let Some(suffix) = derive::suffix_of(code, variants) else {
            self.diagnostics.push(diagnostic(
                file.file(),
                file.header().name().value(),
                ResolveCode::UnderivedAlternative,
                position,
                path,
                format!(
                    "the `type` of `{}` names {code}, which the choice `{}` does not admit",
                    fhir.expression(),
                    fhir.resolved().leaf()
                ),
            ));
            return None;
        };
        let written = self.derived_target(file, fhir, &format!("as({suffix})"), position, path)?;
        Some(Derived::Declared(Alternative::new(code, written)))
    }

    /// Resolves `target` extended by one step the compiler derived.
    ///
    /// The step is one the grammar admits below any element of the kind the
    /// target ends on, so a refusal is an element-table disagreement and is
    /// reported as one for a written path would be.
    fn derived_target(
        &mut self,
        file: &'a ModelMappingFile,
        target: &FhirTarget,
        step: &str,
        position: Position,
        path: &ModelPath,
    ) -> Option<FhirTarget> {
        let written = format!("{}.{step}", target.expression());
        let (code, reason) = match FhirPath::from_str(&written) {
            Ok(expression) => {
                match element::resolve(self.table, target.resolved().resource(), &expression) {
                    Ok(resolved) => {
                        return Some(
                            FhirTarget::new(expression, resolved).at_level(target.level()),
                        );
                    }
                    Err(error) => (ResolveCode::UnknownFhirElement, error.to_string()),
                }
            }
            Err(error) => (ResolveCode::MalformedFhirPath, error.to_string()),
        };
        self.diagnostics.push(diagnostic(
            file.file(),
            file.header().name().value(),
            code,
            position,
            path,
            format!("the derived `{written}` does not resolve: {reason}"),
        ));
        None
    }
}