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
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
//! Struct generation functionality
//!
//! This module handles the generation of Rust structs from FHIR StructureDefinitions.

use std::collections::HashMap;

use crate::config::CodegenConfig;
use crate::fhir_types::StructureDefinition;
use crate::generators::{DocumentationGenerator, FieldGenerator, TypeUtilities};
use crate::rust_types::{RustField, RustStruct, RustType};
use crate::value_sets::ValueSetManager;
use crate::{CodegenError, CodegenResult};

/// Struct generator for FHIR StructureDefinitions
pub struct StructGenerator<'a> {
    config: &'a CodegenConfig,
    type_cache: &'a mut HashMap<String, RustStruct>,
    value_set_manager: &'a mut ValueSetManager,
}

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

    /// Generate a Rust struct from a FHIR StructureDefinition
    pub fn generate_struct(
        &mut self,
        structure_def: &StructureDefinition,
    ) -> CodegenResult<RustStruct> {
        // Skip LogicalModels as they are conceptual models, not implementable types
        if structure_def.kind == "logical" {
            return Err(CodegenError::Generation {
                message: format!(
                    "Skipping LogicalModel '{}' - logical models are not generated as Rust types",
                    structure_def.name
                ),
            });
        }

        // Skip examples
        if structure_def.url.to_lowercase().contains("example") {
            return Err(CodegenError::Generation {
                message: format!(
                    "Skipping example StructureDefinition '{}'",
                    structure_def.name
                ),
            });
        }

        // Skip files that begin with underscore (auto-generated/temporary files)
        if TypeUtilities::should_skip_underscore_prefixed(structure_def) {
            return Err(CodegenError::Generation {
                message: format!(
                    "Skipping underscore-prefixed StructureDefinition '{}' - underscore prefixed files are ignored",
                    structure_def.name
                ),
            });
        }

        // Generate struct name from URL or ID, not the name field
        let struct_name = crate::naming::Naming::struct_name(structure_def);

        // Check if we've already generated this type
        if let Some(cached_struct) = self.type_cache.get(&struct_name) {
            return Ok(cached_struct.clone());
        }

        // Create the struct with enhanced documentation
        let mut rust_struct = RustStruct::new(struct_name.clone());
        rust_struct.doc_comment =
            DocumentationGenerator::generate_struct_documentation(structure_def);

        // 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()]);
        }

        // Add Default derive for profiles since they only have a base field that implements Default
        // Check using TypeRegistry to see if this is a profile
        let is_profile = crate::generators::type_registry::TypeRegistry::is_profile(structure_def);
        if is_profile {
            derives.push("Default".to_string());
        }

        rust_struct.derives = derives;

        // Set the base definition for inheritance if present
        if let Some(base_def) = &structure_def.base_definition {
            rust_struct.base_definition = Some(
                base_def
                    .split('/')
                    .next_back()
                    .unwrap_or(base_def)
                    .to_string(),
            );
        }

        // Handle primitive types specially
        if structure_def.kind == "primitive-type" {
            return self.generate_primitive_type_struct(structure_def, rust_struct);
        }

        // Extract element definitions from differential only (preferred FHIR approach)
        let elements = if let Some(differential) = &structure_def.differential {
            &differential.element
        } else if let Some(snapshot) = &structure_def.snapshot {
            &snapshot.element
        } else {
            return Ok(rust_struct); // No elements to process
        };

        // Process each element definition to create struct fields and nested structs
        let mut nested_structs_info = HashMap::new();
        let mut direct_fields = Vec::new();

        for element in elements {
            // Skip the root element
            if element.path == structure_def.name || element.path == structure_def.base_type {
                continue;
            }

            // Only process elements that belong to this struct
            let base_path = &structure_def.name;
            if !element.path.starts_with(&format!("{base_path}.")) {
                continue;
            }

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

            if field_path.contains('.') {
                // This is a nested field - collect it for nested struct generation
                let nested_field_name = field_path.split('.').next().unwrap();
                nested_structs_info
                    .entry(nested_field_name.to_string())
                    .or_insert_with(Vec::new)
                    .push(element.clone());
            } else {
                // This is a direct field of this struct
                direct_fields.push(element.clone());
            }
        }

        // First pass: Generate nested structs for BackboneElements
        for (nested_field_name, nested_elements) in &nested_structs_info {
            if let Some(nested_struct) = self.generate_nested_struct(
                &struct_name,
                nested_field_name,
                nested_elements,
                structure_def,
            )? {
                // Store the nested struct in cache for later use
                self.type_cache
                    .insert(nested_struct.name.clone(), nested_struct.clone());

                // Register the nested struct in TypeRegistry with proper classification
                crate::generators::type_registry::TypeRegistry::register_type_classification_only(
                    &nested_struct.name,
                    crate::generators::type_registry::TypeClassification::NestedStructure {
                        parent_resource: struct_name.clone(),
                    },
                );
            }
        }

        // Second pass: Process direct fields (now nested structs are available)
        for element in direct_fields {
            let fields = self.create_fields_from_element(&element)?;
            for mut field in fields {
                // Apply Box wrapper for circular dependencies
                field.field_type =
                    Self::apply_box_for_circular_dependencies(field.field_type, &rust_struct.name);
                rust_struct.add_field(field);
            }
        }

        // Cache the generated struct for future use
        self.type_cache.insert(struct_name, rust_struct.clone());

        Ok(rust_struct)
    }

    /// Generate a primitive type struct with special FHIR primitive type semantics
    pub fn generate_primitive_type_struct(
        &mut self,
        structure_def: &StructureDefinition,
        mut rust_struct: RustStruct,
    ) -> CodegenResult<RustStruct> {
        // For primitive types, don't inherit from Element
        rust_struct.base_definition = None;

        // Map FHIR primitive types to Rust types
        let rust_primitive_type = match structure_def.name.as_str() {
            "boolean" => RustType::Boolean,
            "integer" | "positiveInt" | "unsignedInt" => RustType::Integer,
            "decimal" => RustType::Float,
            "string" | "code" | "id" | "markdown" | "uri" | "url" | "canonical" | "oid"
            | "uuid" | "base64Binary" | "xhtml" => RustType::String,
            "date" | "dateTime" | "time" | "instant" => RustType::String, // Could use chrono types later
            _ => RustType::String, // Default to String for unknown primitive types
        };

        // The primitive type is just a type alias or newtype wrapper around the Rust primitive
        // For now, we'll create a struct with a single `value` field
        let value_field = RustField::new("value".to_string(), rust_primitive_type);
        rust_struct.add_field(value_field);

        // Cache the generated struct for future use
        let struct_name = rust_struct.name.clone();
        self.type_cache.insert(struct_name, rust_struct.clone());

        Ok(rust_struct)
    }

    /// Generate a nested struct for BackboneElements
    pub fn generate_nested_struct(
        &mut self,
        parent_struct_name: &str,
        nested_field_name: &str,
        nested_elements: &[crate::fhir_types::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,
            crate::naming::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;
            }

            // Skip the BackboneElement definition itself (where path == base_path)
            if element.path == 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 {
            // 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,
                crate::naming::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 sub_direct_fields = Vec::new();
                let mut sub_sub_nested_structs: HashMap<
                    String,
                    Vec<crate::fhir_types::ElementDefinition>,
                > = HashMap::new();

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

                    // Skip the BackboneElement definition itself (where path == base_path)
                    if element.path == sub_base_path {
                        continue;
                    }

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

                    if sub_field_path.contains('.') {
                        // This is a further sub-nested field - collect it for recursive generation
                        let sub_sub_nested_field_name = sub_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(sub_field_path.to_string())
                                .or_default()
                                .push(element.clone());
                        } else {
                            // This is a direct field of this sub-nested struct
                            sub_direct_fields.push(element.clone());
                        }
                    }
                }

                // First, recursively generate any further sub-nested structs
                for (sub_sub_nested_field_name, sub_sub_nested_elements) in &sub_sub_nested_structs
                {
                    self.generate_deeply_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 sub_direct_fields {
                    let fields = self.create_fields_from_element(&element)?;
                    for field in fields {
                        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
                // Use the parent struct name (first level nested struct's parent is the resource)
                crate::generators::type_registry::TypeRegistry::register_type_classification_only(
                    &sub_nested_struct_name,
                    crate::generators::type_registry::TypeClassification::NestedStructure {
                        parent_resource: parent_struct_name.to_string(),
                    },
                );
            }

            // Now create a field in the parent struct that references this sub-nested struct
            // Find the BackboneElement definition for this field
            let backbone_element_def = sub_nested_elements
                .iter()
                .find(|e| e.path == format!("{base_path}.{sub_nested_field_name}"));

            if let Some(element) = backbone_element_def {
                let fields = self.create_fields_from_element(element)?;
                for field in fields {
                    nested_struct.add_field(field);
                }
            }
        }

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

        Ok(Some(nested_struct))
    }

    /// Recursively generate deeply nested structs (for arbitrary nesting levels)
    fn generate_deeply_nested_struct(
        &mut self,
        parent_nested_struct_name: &str,
        field_name: &str,
        elements: &[crate::fhir_types::ElementDefinition],
        parent_base_path: &str,
    ) -> CodegenResult<()> {
        let nested_struct_name = format!(
            "{}{}",
            parent_nested_struct_name,
            crate::naming::Naming::to_pascal_case(field_name)
        );

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

            nested_struct.doc_comment = Some(
                DocumentationGenerator::generate_sub_nested_struct_documentation(
                    parent_nested_struct_name,
                    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;
            nested_struct.base_definition = Some("BackboneElement".to_string());

            // Process the nested elements with full recursive support
            let base_path = format!("{parent_base_path}.{field_name}");

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

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

                // Skip the BackboneElement definition itself (where path == base_path)
                if element.path == base_path {
                    continue;
                }

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

                if field_path.contains('.') {
                    // This is a further nested field - collect it for recursive generation
                    let sub_nested_field_name = field_path.split('.').next().unwrap();
                    sub_nested_structs
                        .entry(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 nested struct even though it appears as a direct field
                        sub_nested_structs
                            .entry(field_path.to_string())
                            .or_default()
                            .push(element.clone());
                    } else {
                        // This is a direct field of this nested struct
                        direct_fields.push(element.clone());
                    }
                }
            }

            // First, recursively generate any further nested structs
            for (sub_nested_field_name, sub_nested_elements) in &sub_nested_structs {
                self.generate_deeply_nested_struct(
                    &nested_struct_name,
                    sub_nested_field_name,
                    sub_nested_elements,
                    &base_path,
                )?;
            }

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

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

            // Register the deeply nested struct in TypeRegistry with proper classification
            // Extract the root parent resource name (e.g., "MedicationKnowledge" from "MedicationKnowledgeAdministrationguidelinesDosage")
            let root_parent_resource = Self::extract_root_parent_resource(&nested_struct_name);
            crate::generators::type_registry::TypeRegistry::register_type_classification_only(
                &nested_struct_name,
                crate::generators::type_registry::TypeClassification::NestedStructure {
                    parent_resource: root_parent_resource,
                },
            );
        }

        Ok(())
    }

    /// Extract the root parent resource name from a deeply nested struct name
    /// For example: "MedicationKnowledgeAdministrationguidelinesDosage" -> "MedicationKnowledge"
    fn extract_root_parent_resource(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())
    }

    /// Check if a field should use a nested struct type instead of BackboneElement
    pub fn should_use_nested_struct_type(
        &self,
        element: &crate::fhir_types::ElementDefinition,
        element_types: &[crate::fhir_types::ElementType],
    ) -> bool {
        // Check if this element is a BackboneElement and we have nested elements for it
        if let Some(first_type) = element_types.first() {
            if let Some(code) = &first_type.code {
                if code == "BackboneElement" {
                    // Extract parent struct name and field name from the path
                    let path_parts: Vec<&str> = element.path.split('.').collect();
                    if path_parts.len() >= 2 {
                        let _parent_name = path_parts[0];
                        let _field_name = path_parts[1];
                        // We would check here if we have nested elements for this field
                        // For now, always return true for BackboneElements
                        return true;
                    }
                }
            }
        }
        false
    }

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

    /// Create RustField(s) from an ElementDefinition (supports choice types)
    pub fn create_fields_from_element(
        &mut self,
        element: &crate::fhir_types::ElementDefinition,
    ) -> CodegenResult<Vec<RustField>> {
        let mut field_generator =
            FieldGenerator::new(self.config, self.type_cache, self.value_set_manager);
        field_generator.create_fields_from_element(element)
    }

    /// Apply Box wrapper to field types to prevent circular dependencies
    fn apply_box_for_circular_dependencies(
        field_type: RustType,
        current_struct_name: &str,
    ) -> RustType {
        // Known circular dependency pairs that need Box wrapping
        let circular_dependencies = [("Identifier", "Reference"), ("Reference", "Identifier")];

        // Check if we need to wrap this type in Box
        match &field_type {
            RustType::Custom(type_name) => {
                for (struct_a, struct_b) in &circular_dependencies {
                    if (current_struct_name == *struct_a && type_name == *struct_b)
                        || (current_struct_name == *struct_b && type_name == *struct_a)
                    {
                        return RustType::Box(Box::new(field_type));
                    }
                }
                field_type
            }
            RustType::Option(inner) => {
                let boxed_inner = Self::apply_box_for_circular_dependencies(
                    (**inner).clone(),
                    current_struct_name,
                );
                if let RustType::Box(_) = boxed_inner {
                    RustType::Option(Box::new(boxed_inner))
                } else {
                    field_type
                }
            }
            RustType::Vec(inner) => {
                let boxed_inner = Self::apply_box_for_circular_dependencies(
                    (**inner).clone(),
                    current_struct_name,
                );
                if let RustType::Box(_) = boxed_inner {
                    RustType::Vec(Box::new(boxed_inner))
                } else {
                    field_type
                }
            }
            _ => field_type,
        }
    }
}

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

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

        // Test structure with underscore prefixed name
        let underscore_structure = StructureDefinition {
            resource_type: "StructureDefinition".to_string(),
            id: "normal-id".to_string(),
            url: "http://hl7.org/fhir/StructureDefinition/_11179object_class".to_string(),
            name: "_11179object_class".to_string(),
            title: Some("Auto-generated class".to_string()),
            status: "active".to_string(),
            kind: "resource".to_string(),
            is_abstract: false,
            description: Some("An auto-generated resource".to_string()),
            purpose: None,
            base_type: "DomainResource".to_string(),
            base_definition: Some(
                "http://hl7.org/fhir/StructureDefinition/DomainResource".to_string(),
            ),
            version: None,
            differential: None,
            snapshot: None,
        };

        // Test that underscore-prefixed structures are rejected
        let result = generator.generate_struct(&underscore_structure);
        assert!(result.is_err());

        if let Err(CodegenError::Generation { message }) = result {
            assert!(message.contains("underscore prefixed files are ignored"));
            assert!(message.contains("_11179object_class"));
        } else {
            panic!("Expected CodegenError::Generation for underscore-prefixed structure");
        }
    }
}