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

//! The reference-model values the data-type cells read and write.
//!
//! Each [`crate::engine::lens::Lens`] is typed in one openEHR class, and the
//! interpreter holds whichever class the template node carries, so [`RmValue`]
//! is the sum of the classes the FHIR round trip touches. A value crosses both
//! wires a composition is reached through as its canonical JSON, read and
//! written by the ITS-JSON entry points of `openehr-its`: the CDR serves it,
//! and the FLAT builder takes it whole under the `|raw` suffix (openEHR
//! ITS-REST 1.1.0, Simplified Formats, master04 §Raw canonical JSON).
//!
//! Which tail below a node a value carries is the reference-model attribute
//! model `openehr-rm` generates from the RM BMM, so nothing here restates the
//! attributes of a class.

use openehr_base::containers::NonEmptyVec;
use openehr_base::v1_3::base_types::identification::party_ref::PartyRef;
use openehr_its::json::JsonParseError;
use openehr_its::json::from_canonical_value;
use openehr_its::json::to_canonical_value;
use openehr_rm::v1_2::common::generic::party_identified::PartyIdentifiedData;
use openehr_rm::v1_2::data_types::basic::dv_boolean::DvBoolean;
use openehr_rm::v1_2::data_types::basic::dv_identifier::DvIdentifier;
use openehr_rm::v1_2::data_types::encapsulated::dv_multimedia::DvMultimedia;
use openehr_rm::v1_2::data_types::encapsulated::dv_parsable::DvParsable;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_date::DvDate;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_date_time::DvDateTime;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_duration::DvDuration;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_time::DvTime;
use openehr_rm::v1_2::data_types::quantity::dv_count::DvCount;
use openehr_rm::v1_2::data_types::quantity::dv_interval::DvInterval;
use openehr_rm::v1_2::data_types::quantity::dv_ordinal::DvOrdinal;
use openehr_rm::v1_2::data_types::quantity::dv_proportion::DvProportion;
use openehr_rm::v1_2::data_types::quantity::dv_quantity::DvQuantity;
use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;
use openehr_rm::v1_2::data_types::text::dv_coded_text::DvCodedText;
use openehr_rm::v1_2::data_types::text::dv_text::DvText;
use openehr_rm::v1_2::data_types::text::dv_text::DvTextData;
use openehr_rm::v1_2::data_types::uri::dv_uri::DvUri;
use openehr_rm::v1_2::typing::base_name;
use openehr_sdt::flat::attribute_keys::attribute_key;
use openehr_sdt::flat::path::Segment;
use serde_json::Value;

pub mod carried;
pub mod interval;
pub mod null_flavour;
pub(crate) mod tail_walk;

use crate::engine::rm::null_flavour::NULL_FLAVOUR;
use crate::resolve::derive::type_argument;

/// The suffix a whole canonical value travels under in a FLAT key.
///
/// Simplified Formats, master04 §Raw canonical JSON: the value "must include
/// the `_type` property", which the ITS-JSON writer puts first.
pub const RAW: &str = "raw";

/// One openEHR value a data-type cell produced or consumed.
#[derive(Debug, Clone, PartialEq)]
pub enum RmValue {
    /// A `DV_TEXT`.
    Text(DvTextData),
    /// A `DV_CODED_TEXT`.
    CodedText(Box<DvCodedText>),
    /// A `CODE_PHRASE`.
    CodePhrase(CodePhrase),
    /// A `DV_DATE`.
    Date(Box<DvDate>),
    /// A `DV_DATE_TIME`.
    DateTime(Box<DvDateTime>),
    /// A `DV_INTERVAL<DV_DATE_TIME>`.
    DateTimeInterval(Box<DvInterval<DvDateTime>>),
    /// A `DV_INTERVAL<DV_QUANTITY>`.
    QuantityInterval(Box<DvInterval<DvQuantity>>),
    /// A `PARTY_IDENTIFIED`, the composer and every participation.
    Party(PartyIdentifiedData),
    /// A `DV_IDENTIFIER`.
    Identifier(DvIdentifier),
    /// A `DV_PROPORTION`.
    Proportion(Box<DvProportion>),
    /// A `DV_QUANTITY`.
    Quantity(Box<DvQuantity>),
    /// A `DV_COUNT`.
    Count(Box<DvCount>),
    /// A `DV_ORDINAL`.
    Ordinal(Box<DvOrdinal>),
    /// A `DV_TIME`.
    Time(Box<DvTime>),
    /// A `DV_DURATION`.
    Duration(Box<DvDuration>),
    /// A `DV_URI`, or the `DV_EHR_URI` the reference model admits in its place.
    Uri(DvUri),
    /// A `DV_MULTIMEDIA`.
    Multimedia(Box<DvMultimedia>),
    /// A `DV_PARSABLE`.
    Parsable(Box<DvParsable>),
    /// A `DV_BOOLEAN`.
    Boolean(DvBoolean),
    /// A `PARTY_REF`, the party a `ROLE` names as its `performer`.
    PartyRef(PartyRef),
}

/// Why a reference-model value could not be read or written.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RmError {
    /// The engine holds no cell for the class the template node carries.
    #[error("no data-type cell carries the openEHR class {rm_type}")]
    UnknownClass {
        /// The class the Web Template node names.
        rm_type: String,
    },
    /// The canonical JSON does not decode as the class the node names.
    #[error("the value at {node} does not read as {rm_type}")]
    Decode {
        /// The node the value was read from.
        node: String,
        /// The class the node names.
        rm_type: String,
        /// What the strict ITS-JSON reader refused, with its JSON path.
        #[source]
        source: JsonParseError,
    },
    /// A scalar attribute's text does not read as the attribute's type.
    #[error("the {rm_type} attribute at {node} takes {expected}, and `{text}` is none")]
    Scalar {
        /// The node the attribute is below.
        node: String,
        /// The class that owns the attribute.
        rm_type: String,
        /// The text the FHIR element carried.
        text: String,
        /// What the attribute's declared type takes.
        expected: &'static str,
    },
    /// The value has no canonical JSON form.
    #[error("the {rm_type} value has no canonical JSON form: {reason}")]
    Encode {
        /// The class that refused.
        rm_type: &'static str,
        /// What the encoder refused.
        reason: String,
    },
}

impl RmValue {
    /// Returns the openEHR class the value carries.
    #[must_use]
    pub const fn rm_type(&self) -> &'static str {
        match *self {
            Self::Text(_) => "DV_TEXT",
            Self::CodedText(_) => "DV_CODED_TEXT",
            Self::CodePhrase(_) => "CODE_PHRASE",
            Self::Date(_) => "DV_DATE",
            Self::DateTime(_) => "DV_DATE_TIME",
            Self::DateTimeInterval(_) | Self::QuantityInterval(_) => "DV_INTERVAL",
            Self::Party(_) => "PARTY_IDENTIFIED",
            Self::Identifier(_) => "DV_IDENTIFIER",
            Self::Proportion(_) => "DV_PROPORTION",
            Self::Quantity(_) => "DV_QUANTITY",
            Self::Count(_) => "DV_COUNT",
            Self::Ordinal(_) => "DV_ORDINAL",
            Self::Time(_) => "DV_TIME",
            Self::Duration(_) => "DV_DURATION",
            Self::Uri(_) => "DV_URI",
            Self::Multimedia(_) => "DV_MULTIMEDIA",
            Self::Parsable(_) => "DV_PARSABLE",
            Self::Boolean(_) => "DV_BOOLEAN",
            Self::PartyRef(_) => "PARTY_REF",
        }
    }

    /// Reads the canonical JSON of one node as the class the node names.
    ///
    /// A `DV_TEXT` node may hold a `DV_CODED_TEXT`, which the reference model
    /// admits as a subtype
    /// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/data_types.html#_dv_coded_text_class>),
    /// so the discriminator in the document decides between the two. The
    /// reader is the strict ITS-JSON one of `openehr-its`.
    ///
    /// # Errors
    ///
    /// Returns [`RmError::UnknownClass`] for a class no cell carries and
    /// [`RmError::Decode`] when the document does not decode as it.
    pub fn from_canonical(rm_type: &str, node: &str, value: &Value) -> Result<Self, RmError> {
        let refuse = |source: JsonParseError| RmError::Decode {
            node: String::from(node),
            rm_type: String::from(rm_type),
            source,
        };
        match base_name(rm_type) {
            "DV_TEXT" | "DV_CODED_TEXT" => from_canonical_value::<DvText>(value)
                .map(|text| match text {
                    DvText::DvCodedText(coded) => Self::CodedText(Box::new(coded)),
                    DvText::DvText(plain) => Self::Text(plain),
                })
                .map_err(refuse),
            "CODE_PHRASE" => from_canonical_value(value)
                .map(Self::CodePhrase)
                .map_err(refuse),
            "DV_DATE" => from_canonical_value(value)
                .map(|date| Self::Date(Box::new(date)))
                .map_err(refuse),
            "DV_BOOLEAN" => from_canonical_value(value)
                .map(Self::Boolean)
                .map_err(refuse),
            "DV_DATE_TIME" => from_canonical_value(value)
                .map(|date| Self::DateTime(Box::new(date)))
                .map_err(refuse),
            "DV_INTERVAL"
                if type_argument(rm_type).is_some_and(|bound| bound.name() == DV_QUANTITY)
                    || bound_class(value) == Some(DV_QUANTITY) =>
            {
                from_canonical_value(value)
                    .map(|interval| Self::QuantityInterval(Box::new(interval)))
                    .map_err(refuse)
            }
            "DV_INTERVAL" => from_canonical_value(value)
                .map(|interval| Self::DateTimeInterval(Box::new(interval)))
                .map_err(refuse),
            "PARTY_IDENTIFIED" | "PARTY_PROXY" => {
                from_canonical_value(value).map(Self::Party).map_err(refuse)
            }
            "DV_IDENTIFIER" => from_canonical_value(value)
                .map(Self::Identifier)
                .map_err(refuse),
            "DV_PROPORTION" => from_canonical_value(value)
                .map(|proportion| Self::Proportion(Box::new(proportion)))
                .map_err(refuse),
            "DV_QUANTITY" => from_canonical_value(value)
                .map(|quantity| Self::Quantity(Box::new(quantity)))
                .map_err(refuse),
            "DV_COUNT" => from_canonical_value(value)
                .map(|count| Self::Count(Box::new(count)))
                .map_err(refuse),
            "DV_ORDINAL" => from_canonical_value(value)
                .map(|ordinal| Self::Ordinal(Box::new(ordinal)))
                .map_err(refuse),
            "DV_TIME" => from_canonical_value(value)
                .map(|time| Self::Time(Box::new(time)))
                .map_err(refuse),
            "DV_DURATION" => from_canonical_value(value)
                .map(|duration| Self::Duration(Box::new(duration)))
                .map_err(refuse),
            "DV_URI" => from_canonical_value(value).map(Self::Uri).map_err(refuse),
            "DV_MULTIMEDIA" => from_canonical_value(value)
                .map(|multimedia| Self::Multimedia(Box::new(multimedia)))
                .map_err(refuse),
            "DV_PARSABLE" => from_canonical_value(value)
                .map(|parsable| Self::Parsable(Box::new(parsable)))
                .map_err(refuse),
            "PARTY_REF" => from_canonical_value(value)
                .map(Self::PartyRef)
                .map_err(refuse),
            other => Err(RmError::UnknownClass {
                rm_type: String::from(other),
            }),
        }
    }

    /// Returns the canonical JSON of the value, `_type` first.
    ///
    /// # Errors
    ///
    /// Returns [`RmError::Encode`] for a `DV_PROPORTION` whose numerator or
    /// denominator, or a `DV_QUANTITY` whose magnitude, is no finite number,
    /// which JSON has no form for
    /// (<https://www.rfc-editor.org/rfc/rfc8259#section-6>).
    pub fn to_canonical(&self) -> Result<Value, RmError> {
        let encoded = match *self {
            Self::Text(ref text) => to_canonical_value(text),
            Self::CodedText(ref coded) => to_canonical_value(coded.as_ref()),
            Self::CodePhrase(ref code) => to_canonical_value(code),
            Self::Date(ref date) => to_canonical_value(date.as_ref()),
            Self::Boolean(ref boolean) => to_canonical_value(boolean),
            Self::DateTime(ref date) => to_canonical_value(date.as_ref()),
            Self::DateTimeInterval(ref interval) => to_canonical_value(interval.as_ref()),
            Self::QuantityInterval(ref interval) => to_canonical_value(interval.as_ref()),
            Self::Party(ref party) => to_canonical_value(party),
            Self::Identifier(ref identifier) => to_canonical_value(identifier),
            Self::PartyRef(ref party) => to_canonical_value(party),
            Self::Proportion(ref proportion) => {
                for number in [proportion.numerator, proportion.denominator] {
                    if !number.is_finite() {
                        return Err(RmError::Encode {
                            rm_type: "DV_PROPORTION",
                            reason: format!("{number} is not a finite JSON number"),
                        });
                    }
                }
                to_canonical_value(proportion.as_ref())
            }
            Self::Quantity(ref quantity) => {
                if !quantity.magnitude.is_finite() {
                    return Err(RmError::Encode {
                        rm_type: "DV_QUANTITY",
                        reason: format!("{} is not a finite JSON number", quantity.magnitude),
                    });
                }
                to_canonical_value(quantity.as_ref())
            }
            Self::Count(ref count) => to_canonical_value(count.as_ref()),
            Self::Ordinal(ref ordinal) => to_canonical_value(ordinal.as_ref()),
            Self::Time(ref time) => to_canonical_value(time.as_ref()),
            Self::Duration(ref duration) => to_canonical_value(duration.as_ref()),
            Self::Uri(ref uri) => to_canonical_value(uri),
            Self::Multimedia(ref multimedia) => to_canonical_value(multimedia.as_ref()),
            Self::Parsable(ref parsable) => to_canonical_value(parsable.as_ref()),
        };
        Ok(encoded)
    }
}

/// The bound class of a quantity interval node, `DV_INTERVAL<DV_QUANTITY>`.
const DV_QUANTITY: &str = "DV_QUANTITY";

/// Returns the class a `DV_INTERVAL`'s bounds carry, read from the `_type` of
/// whichever bound the document holds.
///
/// `DV_INTERVAL<T>` is generic in its bound class
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/data_types.html#_dv_interval_class>),
/// and the canonical JSON names the class on each bound only.
fn bound_class(value: &Value) -> Option<&str> {
    ["lower", "upper"]
        .into_iter()
        .find_map(|bound| value.get(bound)?.get("_type")?.as_str())
}

/// The attributes of a structural class FLAT writes as a `_`-prefixed family
/// of the class's node.
///
/// `ENTRY.provider` is a `PARTY_PROXY`
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/ehr.html#_entry_class>),
/// and Simplified Formats spells it `_provider` under the entry's node
/// (`docs/specs/its-rest/docs/simplified_formats/master05-rm_mapping.adoc`,
/// §OBSERVATION), the shape `family` spells `_other_participation` in.
/// `EVENT_CONTEXT.health_care_facility` is a `PARTY_IDENTIFIED`
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/ehr.html#_event_context_class>),
/// spelled `_health_care_facility` under the `context` node (the same file,
/// the `EVENT_CONTEXT` section), and `EVENT_CONTEXT.end_time` is an optional
/// `DV_DATE_TIME` the same section spells `_end_time`.
/// `ELEMENT.null_flavour` is a `DV_CODED_TEXT`
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/data_structures.html#_element_class>)
/// the same file spells `_null_flavour` on the node the element shares with
/// its value, beside `_null_reason` (§ELEMENT); a tail reaches it through
/// [`crate::resolve::program::target::OpenehrTarget::tail_class`].
pub const FAMILIES: &[(&str, &str)] = &[
    ("ENTRY", "provider"),
    ("EVENT_CONTEXT", "health_care_facility"),
    ("EVENT_CONTEXT", "end_time"),
    ("ELEMENT", NULL_FLAVOUR),
];

/// The date-time attributes of an entry a Web Template carries no node for.
///
/// Each row is the entry class and the tail that names the attribute; the
/// FLAT key comes from `openehr_sdt::flat::attribute_keys::attribute_key`.
///
/// `HISTORY.origin` is a `DV_DATE_TIME`
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/data_structures.html#_history_class>),
/// spelled `history_origin` under the observation's node, and `ACTION.time`
/// is a mandatory `DV_DATE_TIME`
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/ehr.html#_action_class>),
/// spelled `time` under the action's node
/// (`docs/specs/its-rest/docs/simplified_formats/master05-rm_mapping.adoc`,
/// §OBSERVATION and §ACTION).
pub const ENTRY_TIMES: &[(&str, &str)] = &[("OBSERVATION", "data/origin"), ("ACTION", "time")];

/// Returns the FLAT key the date-time attribute `tail` of an `owner` entry is
/// written under, `None` when [`ENTRY_TIMES`] names no such attribute.
#[must_use]
pub fn entry_time_key(owner: &str, tail: &str) -> Option<&'static str> {
    ENTRY_TIMES
        .iter()
        .any(|&(entry, path)| entry == owner && path == tail)
        .then(|| attribute_key(owner, tail))
        .flatten()
        .map(|row| row.key)
}

/// The attributes of a party root a party context maps although no template
/// node holds them, which the party build places on the root.
///
/// `ROLE.performer` is a mandatory `PARTY_REF` to "the Version container of
/// Actor playing the role" (RM Demographic IM, the `ROLE` class), and an
/// operational template constrains no node for it. No specification governs
/// a party context: our own design.
pub const PARTY_ROOTS: &[(&str, &str)] = &[("ROLE", "performer")];

/// Returns the FLAT family a tail of [`carried::Carried::Family`] below an
/// `owner` node is written under, `None` when no FLAT key names the attribute.
#[must_use]
pub fn family_of(owner: &str, tail: &[&str]) -> Option<Vec<Segment>> {
    let row = attribute_key(owner, &tail.join("/"))?;
    Some(vec![Segment {
        name: row.key.to_owned(),
        index: None,
    }])
}

/// Returns the identifiers a party carries, as the container the model wants.
///
/// `NonEmptyVec` is the reference model's own container for an optional
/// non-empty list, so an empty list is the absent one rather than a present
/// list of nothing.
#[must_use]
pub fn identifiers(values: Vec<DvIdentifier>) -> Option<NonEmptyVec<DvIdentifier>> {
    NonEmptyVec::new(values).ok()
}

#[cfg(test)]
mod tests {
    use super::RmValue;
    use super::carried::Carried;
    use super::carried::carried;
    use super::entry_time_key;
    use openehr_base::v1_3::base_types::identification::terminology_id::TerminologyId;
    use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;

    #[test]
    fn a_code_phrase_writes_all_three_attributes_in_its_canonical_form() {
        let value = RmValue::CodePhrase(CodePhrase {
            terminology_id: TerminologyId {
                value: String::from("local"),
            },
            code_string: String::from("at0017"),
            preferred_term: Some(String::from("Working")),
        });
        let canonical = value.to_canonical().expect("a code phrase encodes");
        assert_eq!(
            canonical,
            serde_json::json!({
                "_type": "CODE_PHRASE",
                "terminology_id": {"_type": "TERMINOLOGY_ID", "value": "local"},
                "code_string": "at0017",
                "preferred_term": "Working"
            })
        );
        assert_eq!(
            RmValue::from_canonical("CODE_PHRASE", "/x", &canonical).expect("it reads back"),
            value
        );
    }

    #[test]
    fn a_date_time_keeps_its_text_byte_for_byte() {
        let value = RmValue::from_canonical(
            "DV_DATE_TIME",
            "/context/start_time",
            &serde_json::json!({"_type": "DV_DATE_TIME", "value": "2026-09-12T10:00:00+02:00"}),
        )
        .expect("the canonical form reads back");
        let canonical = value.to_canonical().expect("a date and time encodes");
        assert_eq!(
            canonical.get("value").and_then(serde_json::Value::as_str),
            Some("2026-09-12T10:00:00+02:00"),
            "the offset survives byte for byte"
        );
    }

    #[test]
    fn a_class_no_cell_carries_names_itself() {
        let error = RmValue::from_canonical("DV_MULTIMEDIA", "/x", &serde_json::Value::Null)
            .expect_err("no cell carries DV_MULTIMEDIA");
        assert!(
            error.to_string().contains("DV_MULTIMEDIA"),
            "the refusal names the class: {error}"
        );
    }

    #[test]
    fn a_coded_text_keeps_its_term_mappings_and_language() {
        let written = serde_json::json!({
            "_type": "DV_CODED_TEXT",
            "value": "Synthetic problem one",
            "mappings": [{
                "_type": "TERM_MAPPING",
                "match": "=",
                "target": {
                    "_type": "CODE_PHRASE",
                    "terminology_id": {"_type": "TERMINOLOGY_ID", "value": "SNOMED-CT"},
                    "code_string": "73211009"
                }
            }],
            "language": {
                "_type": "CODE_PHRASE",
                "terminology_id": {"_type": "TERMINOLOGY_ID", "value": "ISO_639-1"},
                "code_string": "en"
            },
            "defining_code": {
                "_type": "CODE_PHRASE",
                "terminology_id": {"_type": "TERMINOLOGY_ID", "value": "local"},
                "code_string": "at0001"
            }
        });
        let value = RmValue::from_canonical("DV_CODED_TEXT", "/x", &written)
            .expect("the canonical form reads back");
        let canonical = value.to_canonical().expect("a coded text encodes");
        assert_eq!(canonical.get("mappings"), written.get("mappings"));
        assert_eq!(canonical.get("language"), written.get("language"));
    }

    #[test]
    fn a_defective_value_names_the_json_path_it_failed_at() {
        let error = RmValue::from_canonical(
            "DV_TEXT",
            "/x",
            &serde_json::json!({"_type": "DV_TEXT", "value": "text", "undeclared": 1}),
        )
        .expect_err("the strict reader refuses an undeclared key");
        assert!(
            core::error::Error::source(&error).is_some(),
            "the reader's refusal is the source: {error}"
        );
    }

    #[test]
    fn the_entry_provider_is_a_family() {
        assert_eq!(
            carried("EVALUATION", &["provider"]),
            Some(("ENTRY", Carried::Family))
        );
    }

    #[test]
    fn the_context_health_care_facility_is_a_family() {
        assert_eq!(
            carried("EVENT_CONTEXT", &["health_care_facility"]),
            Some(("EVENT_CONTEXT", Carried::Family))
        );
        assert_eq!(carried("EVENT_CONTEXT", &["location"]), None);
    }

    #[test]
    fn the_context_end_time_is_a_family() {
        assert_eq!(
            carried("EVENT_CONTEXT", &["end_time"]),
            Some(("EVENT_CONTEXT", Carried::Family))
        );
    }

    #[test]
    fn the_history_origin_is_carried_on_an_observation_alone() {
        assert_eq!(
            carried("OBSERVATION", &["data", "origin"]),
            Some(("OBSERVATION", Carried::EntryTime))
        );
        assert_eq!(carried("EVALUATION", &["data", "origin"]), None);
        assert_eq!(carried("OBSERVATION", &["data", "period"]), None);
    }

    #[test]
    fn the_time_of_an_action_is_carried_on_an_action_alone() {
        assert_eq!(
            carried("ACTION", &["time"]),
            Some(("ACTION", Carried::EntryTime))
        );
        assert_eq!(entry_time_key("ACTION", "time"), Some("time"));
        assert_eq!(carried("INSTRUCTION", &["time"]), None);
    }
}