fhirconnect 0.2.3

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

//! The FHIR elements the data-type cells read and write.
//!
//! [`crate::tree`] reads and writes the lexical `Value` of `fhir-types`, and a
//! [`crate::engine::lens::Lens`] is typed in the generated element struct, so
//! this module is the one place the two meet. Nothing here models a FHIR
//! element: the generated `Json` and `Primitive` codecs do the work, and
//! [`FhirValue`] only says which of them to run.

use fhir_types::codec::DecodeError;
use fhir_types::codec::EncodeError;
use fhir_types::codec::Json;
use fhir_types::codec::Path;
use fhir_types::codec::Primitive;
use fhir_types::codec::Value;
use fhir_types::r4::attachment::Attachment;
use fhir_types::r4::codeable_concept::CodeableConcept;
use fhir_types::r4::coding::Coding;
use fhir_types::r4::count::Count;
use fhir_types::r4::duration::Duration;
use fhir_types::r4::identifier::Identifier;
use fhir_types::r4::period::Period;
use fhir_types::r4::primitives;
use fhir_types::r4::primitives::Boolean;
use fhir_types::r4::primitives::Date;
use fhir_types::r4::primitives::DateTime;
use fhir_types::r4::primitives::Decimal;
use fhir_types::r4::primitives::Instant;
use fhir_types::r4::primitives::Integer;
use fhir_types::r4::primitives::PositiveInt;
use fhir_types::r4::primitives::Time;
use fhir_types::r4::primitives::UnsignedInt;
use fhir_types::r4::primitives::Url;
use fhir_types::r4::quantity::Quantity;
use fhir_types::r4::range::Range;
use fhir_types::r4::reference::Reference;
use fhir_types::schema::ValueKind;

use crate::model::ast::keyword::DataType;
use crate::tree::element::Location;

/// Which FHIR element a mapping writes.
///
/// The `type` key of a `with` block names it where a mapping carries one
/// (`types-of-mappings/data-type/data-mappings.adoc`); otherwise the element
/// table decides.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FhirKind {
    /// A `string`, and every other primitive that travels as text.
    String,
    /// A `date`.
    Date,
    /// A `dateTime`.
    DateTime,
    /// An `instant`.
    Instant,
    /// A `boolean`.
    Boolean,
    /// A `Coding`.
    Coding,
    /// A `CodeableConcept`.
    CodeableConcept,
    /// A `Period`.
    Period,
    /// A `Reference`.
    Reference,
    /// An `Identifier`.
    Identifier,
    /// A `Quantity`.
    Quantity,
    /// An `integer`.
    Integer,
    /// An `unsignedInt`.
    UnsignedInt,
    /// A `positiveInt`.
    PositiveInt,
    /// A `decimal`.
    Decimal,
    /// A `Count`.
    Count,
    /// A `time`.
    Time,
    /// A `Duration`.
    Duration,
    /// A `url`.
    Url,
    /// An `Attachment`.
    Attachment,
    /// A `Range`.
    Range,
}

impl FhirKind {
    /// Returns the kind the `type` key names, `None` for `NONE` and for the
    /// kinds no cell of this milestone carries.
    #[must_use]
    pub const fn of(data_type: DataType) -> Option<Self> {
        match data_type {
            DataType::String | DataType::Id => Some(Self::String),
            DataType::DateTime => Some(Self::DateTime),
            DataType::Coding => Some(Self::Coding),
            DataType::CodeableConcept => Some(Self::CodeableConcept),
            DataType::Identifier => Some(Self::Identifier),
            DataType::Quantity | DataType::Proportion => Some(Self::Quantity),
            DataType::None | DataType::Dosage => None,
        }
    }

    /// Returns the kind a FHIR type code names, `None` for a type no cell
    /// carries.
    ///
    /// The codes are the `ElementDefinition.type.code` values of the element
    /// table (<https://hl7.org/fhir/R4/elementdefinition.html>), as
    /// [`crate::resolve::derive`] derives them for a mapping with no `type`
    /// key.
    #[must_use]
    pub fn of_code(code: &str) -> Option<Self> {
        match code {
            "string" => Some(Self::String),
            "date" => Some(Self::Date),
            "dateTime" => Some(Self::DateTime),
            "instant" => Some(Self::Instant),
            "boolean" => Some(Self::Boolean),
            "Coding" => Some(Self::Coding),
            "CodeableConcept" => Some(Self::CodeableConcept),
            "Period" => Some(Self::Period),
            "Reference" => Some(Self::Reference),
            "Identifier" => Some(Self::Identifier),
            "Quantity" => Some(Self::Quantity),
            "integer" => Some(Self::Integer),
            "unsignedInt" => Some(Self::UnsignedInt),
            "positiveInt" => Some(Self::PositiveInt),
            "decimal" => Some(Self::Decimal),
            "Count" => Some(Self::Count),
            "time" => Some(Self::Time),
            "Duration" => Some(Self::Duration),
            "url" => Some(Self::Url),
            "Attachment" => Some(Self::Attachment),
            "Range" => Some(Self::Range),
            _ => None,
        }
    }

    /// Returns the kind the element table resolved a path to.
    ///
    /// A primitive element travels as text unless the mapping's `type` key
    /// says otherwise, so only the complex types the cells carry are named
    /// here.
    #[must_use]
    pub fn at(location: &Location) -> Option<Self> {
        match *location {
            Location::Complex(schema) => match schema.path {
                "Coding" => Some(Self::Coding),
                "CodeableConcept" => Some(Self::CodeableConcept),
                "Period" => Some(Self::Period),
                "Reference" => Some(Self::Reference),
                "Identifier" => Some(Self::Identifier),
                "Quantity" => Some(Self::Quantity),
                "Count" => Some(Self::Count),
                "Duration" => Some(Self::Duration),
                "Attachment" => Some(Self::Attachment),
                "Range" => Some(Self::Range),
                _ => None,
            },
            Location::Primitive(ValueKind::Text) | Location::Attribute => Some(Self::String),
            Location::Primitive(_)
            | Location::PrimitiveElement
            | Location::Choice(_)
            | Location::Resource
            | Location::Deferred => None,
        }
    }

    /// Returns the name the diagnostics use.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::String => "string",
            Self::Date => "date",
            Self::DateTime => "dateTime",
            Self::Instant => "instant",
            Self::Boolean => "boolean",
            Self::Coding => "Coding",
            Self::CodeableConcept => "CodeableConcept",
            Self::Period => "Period",
            Self::Reference => "Reference",
            Self::Identifier => "Identifier",
            Self::Quantity => "Quantity",
            Self::Integer => "integer",
            Self::UnsignedInt => "unsignedInt",
            Self::PositiveInt => "positiveInt",
            Self::Decimal => "decimal",
            Self::Count => "Count",
            Self::Time => "time",
            Self::Duration => "Duration",
            Self::Url => "url",
            Self::Attachment => "Attachment",
            Self::Range => "Range",
        }
    }
}

/// One FHIR element a data-type cell produced or consumed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FhirValue {
    /// A `string`.
    String(primitives::String),
    /// A `date`.
    Date(Date),
    /// A `dateTime`.
    DateTime(DateTime),
    /// An `instant`.
    Instant(Instant),
    /// A `boolean`.
    Boolean(Boolean),
    /// A `Coding`.
    Coding(Box<Coding>),
    /// A `CodeableConcept`.
    CodeableConcept(Box<CodeableConcept>),
    /// A `Period`.
    Period(Box<Period>),
    /// A `Reference`.
    Reference(Box<Reference>),
    /// An `Identifier`.
    Identifier(Box<Identifier>),
    /// A `Quantity`.
    Quantity(Box<Quantity>),
    /// An `integer`.
    Integer(Integer),
    /// An `unsignedInt`.
    UnsignedInt(UnsignedInt),
    /// A `positiveInt`.
    PositiveInt(PositiveInt),
    /// A `decimal`.
    Decimal(Decimal),
    /// A `Count`.
    Count(Box<Count>),
    /// A `time`.
    Time(Time),
    /// A `Duration`.
    Duration(Box<Duration>),
    /// A `url`.
    Url(Url),
    /// An `Attachment`.
    Attachment(Box<Attachment>),
    /// A `Range`.
    Range(Box<Range>),
}

/// Why a FHIR element could not be read or written.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum FhirError {
    /// The document does not decode as the element the table names.
    #[error("the value at {element} does not read as {kind}")]
    Decode {
        /// The element path from the table.
        element: String,
        /// The kind the mapping asked for.
        kind: &'static str,
        /// The refusal the generated codec returned.
        #[source]
        source: DecodeError,
    },
    /// The element has no JSON form.
    #[error("the {kind} value has no JSON form")]
    Encode {
        /// The kind that refused.
        kind: &'static str,
        /// The refusal the generated codec returned.
        #[source]
        source: EncodeError,
    },
    /// A primitive carried only an `id` or an `extension`.
    #[error("the {kind} value at {element} carries no value of its own")]
    NoValue {
        /// The element path from the table.
        element: String,
        /// The kind the mapping asked for.
        kind: &'static str,
    },
}

impl FhirValue {
    /// Returns the kind of the element.
    #[must_use]
    pub const fn kind(&self) -> FhirKind {
        match *self {
            Self::String(_) => FhirKind::String,
            Self::Date(_) => FhirKind::Date,
            Self::DateTime(_) => FhirKind::DateTime,
            Self::Instant(_) => FhirKind::Instant,
            Self::Boolean(_) => FhirKind::Boolean,
            Self::Coding(_) => FhirKind::Coding,
            Self::CodeableConcept(_) => FhirKind::CodeableConcept,
            Self::Period(_) => FhirKind::Period,
            Self::Reference(_) => FhirKind::Reference,
            Self::Identifier(_) => FhirKind::Identifier,
            Self::Quantity(_) => FhirKind::Quantity,
            Self::Integer(_) => FhirKind::Integer,
            Self::UnsignedInt(_) => FhirKind::UnsignedInt,
            Self::PositiveInt(_) => FhirKind::PositiveInt,
            Self::Decimal(_) => FhirKind::Decimal,
            Self::Count(_) => FhirKind::Count,
            Self::Time(_) => FhirKind::Time,
            Self::Duration(_) => FhirKind::Duration,
            Self::Url(_) => FhirKind::Url,
            Self::Attachment(_) => FhirKind::Attachment,
            Self::Range(_) => FhirKind::Range,
        }
    }

    /// Reads the value a document holds at `element` as `kind`.
    ///
    /// # Errors
    ///
    /// Returns [`FhirError::Decode`] when the document does not decode as the
    /// element the mapping asked for.
    pub fn read(kind: FhirKind, element: &str, value: &Value) -> Result<Self, FhirError> {
        let mut path = Path::root(element);
        let refuse = |source: DecodeError| FhirError::Decode {
            element: String::from(element),
            kind: kind.as_str(),
            source,
        };
        match kind {
            FhirKind::String => primitives::String::from_json_parts(Some(value), None, &mut path)
                .map(Self::String)
                .map_err(refuse),
            FhirKind::Date => Date::from_json_parts(Some(value), None, &mut path)
                .map(Self::Date)
                .map_err(refuse),
            FhirKind::DateTime => DateTime::from_json_parts(Some(value), None, &mut path)
                .map(Self::DateTime)
                .map_err(refuse),
            FhirKind::Instant => Instant::from_json_parts(Some(value), None, &mut path)
                .map(Self::Instant)
                .map_err(refuse),
            FhirKind::Boolean => Boolean::from_json_parts(Some(value), None, &mut path)
                .map(Self::Boolean)
                .map_err(refuse),
            FhirKind::Coding => object(value, element, kind)
                .and_then(|object| Coding::from_json(object, &mut path).map_err(refuse))
                .map(|coding| Self::Coding(Box::new(coding))),
            FhirKind::CodeableConcept => object(value, element, kind)
                .and_then(|object| CodeableConcept::from_json(object, &mut path).map_err(refuse))
                .map(|concept| Self::CodeableConcept(Box::new(concept))),
            FhirKind::Period => object(value, element, kind)
                .and_then(|object| Period::from_json(object, &mut path).map_err(refuse))
                .map(|period| Self::Period(Box::new(period))),
            FhirKind::Reference => object(value, element, kind)
                .and_then(|object| Reference::from_json(object, &mut path).map_err(refuse))
                .map(|reference| Self::Reference(Box::new(reference))),
            FhirKind::Identifier => object(value, element, kind)
                .and_then(|object| Identifier::from_json(object, &mut path).map_err(refuse))
                .map(|identifier| Self::Identifier(Box::new(identifier))),
            FhirKind::Quantity => object(value, element, kind)
                .and_then(|object| Quantity::from_json(object, &mut path).map_err(refuse))
                .map(|quantity| Self::Quantity(Box::new(quantity))),
            FhirKind::Integer => Integer::from_json_parts(Some(value), None, &mut path)
                .map(Self::Integer)
                .map_err(refuse),
            FhirKind::UnsignedInt => UnsignedInt::from_json_parts(Some(value), None, &mut path)
                .map(Self::UnsignedInt)
                .map_err(refuse),
            FhirKind::PositiveInt => PositiveInt::from_json_parts(Some(value), None, &mut path)
                .map(Self::PositiveInt)
                .map_err(refuse),
            FhirKind::Decimal => Decimal::from_json_parts(Some(value), None, &mut path)
                .map(Self::Decimal)
                .map_err(refuse),
            FhirKind::Count => object(value, element, kind)
                .and_then(|object| Count::from_json(object, &mut path).map_err(refuse))
                .map(|count| Self::Count(Box::new(count))),
            FhirKind::Time => Time::from_json_parts(Some(value), None, &mut path)
                .map(Self::Time)
                .map_err(refuse),
            FhirKind::Duration => object(value, element, kind)
                .and_then(|object| Duration::from_json(object, &mut path).map_err(refuse))
                .map(|duration| Self::Duration(Box::new(duration))),
            FhirKind::Url => Url::from_json_parts(Some(value), None, &mut path)
                .map(Self::Url)
                .map_err(refuse),
            FhirKind::Attachment => object(value, element, kind)
                .and_then(|object| Attachment::from_json(object, &mut path).map_err(refuse))
                .map(|attachment| Self::Attachment(Box::new(attachment))),
            FhirKind::Range => object(value, element, kind)
                .and_then(|object| Range::from_json(object, &mut path).map_err(refuse))
                .map(|range| Self::Range(Box::new(range))),
        }
    }

    /// Returns the JSON the element writes into a document.
    ///
    /// # Errors
    ///
    /// Returns [`FhirError::Encode`] when the generated codec refuses the
    /// value and [`FhirError::NoValue`] for a primitive that carries no value
    /// of its own.
    pub fn write(&self, element: &str) -> Result<Value, FhirError> {
        let kind = self.kind().as_str();
        let complex = |result: Result<fhir_types::codec::Object, EncodeError>| {
            result
                .map(Value::Object)
                .map_err(|source| FhirError::Encode { kind, source })
        };
        let primitive = |result: Result<Option<Value>, EncodeError>| {
            result
                .map_err(|source| FhirError::Encode { kind, source })?
                .ok_or_else(|| FhirError::NoValue {
                    element: String::from(element),
                    kind,
                })
        };
        match *self {
            Self::String(ref text) => primitive(text.value_json()),
            Self::Date(ref date) => primitive(date.value_json()),
            Self::DateTime(ref date) => primitive(date.value_json()),
            Self::Instant(ref instant) => primitive(instant.value_json()),
            Self::Boolean(ref boolean) => primitive(boolean.value_json()),
            Self::Coding(ref coding) => complex(coding.to_json()),
            Self::CodeableConcept(ref concept) => complex(concept.to_json()),
            Self::Period(ref period) => complex(period.to_json()),
            Self::Reference(ref reference) => complex(reference.to_json()),
            Self::Identifier(ref identifier) => complex(identifier.to_json()),
            Self::Quantity(ref quantity) => complex(quantity.to_json()),
            Self::Integer(ref integer) => primitive(integer.value_json()),
            Self::UnsignedInt(ref integer) => primitive(integer.value_json()),
            Self::PositiveInt(ref integer) => primitive(integer.value_json()),
            Self::Decimal(ref decimal) => primitive(decimal.value_json()),
            Self::Count(ref count) => complex(count.to_json()),
            Self::Time(ref time) => primitive(time.value_json()),
            Self::Duration(ref duration) => complex(duration.to_json()),
            Self::Url(ref url) => primitive(url.value_json()),
            Self::Attachment(ref attachment) => complex(attachment.to_json()),
            Self::Range(ref range) => complex(range.to_json()),
        }
    }
}

/// Returns the object a complex element is written as.
fn object<'tree>(
    value: &'tree Value,
    element: &str,
    kind: FhirKind,
) -> Result<&'tree fhir_types::codec::Object, FhirError> {
    let path = Path::root(element);
    fhir_types::codec::expect_object(value, &path).map_err(|source| FhirError::Decode {
        element: String::from(element),
        kind: kind.as_str(),
        source,
    })
}

#[cfg(test)]
mod tests {
    use super::FhirKind;
    use super::FhirValue;
    use fhir_types::codec::Value;

    #[test]
    fn a_coding_reads_and_writes_through_the_generated_codec() {
        let document = Value::from_serde_json(serde_json::json!({
            "system": "http://example.org/fhir/CodeSystem/synthetic-problems",
            "code": "SYN-001"
        }));
        let value = FhirValue::read(FhirKind::Coding, "Condition.code.coding", &document)
            .expect("the object reads as a Coding");
        assert_eq!(value.kind(), FhirKind::Coding);
        let written = value
            .write("Condition.code.coding")
            .expect("a Coding has a JSON form");
        assert_eq!(written, document, "the codec round trips the element");
    }

    #[test]
    fn a_date_time_keeps_the_text_the_document_carried() {
        let document = Value::String(String::from("2026-09-13T10:00:00.123456+02:00"));
        let value = FhirValue::read(FhirKind::DateTime, "Condition.recordedDate", &document)
            .expect("the string reads as a dateTime");
        assert_eq!(
            value
                .write("Condition.recordedDate")
                .expect("a dateTime has a JSON form"),
            document,
            "the fractional seconds and the offset survive"
        );
    }

    #[test]
    fn an_instant_keeps_the_text_the_document_carried() {
        let document = Value::String(String::from("2026-09-13T10:00:00.123+02:00"));
        let value = FhirValue::read(FhirKind::Instant, "Observation.issued", &document)
            .expect("the string reads as an instant");
        assert_eq!(value.kind(), FhirKind::Instant);
        assert_eq!(value.kind().as_str(), "instant");
        assert_eq!(
            value
                .write("Observation.issued")
                .expect("an instant has a JSON form"),
            document,
            "the fractional seconds and the offset survive"
        );
    }

    #[test]
    fn a_date_short_of_an_instant_names_the_element_and_the_kind() {
        let document = Value::String(String::from("2026-09-13"));
        let error = FhirValue::read(FhirKind::Instant, "Observation.issued", &document)
            .expect_err("a date is no instant");
        let message = error.to_string();
        assert!(message.contains("Observation.issued"), "{message}");
        assert!(message.contains("instant"), "{message}");
    }

    #[test]
    fn every_pair_the_resolver_derives_names_a_kind_the_cells_carry() {
        for &(class, codes) in crate::resolve::derive::PAIRS {
            for code in codes {
                assert!(
                    FhirKind::of_code(code).is_some(),
                    "{class} pairs with {code}, which no kind carries"
                );
            }
        }
        assert_eq!(
            FhirKind::of_code(crate::resolve::derive::TEXT),
            Some(FhirKind::String)
        );
    }

    #[test]
    fn a_value_of_the_wrong_shape_names_the_element() {
        let document = Value::String(String::from("not an object"));
        let error = FhirValue::read(FhirKind::Coding, "Condition.code.coding", &document)
            .expect_err("a string is no Coding");
        assert!(
            error.to_string().contains("Condition.code.coding"),
            "the refusal names the element: {error}"
        );
    }
}