fhir-types 0.1.115

Generated per-version FHIR types and terminology operation contracts
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
// @generated by fhir-codegen from hl7.fhir.r4.core 4.0.1, hl7.fhir.r4b.core 4.3.0, hl7.fhir.r5.core 5.0.0, hl7.fhir.r6.core 6.0.0-ballot5, hl7.fhir.r3.core 3.0.2. DO NOT EDIT.
// Change the emitter (tools/fhir-codegen) and regenerate.
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: Apache-2.0
//! The FHIR XML representation shared by every version module, over the
//! version's element schema.
//!
//! XML carries the same element tree as JSON, in the definition's element
//! order: a primitive's value is the `value` attribute, an element id the `id`
//! attribute, `Extension.url` an attribute, a choice element is named with its
//! type, a resource is an element named by its type in the
//! `http://hl7.org/fhir` namespace, a nested resource sits inside its wrapper
//! element, and `Narrative.div` is XHTML passed through
//! (<https://hl7.org/fhir/R4B/xml.html>). The conversion runs between XML and
//! the FHIR JSON object model, so the JSON codec's strictness applies to both.

use std::borrow::Cow;

use quick_xml::events::attributes::Attribute;
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::name::{Namespace, QName, ResolveResult};
use quick_xml::{NsReader, Writer, XmlVersion};

use super::codec::{DecodeError, DecodeErrorKind, EncodeError, Number, Object, Path, Value};
use super::schema::{FieldSchema, Kind, Schemas, TypeSchema, ValueKind};

/// The FHIR XML namespace.
pub const FHIR_NAMESPACE: &str = "http://hl7.org/fhir";

/// The XHTML namespace, the one the narrative `div` is in.
const XHTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";

/// The XML Schema instance namespace, which a resource never declares.
const XML_SCHEMA_INSTANCE_NAMESPACE: &str = "http://www.w3.org/2001/XMLSchema-instance";

/// Writes `object`, a resource in the JSON object model, as FHIR XML.
///
/// # Errors
///
/// Returns [`EncodeError`] when the object names no resource type the schema
/// knows, or a value has no XML form.
pub fn to_xml(schemas: &Schemas, object: &Object) -> Result<String, EncodeError> {
    let mut writer = Writer::new(Vec::new());
    write_resource(schemas, &mut writer, object, true)?;
    String::from_utf8(writer.into_inner()).map_err(|_| EncodeError::Xml {
        reason: String::from("the writer produced invalid UTF-8"),
    })
}

fn xml_error(reason: impl std::fmt::Display) -> EncodeError {
    EncodeError::Xml {
        reason: reason.to_string(),
    }
}

fn write_resource(
    schemas: &Schemas,
    writer: &mut Writer<Vec<u8>>,
    object: &Object,
    root: bool,
) -> Result<(), EncodeError> {
    let name = match object.get("resourceType") {
        Some(Value::String(name)) => name.as_str(),
        _ => {
            return Err(EncodeError::Xml {
                reason: String::from("the resource names no resourceType"),
            });
        }
    };
    let schema = schemas
        .type_named(name)
        .filter(|_| schemas.is_resource(name))
        .ok_or_else(|| EncodeError::Xml {
            reason: format!("no schema for the resource type `{name}`"),
        })?;
    let mut start = BytesStart::new(name);
    if root {
        start.push_attribute(("xmlns", FHIR_NAMESPACE));
    }
    write_complex(schemas, writer, schema, object, start, &["resourceType"])
}

/// Whether `object` carries `field`, so an element with no child is written
/// empty rather than opened and closed.
///
/// A primitive is present under its own name or under the `_name` object that
/// carries its id and extensions, and a choice is present under any of its
/// suffixed names.
fn present(field: &FieldSchema, object: &Object) -> bool {
    match field.kind {
        Kind::Attribute => false,
        Kind::Choice(variants) => variants.iter().any(|(suffix, _)| {
            object.contains_key(&format!("{}{suffix}", field.name))
                || object.contains_key(&format!("_{}{suffix}", field.name))
        }),
        Kind::Primitive(_) => {
            object.contains_key(field.name) || object.contains_key(&format!("_{}", field.name))
        }
        _ => object.contains_key(field.name),
    }
}

/// Writes one complex element: its attributes on the start tag, then its
/// children in schema order.
fn write_complex(
    schemas: &Schemas,
    writer: &mut Writer<Vec<u8>>,
    schema: &TypeSchema,
    object: &Object,
    mut start: BytesStart<'_>,
    skip: &[&str],
) -> Result<(), EncodeError> {
    for field in schema.fields {
        if field.kind == Kind::Attribute
            && let Some(Value::String(text)) = object.get(field.name)
        {
            start.push_attribute((field.name, text.as_str()));
        }
    }
    let children = schema
        .fields
        .iter()
        .any(|field| !skip.contains(&field.name) && present(field, object));
    if !children {
        writer.write_event(Event::Empty(start)).map_err(xml_error)?;
        return Ok(());
    }
    let name = start.name().as_ref().to_owned();
    writer.write_event(Event::Start(start)).map_err(xml_error)?;
    for field in schema.fields {
        if skip.contains(&field.name) {
            continue;
        }
        write_field(schemas, writer, field, field.name, field.kind, object)?;
    }
    writer
        .write_event(Event::End(BytesEnd::new(name)))
        .map_err(xml_error)
}

/// Writes a primitive field: its value, its `_name` id and extensions, or both.
///
/// A repeating primitive writes one element per position, and the two arrays
/// need not be the same length, so the longer decides how many elements there
/// are (<https://hl7.org/fhir/R4B/json.html#primitive>).
fn write_primitive_field(
    schemas: &Schemas,
    writer: &mut Writer<Vec<u8>>,
    field: &FieldSchema,
    name: &str,
    object: &Object,
) -> Result<(), EncodeError> {
    let values = object.get(name);
    let elements = object.get(&format!("_{name}"));
    if values.is_none() && elements.is_none() {
        return Ok(());
    }
    if !field.many {
        return write_primitive(
            schemas,
            writer,
            name,
            values.filter(|v| !v.is_null()),
            elements.and_then(Value::as_object),
        );
    }
    let values = values.and_then(Value::as_array);
    let elements = elements.and_then(Value::as_array);
    let len = values
        .map_or(0, <[Value]>::len)
        .max(elements.map_or(0, <[Value]>::len));
    for index in 0..len {
        let value = values.and_then(|v| v.get(index)).filter(|v| !v.is_null());
        let element = elements
            .and_then(|e| e.get(index))
            .and_then(Value::as_object);
        write_primitive(schemas, writer, name, value, element)?;
    }
    Ok(())
}

/// Writes a complex field: one element per item, each over the named type's
/// own schema.
fn write_complex_field(
    schemas: &Schemas,
    writer: &mut Writer<Vec<u8>>,
    field: &FieldSchema,
    name: &str,
    type_name: &str,
    object: &Object,
) -> Result<(), EncodeError> {
    let schema = schemas
        .type_named(type_name)
        .ok_or_else(|| EncodeError::Xml {
            reason: format!("no schema for the type `{type_name}`"),
        })?;
    for item in items(object.get(name), field.many) {
        let item = item.as_object().ok_or_else(|| EncodeError::Xml {
            reason: format!("`{name}` is not an object"),
        })?;
        write_complex(schemas, writer, schema, item, BytesStart::new(name), &[])?;
    }
    Ok(())
}

fn write_field(
    schemas: &Schemas,
    writer: &mut Writer<Vec<u8>>,
    field: &FieldSchema,
    name: &str,
    kind: Kind,
    object: &Object,
) -> Result<(), EncodeError> {
    match kind {
        Kind::Attribute => Ok(()),
        Kind::Choice(variants) => {
            for (suffix, kind) in variants {
                let key = format!("{name}{suffix}");
                write_field(schemas, writer, field, &key, *kind, object)?;
            }
            Ok(())
        }
        Kind::Primitive(_) => write_primitive_field(schemas, writer, field, name, object),
        Kind::Complex(type_name) => {
            write_complex_field(schemas, writer, field, name, type_name, object)
        }
        Kind::Resource => {
            for item in items(object.get(name), field.many) {
                let item = item.as_object().ok_or_else(|| EncodeError::Xml {
                    reason: format!("`{name}` is not an object"),
                })?;
                writer
                    .write_event(Event::Start(BytesStart::new(name)))
                    .map_err(xml_error)?;
                write_resource(schemas, writer, item, false)?;
                writer
                    .write_event(Event::End(BytesEnd::new(name)))
                    .map_err(xml_error)?;
            }
            Ok(())
        }
        Kind::Xhtml => {
            if object.contains_key(&format!("_{name}")) {
                return Err(EncodeError::Xml {
                    reason: format!(
                        "`_{name}`: an XHTML element carries no id or extension in XML"
                    ),
                });
            }
            match object.get(name) {
                None => Ok(()),
                Some(Value::String(raw)) => writer
                    .write_event(Event::Text(BytesText::from_escaped(raw.as_str())))
                    .map_err(xml_error),
                Some(_) => Err(EncodeError::Xml {
                    reason: format!("`{name}` is not a string"),
                }),
            }
        }
    }
}

/// The items of a field's value: the array's entries when it repeats, else
/// the value itself.
fn items(value: Option<&Value>, many: bool) -> Vec<&Value> {
    match value {
        None => Vec::new(),
        Some(Value::Array(items)) if many => items.iter().collect(),
        Some(value) => vec![value],
    }
}

fn write_primitive(
    schemas: &Schemas,
    writer: &mut Writer<Vec<u8>>,
    name: &str,
    value: Option<&Value>,
    element: Option<&Object>,
) -> Result<(), EncodeError> {
    let mut start = BytesStart::new(name);
    if let Some(Value::String(id)) = element.and_then(|e| e.get("id")) {
        start.push_attribute(("id", id.as_str()));
    }
    if let Some(value) = value {
        let text = match value {
            Value::Bool(b) => b.to_string(),
            Value::Number(n) => n.to_string(),
            Value::String(s) => s.clone(),
            _ => {
                return Err(EncodeError::Xml {
                    reason: format!("`{name}` is not a primitive value"),
                });
            }
        };
        start.push_attribute(("value", text.as_str()));
    }
    let extensions = element
        .and_then(|e| e.get("extension"))
        .and_then(Value::as_array);
    match extensions {
        Some(extensions) if !extensions.is_empty() => {
            let schema = schemas
                .type_named("Extension")
                .ok_or_else(|| EncodeError::Xml {
                    reason: String::from("no schema for the type `Extension`"),
                })?;
            writer.write_event(Event::Start(start)).map_err(xml_error)?;
            for extension in extensions {
                let extension = extension.as_object().ok_or_else(|| EncodeError::Xml {
                    reason: format!("`_{name}.extension` is not an object"),
                })?;
                write_complex(
                    schemas,
                    writer,
                    schema,
                    extension,
                    BytesStart::new("extension"),
                    &[],
                )?;
            }
            writer
                .write_event(Event::End(BytesEnd::new(name)))
                .map_err(xml_error)
        }
        _ => writer.write_event(Event::Empty(start)).map_err(xml_error),
    }
}

/// Reads FHIR XML into the JSON object model of the resource it carries.
///
/// # Errors
///
/// Returns [`DecodeError`] for malformed XML, a root element that is no
/// resource the schema knows, an unknown element or attribute, an element
/// outside the FHIR namespace or a prefixed attribute outside it (R4 xml.html
/// §2.6.1), a narrative `div` outside the XHTML namespace, a declaration of the XML Schema instance namespace (R4 xml.html
/// §2.6.1.1) anywhere, the narrative included, text where an element belongs, or a `value` that is not of the
/// primitive's kind.
pub fn from_xml(schemas: &Schemas, text: &str) -> Result<Object, DecodeError> {
    let mut reader = NsReader::from_str(text);
    reader.config_mut().trim_text(true);
    let mut path = Path::root("Resource");
    let malformed = |path: &Path, e: quick_xml::Error| {
        path.error(DecodeErrorKind::MalformedXml {
            reason: e.to_string(),
        })
    };
    let object = loop {
        match reader.read_event().map_err(|e| malformed(&path, e))? {
            Event::Decl(_) | Event::Comment(_) | Event::PI(_) | Event::DocType(_) => {}
            Event::Start(start) => {
                break read_resource(schemas, &mut reader, &start, false, &mut path)?;
            }
            Event::Empty(start) => {
                break read_resource(schemas, &mut reader, &start, true, &mut path)?;
            }
            Event::Eof => return Err(path.error(DecodeErrorKind::WrongRoot)),
            _ => return Err(path.error(DecodeErrorKind::UnexpectedText)),
        }
    };
    loop {
        match reader.read_event().map_err(|e| malformed(&path, e))? {
            Event::Eof => return Ok(object),
            Event::Comment(_) | Event::PI(_) => {}
            _ => return Err(path.error(DecodeErrorKind::UnexpectedText)),
        }
    }
}

fn local_name(name: &str) -> String {
    name.rsplit(':').next().unwrap_or(name).to_owned()
}

/// Whether `start`, the element the reader has just read, is in `namespace`
/// once its prefix, or the default namespace in scope, is resolved.
///
/// The namespace decides and the prefix never does: `<f:Patient
/// xmlns:f="http://hl7.org/fhir">` is a FHIR element, and `<x:Patient
/// xmlns:x="http://example.org">` or an unprefixed element with no default
/// namespace in scope is not (R4 xml.html §2.6.1,
/// <https://hl7.org/fhir/R4/xml.html>).
fn in_namespace(reader: &NsReader<&[u8]>, start: &BytesStart<'_>, namespace: &str) -> bool {
    matches!(
        reader.resolver().resolve_element(start.name()).0,
        ResolveResult::Bound(Namespace(bound)) if bound == namespace
    )
}

/// Reads one resource element.
///
/// A root or nested resource element outside the FHIR namespace is refused
/// as [`DecodeErrorKind::WrongRoot`]: "FHIR elements are always in the
/// namespace `http://hl7.org/fhir`" (R4 xml.html §2.6.1, the same rule in STU3
/// §2.6.1 and R5 §2.1.6.3, <https://hl7.org/fhir/R4/xml.html>).
fn read_resource(
    schemas: &Schemas,
    reader: &mut NsReader<&[u8]>,
    start: &BytesStart<'_>,
    empty: bool,
    path: &mut Path,
) -> Result<Object, DecodeError> {
    let name = local_name(start.name().as_ref());
    let schema = schemas
        .type_named(&name)
        .filter(|_| schemas.is_resource(&name))
        .filter(|_| in_namespace(reader, start, FHIR_NAMESPACE))
        .ok_or_else(|| path.error(DecodeErrorKind::WrongRoot))?;
    let mut object = read_complex(schemas, reader, schema, start, empty, path)?;
    object.insert(String::from("resourceType"), Value::String(name));
    Ok(object)
}

/// The attribute's local name and unescaped value; `None` for a namespace
/// declaration.
///
/// A declaration of the XML Schema instance namespace is refused as
/// [`DecodeErrorKind::UnknownProperty`] at the declaring attribute's name:
/// exchanged content "SHALL NOT specify the schema or even contain the schema
/// instance namespace in the resource itself" (R4 xml.html §2.6.1.1, the same
/// rule in STU3 §2.6.1.1 and R5 §2.1.6.3.4,
/// <https://hl7.org/fhir/R4/xml.html>). An `xsi:` attribute such as
/// `xsi:schemaLocation` cannot be written without that declaration, so it is
/// refused with it.
///
/// FHIR's own attributes (`value`, `id`, `url`) are unprefixed; a prefixed
/// attribute is read only when its prefix resolves to the FHIR namespace, and
/// one in any other namespace, or under a prefix with no binding in scope, is
/// refused as [`DecodeErrorKind::UnknownProperty`] at its local name: "the
/// only other namespace that occurs in FHIR resources is the XHTML namespace"
/// (R4 xml.html §2.6.1), and XHTML belongs only inside the narrative.
fn attribute(
    reader: &NsReader<&[u8]>,
    attribute: Result<Attribute<'_>, quick_xml::events::attributes::AttrError>,
    path: &mut Path,
) -> Result<Option<(String, String)>, DecodeError> {
    let attribute = attribute.map_err(|e| {
        path.error(DecodeErrorKind::MalformedXml {
            reason: e.to_string(),
        })
    })?;
    let key = attribute.key.as_ref();
    let value = attribute
        .normalized_value(XmlVersion::Explicit1_0)
        .map_err(|e| {
            path.error(DecodeErrorKind::MalformedXml {
                reason: e.to_string(),
            })
        })?;
    if namespace_declaration(key, &value, path)? {
        return Ok(None);
    }
    match reader.resolver().resolve_attribute(QName(key)).0 {
        ResolveResult::Unbound => {}
        ResolveResult::Bound(Namespace(bound)) if bound == FHIR_NAMESPACE => {}
        ResolveResult::Bound(_) | ResolveResult::Unknown(_) => {
            return path.with(&local_name(key), |path| {
                Err(path.error(DecodeErrorKind::UnknownProperty))
            });
        }
    }
    Ok(Some((local_name(key), value.into_owned())))
}

/// Whether the attribute `key` with the unescaped `value` is a namespace
/// declaration, refusing a declaration of the XML Schema instance namespace
/// as [`DecodeErrorKind::UnknownProperty`] at `key` (R4 xml.html §2.6.1.1).
fn namespace_declaration(key: &str, value: &str, path: &mut Path) -> Result<bool, DecodeError> {
    if key != "xmlns" && !key.starts_with("xmlns:") {
        return Ok(false);
    }
    if value == XML_SCHEMA_INSTANCE_NAMESPACE {
        return path.with(
            key,
            |path| Err(path.error(DecodeErrorKind::UnknownProperty)),
        );
    }
    Ok(true)
}

fn read_complex(
    schemas: &Schemas,
    reader: &mut NsReader<&[u8]>,
    schema: &TypeSchema,
    start: &BytesStart<'_>,
    empty: bool,
    path: &mut Path,
) -> Result<Object, DecodeError> {
    let mut object = Object::new();
    for attr in start.attributes() {
        let Some((key, value)) = attribute(reader, attr, path)? else {
            continue;
        };
        let known = schema
            .fields
            .iter()
            .any(|f| f.kind == Kind::Attribute && f.name == key);
        if !known {
            return path.with(&key, |path| {
                Err(path.error(DecodeErrorKind::UnknownProperty))
            });
        }
        object.insert(key, Value::String(value));
    }
    if empty {
        return Ok(object);
    }
    let mut collector = Collector::default();
    loop {
        let event = reader.read_event().map_err(|e| {
            path.error(DecodeErrorKind::MalformedXml {
                reason: e.to_string(),
            })
        })?;
        match event {
            Event::End(_) => break,
            Event::Eof => {
                return Err(path.error(DecodeErrorKind::MalformedXml {
                    reason: String::from("the document ends inside an element"),
                }));
            }
            Event::Comment(_) | Event::PI(_) => {}
            Event::Start(child) => {
                let child = child.into_owned();
                read_child(schemas, reader, schema, &child, false, path, &mut collector)?;
            }
            Event::Empty(child) => {
                let child = child.into_owned();
                read_child(schemas, reader, schema, &child, true, path, &mut collector)?;
            }
            _ => return Err(path.error(DecodeErrorKind::UnexpectedText)),
        }
    }
    collector.finish(schema, &mut object, path)?;
    Ok(object)
}

/// The children read so far, by element name, in arrival order.
#[derive(Default)]
struct Collector {
    /// Complex, resource, and XHTML values by name.
    values: Vec<(String, Value)>,
    /// Primitive positions by name: the value and the element object.
    primitives: Vec<(String, Option<Value>, Option<Value>)>,
}

impl Collector {
    fn finish(
        self,
        schema: &TypeSchema,
        object: &mut Object,
        path: &mut Path,
    ) -> Result<(), DecodeError> {
        Self::place_values(self.values, schema, object, path)?;
        Self::place_primitives(self.primitives, schema, object, path)?;
        drop_null_arrays(object);
        Ok(())
    }

    /// Places the complex and resource children, one key per element name.
    fn place_values(
        values: Vec<(String, Value)>,
        schema: &TypeSchema,
        object: &mut Object,
        path: &mut Path,
    ) -> Result<(), DecodeError> {
        for (name, value) in values {
            let many = field_of(schema, &name).is_some_and(|(f, _, _)| f.many);
            match object.get_mut(&name) {
                None if many => {
                    object.insert(name, Value::Array(vec![value]));
                }
                None => {
                    object.insert(name, value);
                }
                Some(Value::Array(items)) if many => items.push(value),
                Some(_) => {
                    return path.with(&name, |path| {
                        Err(path.error(DecodeErrorKind::WrongCardinality))
                    });
                }
            }
        }
        Ok(())
    }

    /// Places the primitive children: the value under its name, the id and
    /// extensions under `_name`.
    fn place_primitives(
        primitives: Vec<(String, Option<Value>, Option<Value>)>,
        schema: &TypeSchema,
        object: &mut Object,
        path: &mut Path,
    ) -> Result<(), DecodeError> {
        let mut seen: Vec<String> = Vec::new();
        for (name, value, element) in primitives {
            let many = field_of(schema, &name).is_some_and(|(f, _, _)| f.many);
            if many {
                push_primitive(object, &name, value, element, path)?;
                continue;
            }
            if seen.contains(&name) {
                return path.with(&name, |path| {
                    Err(path.error(DecodeErrorKind::WrongCardinality))
                });
            }
            seen.push(name.clone());
            let element_key = format!("_{name}");
            if let Some(value) = value {
                object.insert(name, value);
            }
            if let Some(element) = element {
                object.insert(element_key, element);
            }
        }
        Ok(())
    }
}

/// Appends one occurrence of a repeating primitive to both its arrays, so the
/// value and its `_name` element stay at the same position.
fn push_primitive(
    object: &mut Object,
    name: &str,
    value: Option<Value>,
    element: Option<Value>,
    path: &mut Path,
) -> Result<(), DecodeError> {
    let wrong = |path: &mut Path| {
        path.with(name, |path| {
            Err(path.error(DecodeErrorKind::WrongCardinality))
        })
    };
    match object
        .entry(name.to_owned())
        .or_insert_with(|| Value::Array(Vec::new()))
    {
        Value::Array(values) => values.push(value.unwrap_or(Value::Null)),
        _ => return wrong(path),
    }
    match object
        .entry(format!("_{name}"))
        .or_insert_with(|| Value::Array(Vec::new()))
    {
        Value::Array(elements) => elements.push(element.unwrap_or(Value::Null)),
        _ => return wrong(path),
    }
    Ok(())
}

/// Drops the arrays a repeating primitive left all null.
///
/// A repeating primitive without any value keeps only its `_name` array, and
/// without any element only its values
/// (<https://hl7.org/fhir/R4B/json.html#primitive>).
fn drop_null_arrays(object: &mut Object) {
    let names: Vec<String> = object
        .keys()
        .filter(|k| k.starts_with('_'))
        .cloned()
        .collect();
    for element_key in names {
        let all_null = |v: &Value| v.as_array().is_some_and(|a| a.iter().all(Value::is_null));
        if object.get(&element_key).is_some_and(all_null) {
            object.remove(&element_key);
        }
        let name = element_key.trim_start_matches('_').to_owned();
        if object.get(&name).is_some_and(all_null) {
            object.remove(&name);
        }
    }
}

/// The field a child element belongs to, with the JSON key and the kind of
/// the form it arrived in (a choice's variant).
fn field_of(schema: &TypeSchema, name: &str) -> Option<(&'static FieldSchema, String, Kind)> {
    for field in schema.fields {
        match field.kind {
            Kind::Attribute => {}
            Kind::Choice(variants) => {
                for (suffix, kind) in variants {
                    let key = format!("{}{suffix}", field.name);
                    if key == name {
                        return Some((field, key, *kind));
                    }
                }
            }
            kind if field.name == name => return Some((field, name.to_owned(), kind)),
            _ => {}
        }
    }
    None
}

fn read_child(
    schemas: &Schemas,
    reader: &mut NsReader<&[u8]>,
    schema: &TypeSchema,
    child: &BytesStart<'static>,
    empty: bool,
    path: &mut Path,
    collector: &mut Collector,
) -> Result<(), DecodeError> {
    let name = local_name(child.name().as_ref());
    // NOTE: R4 xml.html §2.6.1: "FHIR elements are always in the namespace
    // http://hl7.org/fhir"; the narrative `div` is XHTML and `read_xhtml` reads it.
    let field = field_of(schema, &name)
        .filter(|(_, _, kind)| *kind == Kind::Xhtml || in_namespace(reader, child, FHIR_NAMESPACE));
    let Some((_, key, kind)) = field else {
        return path.with(&name, |path| {
            Err(path.error(DecodeErrorKind::UnknownElement))
        });
    };
    path.with(&key, |path| match kind {
        Kind::Attribute | Kind::Choice(_) => Err(path.error(DecodeErrorKind::UnknownElement)),
        Kind::Primitive(value_kind) => {
            let (value, element) = read_primitive(schemas, reader, child, empty, value_kind, path)?;
            collector.primitives.push((key.clone(), value, element));
            Ok(())
        }
        Kind::Complex(type_name) => {
            let nested = schemas
                .type_named(type_name)
                .ok_or_else(|| path.error(DecodeErrorKind::UnknownElement))?;
            let value = read_complex(schemas, reader, nested, child, empty, path)?;
            collector.values.push((key.clone(), Value::Object(value)));
            Ok(())
        }
        Kind::Resource => {
            let value = read_wrapped_resource(schemas, reader, empty, path)?;
            collector.values.push((key.clone(), Value::Object(value)));
            Ok(())
        }
        Kind::Xhtml => {
            let raw = read_xhtml(reader, child, empty, path)?;
            collector.values.push((key.clone(), Value::String(raw)));
            Ok(())
        }
    })
}

fn read_primitive(
    schemas: &Schemas,
    reader: &mut NsReader<&[u8]>,
    start: &BytesStart<'_>,
    empty: bool,
    kind: ValueKind,
    path: &mut Path,
) -> Result<(Option<Value>, Option<Value>), DecodeError> {
    let mut value = None;
    let mut element = Object::new();
    for attr in start.attributes() {
        let Some((key, text)) = attribute(reader, attr, path)? else {
            continue;
        };
        match key.as_str() {
            "value" => value = Some(primitive_value(kind, &text, path)?),
            "id" => {
                element.insert(String::from("id"), Value::String(text));
            }
            other => {
                return path.with(other, |path| {
                    Err(path.error(DecodeErrorKind::UnknownProperty))
                });
            }
        }
    }
    if !empty {
        let schema = schemas
            .type_named("Extension")
            .ok_or_else(|| path.error(DecodeErrorKind::UnknownElement))?;
        let mut extensions = Vec::new();
        loop {
            let event = reader.read_event().map_err(|e| {
                path.error(DecodeErrorKind::MalformedXml {
                    reason: e.to_string(),
                })
            })?;
            match event {
                Event::End(_) => break,
                Event::Comment(_) | Event::PI(_) => {}
                Event::Start(child) => {
                    let child = child.into_owned();
                    let extension = read_extension(
                        schemas,
                        reader,
                        schema,
                        &child,
                        false,
                        path,
                        extensions.len(),
                    )?;
                    extensions.push(Value::Object(extension));
                }
                Event::Empty(child) => {
                    let child = child.into_owned();
                    let extension = read_extension(
                        schemas,
                        reader,
                        schema,
                        &child,
                        true,
                        path,
                        extensions.len(),
                    )?;
                    extensions.push(Value::Object(extension));
                }
                Event::Eof => {
                    return Err(path.error(DecodeErrorKind::MalformedXml {
                        reason: String::from("the document ends inside an element"),
                    }));
                }
                _ => return Err(path.error(DecodeErrorKind::UnexpectedText)),
            }
        }
        if !extensions.is_empty() {
            element.insert(String::from("extension"), Value::Array(extensions));
        }
    }
    if value.is_none() && element.is_empty() {
        return Err(path.error(DecodeErrorKind::Empty));
    }
    Ok((
        value,
        (!element.is_empty()).then_some(Value::Object(element)),
    ))
}

/// Reads one `extension` child of a primitive element.
fn read_extension(
    schemas: &Schemas,
    reader: &mut NsReader<&[u8]>,
    schema: &TypeSchema,
    child: &BytesStart<'static>,
    empty: bool,
    path: &mut Path,
    index: usize,
) -> Result<Object, DecodeError> {
    let name = local_name(child.name().as_ref());
    if name != "extension" || !in_namespace(reader, child, FHIR_NAMESPACE) {
        return path.with(&name, |path| {
            Err(path.error(DecodeErrorKind::UnknownElement))
        });
    }
    path.with_index("extension", index, |path| {
        read_complex(schemas, reader, schema, child, empty, path)
    })
}

fn primitive_value(kind: ValueKind, text: &str, path: &Path) -> Result<Value, DecodeError> {
    match kind {
        ValueKind::Boolean => match text {
            "true" => Ok(Value::Bool(true)),
            "false" => Ok(Value::Bool(false)),
            _ => Err(path.error(DecodeErrorKind::BadValue)),
        },
        ValueKind::Integer => text
            .parse::<i64>()
            .map(|i| Value::Number(Number::from(i)))
            .map_err(|_| path.error(DecodeErrorKind::BadValue)),
        ValueKind::Decimal => text
            .parse::<Number>()
            .map(Value::Number)
            .map_err(|_| path.error(DecodeErrorKind::BadValue)),
        ValueKind::Text => Ok(Value::String(text.to_owned())),
    }
}

/// Reads the one resource inside a wrapper element such as `contained`.
fn read_wrapped_resource(
    schemas: &Schemas,
    reader: &mut NsReader<&[u8]>,
    empty: bool,
    path: &mut Path,
) -> Result<Object, DecodeError> {
    if empty {
        return Err(path.error(DecodeErrorKind::Empty));
    }
    let mut resource = None;
    loop {
        let event = reader.read_event().map_err(|e| {
            path.error(DecodeErrorKind::MalformedXml {
                reason: e.to_string(),
            })
        })?;
        match event {
            Event::End(_) => break,
            Event::Comment(_) | Event::PI(_) => {}
            Event::Start(inner) => {
                let inner = inner.into_owned();
                if resource.is_some() {
                    return Err(path.error(DecodeErrorKind::WrongCardinality));
                }
                resource = Some(read_resource(schemas, reader, &inner, false, path)?);
            }
            Event::Empty(inner) => {
                let inner = inner.into_owned();
                if resource.is_some() {
                    return Err(path.error(DecodeErrorKind::WrongCardinality));
                }
                resource = Some(read_resource(schemas, reader, &inner, true, path)?);
            }
            Event::Eof => {
                return Err(path.error(DecodeErrorKind::MalformedXml {
                    reason: String::from("the document ends inside an element"),
                }));
            }
            _ => return Err(path.error(DecodeErrorKind::UnexpectedText)),
        }
    }
    resource.ok_or_else(|| path.error(DecodeErrorKind::Empty))
}

/// Reads the narrative `div` as the self-contained XHTML string FHIR JSON
/// carries.
///
/// The JSON form is "a single escaped string of XHTML" whose root "needs to be
/// a `<div>` in the xhtml namespace" (R4 json.html §2.6.2.1 and §2.6.2.4,
/// <https://hl7.org/fhir/R4/json.html>), and the characters between its first
/// `>` and last `<` are the content a browser takes as `innerHTML` (R4
/// narrative.html §2.4.0, <https://hl7.org/fhir/R4/narrative.html#xhtml>).
/// The string is therefore written in the default-namespace form the R4 JSON
/// example shows, `<div xmlns="http://www.w3.org/1999/xhtml">`: every element
/// loses its prefix, every prefixed namespace declaration is dropped, and the
/// root declares the XHTML namespace when the source declared it on an
/// ancestor. Each attribute value keeps its escaped source text and is written
/// in double quotes, with a `"` it held escaped as `&quot;` (XML 1.0 §2.3
/// `AttValue`, §4.6, <https://www.w3.org/TR/xml/#NT-AttValue>). Text,
/// references, CDATA sections and comments are copied verbatim.
///
/// An element outside the XHTML namespace, the `div` or any element inside
/// it, is refused as [`DecodeErrorKind::UnknownElement`]: "the only other
/// namespace that occurs in FHIR resources is the XHTML namespace" (R4 xml.html
/// §2.6.1), and the narrative is "a root `<div>` element in the xhtml
/// namespace" (R5 xml.html §2.1.6.3.3). A prefixed attribute other than one in
/// the `xml` namespace is refused as [`DecodeErrorKind::UnknownProperty`] for
/// the same reason. A declaration of the XML Schema instance namespace on any
/// of these elements is refused as in the rest of the resource (R4 xml.html
/// §2.6.1.1).
fn read_xhtml(
    reader: &mut NsReader<&[u8]>,
    start: &BytesStart<'_>,
    empty: bool,
    path: &mut Path,
) -> Result<String, DecodeError> {
    let mut raw = String::new();
    write_xhtml_tag(reader, start, true, empty, &mut raw, path)?;
    if empty {
        return Ok(raw);
    }
    // NOTE: R4 narrative.html §2.4.0: the content is the characters between
    // the first `>` and the last `<`, so its whitespace is carried untrimmed.
    reader.config_mut().trim_text(false);
    let copied = copy_xhtml_content(reader, &mut raw, path);
    reader.config_mut().trim_text(true);
    copied.map(|()| raw)
}

/// Copies the content of the XHTML element whose start tag `raw` holds, up to
/// and including its end tag.
fn copy_xhtml_content(
    reader: &mut NsReader<&[u8]>,
    raw: &mut String,
    path: &mut Path,
) -> Result<(), DecodeError> {
    let mut depth: usize = 1;
    loop {
        let event = reader.read_event().map_err(|e| {
            path.error(DecodeErrorKind::MalformedXml {
                reason: e.to_string(),
            })
        })?;
        match event {
            Event::Start(element) => {
                write_xhtml_tag(reader, &element, false, false, raw, path)?;
                depth = depth.saturating_add(1);
            }
            Event::Empty(element) => write_xhtml_tag(reader, &element, false, true, raw, path)?,
            Event::End(element) => {
                raw.push_str("</");
                raw.push_str(&local_name(element.name().as_ref()));
                raw.push('>');
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return Ok(());
                }
            }
            Event::Text(text) => raw.push_str(&text),
            Event::GeneralRef(reference) => {
                raw.push('&');
                raw.push_str(&reference);
                raw.push(';');
            }
            Event::CData(data) => {
                raw.push_str("<![CDATA[");
                raw.push_str(&data);
                raw.push_str("]]>");
            }
            Event::Comment(comment) => {
                raw.push_str("<!--");
                raw.push_str(&comment);
                raw.push_str("-->");
            }
            Event::PI(instruction) => {
                raw.push_str("<?");
                raw.push_str(&instruction);
                raw.push_str("?>");
            }
            Event::Decl(_) | Event::DocType(_) => {
                return Err(path.error(DecodeErrorKind::UnexpectedText));
            }
            Event::Eof => {
                return Err(path.error(DecodeErrorKind::MalformedXml {
                    reason: String::from("the document ends inside an element"),
                }));
            }
        }
    }
}

/// Writes the start tag of `element`, an XHTML element the reader has just
/// read, in the default-namespace form [`read_xhtml`] describes.
fn write_xhtml_tag(
    reader: &NsReader<&[u8]>,
    element: &BytesStart<'_>,
    root: bool,
    empty: bool,
    raw: &mut String,
    path: &mut Path,
) -> Result<(), DecodeError> {
    let mut attributes = Vec::new();
    for attr in element.attributes() {
        let attr = attr.map_err(|e| {
            path.error(DecodeErrorKind::MalformedXml {
                reason: e.to_string(),
            })
        })?;
        refuse_schema_instance(&attr, path)?;
        attributes.push(attr);
    }
    if !in_namespace(reader, element, XHTML_NAMESPACE) {
        return Err(path.error(DecodeErrorKind::UnknownElement));
    }
    let mut tag = String::new();
    let mut declared = false;
    for attr in &attributes {
        let key = attr.key.as_ref();
        if key == "xmlns" {
            if attribute_value(attr, path)? != XHTML_NAMESPACE {
                continue;
            }
            declared = true;
        } else if key.starts_with("xmlns:") {
            continue;
        } else if key.contains(':') && !key.starts_with("xml:") {
            return path.with(
                key,
                |path| Err(path.error(DecodeErrorKind::UnknownProperty)),
            );
        }
        tag.push(' ');
        tag.push_str(key);
        tag.push_str("=\"");
        tag.push_str(&attr.value.replace('"', "&quot;"));
        tag.push('"');
    }
    raw.push('<');
    raw.push_str(&local_name(element.name().as_ref()));
    if root && !declared {
        raw.push_str(" xmlns=\"");
        raw.push_str(XHTML_NAMESPACE);
        raw.push('"');
    }
    raw.push_str(&tag);
    raw.push_str(if empty { "/>" } else { ">" });
    Ok(())
}

/// The unescaped, normalized value of `attribute`.
fn attribute_value<'a>(
    attribute: &'a Attribute<'_>,
    path: &Path,
) -> Result<Cow<'a, str>, DecodeError> {
    attribute
        .normalized_value(XmlVersion::Explicit1_0)
        .map_err(|e| {
            path.error(DecodeErrorKind::MalformedXml {
                reason: e.to_string(),
            })
        })
}

/// Refuses `attribute` when it declares the XML Schema instance namespace.
fn refuse_schema_instance(attribute: &Attribute<'_>, path: &mut Path) -> Result<(), DecodeError> {
    let value = attribute_value(attribute, path)?;
    namespace_declaration(attribute.key.as_ref(), &value, path).map(drop)
}