rh-codegen 0.1.0-beta.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
//! Nested struct generation functionality for FHIR BackboneElements
//!
//! This module provides functionality for generating nested structs from FHIR BackboneElements,
//! which are complex structures that appear within other FHIR structures.

use std::collections::HashMap;

use crate::config::CodegenConfig;
use crate::fhir_types::{ElementDefinition, StructureDefinition};
use crate::generators::{DocumentationGenerator, FieldGenerator, TypeRegistry};
use crate::naming::Naming;
use crate::rust_types::RustStruct;
use crate::CodegenResult;

/// Generator for nested struct types from FHIR BackboneElements
pub struct NestedStructGenerator<'a> {
    config: &'a CodegenConfig,
    type_cache: &'a mut HashMap<String, RustStruct>,
    value_set_manager: &'a mut crate::value_sets::ValueSetManager,
}

impl<'a> NestedStructGenerator<'a> {
    /// Create a new nested struct generator
    pub fn new(
        config: &'a CodegenConfig,
        type_cache: &'a mut HashMap<String, RustStruct>,
        value_set_manager: &'a mut crate::value_sets::ValueSetManager,
    ) -> Self {
        Self {
            config,
            type_cache,
            value_set_manager,
        }
    }

    /// Generate a nested struct for BackboneElements
    pub fn generate_nested_struct(
        &mut self,
        parent_struct_name: &str,
        nested_field_name: &str,
        nested_elements: &[ElementDefinition],
        parent_structure_def: &StructureDefinition,
    ) -> CodegenResult<Option<RustStruct>> {
        // Generate the nested struct name (e.g., BundleEntry, BundleLink)
        let nested_struct_name = format!(
            "{}{}",
            parent_struct_name,
            Naming::to_pascal_case(nested_field_name)
        );

        // Check if we've already generated this nested struct
        if self.type_cache.contains_key(&nested_struct_name) {
            return Ok(None);
        }

        // Create the nested struct
        let mut nested_struct = RustStruct::new(nested_struct_name.clone());

        // Add documentation
        nested_struct.doc_comment = Some(
            DocumentationGenerator::generate_nested_struct_documentation(
                parent_struct_name,
                nested_field_name,
            ),
        );

        // Use config to determine derives
        let mut derives = vec!["Debug".to_string(), "Clone".to_string()];
        if self.config.with_serde {
            derives.extend(vec!["Serialize".to_string(), "Deserialize".to_string()]);
        }
        nested_struct.derives = derives;

        // Set base as BackboneElement since these are typically BackboneElements
        nested_struct.base_definition = Some("BackboneElement".to_string());

        // Process the nested elements
        let base_path = format!("{}.{}", parent_structure_def.name, nested_field_name);
        let mut sub_nested_structs = HashMap::new();
        let mut direct_fields = Vec::new();

        for element in nested_elements {
            if !element.path.starts_with(&base_path) {
                continue;
            }

            let field_path = element.path.strip_prefix(&format!("{base_path}.")).unwrap();

            if field_path.contains('.') {
                // This is a sub-nested field - collect it for recursive nested struct generation
                let sub_nested_field_name = field_path.split('.').next().unwrap();
                sub_nested_structs
                    .entry(sub_nested_field_name.to_string())
                    .or_insert_with(Vec::new)
                    .push(element.clone());
            } else {
                // Check if this direct field is itself a BackboneElement that needs a nested struct
                let is_backbone_element = element
                    .element_type
                    .as_ref()
                    .and_then(|types| types.first())
                    .and_then(|t| t.code.as_ref())
                    .map(|code| code == "BackboneElement")
                    .unwrap_or(false);

                if is_backbone_element {
                    // Treat this as a sub-nested struct even though it appears as a direct field
                    sub_nested_structs
                        .entry(field_path.to_string())
                        .or_insert_with(Vec::new)
                        .push(element.clone());
                } else {
                    // This is a direct field of this nested struct
                    direct_fields.push(element.clone());
                }
            }
        }

        // First, generate any sub-nested structs
        for (sub_nested_field_name, sub_nested_elements) in &sub_nested_structs {
            self.generate_sub_nested_struct(
                &nested_struct_name,
                sub_nested_field_name,
                sub_nested_elements,
                &base_path,
            )?;
        }

        // Then, process direct fields (now sub-nested structs are available)
        for element in direct_fields {
            if let Some(field) = self.create_field_from_element(&element)? {
                nested_struct.add_field(field);
            }
        }

        // Store the nested struct in cache before returning
        self.type_cache
            .insert(nested_struct_name.clone(), nested_struct.clone());

        // Register the nested struct in TypeRegistry with proper classification
        // Get the parent resource name from the parent struct name
        let parent_resource = parent_struct_name.to_string();
        TypeRegistry::register_type_classification_only(
            &nested_struct_name,
            crate::generators::type_registry::TypeClassification::NestedStructure {
                parent_resource,
            },
        );

        Ok(Some(nested_struct))
    }

    /// Generate a sub-nested struct (nested within a nested struct)
    fn generate_sub_nested_struct(
        &mut self,
        nested_struct_name: &str,
        sub_nested_field_name: &str,
        sub_nested_elements: &[ElementDefinition],
        base_path: &str,
    ) -> CodegenResult<()> {
        // For recursive calls, we need to create a modified context
        // The base path for sub-nested structs should be the current nested struct's path
        let sub_nested_struct_name = format!(
            "{}{}",
            nested_struct_name,
            Naming::to_pascal_case(sub_nested_field_name)
        );

        if !self.type_cache.contains_key(&sub_nested_struct_name) {
            let mut sub_nested_struct = RustStruct::new(sub_nested_struct_name.clone());

            sub_nested_struct.doc_comment = Some(
                DocumentationGenerator::generate_sub_nested_struct_documentation(
                    nested_struct_name,
                    sub_nested_field_name,
                ),
            );

            // Use config to determine derives
            let mut derives = vec!["Debug".to_string(), "Clone".to_string()];
            if self.config.with_serde {
                derives.extend(vec!["Serialize".to_string(), "Deserialize".to_string()]);
            }
            sub_nested_struct.derives = derives;
            sub_nested_struct.base_definition = Some("BackboneElement".to_string());

            // Process the sub-nested elements with full recursive support
            let sub_base_path = format!("{base_path}.{sub_nested_field_name}");

            // Separate sub-nested elements into direct fields and further sub-nested structures
            let mut direct_fields = Vec::new();
            let mut sub_sub_nested_structs: HashMap<String, Vec<ElementDefinition>> =
                HashMap::new();

            for element in sub_nested_elements {
                if !element.path.starts_with(&sub_base_path) {
                    continue;
                }

                let field_path = element
                    .path
                    .strip_prefix(&format!("{sub_base_path}."))
                    .unwrap();

                if field_path.contains('.') {
                    // This is a further sub-nested field - collect it for recursive generation
                    let sub_sub_nested_field_name = field_path.split('.').next().unwrap();
                    sub_sub_nested_structs
                        .entry(sub_sub_nested_field_name.to_string())
                        .or_default()
                        .push(element.clone());
                } else {
                    // Check if this direct field is itself a BackboneElement that needs a nested struct
                    let is_backbone_element = element
                        .element_type
                        .as_ref()
                        .and_then(|types| types.first())
                        .and_then(|t| t.code.as_ref())
                        .map(|code| code == "BackboneElement")
                        .unwrap_or(false);

                    if is_backbone_element {
                        // Treat this as a further sub-nested struct even though it appears as a direct field
                        sub_sub_nested_structs
                            .entry(field_path.to_string())
                            .or_default()
                            .push(element.clone());
                    } else {
                        // This is a direct field of this sub-nested struct
                        direct_fields.push(element.clone());
                    }
                }
            }

            // First, generate any further sub-nested structs recursively
            for (sub_sub_nested_field_name, sub_sub_nested_elements) in &sub_sub_nested_structs {
                self.generate_sub_nested_struct(
                    &sub_nested_struct_name,
                    sub_sub_nested_field_name,
                    sub_sub_nested_elements,
                    &sub_base_path,
                )?;
            } // Then, process direct fields (now further sub-nested structs are available)
            for element in direct_fields {
                if let Some(field) = self.create_field_from_element(&element)? {
                    sub_nested_struct.add_field(field);
                }
            }

            // Store the sub-nested struct in cache
            self.type_cache
                .insert(sub_nested_struct_name.clone(), sub_nested_struct);

            // Register the sub-nested struct in TypeRegistry with proper classification
            // Extract the parent resource from the nested_struct_name
            // Use a simple approach: extract from the beginning of nested_struct_name
            let parent_resource = Self::extract_parent_resource_name(nested_struct_name);

            TypeRegistry::register_type_classification_only(
                &sub_nested_struct_name,
                crate::generators::type_registry::TypeClassification::NestedStructure {
                    parent_resource,
                },
            );
        }

        Ok(())
    }

    /// Extract parent resource name from a nested structure name
    /// For example: "ActivityDefinitionParticipant" -> "ActivityDefinition"
    fn extract_parent_resource_name(nested_struct_name: &str) -> String {
        // Use the TypeRegistry's method for consistency
        crate::generators::type_registry::TypeRegistry::extract_parent_from_name(nested_struct_name)
            .unwrap_or_else(|| nested_struct_name.to_string())
    }

    /// Create a RustField from an ElementDefinition
    fn create_field_from_element(
        &mut self,
        element: &ElementDefinition,
    ) -> CodegenResult<Option<crate::rust_types::RustField>> {
        let mut field_generator =
            FieldGenerator::new(self.config, self.type_cache, self.value_set_manager);
        field_generator.create_field_from_element(element)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::CodegenConfig;
    use crate::fhir_types::{
        ElementDefinition, ElementType, StructureDefinition, StructureDefinitionDifferential,
    };
    use crate::value_sets::ValueSetManager;

    #[test]
    fn test_nested_struct_generation() {
        let config = CodegenConfig::default();
        let mut type_cache = HashMap::new();
        let mut value_set_manager = ValueSetManager::new();
        let mut generator =
            NestedStructGenerator::new(&config, &mut type_cache, &mut value_set_manager);

        // Create a simplified Bundle StructureDefinition with nested entry
        let bundle_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Bundle".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Bundle".to_string(),
            name: "Bundle".to_string(),
            title: Some("Bundle".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("A container for a collection of resources".to_string()),
            purpose: None,
            base_type: "Bundle".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Resource".to_string()),
            version: None,
            differential: Some(StructureDefinitionDifferential {
                element: vec![
                    ElementDefinition {
                        id: Some("Bundle.entry".to_string()),
                        path: "Bundle.entry".to_string(),
                        short: Some("Entry in the bundle".to_string()),
                        definition: None,
                        min: Some(0),
                        max: Some("*".to_string()),
                        element_type: Some(vec![ElementType {
                            code: Some("BackboneElement".to_string()),
                            target_profile: None,
                        }]),
                        fixed: None,
                        pattern: None,
                        binding: None,
                        constraint: None,
                    },
                    ElementDefinition {
                        id: Some("Bundle.entry.resource".to_string()),
                        path: "Bundle.entry.resource".to_string(),
                        short: Some("A resource in the bundle".to_string()),
                        definition: None,
                        min: Some(0),
                        max: Some("1".to_string()),
                        element_type: Some(vec![ElementType {
                            code: Some("Resource".to_string()),
                            target_profile: None,
                        }]),
                        fixed: None,
                        pattern: None,
                        binding: None,
                        constraint: None,
                    },
                ],
            }),
            snapshot: None,
        };

        let nested_elements = bundle_structure
            .differential
            .as_ref()
            .unwrap()
            .element
            .clone();

        // Filter to only include the sub-elements of Bundle.entry (not Bundle.entry itself)
        let filtered_elements: Vec<_> = nested_elements
            .into_iter()
            .filter(|e| e.path.starts_with("Bundle.entry."))
            .collect();

        // Generate the nested struct
        let result = generator.generate_nested_struct(
            "Bundle",
            "entry",
            &filtered_elements,
            &bundle_structure,
        );
        assert!(result.is_ok(), "Should generate nested struct successfully");

        let bundle_entry_struct = result.unwrap();
        assert!(
            bundle_entry_struct.is_some(),
            "Should return a nested struct"
        );

        let bundle_entry_struct = bundle_entry_struct.unwrap();
        assert_eq!(bundle_entry_struct.name, "BundleEntry");
        assert_eq!(
            bundle_entry_struct.base_definition,
            Some("BackboneElement".to_string())
        );

        // Check that the struct was added to the type cache
        assert!(
            type_cache.contains_key("BundleEntry"),
            "BundleEntry should be cached"
        );

        // Check that the nested struct has the expected fields
        let resource_field = bundle_entry_struct
            .fields
            .iter()
            .find(|f| f.name == "resource");
        assert!(
            resource_field.is_some(),
            "BundleEntry should have a resource field"
        );
    }

    #[test]
    fn test_nested_struct_caching() {
        let config = CodegenConfig::default();
        let mut type_cache = HashMap::new();
        let mut value_set_manager = ValueSetManager::new();

        // Create a dummy nested struct and add it to cache
        let existing_struct = RustStruct::new("BundleEntry".to_string());
        type_cache.insert("BundleEntry".to_string(), existing_struct);

        let mut generator =
            NestedStructGenerator::new(&config, &mut type_cache, &mut value_set_manager);

        let bundle_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Bundle".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Bundle".to_string(),
            name: "Bundle".to_string(),
            title: Some("Bundle".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("A container for a collection of resources".to_string()),
            purpose: None,
            base_type: "Bundle".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Resource".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        let nested_elements = vec![];

        // Generate the nested struct - should return None due to caching
        let result = generator.generate_nested_struct(
            "Bundle",
            "entry",
            &nested_elements,
            &bundle_structure,
        );
        assert!(result.is_ok(), "Should handle cached struct successfully");

        let bundle_entry_struct = result.unwrap();
        assert!(
            bundle_entry_struct.is_none(),
            "Should return None for cached struct"
        );
    }

    #[test]
    fn test_nested_struct_documentation() {
        let config = CodegenConfig::default();
        let mut type_cache = HashMap::new();
        let mut value_set_manager = ValueSetManager::new();
        let mut generator =
            NestedStructGenerator::new(&config, &mut type_cache, &mut value_set_manager);

        let bundle_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Bundle".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Bundle".to_string(),
            name: "Bundle".to_string(),
            title: Some("Bundle".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("A container for a collection of resources".to_string()),
            purpose: None,
            base_type: "Bundle".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Resource".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        let nested_elements = vec![];

        // Generate the nested struct
        let result = generator.generate_nested_struct(
            "Bundle",
            "entry",
            &nested_elements,
            &bundle_structure,
        );
        assert!(result.is_ok(), "Should generate nested struct successfully");

        let bundle_entry_struct = result.unwrap().unwrap();

        // Check documentation was generated
        assert!(
            bundle_entry_struct.doc_comment.is_some(),
            "Should have documentation"
        );
        let doc = bundle_entry_struct.doc_comment.unwrap();
        assert!(
            doc.contains("Bundle"),
            "Documentation should mention parent struct"
        );
        assert!(
            doc.contains("entry"),
            "Documentation should mention field name"
        );
    }

    #[test]
    fn test_nested_struct_derives() {
        let config = CodegenConfig {
            with_serde: true,
            ..Default::default()
        };
        let mut type_cache = HashMap::new();
        let mut value_set_manager = ValueSetManager::new();
        let mut generator =
            NestedStructGenerator::new(&config, &mut type_cache, &mut value_set_manager);

        let bundle_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "Bundle".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/Bundle".to_string(),
            name: "Bundle".to_string(),
            title: Some("Bundle".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("A container for a collection of resources".to_string()),
            purpose: None,
            base_type: "Bundle".to_string(),
            base_definition: Some("http://hl7.org/fhir/StructureDefinition/Resource".to_string()),
            version: None,
            differential: None,
            snapshot: None,
        };

        let nested_elements = vec![];

        // Generate the nested struct
        let result = generator.generate_nested_struct(
            "Bundle",
            "entry",
            &nested_elements,
            &bundle_structure,
        );
        assert!(result.is_ok(), "Should generate nested struct successfully");

        let bundle_entry_struct = result.unwrap().unwrap();

        // Check derives include serde when enabled
        assert!(bundle_entry_struct.derives.contains(&"Debug".to_string()));
        assert!(bundle_entry_struct.derives.contains(&"Clone".to_string()));
        assert!(bundle_entry_struct
            .derives
            .contains(&"Serialize".to_string()));
        assert!(bundle_entry_struct
            .derives
            .contains(&"Deserialize".to_string()));
    }
}