fhir 1.2.0

Fast Healthcare Interoperability Resources (FHIR) data model for Rust: the complete FHIR R5, R4, and R3 resources, datatypes, and code systems as serde-serializable types, plus a spec-driven code generator.
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
//! Rendering a [`TypePlan`] as Rust source.
//!
//! Everything here is text assembly: the decisions were already made in
//! [`super::plan`]. The output must match `AGENTS/conventions.md` exactly — the
//! same derives in the same order, `skip_serializing_none`, camelCase renaming,
//! `Vec` defaults, primitive-extension siblings, and a round-trip doctest — so
//! that a generated release module is indistinguishable in style from the
//! hand-tended one.

use std::fmt::Write as _;

use super::naming;
use super::plan::{ChoicePlan, FieldPlan, StructPlan, TypePlan, Wrapper};
use super::version::Version;

/// The derives every model struct carries, in the mandated order.
const STRUCT_DERIVES: &str = "Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq, Validate";

/// The same, for a struct that cannot have a default (it has a `1..*` field).
const STRUCT_DERIVES_NO_DEFAULT: &str = "Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate";

/// Render the complete Rust module for one datatype or resource.
#[must_use]
pub fn render_type(plan: &TypePlan, version: Version) -> String {
    let mut out = String::new();
    out.push_str(&module_header(plan, version));
    out.push_str(&imports(plan, version));

    for structure in &plan.structs {
        out.push('\n');
        out.push_str(&render_struct(structure, plan, version));
    }

    for choice in &plan.choices {
        out.push('\n');
        out.push_str(&render_choice(choice, version));
    }

    if let Some(root) = plan.structs.first()
        && root.has_default
    {
        out.push('\n');
        out.push_str(&render_tests(&root.name));
    }
    out
}

/// The `//!` module header: the FHIR name, canonical URL, version, summary, and
/// a link to the published specification.
fn module_header(plan: &TypePlan, version: Version) -> String {
    let mut out = format!("//! {}\n//!\n", plan.type_name);
    let _ = write!(out, "//! URL: {}\n//!\n", plan.url);
    let _ = write!(out, "//! Version: {}\n//!\n", plan.version);
    if !plan.short.is_empty() {
        out.push_str(&naming::module_doc_comment(&plan.short));
        out.push_str("//!\n");
    }
    let _ = writeln!(out, "//! FHIR {}: <{}>", version.label(), version.spec_url());
    out
}

/// The `use` block. Generated modules import their release's datatypes as
/// `types`, so every rendered type name is release-agnostic.
fn imports(plan: &TypePlan, version: Version) -> String {
    let module = version.module();
    let derives = if plan.structs.iter().any(|s| s.is_root) {
        "use fhir_derive_macros::{Builder, Validate};\n"
    } else {
        "use fhir_derive_macros::Validate;\n"
    };
    format!(
        "\n// The `types` import is unused by a handful of types that have only \
         primitive fields.\n#![allow(unused_imports)]\n\n\
         use crate::{module}::types;\n\
         use ::serde::{{Deserialize, Serialize}};\n{derives}"
    )
}

/// Render one struct: the type's root, or one of its backbone elements.
fn render_struct(structure: &StructPlan, plan: &TypePlan, version: Version) -> String {
    let mut out = String::new();

    let doc = if structure.is_root && !plan.description.is_empty() {
        &plan.description
    } else {
        &structure.doc
    };
    out.push_str(&naming::doc_comment(doc, ""));
    out.push_str(&example_doctest(&structure.name, plan, version, structure.has_default));

    out.push_str("#[serde_with::skip_serializing_none]\n");
    let derives = if structure.has_default { STRUCT_DERIVES } else { STRUCT_DERIVES_NO_DEFAULT };
    let builder = if structure.is_root { ", Builder" } else { "" };
    let _ = writeln!(out, "#[derive({derives}{builder})]");
    out.push_str("#[serde(rename_all = \"camelCase\")]\n");
    out.push_str(&version_attribute(version));
    let _ = writeln!(out, "pub struct {} {{", structure.name);

    for (index, field) in structure.fields.iter().enumerate() {
        if index > 0 {
            out.push('\n');
        }
        out.push_str(&render_field(field));
    }

    out.push_str("}\n");
    out
}

/// The `# Examples` doctest that round-trips a default value.
///
/// A type with a `1..*` field has no default, so its example is `ignore`d
/// rather than dropped: the import line still documents where the type lives.
fn example_doctest(
    name: &str,
    plan: &TypePlan,
    version: Version,
    has_default: bool,
) -> String {
    let module = version.module();
    let group = if plan.is_resource { "resources" } else { "types" };
    let fence = if has_default { "```" } else { "```ignore" };
    format!(
        "///\n\
         /// # Examples\n\
         ///\n\
         /// {fence}\n\
         /// use fhir::{module}::{group}::{}::{name};\n\
         ///\n\
         /// let value = {name}::default();\n\
         /// let json = ::serde_json::to_value(&value).unwrap();\n\
         /// let back: {name} = ::serde_json::from_value(json).unwrap();\n\
         /// assert_eq!(value, back);\n\
         /// ```\n",
        plan.module,
    )
}

/// The `#[fhir_version(…)]` selector the derive macros read.
///
/// R5 is the macros' default, so only other releases need to say so.
#[must_use]
pub fn version_attribute(version: Version) -> String {
    match version {
        Version::R5 => String::new(),
        other => format!("#[fhir_version(\"{}\")]\n", other.module()),
    }
}

/// Render one field, plus its primitive-extension sibling when it has one.
fn render_field(field: &FieldPlan) -> String {
    let mut out = String::new();
    out.push_str(&naming::doc_comment(&field.doc, "    "));

    if let Some(choice) = &field.choice {
        // A choice enum's variants carry the FHIR keys, so it is flattened onto
        // the parent object rather than nested under the field name.
        let cardinality = if field.min >= 1 {
            format!(
                "    /// The `{}` choice element ({}..{}); see [`{choice}`]. It is \
                 `Option` even though the specification makes it mandatory, because \
                 a choice enum has no default.\n",
                field.path, field.min, field.max
            )
        } else {
            format!(
                "    /// The `{}` choice element ({}..{}); see [`{choice}`].\n",
                field.path, field.min, field.max
            )
        };
        out.push_str(&cardinality);
        out.push_str("    #[serde(flatten)]\n");
        let _ = writeln!(out, "    pub {}: Option<{choice}>,", field.ident);
        return out;
    }

    let inner = if field.boxed {
        format!("Box<{}>", field.inner_type)
    } else {
        field.inner_type.clone()
    };

    // `rename_all = "camelCase"` covers almost every field, but it cannot
    // reproduce a name with consecutive capitals such as `truthTP`, so those
    // spell their key out.
    if naming::needs_explicit_rename(&field.ident, &field.wire) {
        let _ = writeln!(out, "    #[serde(rename = {:?})]", field.wire);
    }

    match field.wrapper {
        Wrapper::Option => {
            let _ = writeln!(out, "    pub {}: Option<{inner}>,", field.ident);
        }
        Wrapper::Required => {
            let _ = writeln!(out, "    pub {}: {inner},", field.ident);
        }
        Wrapper::Vec => {
            out.push_str("    #[serde(default, skip_serializing_if = \"Vec::is_empty\")]\n");
            let _ = writeln!(out, "    pub {}: Vec<{inner}>,", field.ident);
        }
        Wrapper::Vec1 => {
            let _ = writeln!(out, "    pub {}: ::vec1::Vec1<{inner}>,", field.ident);
        }
    }

    if let Some(sibling) = &field.sibling {
        let _ = write!(
            out,
            "    /// Primitive extension sibling for [`{}`](Self::{}) (FHIR `{}`):\n\
             \x20   /// carries `id` and/or `extension` for the primitive value.\n\
             \x20   #[serde(rename = \"{}\")]\n",
            field.ident, field.ident, sibling.wire, sibling.wire,
        );
        if sibling.is_multiple {
            out.push_str("    #[serde(default, skip_serializing_if = \"Vec::is_empty\")]\n");
            let _ = writeln!(out, "    pub {}: Vec<Option<types::Element>>,", sibling.ident);
        } else {
            let _ = writeln!(out, "    pub {}: Option<types::Element>,", sibling.ident);
        }
    }

    out
}

/// Render one `value[x]` choice enum.
fn render_choice(choice: &ChoicePlan, version: Version) -> String {
    let mut out = String::new();
    let _ = writeln!(
        out,
        "/// The `{}` choice element (see `spec/11-choice-types.md`).",
        choice.path
    );
    out.push_str(
        "#[derive(Debug, Clone, PartialEq, Eq, fhir_derive_macros::FhirChoice, Validate)]\n",
    );
    out.push_str(&version_attribute(version));
    // The variants hold datatypes of very different sizes; boxing every one of
    // them would cost an allocation on the common small variants.
    out.push_str("#[allow(clippy::large_enum_variant)]\n");
    let _ = writeln!(out, "pub enum {} {{", choice.name);
    for variant in &choice.variants {
        let _ = writeln!(out, "    /// `{}` variant.", variant.key);
        let _ = writeln!(out, "    #[fhir(\"{}\")]", variant.key);
        let _ = writeln!(out, "    {}({}),", variant.name, variant.payload);
    }
    out.push_str("}\n");
    out
}

/// The per-module unit tests: a default value, and a JSON round trip.
fn render_tests(name: &str) -> String {
    format!(
        "#[cfg(test)]\n\
         mod tests {{\n\
         \x20   use super::*;\n\
         \x20   type T = {name};\n\
         \n\
         \x20   #[test]\n\
         \x20   fn test_default() {{\n\
         \x20       let _ = T::default();\n\
         \x20   }}\n\
         \n\
         \x20   #[test]\n\
         \x20   fn test_serde_round_trip() {{\n\
         \x20       let value = T::default();\n\
         \x20       let json = ::serde_json::to_value(&value).expect(\"to_value\");\n\
         \x20       let back: T = ::serde_json::from_value(json).expect(\"from_value\");\n\
         \x20       assert_eq!(value, back);\n\
         \x20   }}\n\
         }}\n"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codegen::plan::{plan_type, Context};
    use crate::codegen::spec::StructureDefinition;

    fn ctx() -> Context {
        Context {
            primitives: ["string", "boolean", "dateTime"].into_iter().map(str::to_string).collect(),
            code_enums: std::collections::BTreeSet::new(),
            module: "r4".to_string(),
        }
    }

    fn sample_plan() -> TypePlan {
        let sd: StructureDefinition = ::serde_json::from_value(::serde_json::json!({
            "name": "Sample", "type": "Sample", "kind": "resource",
            "url": "http://example.org/Sample", "version": "4.0.1",
            "description": "A sample resource.",
            "snapshot": { "element": [
                { "path": "Sample", "short": "A sample" },
                { "path": "Sample.note", "min": 0, "max": "1", "short": "A note",
                  "type": [{ "code": "string" }] },
                { "path": "Sample.tag", "min": 0, "max": "*", "short": "Tags",
                  "type": [{ "code": "CodeableConcept" }] },
                { "path": "Sample.value[x]", "min": 0, "max": "1", "short": "The value",
                  "type": [{ "code": "Quantity" }, { "code": "string" }] },
            ]}
        }))
        .unwrap();
        plan_type(&sd, &ctx()).unwrap()
    }

    #[test]
    fn header_names_the_release() {
        let out = render_type(&sample_plan(), Version::R4);
        assert!(out.starts_with("//! Sample\n"));
        assert!(out.contains("//! URL: http://example.org/Sample"));
        assert!(out.contains("//! Version: 4.0.1"));
        assert!(out.contains("//! FHIR R4: <https://hl7.org/fhir/R4/>"));
        assert!(out.contains("use crate::r4::types;"));
    }

    #[test]
    fn struct_follows_the_conventions() {
        let out = render_type(&sample_plan(), Version::R4);
        assert!(out.contains("#[serde_with::skip_serializing_none]\n"));
        assert!(out.contains(
            "#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq, Validate, Builder)]"
        ));
        assert!(out.contains("#[serde(rename_all = \"camelCase\")]"));
        assert!(out.contains("#[fhir_version(\"r4\")]"));
        assert!(out.contains("pub struct Sample {"));
    }

    #[test]
    fn cardinality_and_siblings_render() {
        let out = render_type(&sample_plan(), Version::R4);
        assert!(out.contains("pub note: Option<types::String>,"));
        // A repeating field defaults to empty and is skipped when empty.
        assert!(out.contains("#[serde(default, skip_serializing_if = \"Vec::is_empty\")]"));
        assert!(out.contains("pub tag: Vec<types::CodeableConcept>,"));
        // A primitive field carries its `_note` extension sibling.
        assert!(out.contains("#[serde(rename = \"_note\")]"));
        assert!(out.contains("pub note_ext: Option<types::Element>,"));
    }

    #[test]
    fn names_camel_case_cannot_reproduce_are_renamed() {
        let sd: StructureDefinition = ::serde_json::from_value(::serde_json::json!({
            "name": "Sample", "type": "Sample", "kind": "resource",
            "url": "u", "version": "4.0.1",
            "snapshot": { "element": [
                { "path": "Sample" },
                { "path": "Sample.truthTP", "min": 0, "max": "1",
                  "type": [{ "code": "string" }] },
                { "path": "Sample.plainName", "min": 0, "max": "1",
                  "type": [{ "code": "string" }] },
            ]}
        }))
        .unwrap();
        let out = render_type(&plan_type(&sd, &ctx()).unwrap(), Version::R4);
        assert!(out.contains("#[serde(rename = \"truthTP\")]"));
        assert!(out.contains("pub truth_tp: Option<types::String>,"));
        // Its extension sibling keeps the original spelling too.
        assert!(out.contains("#[serde(rename = \"_truthTP\")]"));
        // An ordinary name is left to `rename_all`.
        assert!(!out.contains("#[serde(rename = \"plainName\")]"));
    }

    #[test]
    fn choice_field_is_flattened_and_enum_is_emitted() {
        let out = render_type(&sample_plan(), Version::R4);
        assert!(out.contains("#[serde(flatten)]"));
        assert!(out.contains("pub value: Option<SampleValue>,"));
        assert!(out.contains("pub enum SampleValue {"));
        assert!(out.contains("#[fhir(\"valueQuantity\")]"));
        assert!(out.contains("Quantity(Box<types::Quantity>),"));
        assert!(out.contains("String(crate::r4::choice::Primitive<types::String>),"));
    }

    #[test]
    fn r5_needs_no_version_attribute() {
        let out = render_type(&sample_plan(), Version::R5);
        assert!(!out.contains("#[fhir_version"));
        assert!(out.contains("use crate::r5::types;"));
    }

    #[test]
    fn tests_and_doctest_are_emitted_for_defaultable_types() {
        let out = render_type(&sample_plan(), Version::R4);
        assert!(out.contains("fn test_serde_round_trip()"));
        assert!(out.contains("/// use fhir::r4::resources::sample::Sample;"));
        assert!(!out.contains("```ignore"));
    }

    #[test]
    fn types_without_a_default_skip_the_tests() {
        let sd: StructureDefinition = ::serde_json::from_value(::serde_json::json!({
            "name": "Sample", "type": "Sample", "kind": "resource",
            "url": "u", "version": "4.0.1",
            "snapshot": { "element": [
                { "path": "Sample" },
                { "path": "Sample.item", "min": 1, "max": "*",
                  "type": [{ "code": "CodeableConcept" }] },
            ]}
        }))
        .unwrap();
        let plan = plan_type(&sd, &ctx()).unwrap();
        let out = render_type(&plan, Version::R4);
        assert!(out.contains("pub item: ::vec1::Vec1<types::CodeableConcept>,"));
        assert!(out.contains("#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate, Builder)]"));
        assert!(out.contains("```ignore"));
        assert!(!out.contains("mod tests"));
    }
}