rh-codegen 0.2.1

Code generation library for creating Rust types from FHIR StructureDefinitions
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
//! Metadata generation for FHIR types
//!
//! This module generates metadata module files containing type information for all FHIR resources
//! and datatypes. The metadata is split by category (resources, datatypes, primitives, profiles)
//! to improve incremental compile times.
//!
//! This metadata enables runtime path resolution like "Patient.name.given" -> string.

use crate::fhir_types::{ElementDefinition, StructureDefinition};
use crate::metadata::{
    FhirFieldType, FhirPrimitiveType, FieldInfo, MetadataRegistry, TypeMetadata,
};
use std::collections::HashMap;

/// Category for partitioning metadata types into separate files
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MetadataCategory {
    Resources,
    Datatypes,
    Primitives,
    Profiles,
    Other,
}

impl MetadataCategory {
    fn module_name(self) -> &'static str {
        match self {
            Self::Resources => "resources",
            Self::Datatypes => "datatypes",
            Self::Primitives => "primitives",
            Self::Profiles => "profiles",
            Self::Other => "other",
        }
    }

    fn doc_label(self) -> &'static str {
        match self {
            Self::Resources => "FHIR resources",
            Self::Datatypes => "FHIR datatypes",
            Self::Primitives => "FHIR primitive types",
            Self::Profiles => "FHIR profiles",
            Self::Other => "other FHIR types",
        }
    }
}

/// Classify a StructureDefinition into a metadata category
fn classify_metadata(sd: &StructureDefinition) -> MetadataCategory {
    match sd.kind.as_str() {
        "resource" => MetadataCategory::Resources,
        "complex-type" => MetadataCategory::Datatypes,
        "primitive-type" => MetadataCategory::Primitives,
        _ => MetadataCategory::Other,
    }
}

fn metadata_category_priority(category: MetadataCategory) -> u8 {
    match category {
        MetadataCategory::Primitives => 0,
        MetadataCategory::Datatypes => 1,
        MetadataCategory::Resources => 2,
        MetadataCategory::Profiles => 3,
        MetadataCategory::Other => 4,
    }
}

fn sorted_structure_definitions(
    structure_defs: &[StructureDefinition],
) -> Vec<&StructureDefinition> {
    let mut sorted_defs: Vec<_> = structure_defs.iter().collect();
    sorted_defs.sort_by(|left, right| {
        left.name
            .cmp(&right.name)
            .then_with(|| {
                metadata_category_priority(classify_metadata(left))
                    .cmp(&metadata_category_priority(classify_metadata(right)))
            })
            .then_with(|| left.url.cmp(&right.url))
            .then_with(|| left.id.cmp(&right.id))
    });
    sorted_defs
}

/// Build metadata registry from StructureDefinitions
pub fn build_metadata_registry(structure_defs: &[StructureDefinition]) -> MetadataRegistry {
    let mut registry = MetadataRegistry::new();

    for structure_def in sorted_structure_definitions(structure_defs) {
        if let Some(type_metadata) = extract_type_metadata(structure_def) {
            // Only add if not already present (avoid duplicates)
            if !registry.types.contains_key(&type_metadata.name) {
                registry.add_type(type_metadata);
            }
        }
    }

    registry
}

/// Extract metadata from a single StructureDefinition
fn extract_type_metadata(structure_def: &StructureDefinition) -> Option<TypeMetadata> {
    let type_name = structure_def.name.as_str();
    let mut fields = HashMap::new();

    // Get the snapshot elements
    let snapshot = structure_def.snapshot.as_ref()?;
    let elements = &snapshot.element;

    // Skip the first element (it's the resource itself, e.g., "Patient")
    for element in elements.iter().skip(1) {
        if let Some(field_info) = extract_field_info(element, type_name) {
            if let Some(field_name) = extract_field_name(&element.path, type_name) {
                fields.insert(field_name, field_info);
            }
        }
    }

    Some(TypeMetadata {
        name: type_name.to_string(),
        fields,
    })
}

/// Extract field name from element path (e.g., "Patient.birthDate" -> "birthDate")
fn extract_field_name(path: &str, type_name: &str) -> Option<String> {
    let prefix = format!("{type_name}.");

    if !path.starts_with(&prefix) {
        return None;
    }

    let field_path = &path[prefix.len()..];

    // Only take the immediate child field (not nested paths like "name.given")
    // We'll handle those through recursive resolution
    let field_name = field_path.split('.').next()?;

    Some(field_name.to_string())
}

/// Extract field information from an ElementDefinition
fn extract_field_info(element: &ElementDefinition, _type_name: &str) -> Option<FieldInfo> {
    let element_types = element.element_type.as_ref()?;

    if element_types.is_empty() {
        return None;
    }

    // Get cardinality
    let min = element.min.unwrap_or(0);
    let max = element.max.as_ref().and_then(|m| {
        if m == "*" {
            None
        } else {
            m.parse::<u32>().ok()
        }
    });

    // Determine if this is a choice type (has [x] suffix in name)
    let is_choice_type = element.path.contains("[x]");

    // Collect all types (for choice types)
    let choice_types: Vec<String> = element_types
        .iter()
        .filter_map(|et| et.code.clone())
        .collect();

    // Use the first type as the primary field type
    let primary_type_code = element_types[0].code.as_ref()?;
    let field_type = determine_field_type(primary_type_code);

    Some(FieldInfo {
        field_type,
        min,
        max,
        is_choice_type,
        choice_types,
    })
}

/// Determine the FhirFieldType from a FHIR type code string
fn determine_field_type(type_code: &str) -> FhirFieldType {
    // Check if it's a primitive type
    if let Some(primitive) = FhirPrimitiveType::from_fhir_type(type_code) {
        return FhirFieldType::Primitive(primitive);
    }

    // Check for Reference
    if type_code == "Reference" {
        return FhirFieldType::Reference;
    }

    // Check for BackboneElement (typically internal structures)
    if type_code == "BackboneElement" {
        return FhirFieldType::BackboneElement(type_code.to_string());
    }

    // Otherwise it's a complex type
    FhirFieldType::Complex(type_code.to_string())
}

/// Generate the metadata.rs file content
pub fn generate_metadata_code(registry: &MetadataRegistry) -> String {
    let mut code = String::new();

    // File header and imports
    code.push_str(
        r#"//! FHIR type metadata
//!
//! This module provides compile-time metadata about FHIR types, enabling
//! path resolution like "Patient.name.given" -> FhirPrimitiveType::String.
//!
//! Generated automatically - do not edit manually.

use phf::{phf_map, Map};

"#,
    );

    // Generate FhirPrimitiveType enum
    code.push_str(
        r#"/// FHIR primitive types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FhirPrimitiveType {
    Boolean,
    Integer,
    String,
    Date,
    DateTime,
    Instant,
    Time,
    Decimal,
    Uri,
    Url,
    Canonical,
    Code,
    Oid,
    Id,
    Markdown,
    Base64Binary,
    UnsignedInt,
    PositiveInt,
}

"#,
    );

    // Generate FhirFieldType enum
    code.push_str(
        r#"/// FHIR field type (primitive, complex, reference, or backbone element)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FhirFieldType {
    Primitive(FhirPrimitiveType),
    Complex(&'static str),
    Reference,
    BackboneElement(&'static str),
}

"#,
    );

    // Generate FieldInfo struct
    code.push_str(
        r#"/// Information about a field in a FHIR resource or datatype
#[derive(Debug, Clone)]
pub struct FieldInfo {
    pub field_type: FhirFieldType,
    pub min: u32,
    pub max: Option<u32>,
    pub is_choice_type: bool,
}

"#,
    );

    // Track generated const names to avoid duplicates
    let mut generated_consts = std::collections::HashSet::new();

    let mut sorted_types: Vec<_> = registry.types.iter().collect();
    sorted_types.sort_by_key(|(left_name, _)| *left_name);

    // Generate phf maps for each type (skip duplicates)
    for (type_name, type_metadata) in sorted_types {
        // Create sanitized const name
        let sanitized_name: String = type_name
            .chars()
            .map(|c| if c.is_alphanumeric() { c } else { '_' })
            .collect();
        let const_name = format!("{}_FIELDS", sanitized_name.to_uppercase());

        // Skip if already generated
        if generated_consts.contains(&const_name) {
            continue;
        }

        generate_type_map(&mut code, type_name, type_metadata);
        generated_consts.insert(const_name);
    }

    // Generate the main registry (only include types that were generated)
    generate_registry_map(&mut code, &registry.types, &generated_consts);

    // Generate helper functions
    code.push_str(
        r#"
/// Get field information for a specific field in a type
pub fn get_field_info(type_name: &str, field_name: &str) -> Option<&'static FieldInfo> {
    FHIR_TYPE_REGISTRY
        .get(type_name)
        .and_then(|fields| fields.get(field_name))
}

/// Resolve a nested path like "Patient.name.given" to its field type
pub fn resolve_path(path: &str) -> Option<&'static FhirFieldType> {
    let parts: Vec<&str> = path.split('.').collect();
    if parts.is_empty() {
        return None;
    }

    let mut current_type_name = parts[0];
    
    for (idx, &field_name) in parts[1..].iter().enumerate() {
        let field_info = get_field_info(current_type_name, field_name)?;
        
        // If this is the last field, return its type
        if idx == parts.len() - 2 {
            return Some(&field_info.field_type);
        }
        
        // Otherwise, navigate to the next type
        match &field_info.field_type {
            FhirFieldType::Complex(type_name) | FhirFieldType::BackboneElement(type_name) => {
                current_type_name = type_name;
            }
            _ => return None, // Can't navigate further
        }
    }
    
    None
}
"#,
    );

    code
}

/// Generate a phf map for a single type's fields
fn generate_type_map(code: &mut String, type_name: &str, type_metadata: &TypeMetadata) {
    // Sanitize type name to create valid Rust identifier
    // Replace any non-alphanumeric characters with underscores
    let sanitized_name: String = type_name
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '_' })
        .collect();
    let const_name = format!("{}_FIELDS", sanitized_name.to_uppercase());

    code.push_str(&format!("/// Field metadata for {type_name}\n"));
    code.push_str("#[rustfmt::skip]\n");
    code.push_str(&format!(
        "pub static {const_name}: Map<&'static str, FieldInfo> = phf_map! {{\n"
    ));

    let mut sorted_fields: Vec<_> = type_metadata.fields.iter().collect();
    sorted_fields.sort_by_key(|(left_name, _)| *left_name);

    for (field_name, field_info) in sorted_fields {
        code.push_str(&format!("    \"{field_name}\" => FieldInfo {{\n"));

        // Generate field_type
        code.push_str("        field_type: ");
        match &field_info.field_type {
            FhirFieldType::Primitive(prim) => {
                code.push_str(&format!(
                    "FhirFieldType::Primitive(FhirPrimitiveType::{})",
                    prim.variant_name()
                ));
            }
            FhirFieldType::Complex(name) => {
                code.push_str(&format!("FhirFieldType::Complex(\"{name}\")"));
            }
            FhirFieldType::Reference => {
                code.push_str("FhirFieldType::Reference");
            }
            FhirFieldType::BackboneElement(name) => {
                code.push_str(&format!("FhirFieldType::BackboneElement(\"{name}\")"));
            }
        }
        code.push_str(",\n");

        // Generate cardinality
        code.push_str(&format!("        min: {},\n", field_info.min));
        code.push_str("        max: ");
        if let Some(max) = field_info.max {
            code.push_str(&format!("Some({max})"));
        } else {
            code.push_str("None");
        }
        code.push_str(",\n");

        // Generate is_choice_type
        code.push_str(&format!(
            "        is_choice_type: {},\n",
            field_info.is_choice_type
        ));

        code.push_str("    },\n");
    }

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

/// Generate the main registry map
fn generate_registry_map(
    code: &mut String,
    types: &HashMap<String, TypeMetadata>,
    generated_consts: &std::collections::HashSet<String>,
) {
    code.push_str("/// Main FHIR type registry mapping type names to their field metadata\n");
    code.push_str(
        "pub static FHIR_TYPE_REGISTRY: Map<&'static str, &'static Map<&'static str, FieldInfo>> = phf_map! {\n",
    );

    let mut sorted_type_names: Vec<_> = types.keys().collect();
    sorted_type_names.sort();

    for type_name in sorted_type_names {
        let sanitized_name: String = type_name
            .chars()
            .map(|c| if c.is_alphanumeric() { c } else { '_' })
            .collect();
        let const_name = format!("{}_FIELDS", sanitized_name.to_uppercase());

        if generated_consts.contains(&const_name) {
            code.push_str(&format!("    \"{type_name}\" => &{const_name},\n"));
        }
    }

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

/// Generate split metadata files organized by category (resources, datatypes, primitives, profiles).
///
/// Returns a map from filename (relative to metadata dir) to file content.
/// Categories: resources.rs, datatypes.rs, primitives.rs, profiles.rs, other.rs, mod.rs
pub fn generate_metadata_code_split(
    registry: &MetadataRegistry,
    structure_defs: &[StructureDefinition],
) -> HashMap<String, String> {
    let mut files = HashMap::new();

    // Build name -> category mapping from structure definitions (first definition wins for duplicates)
    let mut name_to_category: HashMap<&str, MetadataCategory> = HashMap::new();
    for sd in sorted_structure_definitions(structure_defs) {
        name_to_category
            .entry(&sd.name)
            .or_insert_with(|| classify_metadata(sd));
    }

    // Partition types by category
    let mut categories: HashMap<MetadataCategory, Vec<(&String, &TypeMetadata)>> = HashMap::new();
    let mut sorted_registry_types: Vec<_> = registry.types.iter().collect();
    sorted_registry_types.sort_by_key(|(left_name, _)| *left_name);

    for (type_name, type_metadata) in sorted_registry_types {
        let category = name_to_category
            .get(type_name.as_str())
            .copied()
            .unwrap_or(MetadataCategory::Other);
        categories
            .entry(category)
            .or_default()
            .push((type_name, type_metadata));
    }

    // Track all generated const names across categories for the main registry
    let mut all_generated_consts = std::collections::HashSet::new();

    // Generate each category file
    let category_order = [
        MetadataCategory::Resources,
        MetadataCategory::Datatypes,
        MetadataCategory::Primitives,
        MetadataCategory::Profiles,
        MetadataCategory::Other,
    ];

    for &category in &category_order {
        let mut types = categories.get(&category).cloned().unwrap_or_default();
        types.sort_by_key(|(left_name, _)| *left_name);
        if types.is_empty() {
            continue;
        }

        let mut code = String::new();
        code.push_str(&format!(
            "//! Field metadata for {}\n\nuse phf::{{phf_map, Map}};\nuse super::*;\n\n",
            category.doc_label()
        ));

        let mut category_consts = std::collections::HashSet::new();

        for (type_name, type_metadata) in &types {
            let sanitized_name: String = type_name
                .chars()
                .map(|c| if c.is_alphanumeric() { c } else { '_' })
                .collect();
            let const_name = format!("{}_FIELDS", sanitized_name.to_uppercase());

            // Skip if already generated in a previous category (avoids ambiguous re-exports)
            if all_generated_consts.contains(&const_name) {
                continue;
            }

            if category_consts.contains(&const_name) {
                continue;
            }

            generate_type_map(&mut code, type_name, type_metadata);
            category_consts.insert(const_name.clone());
            all_generated_consts.insert(const_name);
        }

        let filename = format!("{}.rs", category.module_name());
        files.insert(filename, code);
    }

    // Generate mod.rs that re-exports everything and contains the main registry + helper functions
    let mut mod_code = String::new();
    mod_code.push_str(
        r#"//! FHIR type metadata
//!
//! This module provides compile-time metadata about FHIR types, enabling
//! path resolution like "Patient.name.given" -> FhirPrimitiveType::String.
//!
//! Generated automatically - do not edit manually.

pub use phf;
use phf::{phf_map, Map};

"#,
    );

    // Declare sub-modules
    for &category in &category_order {
        let filename = format!("{}.rs", category.module_name());
        if files.contains_key(&filename) {
            mod_code.push_str(&format!("mod {};\n", category.module_name()));
            mod_code.push_str(&format!("pub use {}::*;\n", category.module_name()));
        }
    }

    mod_code.push('\n');

    // Generate FhirPrimitiveType enum in mod.rs (used by all categories)
    mod_code.push_str(
        r#"/// FHIR primitive types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FhirPrimitiveType {
    Boolean,
    Integer,
    String,
    Date,
    DateTime,
    Instant,
    Time,
    Decimal,
    Uri,
    Url,
    Canonical,
    Code,
    Oid,
    Id,
    Markdown,
    Base64Binary,
    UnsignedInt,
    PositiveInt,
}

"#,
    );

    // Generate FhirFieldType enum
    mod_code.push_str(
        r#"/// FHIR field type (primitive, complex, reference, or backbone element)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FhirFieldType {
    Primitive(FhirPrimitiveType),
    Complex(&'static str),
    Reference,
    BackboneElement(&'static str),
}

"#,
    );

    // Generate FieldInfo struct
    mod_code.push_str(
        r#"/// Information about a field in a FHIR resource or datatype
#[derive(Debug, Clone)]
pub struct FieldInfo {
    pub field_type: FhirFieldType,
    pub min: u32,
    pub max: Option<u32>,
    pub is_choice_type: bool,
}

"#,
    );

    // Generate the main registry that pulls from all categories
    generate_registry_map(&mut mod_code, &registry.types, &all_generated_consts);

    mod_code.push_str(
        r#"
/// Get field information for a specific field in a type
pub fn get_field_info(type_name: &str, field_name: &str) -> Option<&'static FieldInfo> {
    FHIR_TYPE_REGISTRY
        .get(type_name)
        .and_then(|fields| fields.get(field_name))
}

/// Resolve a nested path like "Patient.name.given" to its field type
pub fn resolve_path(path: &str) -> Option<&'static FhirFieldType> {
    let parts: Vec<&str> = path.split('.').collect();
    if parts.is_empty() {
        return None;
    }

    let mut current_type_name = parts[0];

    for (idx, &field_name) in parts[1..].iter().enumerate() {
        let field_info = get_field_info(current_type_name, field_name)?;

        // If this is the last field, return its type
        if idx == parts.len() - 2 {
            return Some(&field_info.field_type);
        }

        // Otherwise, navigate to the next type
        match &field_info.field_type {
            FhirFieldType::Complex(type_name) | FhirFieldType::BackboneElement(type_name) => {
                current_type_name = type_name;
            }
            _ => return None, // Can't navigate further
        }
    }

    None
}
"#,
    );

    files.insert("mod.rs".to_string(), mod_code);

    files
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_field_name() {
        assert_eq!(
            extract_field_name("Patient.birthDate", "Patient"),
            Some("birthDate".to_string())
        );

        assert_eq!(
            extract_field_name("Patient.name.given", "Patient"),
            Some("name".to_string())
        );

        assert_eq!(extract_field_name("Patient", "Patient"), None);
    }

    #[test]
    fn test_determine_field_type() {
        assert_eq!(
            determine_field_type("date"),
            FhirFieldType::Primitive(FhirPrimitiveType::Date)
        );

        assert_eq!(
            determine_field_type("string"),
            FhirFieldType::Primitive(FhirPrimitiveType::String)
        );

        assert_eq!(determine_field_type("Reference"), FhirFieldType::Reference);

        assert!(matches!(
            determine_field_type("HumanName"),
            FhirFieldType::Complex(_)
        ));
    }
}