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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! Which data-type cell a mapping runs.
//!
//! A cell is one row of the specification's data-type chapter, so it is fixed
//! by the pair of classes a mapping names: the openEHR class the Web Template
//! node carries and the FHIR element the `type` key or the element table
//! names. This module is that lookup, and nothing more: every conversion
//! lives in [`crate::engine::lens`] and runs both ways there.

use fhir_types::r4::attachment::Attachment;
use openehr_mapping_core::index::ordinals::OrdinalOption;
use openehr_rm::v1_2::data_types::encapsulated::dv_multimedia::DvMultimedia;
use openehr_rm::v1_2::data_types::text::dv_coded_text::DvCodedText;
use openehr_rm::v1_2::data_types::text::dv_text::DvTextData;
use openehr_rm::v1_2::typing::base_name;

use crate::engine::fhir::FhirKind;
use crate::engine::fhir::FhirValue;
use crate::engine::lens::Fallback;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::boolean::BooleanLens;
use crate::engine::lens::code_phrase::CodePhraseLens;
use crate::engine::lens::coded_text::CodedTextLens;
use crate::engine::lens::count::CountLens;
use crate::engine::lens::date::DateLens;
use crate::engine::lens::date_time::DateTimeLens;
use crate::engine::lens::date_time::InstantLens;
use crate::engine::lens::date_time::PeriodStartLens;
use crate::engine::lens::duration::DurationLens;
use crate::engine::lens::encapsulated::EncapsulatedLens;
use crate::engine::lens::interval::DateTimeIntervalLens;
use crate::engine::lens::ordinal::OrdinalLens;
use crate::engine::lens::party::IdentifierLens;
use crate::engine::lens::party::PartyLens;
use crate::engine::lens::proportion::PercentLens;
use crate::engine::lens::quantity::QuantityLens;
use crate::engine::lens::range::QuantityIntervalLens;
use crate::engine::lens::string::StringLens;
use crate::engine::lens::text::TextLens;
use crate::engine::lens::time::TimeLens;
use crate::engine::lens::uri::UriLens;
use crate::engine::rm::RmValue;
use crate::model::ast::keyword::Direction;
use crate::resolve::derive;

use crate::engine::cell::held::held_boolean;
use crate::engine::cell::held::held_code_phrase;
use crate::engine::cell::held::held_coded;
use crate::engine::cell::held::held_count;
use crate::engine::cell::held::held_date;
use crate::engine::cell::held::held_date_time;
use crate::engine::cell::held::held_duration;
use crate::engine::cell::held::held_identifier;
use crate::engine::cell::held::held_interval;
use crate::engine::cell::held::held_multimedia;
use crate::engine::cell::held::held_ordinal;
use crate::engine::cell::held::held_parsable;
use crate::engine::cell::held::held_party;
use crate::engine::cell::held::held_proportion;
use crate::engine::cell::held::held_quantity;
use crate::engine::cell::held::held_quantity_interval;
use crate::engine::cell::held::held_text;
use crate::engine::cell::held::held_time;
use crate::engine::cell::held::held_uri;

mod held;
pub mod withheld;

/// What a cell produced, with the one-way rows it took.
#[derive(Debug, Clone, PartialEq)]
pub struct Produced<T> {
    /// The converted value.
    pub value: T,
    /// The rows the cell filled by a rule that runs one way.
    pub fallbacks: Vec<Fallback>,
}

/// Reads an openEHR value into the FHIR element `kind` names.
///
/// # Errors
///
/// Returns [`LensError::NoCell`] when the specification's chapter has no row
/// for the pair, and whatever the cell refuses otherwise.
pub fn get(
    source: &RmValue,
    kind: FhirKind,
    binding: Option<&str>,
) -> Result<FhirValue, LensError> {
    let coded = coded_lens(binding);
    match (source, kind) {
        (RmValue::Text(text), FhirKind::String) => TextLens.get(text).map(FhirValue::String),
        (RmValue::Text(text), FhirKind::Coding) => TextLens
            .get(text)
            .map(|coding| FhirValue::Coding(Box::new(coding))),
        (RmValue::Text(text), FhirKind::CodeableConcept) => TextLens
            .get(text)
            .map(|concept| FhirValue::CodeableConcept(Box::new(concept))),
        (RmValue::CodedText(text), FhirKind::Coding) => coded
            .get(text.as_ref())
            .map(|coding| FhirValue::Coding(Box::new(coding))),
        (RmValue::CodedText(text), FhirKind::CodeableConcept) => coded
            .get(text.as_ref())
            .map(|concept| FhirValue::CodeableConcept(Box::new(concept))),
        (RmValue::CodedText(text), FhirKind::String) => {
            TextLens.get(&plain(text.as_ref())).map(FhirValue::String)
        }
        (RmValue::CodePhrase(code), FhirKind::Coding) => CodePhraseLens
            .get(code)
            .map(|coding| FhirValue::Coding(Box::new(coding))),
        (RmValue::Date(date), FhirKind::Date) => DateLens.get(date.as_ref()).map(FhirValue::Date),
        (RmValue::Boolean(boolean), FhirKind::Boolean) => {
            BooleanLens.get(boolean).map(FhirValue::Boolean)
        }
        (RmValue::DateTime(date), FhirKind::DateTime) => {
            DateTimeLens.get(date.as_ref()).map(FhirValue::DateTime)
        }
        (RmValue::DateTime(date), FhirKind::Instant) => {
            InstantLens.get(date.as_ref()).map(FhirValue::Instant)
        }
        (RmValue::DateTime(date), FhirKind::Period) => PeriodStartLens
            .get(date.as_ref())
            .map(|period| FhirValue::Period(Box::new(period))),
        (RmValue::DateTimeInterval(interval), FhirKind::Period) => DateTimeIntervalLens
            .get(interval.as_ref())
            .map(|period| FhirValue::Period(Box::new(period))),
        (RmValue::Party(party), FhirKind::Reference) => PartyLens
            .get(party)
            .map(|reference| FhirValue::Reference(Box::new(reference))),
        (RmValue::Identifier(identifier), FhirKind::Identifier) => IdentifierLens
            .get(identifier)
            .map(|identifier| FhirValue::Identifier(Box::new(identifier))),
        (RmValue::Proportion(proportion), FhirKind::Quantity) => PercentLens
            .get(proportion.as_ref())
            .map(|quantity| FhirValue::Quantity(Box::new(quantity))),
        (RmValue::Quantity(quantity), FhirKind::Quantity) => QuantityLens
            .get(quantity.as_ref())
            .map(|quantity| FhirValue::Quantity(Box::new(quantity))),
        (RmValue::Quantity(quantity), FhirKind::Decimal) => {
            QuantityLens.get(quantity.as_ref()).map(FhirValue::Decimal)
        }
        (RmValue::Quantity(quantity), FhirKind::Integer) => {
            QuantityLens.get(quantity.as_ref()).map(FhirValue::Integer)
        }
        (RmValue::Count(count), FhirKind::Integer) => {
            CountLens.get(count.as_ref()).map(FhirValue::Integer)
        }
        (RmValue::Count(count), FhirKind::UnsignedInt) => {
            CountLens.get(count.as_ref()).map(FhirValue::UnsignedInt)
        }
        (RmValue::Count(count), FhirKind::PositiveInt) => {
            CountLens.get(count.as_ref()).map(FhirValue::PositiveInt)
        }
        (RmValue::Count(count), FhirKind::Quantity) => CountLens
            .get(count.as_ref())
            .map(|quantity| FhirValue::Quantity(Box::new(quantity))),
        (RmValue::Count(count), FhirKind::Count) => CountLens
            .get(count.as_ref())
            .map(|count| FhirValue::Count(Box::new(count))),
        (RmValue::Ordinal(ordinal), FhirKind::CodeableConcept) => OrdinalLens::new(coded, &[])
            .get(ordinal.as_ref())
            .map(|concept| FhirValue::CodeableConcept(Box::new(concept))),
        (RmValue::Time(time), FhirKind::Time) => TimeLens.get(time.as_ref()).map(FhirValue::Time),
        (RmValue::Duration(duration), FhirKind::Duration) => DurationLens
            .get(duration.as_ref())
            .map(|duration| FhirValue::Duration(Box::new(duration))),
        (RmValue::Uri(uri), FhirKind::Url) => UriLens.get(uri).map(FhirValue::Url),
        (RmValue::QuantityInterval(interval), FhirKind::Range) => QuantityIntervalLens
            .get(interval.as_ref())
            .map(|range| FhirValue::Range(Box::new(range))),
        (RmValue::Multimedia(multimedia), FhirKind::Attachment) => EncapsulatedLens
            .get(multimedia.as_ref())
            .map(|attachment| FhirValue::Attachment(Box::new(attachment))),
        (RmValue::Parsable(parsable), FhirKind::Attachment) => EncapsulatedLens
            .get(parsable.as_ref())
            .map(|attachment| FhirValue::Attachment(Box::new(attachment))),
        (source, kind) => Err(no_cell(source, kind, Direction::OpenehrToFhir)),
    }
}

/// The openEHR foundation class of a text attribute a tail ends on.
pub const STRING: &str = "String";

/// Reads an openEHR `String` attribute into the FHIR element `kind` names,
/// through the `String.adoc` cells.
///
/// # Errors
///
/// Returns [`LensError::NoCell`] for a kind `String.adoc` writes no row for,
/// and whatever the cell refuses otherwise.
pub fn get_string(text: &str, kind: FhirKind) -> Result<FhirValue, LensError> {
    let text = String::from(text);
    match kind {
        FhirKind::Coding => StringLens
            .get(&text)
            .map(|coding| FhirValue::Coding(Box::new(coding))),
        FhirKind::Identifier => StringLens
            .get(&text)
            .map(|identifier| FhirValue::Identifier(Box::new(identifier))),
        FhirKind::Reference => StringLens
            .get(&text)
            .map(|reference| FhirValue::Reference(Box::new(reference))),
        other => Err(LensError::NoCell {
            rm_type: String::from(STRING),
            kind: other.as_str(),
            direction: Direction::OpenehrToFhir,
        }),
    }
}

/// Writes a FHIR element into the text of an openEHR `String` attribute,
/// through the `String.adoc` cells; `None` for an element those cells do not
/// pair with text.
///
/// # Errors
///
/// Returns whatever the cell refuses.
#[must_use]
pub fn put_string(view: &FhirValue) -> Option<Result<Produced<String>, LensError>> {
    let (value, fallbacks) = match *view {
        FhirValue::Coding(ref coding) => (
            StringLens.put(coding.as_ref(), None),
            StringLens.fallbacks(coding.as_ref()),
        ),
        FhirValue::Identifier(ref identifier) => (
            StringLens.put(identifier.as_ref(), None),
            StringLens.fallbacks(identifier.as_ref()),
        ),
        FhirValue::Reference(ref reference) => (
            StringLens.put(reference.as_ref(), None),
            StringLens.fallbacks(reference.as_ref()),
        ),
        _ => return None,
    };
    Some(value.map(|value| Produced { value, fallbacks }))
}

/// Writes a FHIR element back into the openEHR class `rm_type` names.
///
/// `existing` is the value the target already holds, which carries the
/// attributes the cell's table marks as having no FHIR counterpart, and
/// `ordinals` the options the template constrains at a `DV_ORDINAL` node.
///
/// # Errors
///
/// Returns [`LensError::NoCell`] when the specification's chapter has no row
/// for the pair, and whatever the cell refuses otherwise.
pub fn put(
    view: &FhirValue,
    rm_type: &str,
    existing: Option<&RmValue>,
    binding: Option<&str>,
    ordinals: &[OrdinalOption],
) -> Result<Produced<RmValue>, LensError> {
    let coded = coded_lens(binding);
    let value = match (base_name(rm_type), view) {
        ("DV_TEXT", FhirValue::String(text)) => {
            TextLens.put(text, held_text(existing)).map(RmValue::Text)
        }
        ("DV_TEXT", FhirValue::Coding(coding)) => TextLens
            .put(coding.as_ref(), held_text(existing))
            .map(RmValue::Text),
        ("DV_TEXT", FhirValue::CodeableConcept(concept)) => TextLens
            .put(concept.as_ref(), held_text(existing))
            .map(RmValue::Text),
        ("DV_CODED_TEXT", FhirValue::Coding(coding)) => coded
            .put(coding.as_ref(), held_coded(existing))
            .map(|text| RmValue::CodedText(Box::new(text))),
        ("DV_CODED_TEXT", FhirValue::CodeableConcept(concept)) => coded
            .put(concept.as_ref(), held_coded(existing))
            .map(|text| RmValue::CodedText(Box::new(text))),
        ("CODE_PHRASE", FhirValue::Coding(coding)) => CodePhraseLens
            .put(coding.as_ref(), held_code_phrase(existing))
            .map(RmValue::CodePhrase),
        ("DV_DATE", FhirValue::Date(date)) => DateLens
            .put(date, held_date(existing))
            .map(|date| RmValue::Date(Box::new(date))),
        ("DV_BOOLEAN", FhirValue::Boolean(boolean)) => BooleanLens
            .put(boolean, held_boolean(existing))
            .map(RmValue::Boolean),
        ("DV_DATE_TIME", FhirValue::DateTime(date)) => DateTimeLens
            .put(date, held_date_time(existing))
            .map(|date| RmValue::DateTime(Box::new(date))),
        ("DV_DATE_TIME", FhirValue::Instant(instant)) => InstantLens
            .put(instant, held_date_time(existing))
            .map(|date| RmValue::DateTime(Box::new(date))),
        ("DV_DATE_TIME", FhirValue::Period(period)) => PeriodStartLens
            .put(period.as_ref(), held_date_time(existing))
            .map(|date| RmValue::DateTime(Box::new(date))),
        ("DV_INTERVAL", FhirValue::Period(period)) if bounded_by(rm_type, DATE_TIME) => {
            DateTimeIntervalLens
                .put(period.as_ref(), held_interval(existing))
                .map(|interval| RmValue::DateTimeInterval(Box::new(interval)))
        }
        ("PARTY_IDENTIFIED" | "PARTY_PROXY", FhirValue::Reference(reference)) => PartyLens
            .put(reference.as_ref(), held_party(existing))
            .map(RmValue::Party),
        ("DV_IDENTIFIER", FhirValue::Identifier(identifier)) => IdentifierLens
            .put(identifier.as_ref(), held_identifier(existing))
            .map(RmValue::Identifier),
        ("DV_PROPORTION", FhirValue::Quantity(quantity)) => PercentLens
            .put(quantity.as_ref(), held_proportion(existing))
            .map(|proportion| RmValue::Proportion(Box::new(proportion))),
        ("DV_QUANTITY", FhirValue::Quantity(quantity)) => QuantityLens
            .put(quantity.as_ref(), held_quantity(existing))
            .map(|quantity| RmValue::Quantity(Box::new(quantity))),
        ("DV_QUANTITY", FhirValue::Decimal(decimal)) => QuantityLens
            .put(decimal, held_quantity(existing))
            .map(|quantity| RmValue::Quantity(Box::new(quantity))),
        ("DV_QUANTITY", FhirValue::Integer(integer)) => QuantityLens
            .put(integer, held_quantity(existing))
            .map(|quantity| RmValue::Quantity(Box::new(quantity))),
        ("DV_COUNT", view) => put_count(view, existing),
        ("DV_ORDINAL", FhirValue::CodeableConcept(concept)) => OrdinalLens::new(coded, ordinals)
            .put(concept.as_ref(), held_ordinal(existing))
            .map(|ordinal| RmValue::Ordinal(Box::new(ordinal))),
        ("DV_TIME", FhirValue::Time(time)) => TimeLens
            .put(time, held_time(existing))
            .map(|time| RmValue::Time(Box::new(time))),
        ("DV_DURATION", FhirValue::Duration(duration)) => DurationLens
            .put(duration.as_ref(), held_duration(existing))
            .map(|duration| RmValue::Duration(Box::new(duration))),
        ("DV_URI", FhirValue::Url(url)) => UriLens.put(url, held_uri(existing)).map(RmValue::Uri),
        ("DV_INTERVAL", FhirValue::Range(range)) if bounded_by(rm_type, QUANTITY) => {
            QuantityIntervalLens
                .put(range.as_ref(), held_quantity_interval(existing))
                .map(|interval| RmValue::QuantityInterval(Box::new(interval)))
        }
        ("DV_MULTIMEDIA", FhirValue::Attachment(attachment)) => EncapsulatedLens
            .put(attachment.as_ref(), held_multimedia(existing))
            .map(|multimedia| RmValue::Multimedia(Box::new(multimedia))),
        ("DV_PARSABLE", FhirValue::Attachment(attachment)) => EncapsulatedLens
            .put(attachment.as_ref(), held_parsable(existing))
            .map(|parsable| RmValue::Parsable(Box::new(parsable))),
        (rm_type, view) => Err(LensError::NoCell {
            rm_type: String::from(rm_type),
            kind: view.kind().as_str(),
            direction: Direction::FhirToOpenehr,
        }),
    }?;
    Ok(Produced {
        value,
        fallbacks: fallbacks(view, rm_type, existing, binding),
    })
}

/// Writes a FHIR element back into a `DV_COUNT`, through the `DV_COUNT.adoc`
/// cells and the restricted integers of R4.
fn put_count(view: &FhirValue, existing: Option<&RmValue>) -> Result<RmValue, LensError> {
    let held = held_count(existing);
    let count = match *view {
        FhirValue::Integer(ref integer) => CountLens.put(integer, held),
        FhirValue::UnsignedInt(ref integer) => CountLens.put(integer, held),
        FhirValue::PositiveInt(ref integer) => CountLens.put(integer, held),
        FhirValue::Quantity(ref quantity) => CountLens.put(quantity.as_ref(), held),
        FhirValue::Count(ref count) => CountLens.put(count.as_ref(), held),
        ref other => Err(LensError::NoCell {
            rm_type: String::from("DV_COUNT"),
            kind: other.kind().as_str(),
            direction: Direction::FhirToOpenehr,
        }),
    }?;
    Ok(RmValue::Count(Box::new(count)))
}

/// Returns the one-way rows the cell would take writing `view` over
/// `existing`.
fn fallbacks(
    view: &FhirValue,
    rm_type: &str,
    existing: Option<&RmValue>,
    binding: Option<&str>,
) -> Vec<Fallback> {
    let coded = coded_lens(binding);
    // NOTE: DV_QUANTITY.adoc §Primitives hardcodes `units` as 1, which is a
    // one-way row only where no held value supplies the units.
    let unheld = held_quantity(existing).is_none();
    match (base_name(rm_type), view) {
        ("DV_QUANTITY", FhirValue::Quantity(quantity)) => QuantityLens.fallbacks(quantity.as_ref()),
        ("DV_DURATION", FhirValue::Duration(duration)) => DurationLens.fallbacks(duration.as_ref()),
        ("DV_INTERVAL", FhirValue::Range(range)) if bounded_by(rm_type, QUANTITY) => {
            QuantityIntervalLens.fallbacks(range.as_ref())
        }
        ("DV_MULTIMEDIA", FhirValue::Attachment(attachment)) => {
            Lens::<DvMultimedia, Attachment>::fallbacks(&EncapsulatedLens, attachment.as_ref())
        }
        ("DV_QUANTITY", FhirValue::Decimal(decimal)) if unheld => QuantityLens.fallbacks(decimal),
        ("DV_QUANTITY", FhirValue::Integer(integer)) if unheld => QuantityLens.fallbacks(integer),
        ("DV_TEXT", FhirValue::String(text)) => TextLens.fallbacks(text),
        ("DV_TEXT", FhirValue::Coding(coding)) => TextLens.fallbacks(coding.as_ref()),
        ("DV_TEXT", FhirValue::CodeableConcept(concept)) => TextLens.fallbacks(concept.as_ref()),
        ("DV_CODED_TEXT", FhirValue::Coding(coding)) => coded.fallbacks(coding.as_ref()),
        ("DV_CODED_TEXT", FhirValue::CodeableConcept(concept)) => coded.fallbacks(concept.as_ref()),
        ("DV_ORDINAL", FhirValue::CodeableConcept(concept)) => {
            OrdinalLens::new(coded, &[]).fallbacks(concept.as_ref())
        }
        ("CODE_PHRASE", FhirValue::Coding(coding)) => CodePhraseLens.fallbacks(coding.as_ref()),
        ("DV_DATE", FhirValue::Date(date)) => DateLens.fallbacks(date),
        ("DV_BOOLEAN", FhirValue::Boolean(boolean)) => BooleanLens.fallbacks(boolean),
        ("DV_DATE_TIME", FhirValue::DateTime(date)) => DateTimeLens.fallbacks(date),
        ("DV_DATE_TIME", FhirValue::Period(period)) => PeriodStartLens.fallbacks(period.as_ref()),
        ("DV_INTERVAL", FhirValue::Period(period)) if bounded_by(rm_type, DATE_TIME) => {
            DateTimeIntervalLens.fallbacks(period.as_ref())
        }
        ("PARTY_IDENTIFIED" | "PARTY_PROXY", FhirValue::Reference(reference)) => {
            PartyLens.fallbacks(reference.as_ref())
        }
        ("DV_IDENTIFIER", FhirValue::Identifier(identifier)) => {
            IdentifierLens.fallbacks(identifier.as_ref())
        }
        ("DV_PROPORTION", FhirValue::Quantity(quantity)) => {
            PercentLens.fallbacks(quantity.as_ref())
        }
        (_rm_type, _view) => Vec::new(),
    }
}

/// The bound class of the `DV_INTERVAL` the `Period` cell writes.
const DATE_TIME: &str = "DV_DATE_TIME";

/// The bound class of the `DV_INTERVAL` the `Range` cell writes.
const QUANTITY: &str = "DV_QUANTITY";

/// Returns whether a `DV_INTERVAL` node of `rm_type` may hold bounds of
/// `class`: its parameter is `class`, or it names none.
///
/// `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>),
/// so a `Period` written into a quantity interval would build the wrong
/// value; the parameter decides the cell.
fn bounded_by(rm_type: &str, class: &str) -> bool {
    derive::type_argument(rm_type).is_none_or(|argument| argument.name() == class)
}

/// Returns the coded-text lens for an element with or without a binding.
fn coded_lens(binding: Option<&str>) -> CodedTextLens {
    binding.map_or_else(CodedTextLens::unbound, CodedTextLens::bound)
}

/// Returns the refusal for a pair the data-type chapter has no row for.
fn no_cell(source: &RmValue, kind: FhirKind, direction: Direction) -> LensError {
    LensError::NoCell {
        rm_type: String::from(source.rm_type()),
        kind: kind.as_str(),
        direction,
    }
}

/// Returns the plain text of a coded one, for the `string` cell.
///
/// `DV_CODED_TEXT` is a subtype of `DV_TEXT`
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/data_types.html#_dv_coded_text_class>),
/// so the `DV_TEXT` rows apply to it unchanged.
fn plain(coded: &DvCodedText) -> DvTextData {
    DvTextData {
        value: coded.value.clone(),
        hyperlink: coded.hyperlink.clone(),
        formatting: coded.formatting.clone(),
        mappings: coded.mappings.clone(),
        language: coded.language.clone(),
        encoding: coded.encoding.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::get;
    use super::put;
    use super::withheld::withheld;
    use crate::engine::fhir::FhirKind;
    use crate::engine::fhir::FhirValue;
    use crate::engine::lens::term_mapping::Cause;
    use crate::engine::rm::RmValue;
    use openehr_base::v1_3::base_types::identification::terminology_id::TerminologyId;
    use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;

    /// Returns a synthetic `CODE_PHRASE`.
    fn code() -> CodePhrase {
        CodePhrase {
            terminology_id: TerminologyId {
                value: String::from("local"),
            },
            code_string: String::from("at0017"),
            preferred_term: None,
        }
    }

    #[test]
    fn a_code_phrase_against_a_coding_runs_its_cell() {
        let produced = get(&RmValue::CodePhrase(code()), FhirKind::Coding, None)
            .expect("the CODE_PHRASE cell carries the pair");
        assert_eq!(produced.kind(), FhirKind::Coding);
    }

    #[test]
    fn a_date_time_against_an_instant_runs_its_cell_both_ways() {
        let held = RmValue::from_canonical(
            "DV_DATE_TIME",
            "/synthetic",
            &serde_json::json!({ "_type": "DV_DATE_TIME", "value": "2026-09-13T10:00:00+01:00" }),
        )
        .expect("a DV_DATE_TIME");
        let view = get(&held, FhirKind::Instant, None).expect("the instant cell carries the pair");
        assert_eq!(view.kind(), FhirKind::Instant);
        let back =
            put(&view, "DV_DATE_TIME", Some(&held), None, &[]).expect("the instant cell runs back");
        assert_eq!(back.value, held, "the instant round trips");
        assert!(back.fallbacks.is_empty(), "the cell took no one-way row");
    }

    #[test]
    fn a_pair_the_chapter_has_no_row_for_is_refused() {
        let error = get(&RmValue::CodePhrase(code()), FhirKind::Period, None)
            .expect_err("no row pairs a CODE_PHRASE with a Period");
        assert!(
            error.to_string().contains("CODE_PHRASE"),
            "the refusal names the class: {error}"
        );
    }

    #[test]
    fn the_target_class_decides_the_cell_going_back() {
        let coding = fhir_types::r4::coding::Coding {
            system: Some(fhir_types::r4::primitives::Uri::from("local")),
            code: Some(fhir_types::r4::primitives::Code::from("at0017")),
            ..fhir_types::r4::coding::Coding::default()
        };
        let produced = put(
            &FhirValue::Coding(Box::new(coding)),
            "CODE_PHRASE",
            None,
            None,
            &[],
        )
        .expect("the CODE_PHRASE cell carries the pair");
        assert_eq!(produced.value.rm_type(), "CODE_PHRASE");
        assert!(
            produced.fallbacks.is_empty(),
            "the cell took no one-way row"
        );
    }

    #[test]
    fn a_generic_interval_node_runs_the_cell_of_its_bound_class() {
        // RM 1.1.0 data_types §DV_INTERVAL: the Web Template names the node
        // `DV_INTERVAL<DV_QUANTITY>`, and DV_INTERVAL.adoc §Range is its cell.
        let held = RmValue::from_canonical(
            "DV_INTERVAL<DV_QUANTITY>",
            "/synthetic",
            &serde_json::json!({
                "_type": "DV_INTERVAL",
                "lower_unbounded": true,
                "upper_unbounded": true,
                "lower_included": false,
                "upper_included": false,
            }),
        )
        .expect("a quantity interval with no bounds");
        assert!(matches!(held, RmValue::QuantityInterval(_)));
        let view = FhirValue::Range(Box::default());
        let produced = put(&view, "DV_INTERVAL<DV_QUANTITY>", Some(&held), None, &[])
            .expect("the Range cell carries the node");
        assert_eq!(produced.value, held);
    }

    #[test]
    fn the_interval_parameter_refuses_the_other_cell() {
        // RM 1.1.0 data_types §DV_INTERVAL: the bound class is the parameter.
        let period = FhirValue::Period(Box::default());
        let error = put(&period, "DV_INTERVAL<DV_QUANTITY>", None, None, &[])
            .expect_err("a Period builds no quantity interval");
        assert!(error.to_string().contains("Period"), "{error}");
        let range = FhirValue::Range(Box::default());
        let error = put(&range, "DV_INTERVAL<DV_DATE_TIME>", None, None, &[])
            .expect_err("a Range builds no date-time interval");
        assert!(error.to_string().contains("Range"), "{error}");
        assert!(
            put(&period, "DV_INTERVAL<DV_DATE_TIME>", None, None, &[]).is_ok(),
            "a Period builds a date-time interval"
        );
    }

    #[test]
    fn a_quantity_and_a_count_run_their_cells_both_ways() {
        // DV_QUANTITY.adoc §Quantity and §Primitives, DV_COUNT.adoc §Primitive,
        // §Quantity and §Count.
        let quantity = RmValue::from_canonical(
            "DV_QUANTITY",
            "/synthetic",
            &serde_json::json!({
                "_type": "DV_QUANTITY", "magnitude": 7.25, "precision": 2, "units": "mg",
            }),
        )
        .expect("a DV_QUANTITY");
        let count = RmValue::from_canonical(
            "DV_COUNT",
            "/synthetic",
            &serde_json::json!({ "_type": "DV_COUNT", "magnitude": 3 }),
        )
        .expect("a DV_COUNT");
        for (value, kinds) in [
            (
                &quantity,
                &[FhirKind::Quantity, FhirKind::Decimal, FhirKind::Quantity][..],
            ),
            (
                &count,
                &[
                    FhirKind::Integer,
                    FhirKind::UnsignedInt,
                    FhirKind::PositiveInt,
                    FhirKind::Quantity,
                    FhirKind::Count,
                ][..],
            ),
        ] {
            for &kind in kinds {
                let view = get(value, kind, None).expect("the chapter has the row");
                assert_eq!(view.kind(), kind);
                let back =
                    put(&view, value.rm_type(), Some(value), None, &[]).expect("the row runs back");
                assert_eq!(&back.value, value, "{kind:?} round trips");
            }
        }
        let error = get(&quantity, FhirKind::Integer, None).expect_err("7.25 is no integer");
        assert!(error.to_string().contains("DV_QUANTITY"), "{error}");
    }

    #[test]
    fn a_primitive_declares_the_unity_units_only_when_nothing_is_held() {
        let view = FhirValue::Integer(fhir_types::r4::primitives::Integer::from(3));
        let fresh = put(&view, "DV_QUANTITY", None, None, &[]).expect("the integer travels");
        assert_eq!(fresh.fallbacks.len(), 1, "units is the specification's 1");
        let held =
            put(&view, "DV_QUANTITY", Some(&fresh.value), None, &[]).expect("the integer travels");
        assert!(held.fallbacks.is_empty(), "the held units return");
    }

    /// Returns two synthetic `TERM_MAPPING`s, one `=` and one `>`.
    fn mappings() -> serde_json::Value {
        let term = |relation: &str, code: &str| {
            serde_json::json!({
                "_type": "TERM_MAPPING",
                "match": relation,
                "target": {
                    "_type": "CODE_PHRASE",
                    "terminology_id": {"_type": "TERMINOLOGY_ID", "value": "http://example.org/fhir/CodeSystem/synthetic"},
                    "code_string": code,
                },
            })
        };
        serde_json::json!([term("=", "SYN-001"), term(">", "SYN-002")])
    }

    /// Returns a synthetic `DV_TEXT` annotated with [`mappings`].
    fn text() -> RmValue {
        let value = serde_json::json!({
            "_type": "DV_TEXT",
            "value": "a synthetic rubric",
            "mappings": mappings(),
        });
        RmValue::from_canonical("DV_TEXT", "/synthetic", &value).expect("a DV_TEXT")
    }

    /// Returns a synthetic `DV_CODED_TEXT` annotated with [`mappings`].
    fn coded_text() -> RmValue {
        let value = serde_json::json!({
            "_type": "DV_CODED_TEXT",
            "value": "a synthetic rubric",
            "mappings": mappings(),
            "defining_code": {
                "_type": "CODE_PHRASE",
                "terminology_id": {"_type": "TERMINOLOGY_ID", "value": "local"},
                "code_string": "at0017",
            },
        });
        RmValue::from_canonical("DV_CODED_TEXT", "/synthetic", &value).expect("a DV_CODED_TEXT")
    }

    /// Returns the cause and code of every term `withheld` reports.
    fn reported(source: &RmValue, kind: FhirKind) -> Vec<(Cause, String)> {
        withheld(source, kind, None)
            .iter()
            .map(|taken| (taken.cause(), String::from(taken.code())))
            .collect()
    }

    #[test]
    fn a_cell_with_no_coding_withholds_every_term_mapping() {
        // DV_TEXT.adoc §String and DV_CODED_TEXT.adoc §Coding give `mappings`
        // no FHIRpath row.
        let every = vec![
            (Cause::Uncarried, String::from("SYN-001")),
            (Cause::Uncarried, String::from("SYN-002")),
        ];
        assert_eq!(reported(&text(), FhirKind::String), every);
        assert_eq!(reported(&coded_text(), FhirKind::String), every);
        assert_eq!(reported(&coded_text(), FhirKind::Coding), every);
    }

    #[test]
    fn a_coded_text_read_as_a_string_names_its_defining_code() {
        // DV_CODED_TEXT.adoc §STRING: the chapter writes no string row, so the
        // DV_TEXT cell carries the rubric and the code is declared.
        let source = coded_text();
        let dropped = super::withheld::uncarried_code(&source, FhirKind::String).map(|code| {
            (
                code.terminology_id.value.as_str(),
                code.code_string.as_str(),
            )
        });
        assert_eq!(dropped, Some(("local", "at0017")));
        let produced = get(&source, FhirKind::String, None).expect("the DV_TEXT cell runs");
        assert_eq!(produced.kind(), FhirKind::String);
    }

    #[test]
    fn a_cell_with_a_coding_drops_no_defining_code() {
        for kind in [FhirKind::Coding, FhirKind::CodeableConcept] {
            assert_eq!(super::withheld::uncarried_code(&coded_text(), kind), None);
        }
        assert_eq!(
            super::withheld::uncarried_code(&text(), FhirKind::String),
            None
        );
    }

    #[test]
    fn a_cell_with_codings_withholds_only_what_no_coding_states() {
        // TERM_MAPPING.adoc: `match` is "hard coded to `=`".
        let relation = vec![(Cause::Match, String::from("SYN-002"))];
        assert_eq!(reported(&text(), FhirKind::Coding), relation);
        assert_eq!(reported(&text(), FhirKind::CodeableConcept), relation);
        assert_eq!(reported(&coded_text(), FhirKind::CodeableConcept), relation);
    }
}