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

//! The resolved sides of a mapping: the FHIR element and the openEHR node.

use core::fmt;

use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::index::paths::FlatId;
use openehr_rm::v1_2::paths::RmPath;

use crate::tree::element::Location;
use crate::tree::element::Move;
use crate::tree::element::Resolved;
use crate::tree::path::FhirPath;
use crate::tree::path::Writability;

/// The reference-model class of a leaf of an item structure, whose attributes a
/// tail on the element names.
const ELEMENT: &str = "ELEMENT";

/// A `with.fhir` expression, bound to its anchor and resolved against the
/// element table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FhirTarget {
    expression: FhirPath,
    resolved: Resolved,
    level: usize,
}

impl FhirTarget {
    /// Pairs an anchored expression with its element-table resolution, rooted
    /// at the program's own resource.
    #[must_use]
    pub const fn new(expression: FhirPath, resolved: Resolved) -> Self {
        Self {
            expression,
            resolved,
            level: 0,
        }
    }

    /// Returns this target rooted at the resource `level` references deep.
    ///
    /// The program's own resource is level `0`, and each `reference` mapping
    /// the expression is written inside adds one. A `^` run that climbs out
    /// of a referenced resource binds the expression to an enclosing one,
    /// which is what the worked `^^` example does
    /// (`docs/specs/fhirconnect/modules/ROOT/pages/basics/path_operators.adoc`,
    /// §Recurrence and parent elements).
    #[must_use]
    pub const fn at_level(mut self, level: usize) -> Self {
        self.level = level;
        self
    }

    /// Returns how many references deep the resource the expression is
    /// rooted at lies.
    #[must_use]
    pub const fn level(&self) -> usize {
        self.level
    }

    /// Returns the `$resource`-rooted expression.
    #[must_use]
    pub const fn expression(&self) -> &FhirPath {
        &self.expression
    }

    /// Returns the element-table resolution.
    #[must_use]
    pub const fn resolved(&self) -> &Resolved {
        &self.resolved
    }

    /// Returns whether the expression can be written through.
    #[must_use]
    pub const fn writability(&self) -> &Writability {
        self.expression.writability()
    }

    /// Returns whether the expression names many values.
    ///
    /// The element the walk ends on decides it, unless a later step picks one
    /// of the values a document already holds: an index, an ordinal, a
    /// predicate, or the `extension(url)` shortcut, whose url "is the
    /// identity" of one extension
    /// (<https://hl7.org/fhir/R4/extensibility.html>). This is the FHIR-side
    /// counterpart of [`OpenehrTarget::occurrences`].
    #[must_use]
    pub fn repeats(&self) -> bool {
        let mut repeats = false;
        for step in self.resolved.moves() {
            match *step {
                Move::Member(ref field) | Move::Choice { ref field, .. } => {
                    repeats = field.repeats();
                }
                Move::Extension { .. } | Move::Ordinal(_) | Move::Index(_) | Move::Predicate(_) => {
                    repeats = false;
                }
                Move::Resolve { .. } => {}
            }
        }
        repeats
    }
}

impl fmt::Display for FhirTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let writability = match *self.writability() {
            Writability::Writable => "writable",
            Writability::ReadOnly { .. } => "read-only",
        };
        write!(
            f,
            "{} -> {} {} {}",
            self.expression,
            self.resolved.leaf(),
            location_name(self.resolved.location()),
            writability
        )
    }
}

/// Names where a resolved FHIR path ends, for a rendering that stays stable.
fn location_name(location: &Location) -> &'static str {
    match *location {
        Location::Complex(_) => "complex",
        Location::Primitive(_) => "primitive",
        Location::Attribute => "attribute",
        Location::PrimitiveElement => "primitive-element",
        Location::Choice(_) => "choice",
        Location::Resource => "resource",
        Location::Deferred => "deferred",
    }
}

/// A `with.openehr` path, bound to its anchor and resolved against the Web
/// Template.
///
/// The Web Template indexes the nodes a template constrains, and an openEHR
/// path may reach below the deepest of them into the reference model, so a
/// target carries the node plus the attribute tail under it. No specification
/// governs the meeting of a mapping path and a Web Template: this split is
/// FerroBRIDGE's own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenehrTarget {
    path: RmPath,
    node: ResolvedNode,
    tail: RmPath,
    occurrences: Vec<FlatId>,
    lists: Vec<ListAxis>,
    leaf_class: Option<String>,
    on_element: bool,
    value_class: Option<String>,
}

/// One `List` attribute a tail steps through: an occurrence axis inside the
/// value of a template node, whose instances are the list's elements.
///
/// An openEHR RM `List` is ordered, so an element is addressed by its 1-based
/// position (openEHR BASE Release 1.2.0 §Paths and Locators, "Using
/// Positional Predicates"). Two targets share the axis when they name the same
/// attributes below the same node, which is what pairs a mapping anchored on
/// the list with the children that name the attributes of one element. No
/// specification governs the axis: our own design.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListAxis {
    node: FlatId,
    on_element: bool,
    attributes: Vec<String>,
}

impl ListAxis {
    /// Returns the position in the tail of the list attribute, the last of
    /// [`Self::attributes`].
    #[must_use]
    pub fn depth(&self) -> usize {
        self.attributes.len().saturating_sub(1)
    }

    /// Returns the attributes from the node down to the list, outermost first.
    #[must_use]
    pub fn attributes(&self) -> &[String] {
        &self.attributes
    }

    /// Returns the name the recurrence counters key the axis by, distinct
    /// from every template node's flat id since a flat id holds no `|`.
    #[must_use]
    pub fn key(&self) -> String {
        let side = if self.on_element { "element" } else { "value" };
        format!(
            "{}|{side}|{}",
            self.node.as_str(),
            self.attributes.join("/")
        )
    }
}

impl OpenehrTarget {
    /// Pairs a resolved path with the template node it names.
    #[must_use]
    pub fn new(path: RmPath, node: ResolvedNode, tail: RmPath, occurrences: Vec<FlatId>) -> Self {
        let mut target = Self {
            path,
            node,
            tail,
            occurrences,
            lists: Vec::new(),
            leaf_class: None,
            on_element: false,
            value_class: None,
        };
        target.lists = target.list_axes();
        target
    }

    /// Returns the `List` attributes the tail steps through, outermost first.
    fn list_axes(&self) -> Vec<ListAxis> {
        let segments: Vec<&str> = self
            .tail
            .segments
            .iter()
            .map(|segment| segment.attribute.as_str())
            .collect();
        // NOTE: a tail the engine cannot walk is refused at load
        // (`fc-uncarried-tail`), so it legitimately has no list axis here.
        let steps = crate::engine::rm::carried::list_steps(self.tail_class(), &segments)
            .unwrap_or_default();
        steps
            .into_iter()
            .map(|depth| ListAxis {
                node: self.node.flat_id().clone(),
                on_element: self.on_element,
                attributes: segments
                    .get(..=depth)
                    .unwrap_or_default()
                    .iter()
                    .map(|segment| String::from(*segment))
                    .collect(),
            })
            .collect()
    }

    /// Returns the `List` attributes the tail steps through, outermost first,
    /// each an occurrence axis below the node's own [`Self::occurrences`].
    #[must_use]
    pub fn lists(&self) -> &[ListAxis] {
        &self.lists
    }

    /// Returns whether the tail ends on a `List` attribute, which names the
    /// list as an axis and holds no single value.
    #[must_use]
    pub fn ends_on_list(&self) -> bool {
        self.lists
            .last()
            .is_some_and(|axis| axis.attributes.len() == self.tail.segments.len())
    }

    /// Returns this target with its tail naming attributes of the `ELEMENT`
    /// the Web Template compacted into the node, its value.
    ///
    /// An `ELEMENT` is a `LOCATABLE` (openEHR RM, the `LOCATABLE` class), so a
    /// path that names one reaches its `links` although the template carries
    /// only the node of its value.
    #[must_use]
    pub fn with_element_tail(mut self) -> Self {
        self.on_element = true;
        self.lists = self.list_axes();
        self
    }

    /// Returns whether the tail names attributes of the `ELEMENT` the node
    /// is the value of, rather than attributes of the node.
    #[must_use]
    pub const fn on_element(&self) -> bool {
        self.on_element
    }

    /// Returns the reference-model class the tail's first attribute is looked
    /// up on: `ELEMENT` when the tail names the element's attributes, the
    /// node's class otherwise.
    #[must_use]
    pub fn tail_class(&self) -> &str {
        if self.on_element {
            ELEMENT
        } else {
            self.node.rm_type()
        }
    }

    /// Returns this target with `class` as the class of the value it writes
    /// at its node, where that differs from the node's own class.
    ///
    /// A `DV_CODED_TEXT` node whose value set is open may hold a `DV_TEXT`
    /// (Simplified Formats, §Open Value-Sets and the `|other` Suffix), which
    /// is what a `manual` entry writing no `defining_code` there creates.
    #[must_use]
    pub fn with_value_class(mut self, class: impl Into<String>) -> Self {
        self.value_class = Some(class.into());
        self
    }

    /// Returns the class of the value this target writes at its node: the
    /// class [`Self::with_value_class`] set, the node's class otherwise.
    #[must_use]
    pub fn value_class(&self) -> &str {
        self.value_class
            .as_deref()
            .unwrap_or_else(|| self.node.rm_type())
    }

    /// Returns this target with `class` as the reference-model class of the
    /// last attribute its tail names.
    #[must_use]
    pub fn with_leaf_class(mut self, class: impl Into<String>) -> Self {
        self.leaf_class = Some(class.into());
        self
    }

    /// Returns the reference-model class of the last attribute the tail names,
    /// `None` for a path that names the node itself.
    ///
    /// The resolver reads it from the RM attribute model
    /// (<https://docs.rs/openehr-rm/0.0.69/openehr_rm/v1_2/model/fn.attribute.html>),
    /// and it is the class, in place of the node's, whose value the engine
    /// reads and writes at the end of the tail.
    #[must_use]
    pub fn leaf_class(&self) -> Option<&str> {
        self.leaf_class.as_deref()
    }

    /// Returns the absolute openEHR path the mapping names.
    #[must_use]
    pub const fn path(&self) -> &RmPath {
        &self.path
    }

    /// Returns the template node the path resolves to.
    #[must_use]
    pub const fn node(&self) -> &ResolvedNode {
        &self.node
    }

    /// Returns the reference-model attributes below the node, empty when the
    /// path names the node itself.
    #[must_use]
    pub const fn tail(&self) -> &RmPath {
        &self.tail
    }

    /// Returns the repeating nodes on the way to this one, outermost first.
    ///
    /// One occurrence index belongs to each of them, which is what makes an
    /// occurrence a structured index rather than a pattern over a rendered
    /// path.
    #[must_use]
    pub fn occurrences(&self) -> &[FlatId] {
        &self.occurrences
    }
}

impl fmt::Display for OpenehrTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} -> {} {}",
            self.path,
            self.node.aql_path().as_str(),
            self.node.rm_type()
        )?;
        if !self.tail.segments.is_empty() {
            write!(f, " tail {}", self.tail)?;
        }
        if !self.occurrences.is_empty() {
            let axes: Vec<&str> = self.occurrences.iter().map(FlatId::as_str).collect();
            write!(f, " occurrences [{}]", axes.join(", "))?;
        }
        if !self.lists.is_empty() {
            let lists: Vec<String> = self
                .lists
                .iter()
                .map(|axis| axis.attributes.join("/"))
                .collect();
            write!(f, " lists [{}]", lists.join(", "))?;
        }
        Ok(())
    }
}

/// One side of a mapping, on the side the path belongs to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
    /// A FHIR expression.
    Fhir(Box<FhirTarget>),
    /// An openEHR path.
    Openehr(Box<OpenehrTarget>),
}

impl fmt::Display for Target {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Fhir(ref target) => write!(f, "fhir {target}"),
            Self::Openehr(ref target) => write!(f, "openehr {target}"),
        }
    }
}

/// How a condition's `targetRoot` stands to the path it guards.
///
/// The `targetRoot` "defines what element is returned once filtered ... the
/// returned element is matched against the path in the `with` method", and a
/// condition may also "be unattached to the path contained in the `with:`
/// method and point to a different path", which is "handled as simple
/// true/false"
/// (`docs/specs/fhirconnect/modules/ROOT/pages/basics/Conditions.adoc`,
/// §targetRoot). The compiler decides which of the four it is, over the
/// anchored paths, so the engine never compares path text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Attachment {
    /// The `targetRoot` is the guarded path, so the condition filters the
    /// values that path maps.
    Element,
    /// The `targetRoot` is above the guarded path.
    Ancestor,
    /// The `targetRoot` is below the guarded path, which is the shape a
    /// preprocessor gate writes and a mapping-level condition is refused for.
    Descendant,
    /// Neither path contains the other, so the condition is a plain true or
    /// false test.
    Unrelated,
}

impl fmt::Display for Attachment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Element => f.write_str("element"),
            Self::Ancestor => f.write_str("ancestor"),
            Self::Descendant => f.write_str("descendant"),
            Self::Unrelated => f.write_str("unrelated"),
        }
    }
}