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

//! The refusals of a run.

use core::fmt;

use openehr_mapping_core::composition::PositionError;
use openehr_mapping_core::template::PathError;
use openehr_rm::v1_2::paths::EhrUriError;
use openehr_rm::v1_2::paths::write::SetPathError;

use crate::engine::condition::ConditionError;
use crate::engine::demographics::DemographicsError;
use crate::engine::family::FamilyError;
use crate::engine::fhir::FhirError;
use crate::engine::invariant::Breach;
use crate::engine::lens::LensError;
use crate::engine::rm::RmError;
use crate::engine::seam::ReferenceError;
use crate::engine::terminology::TerminologyError;
use crate::resolve::program::hierarchy::Create;
use openehr_mapping_core::party::PartyClass;
use openehr_mapping_core::party::PartyError;

use crate::tree::error::ReadError;
use crate::tree::error::WriteError;

use crate::engine::traverse::functions::MappingCodeError;

/// Why a run refused.
///
/// Every variant names the mapping it refused in, so a diagnostic points at
/// the file the mapping author edits.
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
    /// The program's own condition does not admit the input.
    #[error("the context {context} does not apply to this input")]
    NotApplicable {
        /// The context mapping the program compiled from.
        context: String,
    },
    /// A party program reached an entry point that runs over a composition.
    #[error(
        "the context {context} is a party context rooted at a {party}, and this entry point runs \
         over a composition"
    )]
    PartyProgram {
        /// The context mapping the program compiled from.
        context: String,
        /// The demographic class the program is rooted at.
        party: PartyClass,
    },
    /// A composition program reached an entry point that runs over a party.
    #[error("the context {context} is no party context, and this entry point runs over a party")]
    CompositionProgram {
        /// The context mapping the program compiled from.
        context: String,
    },
    /// The values a party program produced do not build a party.
    #[error("the values the run produced do not build a party")]
    PartyBuild {
        /// What the party build refused.
        #[source]
        source: Box<PartyError>,
    },
    /// A `manual` path writes a `$context` member and the run carries no call
    /// context.
    #[error("{mapping} writes `$context.{member}`, and this run carries no call context")]
    ContextMember {
        /// The dotted name of the manual entry.
        mapping: String,
        /// The `$context` member the path names.
        member: String,
    },
    /// A condition could not be decided.
    #[error("the condition of {mapping} could not be decided")]
    Condition {
        /// The mapping the condition belongs to.
        mapping: String,
        /// The refusal the evaluator returned.
        #[source]
        source: Box<ConditionError>,
    },
    /// The input side could not be read.
    #[error("{mapping} could not read {expression}")]
    Read {
        /// The mapping being run.
        mapping: String,
        /// The expression that refused.
        expression: String,
        /// The refusal the path model returned.
        #[source]
        source: Box<ReadError>,
    },
    /// The output side could not be written.
    #[error("{mapping} could not write {element}")]
    Write {
        /// The mapping being run.
        mapping: String,
        /// The element that refused.
        element: String,
        /// The refusal the path model returned.
        #[source]
        source: Box<WriteError>,
    },
    /// The data-type cell refused the value.
    #[error("{mapping} could not convert {element}")]
    Cell {
        /// The mapping being run.
        mapping: String,
        /// The element the cell refused.
        element: String,
        /// The refusal the cell returned.
        #[source]
        source: Box<LensError>,
    },
    /// An openEHR value could not be read or written.
    #[error("{mapping} could not carry the openEHR value at {node}")]
    Rm {
        /// The mapping being run.
        mapping: String,
        /// The node the value belongs to.
        node: String,
        /// The refusal the value model returned.
        #[source]
        source: Box<RmError>,
    },
    /// A tail attribute could not be written into the openEHR value at its
    /// place (`openehr_rm::v1_2::paths::set_at_path`), such as an element of a
    /// `List` past the one after its last.
    #[error("{mapping} could not write its tail into the openEHR value at {node}")]
    TailWrite {
        /// The mapping being run.
        mapping: String,
        /// The node the value belongs to.
        node: String,
        /// The refusal the path writer returned.
        #[source]
        source: Box<SetPathError>,
    },
    /// A FHIR element could not be read or written.
    #[error("{mapping} could not carry the FHIR element {element}")]
    Fhir {
        /// The mapping being run.
        mapping: String,
        /// The element the value belongs to.
        element: String,
        /// The refusal the element model returned.
        #[source]
        source: Box<FhirError>,
    },
    /// The template could not answer for a node.
    #[error("{mapping} could not reach {node} in the template")]
    Template {
        /// The mapping being run.
        mapping: String,
        /// The node the mapping names.
        node: String,
        /// The refusal the index returned.
        #[source]
        source: Box<PathError>,
    },
    /// An instance index has no openEHR position.
    #[error("{mapping} produced an instance index with no openEHR position")]
    Position {
        /// The mapping being run.
        mapping: String,
        /// The refusal the position model returned.
        #[source]
        source: PositionError,
    },
    /// A FHIR time and an `EVENT` node cannot carry each other
    /// (`types-of-mappings/data-type/EVENT.adoc`).
    #[error("{mapping} cannot carry {element} as an event time: {reason}")]
    EventTime {
        /// The mapping being run.
        mapping: String,
        /// The FHIR element the time is read at or written to.
        element: String,
        /// Why the time cannot be carried.
        reason: EventRefusal,
    },
    /// Neither the mapping nor the element table says which element to write.
    #[error("{mapping} names no FHIR data type for {element}, and the table fixes none")]
    UnknownElement {
        /// The mapping being run.
        mapping: String,
        /// The element the mapping writes.
        element: String,
    },
    /// The mapping names an openEHR path below the template's deepest node
    /// that no FLAT part of the node's class carries.
    ///
    /// A value is written through the Simplified Formats attribute tables of
    /// its class, so an attribute those tables do not name would be merged
    /// into the value and lost on the way to the wire.
    #[error("{mapping} names {tail} below {node}, and no FLAT part of its class carries it")]
    UnsupportedTail {
        /// The mapping being run.
        mapping: String,
        /// The node the path resolved to.
        node: String,
        /// The reference-model attributes below it.
        tail: String,
    },
    /// A required child produced no value.
    ///
    /// "The mapping should fail if the child is not provided"
    /// (`engine/Fail.adoc`).
    #[error("{mapping} produced no value for {node}, which the template requires")]
    MissingRequired {
        /// The mapping that produced nothing.
        mapping: String,
        /// The node the template requires.
        node: String,
    },
    /// A slot chain enters one model mapping more often than
    /// [`crate::resolve::program::SLOT_DEPTH_LIMIT`] admits.
    #[error("the slot chain {chain} enters {model} past the limit of {limit}")]
    SlotDepth {
        /// The chain as the traversal entered it.
        chain: String,
        /// The model the chain enters too often.
        model: String,
        /// The most times one model may stand on a chain.
        limit: usize,
    },
    /// A registered function did not produce a value.
    #[error("{mapping} could not run the function {code}")]
    MappingCode {
        /// The mapping being run.
        mapping: String,
        /// The function the mapping names.
        code: String,
        /// The refusal the registry returned.
        #[source]
        source: Box<MappingCodeError>,
    },
    /// A reference could not be resolved, or a created resource took no id.
    #[error("{mapping} could not resolve its reference")]
    Reference {
        /// The mapping being run.
        mapping: String,
        /// The refusal the seam returned.
        #[source]
        source: Box<ReferenceError>,
    },
    /// A reference chain reaches a resource it already entered.
    ///
    /// "To prevent circular dependencies in FHIR, the mapping engine should
    /// either stop at a given level of references or keep track of which ones
    /// are already resolved" (`engine/references.adoc`).
    #[error("{mapping} reaches {reference} a second time in one reference chain")]
    ReferenceCycle {
        /// The mapping being run.
        mapping: String,
        /// The reference the chain reaches again.
        reference: String,
    },
    /// A `link` target that no `DV_EHR_URI` can carry.
    ///
    /// `LINK.target` is a `DV_EHR_URI`, "a `DV_URI` which has the scheme name
    /// 'ehr'"
    /// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/data_types.html#_dv_ehr_uri_class>).
    #[error("{mapping} links to {target}, which is no ehr: URI")]
    LinkTarget {
        /// The mapping being run.
        mapping: String,
        /// The reference the FHIR side carries.
        target: String,
        /// Why the `ehr:` URI parser of `openehr-rm` refused it.
        #[source]
        source: EhrUriError,
    },
    /// Two `link` mappings name the one resource a `reference` mapping
    /// creates as standing in two compositions, and the reference to it holds
    /// one.
    #[error("{mapping} links the resource it sits in to {second}, already linked to {first}")]
    LinkedTwice {
        /// The mapping being run.
        mapping: String,
        /// The `ehr:` URI the resource was linked to first.
        first: String,
        /// The `ehr:` URI the second link names.
        second: String,
    },
    /// A reference-model family the node carries does not decode.
    #[error("{mapping} could not read the family its node carries")]
    Family {
        /// The mapping being run.
        mapping: String,
        /// The refusal of the typed read.
        #[source]
        source: Box<FamilyError>,
    },
    /// A composition attribute the FLAT builder sets through the `ctx/`
    /// vocabulary carries a part that vocabulary has no key for.
    ///
    /// Simplified Formats master06 §Composer and §Language and Territory set
    /// `COMPOSITION.composer`, `language` and `territory` from `ctx/` keys,
    /// and the builder takes no `|raw` value there, so the part would be lost.
    #[error("{mapping} writes {node}, whose value the FLAT context keys do not carry whole")]
    ContextAttribute {
        /// The mapping, or the node when no mapping is known.
        mapping: String,
        /// The `aqlPath` of the node.
        node: String,
    },
    /// A `link` whose FHIR side is no reference, which is the linked
    /// composition the specification leaves to a second context run.
    ///
    /// "If a context mapping for this `meta.url` is found, it is executed and
    /// saved as a separate composition"
    /// (`types-of-mappings/concept-type/concept-mappings.adoc`, §Linked
    /// mappings), and one run produces one composition.
    #[error("{mapping} links a separate composition, which one run does not produce")]
    LinkedComposition {
        /// The mapping being run.
        mapping: String,
    },
    /// A `hierarchy.split` the template or the direction cannot carry.
    #[error("the split of {model} cannot run: {reason}")]
    Split {
        /// The model mapping the hierarchy belongs to.
        model: String,
        /// What the split names that cannot be created.
        reason: SplitRefusal,
    },
    /// A reference the path model left for the engine to resolve.
    #[error("{mapping} reads through a reference at {expression}, which the engine resolves")]
    DeferredReference {
        /// The mapping being run.
        mapping: String,
        /// The expression that reached the reference.
        expression: String,
    },
    /// The demographics endpoint did not resolve a party reference, which is
    /// never dropped.
    #[error("{mapping} could not resolve its party reference through the demographics endpoint")]
    Demographics {
        /// The mapping being run.
        mapping: String,
        /// The refusal of the endpoint.
        #[source]
        source: Box<DemographicsError>,
    },
    /// A reference onto a `PARTY_REF` names a party of another server, which
    /// the demographic store of the CDR does not hold.
    #[error(
        "{mapping} names {reference}, which is no party of this server, so no PARTY_REF of the \
         CDR's demographic store carries it"
    )]
    ForeignParty {
        /// The mapping being run.
        mapping: String,
        /// The reference as the document carried it.
        reference: String,
    },
    /// A mapping onto a `PARTY_REF` names a FHIR element whose reference
    /// admits no single resource type.
    #[error("{mapping} maps {element} onto a PARTY_REF, and its reference admits no single type")]
    PartyRefTarget {
        /// The mapping being run.
        mapping: String,
        /// The FHIR element.
        element: String,
    },
    /// A code could not be translated through the concept map its mapping
    /// names.
    #[error("{mapping} could not translate its code through {conceptmap}")]
    Terminology {
        /// The mapping being run.
        mapping: String,
        /// The `ConceptMap.url` the mapping names.
        conceptmap: String,
        /// The refusal of the seam or of its answer.
        #[source]
        source: Box<TerminologyError>,
    },
    /// The terminology server failed while the engine asked it for the
    /// display of a code.
    #[error("{mapping} could not resolve the display of {code} in {system}")]
    DisplayLookup {
        /// The mapping being run.
        mapping: String,
        /// The code system.
        system: String,
        /// The code.
        code: String,
        /// The refusal of the seam.
        #[source]
        source: Box<TerminologyError>,
    },
    /// The terminology server does not know a code that carries no display,
    /// and the deployment did not choose the code as its display.
    #[error("{mapping} found no display for {code} in {system}, and openEHR requires one")]
    UnknownDisplay {
        /// The mapping being run.
        mapping: String,
        /// The code system.
        system: String,
        /// The code.
        code: String,
    },
    /// A code the concept map does not translate, at an element the output
    /// requires.
    ///
    /// An untranslated code is never written under a system it was not
    /// translated into, so a required element is left with nothing.
    #[error("{mapping} found no translation through {conceptmap} for {element}, which is required")]
    Untranslated {
        /// The mapping being run.
        mapping: String,
        /// The `ConceptMap.url` the mapping names.
        conceptmap: String,
        /// The output element: an openEHR `aqlPath` or a FHIR element path.
        element: String,
    },
    /// The composition did not build.
    #[error("the values the run produced do not build a composition")]
    Build {
        /// The refusal the builder returned.
        #[source]
        source: Box<PathError>,
    },
    /// The FHIR document the run produced breaks an error-severity
    /// constraint of the base specification, so it does not leave the engine
    /// (R4 conformance-rules.html §2.1.0.6: "a rule that all resources must
    /// conform to").
    #[error("the resource the context {context} produced breaks a constraint")]
    Invariant {
        /// The context mapping the program compiled from.
        context: String,
        /// The constraint and the element that breaks it.
        #[source]
        breach: Breach,
    },
}

/// Why an event time cannot be carried between a FHIR time and an `EVENT`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventRefusal {
    /// The FHIR element is of a type `EVENT.adoc` pairs with no event class.
    Type,
    /// A FHIR `time` has no date, and `EVENT.time` is a `DV_DATE_TIME`.
    NoDate,
    /// The period misses a bound, so it has no trailing edge or no width.
    OpenPeriod,
    /// The period ends before it starts, or a bound is partial, so it has no
    /// exact width.
    NoWidth,
    /// The event is of the class the FHIR element has no target for.
    OtherClass,
    /// The `INTERVAL_EVENT` holds no readable `time` or `width`.
    Unreadable,
}

impl fmt::Display for EventRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match *self {
            Self::Type => "its type is paired with no event class",
            Self::NoDate => "a time has no date, and an event's time is a date and time",
            Self::OpenPeriod => "the period misses a bound",
            Self::NoWidth => {
                "the period has no exact width: it ends before it starts or a bound is partial"
            }
            Self::OtherClass => "the event is of the class the element has no alternative for",
            Self::Unreadable => "the interval event holds no readable time or width",
        })
    }
}

/// Why a `hierarchy.split` cannot run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SplitRefusal {
    /// The element to create is a template node that does not repeat, so no
    /// second instance of it exists.
    NotRepeating {
        /// The `aqlPath` of the node.
        node: String,
    },
    /// The side names an element the other side creates.
    ///
    /// `resource` is created on the FHIR side and `event` and `archetype` on
    /// the openEHR side (`types-of-mappings/concept-type/HierarchyMappings.adoc`,
    /// §split).
    WrongSide {
        /// The element the side names.
        create: Create,
    },
    /// A FHIR split names a path, and a resource is created at the root.
    ///
    /// "This is left empty if the element is the archetype or resource
    /// itself" (`HierarchyMappings.adoc`, §Hierarchy and unique values).
    ResourcePath,
    /// The side names no element to create.
    NoCreate,
    /// The hierarchy names no `with` path on the side the split iterates.
    NoWith,
}

impl fmt::Display for SplitRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::NotRepeating { ref node } => {
                write!(f, "{node} does not repeat, so it takes no second instance")
            }
            Self::WrongSide { create } => {
                write!(f, "`{create}` is created on the other side")
            }
            Self::ResourcePath => {
                f.write_str("a resource is created at the root, and the split names a path")
            }
            Self::NoCreate => f.write_str("the split names no element to create"),
            Self::NoWith => f.write_str("the hierarchy names no path to iterate"),
        }
    }
}