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

//! `DV_COUNT` against FHIR `integer`, `unsignedInt`, `positiveInt`, `Quantity`
//! and `Count`.
//!
//! The rows are
//! `docs/specs/fhirconnect/modules/ROOT/pages/types-of-mappings/data-type/DV_COUNT.adoc`
//! §Primitive, §Quantity and §Count: `value` is `magnitude`, and nothing else
//! of either side has a counterpart. A `Count` writes `code` `1`, as the page
//! says, with the UCUM system R4 `cnt-3` names beside it
//! (<https://hl7.org/fhir/R4/datatypes.html#Count>).
//!
//! `magnitude` is an `Integer64` and a FHIR `integer` a 32-bit number, so a
//! count outside that range is refused going out, and a `decimal` that is not
//! a whole number is refused coming in. None of the three tables carries
//! `magnitude_status`, so a count whose status is not a point value is
//! refused rather than written as one, and a `comparator` coming in is
//! refused rather than dropped.
//!
//! The `DV_COUNT` page names only `integer` among the primitives, and R4
//! defines `unsignedInt` and `positiveInt` as integers from 0 and from 1
//! (<https://hl7.org/fhir/R4/datatypes.html#unsignedInt>). Pairing a count
//! with them carries it as the integer it is, and a count below the least
//! value is refused going out, never clamped: no specification governs the
//! pairing, our own design.

use fhir_types::r4::count::Count;
use fhir_types::r4::primitives::Code;
use fhir_types::r4::primitives::Decimal;
use fhir_types::r4::primitives::Integer;
use fhir_types::r4::primitives::PositiveInt;
use fhir_types::r4::primitives::UnsignedInt;
use fhir_types::r4::primitives::Uri;
use fhir_types::r4::quantity::Quantity;
use openehr_rm::v1_2::data_types::quantity::dv_count::DvCount;

use crate::engine::lens::Fallback;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::code_phrase::text_of;
use crate::engine::lens::number::decimal_text;
use crate::engine::lens::number::narrow;
use crate::engine::lens::number::point;
use crate::engine::lens::number::whole;
use crate::engine::lens::quantity::UCUM;
use crate::model::ast::keyword::Direction;

/// The name the `integer` cell carries in a diagnostic.
pub const INTEGER_CELL: &str = "DV_COUNT against integer";

/// The name the `unsignedInt` cell carries in a diagnostic.
pub const UNSIGNED_INT_CELL: &str = "DV_COUNT against unsignedInt";

/// The name the `positiveInt` cell carries in a diagnostic.
pub const POSITIVE_INT_CELL: &str = "DV_COUNT against positiveInt";

/// The name the `Quantity` cell carries in a diagnostic.
pub const QUANTITY_CELL: &str = "DV_COUNT against Quantity";

/// The name the `Count` cell carries in a diagnostic.
pub const COUNT_CELL: &str = "DV_COUNT against Count";

/// The UCUM unit of a count, "for Count code = 1" (`DV_COUNT.adoc` §Count).
pub const UNITY: &str = "1";

/// `DV_COUNT` against `integer`, `unsignedInt`, `positiveInt`, `Quantity` and
/// `Count`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CountLens;

impl Lens<DvCount, Integer> for CountLens {
    fn cell(&self) -> &'static str {
        INTEGER_CELL
    }

    fn get(&self, source: &DvCount) -> Result<Integer, LensError> {
        point(source.magnitude_status.as_deref(), INTEGER_CELL)?;
        narrow(source.magnitude, INTEGER_CELL, "DV_COUNT.magnitude").map(Integer::from)
    }

    fn put(&self, view: &Integer, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
        let value = view.value.ok_or(LensError::Missing {
            cell: INTEGER_CELL,
            attribute: "DV_COUNT.magnitude",
            direction: Direction::FhirToOpenehr,
        })?;
        Ok(counted(i64::from(value), existing))
    }

    fn fallbacks(&self, _view: &Integer) -> Vec<Fallback> {
        Vec::new()
    }
}

impl Lens<DvCount, Quantity> for CountLens {
    fn cell(&self) -> &'static str {
        QUANTITY_CELL
    }

    fn get(&self, source: &DvCount) -> Result<Quantity, LensError> {
        point(source.magnitude_status.as_deref(), QUANTITY_CELL)?;
        Ok(Quantity {
            value: Some(Decimal::from(source.magnitude.to_string().as_str())),
            ..Quantity::default()
        })
    }

    fn put(&self, view: &Quantity, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
        unbounded(view.comparator.as_ref(), QUANTITY_CELL)?;
        let text = decimal_text(view.value.as_ref(), QUANTITY_CELL, "DV_COUNT.magnitude")?;
        Ok(counted(
            whole(text, QUANTITY_CELL, "Quantity.value")?,
            existing,
        ))
    }

    fn fallbacks(&self, _view: &Quantity) -> Vec<Fallback> {
        Vec::new()
    }
}

impl Lens<DvCount, Count> for CountLens {
    fn cell(&self) -> &'static str {
        COUNT_CELL
    }

    fn get(&self, source: &DvCount) -> Result<Count, LensError> {
        point(source.magnitude_status.as_deref(), COUNT_CELL)?;
        Ok(Count {
            value: Some(Decimal::from(source.magnitude.to_string().as_str())),
            system: Some(Uri::from(UCUM)),
            code: Some(Code::from(UNITY)),
            ..Count::default()
        })
    }

    fn put(&self, view: &Count, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
        unbounded(view.comparator.as_ref(), COUNT_CELL)?;
        let code = text_of(view.code.as_ref().map(|code| &code.value));
        if let Some(other) = code.filter(|&code| code != UNITY) {
            return Err(LensError::Shape {
                cell: COUNT_CELL,
                attribute: "Count.code",
                found: String::from(other),
                reason: "R4 cnt-3 fixes the code of a Count at 1",
                direction: Direction::FhirToOpenehr,
            });
        }
        let text = decimal_text(view.value.as_ref(), COUNT_CELL, "DV_COUNT.magnitude")?;
        Ok(counted(whole(text, COUNT_CELL, "Count.value")?, existing))
    }

    fn fallbacks(&self, _view: &Count) -> Vec<Fallback> {
        Vec::new()
    }
}

impl Lens<DvCount, UnsignedInt> for CountLens {
    fn cell(&self) -> &'static str {
        UNSIGNED_INT_CELL
    }

    fn get(&self, source: &DvCount) -> Result<UnsignedInt, LensError> {
        point(source.magnitude_status.as_deref(), UNSIGNED_INT_CELL)?;
        restricted(
            source.magnitude,
            0,
            UNSIGNED_INT_CELL,
            "a FHIR unsignedInt is an integer from 0",
        )
        .map(UnsignedInt::from)
    }

    fn put(&self, view: &UnsignedInt, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
        let value = view.value.ok_or(LensError::Missing {
            cell: UNSIGNED_INT_CELL,
            attribute: "DV_COUNT.magnitude",
            direction: Direction::FhirToOpenehr,
        })?;
        Ok(counted(i64::from(value), existing))
    }

    fn fallbacks(&self, _view: &UnsignedInt) -> Vec<Fallback> {
        Vec::new()
    }
}

impl Lens<DvCount, PositiveInt> for CountLens {
    fn cell(&self) -> &'static str {
        POSITIVE_INT_CELL
    }

    fn get(&self, source: &DvCount) -> Result<PositiveInt, LensError> {
        point(source.magnitude_status.as_deref(), POSITIVE_INT_CELL)?;
        restricted(
            source.magnitude,
            1,
            POSITIVE_INT_CELL,
            "a FHIR positiveInt is an integer from 1",
        )
        .map(PositiveInt::from)
    }

    fn put(&self, view: &PositiveInt, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
        let value = view.value.ok_or(LensError::Missing {
            cell: POSITIVE_INT_CELL,
            attribute: "DV_COUNT.magnitude",
            direction: Direction::FhirToOpenehr,
        })?;
        Ok(counted(i64::from(value), existing))
    }

    fn fallbacks(&self, _view: &PositiveInt) -> Vec<Fallback> {
        Vec::new()
    }
}

/// Returns `magnitude` as a restricted R4 integer whose least value is
/// `least`, refusing a count outside `least..=2,147,483,647` and never
/// clamping it (<https://hl7.org/fhir/R4/datatypes.html#unsignedInt>,
/// <https://hl7.org/fhir/R4/datatypes.html#positiveInt>).
fn restricted(
    magnitude: i64,
    least: u32,
    cell: &'static str,
    reason: &'static str,
) -> Result<u32, LensError> {
    let integer = narrow(magnitude, cell, "DV_COUNT.magnitude")?;
    u32::try_from(integer)
        .ok()
        .filter(|value| *value >= least)
        .ok_or_else(|| LensError::Shape {
            cell,
            attribute: "DV_COUNT.magnitude",
            found: magnitude.to_string(),
            reason,
            direction: Direction::OpenehrToFhir,
        })
}

/// Refuses a comparator, which none of the tables gives an openEHR row, so
/// writing the count without it would state a bounded value as exact.
fn unbounded(comparator: Option<&Code>, cell: &'static str) -> Result<(), LensError> {
    match text_of(comparator.map(|code| &code.value)) {
        Some(found) => Err(LensError::Shape {
            cell,
            attribute: "Quantity.comparator",
            found: String::from(found),
            reason: "DV_COUNT.adoc gives comparator no openEHR row",
            direction: Direction::FhirToOpenehr,
        }),
        None => Ok(()),
    }
}

/// Returns the count of `magnitude`, with the attributes no FHIR element
/// carries taken from the held value.
fn counted(magnitude: i64, existing: Option<&DvCount>) -> DvCount {
    DvCount {
        normal_status: existing.and_then(|held| held.normal_status.clone()),
        normal_range: existing.and_then(|held| held.normal_range.clone()),
        other_reference_ranges: existing.and_then(|held| held.other_reference_ranges.clone()),
        magnitude_status: existing.and_then(|held| held.magnitude_status.clone()),
        accuracy: existing.and_then(|held| held.accuracy),
        accuracy_is_percent: existing.and_then(|held| held.accuracy_is_percent),
        magnitude,
    }
}

#[cfg(test)]
mod tests {
    use super::CountLens;
    use crate::engine::lens::Lens;
    use crate::engine::lens::LensError;
    use crate::engine::lens::quantity::UCUM;
    use fhir_types::r4::count::Count;
    use fhir_types::r4::primitives::Code;
    use fhir_types::r4::primitives::Decimal;
    use fhir_types::r4::primitives::Integer;
    use fhir_types::r4::primitives::PositiveInt;
    use fhir_types::r4::primitives::UnsignedInt;
    use fhir_types::r4::quantity::Quantity;
    use openehr_rm::v1_2::data_types::quantity::dv_count::DvCount;
    use proptest::option;
    use proptest::prop_compose;
    use proptest::prop_oneof;
    use proptest::proptest;
    use proptest::strategy::Just;

    /// Returns a synthetic count of `magnitude`.
    fn count(magnitude: i64) -> DvCount {
        DvCount {
            normal_status: None,
            normal_range: None,
            other_reference_ranges: None,
            magnitude_status: None,
            accuracy: None,
            accuracy_is_percent: None,
            magnitude,
        }
    }

    prop_compose! {
        /// A count inside the FHIR integer range, as a point value.
        fn counted()(
            magnitude in i64::from(i32::MIN)..=i64::from(i32::MAX),
            magnitude_status in prop_oneof![Just(None), Just(Some(String::from("=")))],
            accuracy in option::of(0i32..10),
        ) -> DvCount {
            DvCount { magnitude_status, accuracy: accuracy.map(f64::from), ..count(magnitude) }
        }
    }

    proptest! {
        #[test]
        fn integer_get_put(source in counted()) {
            let view: Integer = CountLens.get(&source).expect("the count travels");
            let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
            assert_eq!(back, source, "GetPut failed for {source:?}");
        }

        #[test]
        fn integer_put_get(value in proptest::num::i32::ANY) {
            let view = Integer::from(value);
            let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
            let again: Integer = CountLens.get(&back).expect("the count travels");
            assert_eq!(again, view, "PutGet failed for {view:?}");
        }

        #[test]
        fn unsigned_int_get_put(magnitude in 0..=i64::from(i32::MAX)) {
            let source = count(magnitude);
            let view: UnsignedInt = CountLens.get(&source).expect("the count travels");
            let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
            assert_eq!(back, source, "GetPut failed for {source:?}");
        }

        #[test]
        fn unsigned_int_put_get(value in 0..=i32::MAX.unsigned_abs()) {
            let view = UnsignedInt::from(value);
            let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
            let again: UnsignedInt = CountLens.get(&back).expect("the count travels");
            assert_eq!(again, view, "PutGet failed for {view:?}");
        }

        #[test]
        fn positive_int_get_put(magnitude in 1..=i64::from(i32::MAX)) {
            let source = count(magnitude);
            let view: PositiveInt = CountLens.get(&source).expect("the count travels");
            let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
            assert_eq!(back, source, "GetPut failed for {source:?}");
        }

        #[test]
        fn positive_int_put_get(value in 1..=i32::MAX.unsigned_abs()) {
            let view = PositiveInt::from(value);
            let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
            let again: PositiveInt = CountLens.get(&back).expect("the count travels");
            assert_eq!(again, view, "PutGet failed for {view:?}");
        }

        #[test]
        fn quantity_get_put(source in counted()) {
            let view: Quantity = CountLens.get(&source).expect("the count travels");
            let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
            assert_eq!(back, source, "GetPut failed for {source:?}");
        }

        #[test]
        fn quantity_put_get(source in counted()) {
            let view: Quantity = CountLens.get(&source).expect("the count travels");
            let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
            let again: Quantity = CountLens.get(&back).expect("the count travels");
            assert_eq!(again, view, "PutGet failed for {view:?}");
        }

        #[test]
        fn count_get_put(source in counted()) {
            let view: Count = CountLens.get(&source).expect("the count travels");
            let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
            assert_eq!(back, source, "GetPut failed for {source:?}");
        }

        #[test]
        fn count_put_get(source in counted()) {
            let view: Count = CountLens.get(&source).expect("the count travels");
            let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
            let again: Count = CountLens.get(&back).expect("the count travels");
            assert_eq!(again, view, "PutGet failed for {view:?}");
        }
    }

    #[test]
    fn a_count_writes_the_code_one_in_ucum() {
        // DV_COUNT.adoc §Count: "for Count code = 1"; R4 cnt-3 names UCUM.
        let view: Count = CountLens.get(&count(4)).expect("the count travels");
        assert_eq!(
            (
                view.value.and_then(|value| value.value),
                view.code.and_then(|code| code.value),
                view.system.and_then(|system| system.value),
            ),
            (
                Some(String::from("4")),
                Some(String::from("1")),
                Some(String::from(UCUM)),
            )
        );
    }

    #[test]
    fn a_count_outside_the_fhir_integer_range_is_refused() {
        let error = Lens::<DvCount, Integer>::get(&CountLens, &count(i64::from(i32::MAX) + 1))
            .expect_err("a FHIR integer is 32-bit");
        assert!(
            matches!(error, LensError::Shape { attribute, .. } if attribute == "DV_COUNT.magnitude"),
            "the refusal names the magnitude: {error}"
        );
    }

    #[test]
    fn a_negative_count_is_no_unsigned_int() {
        // R4 datatypes.html#unsignedInt: an integer from 0; the count is refused, never clamped.
        let error = Lens::<DvCount, UnsignedInt>::get(&CountLens, &count(-1))
            .expect_err("an unsignedInt is from 0");
        assert!(
            matches!(error, LensError::Shape { attribute, ref found, .. } if attribute == "DV_COUNT.magnitude" && found == "-1"),
            "the refusal names the magnitude: {error}"
        );
    }

    #[test]
    fn a_zero_count_is_an_unsigned_int_and_no_positive_int() {
        // R4 datatypes.html#positiveInt: an integer from 1.
        let zero: UnsignedInt = CountLens.get(&count(0)).expect("0 is an unsignedInt");
        assert_eq!(zero.value, Some(0));
        let error = Lens::<DvCount, PositiveInt>::get(&CountLens, &count(0))
            .expect_err("a positiveInt is from 1");
        assert!(
            matches!(error, LensError::Shape { attribute, ref found, .. } if attribute == "DV_COUNT.magnitude" && found == "0"),
            "the refusal names the magnitude: {error}"
        );
    }

    #[test]
    fn a_count_beyond_the_fhir_integer_range_is_no_unsigned_int() {
        let error = Lens::<DvCount, UnsignedInt>::get(&CountLens, &count(i64::from(i32::MAX) + 1))
            .expect_err("an unsignedInt ends at 2,147,483,647");
        assert!(matches!(error, LensError::Shape { .. }), "{error}");
    }

    #[test]
    fn a_fractional_quantity_is_no_count() {
        let view = Quantity {
            value: Some(Decimal::from("2.5")),
            ..Quantity::default()
        };
        let error = CountLens.put(&view, None).expect_err("a count is whole");
        assert!(
            matches!(error, LensError::Shape { attribute, .. } if attribute == "Quantity.value"),
            "the refusal names the value: {error}"
        );
    }

    #[test]
    fn a_count_coded_otherwise_is_refused() {
        let view = Count {
            value: Some(Decimal::from("2")),
            code: Some(Code::from("mg")),
            ..Count::default()
        };
        let error = CountLens
            .put(&view, None)
            .expect_err("cnt-3 fixes the code");
        assert!(
            matches!(error, LensError::Shape { attribute, .. } if attribute == "Count.code"),
            "the refusal names the code: {error}"
        );
    }

    #[test]
    fn a_comparator_going_in_is_refused() {
        let view = Quantity {
            value: Some(Decimal::from("2")),
            comparator: Some(Code::from("<")),
            ..Quantity::default()
        };
        assert!(CountLens.put(&view, None).is_err());
        let count = Count {
            value: Some(Decimal::from("2")),
            comparator: Some(Code::from(">=")),
            ..Count::default()
        };
        assert!(CountLens.put(&count, None).is_err());
    }

    #[test]
    fn a_bounded_count_has_no_comparator_to_carry_it() {
        let source = DvCount {
            magnitude_status: Some(String::from("<")),
            ..count(4)
        };
        assert!(Lens::<DvCount, Integer>::get(&CountLens, &source).is_err());
        assert!(Lens::<DvCount, Quantity>::get(&CountLens, &source).is_err());
        assert!(Lens::<DvCount, Count>::get(&CountLens, &source).is_err());
    }
}