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
//! ValueSet management and code generation utilities
//!
//! This module handles FHIR ValueSets, including generation of Rust enums
//! from ValueSet codes and management of code system mappings.

use crate::fhir_types::{CodeSystem, ValueSet, ValueSetComposeConcept, ValueSetExpansionContains};
use crate::rust_types::{RustEnum, RustEnumVariant};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Manages FHIR ValueSets and their conversion to Rust enums
#[derive(Debug, Clone)]
pub struct ValueSetManager {
    /// Directory containing ValueSet JSON files
    value_set_dir: Option<PathBuf>,
    /// Cache of ValueSet URLs to generated enum names
    value_set_cache: HashMap<String, String>,
    /// Cache of generated enums by name
    enum_cache: HashMap<String, RustEnum>,
}

impl ValueSetManager {
    pub fn new() -> Self {
        Self {
            value_set_dir: None,
            value_set_cache: HashMap::new(),
            enum_cache: HashMap::new(),
        }
    }

    pub fn new_with_directory<P: AsRef<Path>>(value_set_dir: P) -> Self {
        Self {
            value_set_dir: Some(value_set_dir.as_ref().to_path_buf()),
            value_set_cache: HashMap::new(),
            enum_cache: HashMap::new(),
        }
    }

    /// Generate a Rust enum name from a ValueSet URL
    pub fn generate_enum_name(&self, value_set_url: &str) -> String {
        // Extract the last part of the URL and convert to PascalCase
        let name = value_set_url
            .split('/')
            .next_back()
            .unwrap_or("UnknownValueSet")
            .split(&['-', '.'][..])
            .filter(|part| !part.is_empty())
            .map(|part| {
                let mut chars = part.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                }
            })
            .collect::<String>();

        // Ensure it's a valid Rust identifier
        if name.chars().next().unwrap_or('0').is_ascii_digit() {
            format!("ValueSet{name}")
        } else {
            name
        }
    }

    /// Check if a ValueSet is already cached
    pub fn is_cached(&self, value_set_url: &str) -> bool {
        self.value_set_cache.contains_key(value_set_url)
    }

    /// Get the enum name for a cached ValueSet
    pub fn get_enum_name(&self, value_set_url: &str) -> Option<&String> {
        self.value_set_cache.get(value_set_url)
    }

    /// Cache a ValueSet with its generated enum
    pub fn cache_value_set(
        &mut self,
        value_set_url: String,
        enum_name: String,
        rust_enum: RustEnum,
    ) {
        self.value_set_cache
            .insert(value_set_url, enum_name.clone());
        self.enum_cache.insert(enum_name, rust_enum);
    }

    /// Get all cached enums
    pub fn get_cached_enums(&self) -> &HashMap<String, RustEnum> {
        &self.enum_cache
    }

    /// Get available codes from a ValueSet for documentation purposes
    /// Returns a list of (code, display) tuples
    pub fn get_value_set_codes(
        &self,
        value_set_url: &str,
        version: Option<&str>,
    ) -> Result<Vec<(String, Option<String>)>, String> {
        // Try to find and load the ValueSet file
        let value_set = match self.load_value_set(value_set_url, version) {
            Ok(vs) => vs,
            Err(err) => {
                eprintln!("Warning: Could not load ValueSet '{value_set_url}': {err}");
                return Err(format!("ValueSet not found: {value_set_url}"));
            }
        };

        let mut codes = Vec::new();

        // Try to get codes from expansion first
        if let Some(expansion) = &value_set.expansion {
            if let Some(contains) = &expansion.contains {
                for concept in contains {
                    codes.push((concept.code.clone(), concept.display.clone()));
                }
                if !codes.is_empty() {
                    return Ok(codes);
                }
            }
        }

        // Fallback to compose if no expansion or expansion is empty
        if let Some(compose) = &value_set.compose {
            if let Some(includes) = &compose.include {
                for include in includes {
                    if let Some(concepts) = &include.concept {
                        for concept in concepts {
                            codes.push((concept.code.clone(), concept.display.clone()));
                        }
                    }
                }
            }
        }

        if codes.is_empty() {
            Err("No codes found in ValueSet".to_string())
        } else {
            Ok(codes)
        }
    }

    /// Generate enum from ValueSet, trying expansion first, then compose
    pub fn generate_enum_from_value_set(
        &mut self,
        value_set_url: &str,
        version: Option<&str>,
    ) -> Result<String, String> {
        let enum_name = self.generate_enum_name(value_set_url);

        if self.is_cached(value_set_url) {
            return Ok(enum_name);
        }

        // Try to find and load the ValueSet file
        let value_set = match self.load_value_set(value_set_url, version) {
            Ok(vs) => vs,
            Err(err) => {
                eprintln!("Warning: Could not load ValueSet '{value_set_url}': {err}");
                return Err(format!("ValueSet not found: {value_set_url}"));
            }
        };

        // Try to generate enum from expansion first
        if let Some(expansion) = &value_set.expansion {
            if let Some(contains) = &expansion.contains {
                if !contains.is_empty() {
                    let rust_enum =
                        self.create_enum_from_expansion(&enum_name, contains, value_set_url);
                    self.cache_value_set(value_set_url.to_string(), enum_name.clone(), rust_enum);
                    return Ok(enum_name);
                }
            }
        }

        // Fallback to compose if no expansion or expansion is empty
        if let Some(compose) = &value_set.compose {
            if let Some(includes) = &compose.include {
                // Check if there are any filters - if so, we can't generate enum
                for include in includes {
                    if include.filter.is_some() && !include.filter.as_ref().unwrap().is_empty() {
                        eprintln!("Warning: ValueSet '{value_set_url}' has filters, cannot generate enum. Falling back to String.");
                        return Err("ValueSet has filters".to_string());
                    }
                }

                // Try to generate from explicit concepts
                let mut all_concepts = Vec::new();
                for include in includes {
                    if let Some(concepts) = &include.concept {
                        all_concepts.extend(concepts.iter().cloned());
                    } else if let Some(system) = &include.system {
                        // Try to load the entire code system
                        if let Ok(code_system) = self.load_code_system(system) {
                            if let Some(cs_concepts) = &code_system.concept {
                                for cs_concept in cs_concepts {
                                    let compose_concept = ValueSetComposeConcept {
                                        code: cs_concept.code.clone(),
                                        display: cs_concept.display.clone(),
                                    };
                                    all_concepts.push(compose_concept);
                                }
                            }
                        }
                    }
                }

                if !all_concepts.is_empty() {
                    let rust_enum =
                        self.create_enum_from_concepts(&enum_name, &all_concepts, value_set_url);
                    self.cache_value_set(value_set_url.to_string(), enum_name.clone(), rust_enum);
                    return Ok(enum_name);
                }
            }
        }

        // If all methods fail, return error
        eprintln!("Warning: Could not generate enum for ValueSet '{value_set_url}', no expansion or compose concepts found. Falling back to String.");
        Err("No concepts found in ValueSet".to_string())
    }

    /// Load a ValueSet from file
    fn load_value_set(
        &self,
        value_set_url: &str,
        _version: Option<&str>,
    ) -> Result<ValueSet, String> {
        let value_set_dir = self
            .value_set_dir
            .as_ref()
            .ok_or("No ValueSet directory configured")?;

        // Extract the ID from the URL (last part after '/')
        let id = value_set_url
            .split('/')
            .next_back()
            .ok_or("Invalid ValueSet URL")?;

        // Try common filename patterns
        let filenames = vec![
            format!("ValueSet-{}.json", id),
            format!("valueset-{}.json", id),
            format!("{}.json", id),
        ];

        for filename in filenames {
            let file_path = value_set_dir.join(&filename);
            if file_path.exists() {
                let content = fs::read_to_string(&file_path)
                    .map_err(|e| format!("Failed to read file '{}': {}", file_path.display(), e))?;

                let value_set: ValueSet = serde_json::from_str(&content)
                    .map_err(|e| format!("Failed to parse ValueSet JSON: {e}"))?;
                return Ok(value_set);
            }
        }

        Err(format!("ValueSet file not found for ID: {id}"))
    }

    /// Load a CodeSystem from file
    fn load_code_system(&self, system_url: &str) -> Result<CodeSystem, String> {
        let value_set_dir = self
            .value_set_dir
            .as_ref()
            .ok_or("No ValueSet directory configured")?;

        // Extract the ID from the URL (last part after '/')
        let id = system_url
            .split('/')
            .next_back()
            .ok_or("Invalid CodeSystem URL")?;

        // Try common filename patterns
        let filenames = vec![
            format!("CodeSystem-{}.json", id),
            format!("codesystem-{}.json", id),
            format!("{}.json", id),
        ];

        for filename in filenames {
            let file_path = value_set_dir.join(&filename);
            if file_path.exists() {
                let content = fs::read_to_string(&file_path)
                    .map_err(|e| format!("Failed to read file '{}': {}", file_path.display(), e))?;

                let code_system: CodeSystem = serde_json::from_str(&content)
                    .map_err(|e| format!("Failed to parse CodeSystem JSON: {e}"))?;
                return Ok(code_system);
            }
        }

        Err(format!("CodeSystem file not found for ID: {id}"))
    }

    /// Create enum from ValueSet expansion
    fn create_enum_from_expansion(
        &self,
        enum_name: &str,
        contains: &[ValueSetExpansionContains],
        value_set_url: &str,
    ) -> RustEnum {
        let mut rust_enum = RustEnum::new(enum_name.to_string());
        rust_enum.doc_comment = Some(format!(" Generated enum for ValueSet: {value_set_url}"));

        for concept in contains {
            let variant_name = ValueSetConcept::new(concept.code.clone()).to_variant_name();
            let mut variant = RustEnumVariant::new(variant_name);

            if let Some(display) = &concept.display {
                variant.doc_comment = Some(format!(" {}", display.clone()));
            }

            // Add serde annotation to map to the original code
            variant.serde_rename = Some(concept.code.clone());

            rust_enum.add_variant(variant);
        }

        rust_enum
    }

    /// Create enum from ValueSet compose concepts
    fn create_enum_from_concepts(
        &self,
        enum_name: &str,
        concepts: &[ValueSetComposeConcept],
        value_set_url: &str,
    ) -> RustEnum {
        let mut rust_enum = RustEnum::new(enum_name.to_string());
        rust_enum.doc_comment = Some(format!(" Generated enum for ValueSet: {value_set_url}"));

        for concept in concepts {
            let variant_name = ValueSetConcept::new(concept.code.clone()).to_variant_name();
            let mut variant = RustEnumVariant::new(variant_name);

            if let Some(display) = &concept.display {
                variant.doc_comment = Some(format!(" {}", display.clone()));
            }

            // Add serde annotation to map to the original code
            variant.serde_rename = Some(concept.code.clone());

            rust_enum.add_variant(variant);
        }

        rust_enum
    }

    /// Generate a basic enum for unknown ValueSets (fallback)
    pub fn generate_placeholder_enum(&mut self, value_set_url: &str) -> String {
        let enum_name = self.generate_enum_name(value_set_url);

        if !self.is_cached(value_set_url) {
            let mut rust_enum = RustEnum::new(enum_name.clone());
            rust_enum.doc_comment = Some(format!(" Generated enum for ValueSet: {value_set_url}"));

            // Add a placeholder variant
            rust_enum.add_variant(RustEnumVariant::new("Unknown".to_string()));

            self.cache_value_set(value_set_url.to_string(), enum_name.clone(), rust_enum);
        }

        enum_name
    }
}

impl Default for ValueSetManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Represents a FHIR ValueSet concept
#[derive(Debug, Clone)]
pub struct ValueSetConcept {
    pub code: String,
    pub display: Option<String>,
    pub definition: Option<String>,
    pub system: Option<String>,
}

impl ValueSetConcept {
    pub fn new(code: String) -> Self {
        Self {
            code,
            display: None,
            definition: None,
            system: None,
        }
    }

    /// Convert the concept code to a valid Rust enum variant name
    pub fn to_variant_name(&self) -> String {
        // Handle special cases first
        let sanitized_code = match self.code.as_str() {
            "=" => "Equal".to_string(),
            "!=" => "NotEqual".to_string(),
            "<" => "LessThan".to_string(),
            "<=" => "LessThanOrEqual".to_string(),
            ">" => "GreaterThan".to_string(),
            ">=" => "GreaterThanOrEqual".to_string(),
            "+" => "Plus".to_string(),
            "-" => "Minus".to_string(),
            "*" => "Star".to_string(),
            "/" => "Slash".to_string(),
            "&" => "Ampersand".to_string(),
            "|" => "Pipe".to_string(),
            "%" => "Percent".to_string(),
            "#" => "Hash".to_string(),
            "@" => "At".to_string(),
            "!" => "Exclamation".to_string(),
            "?" => "Question".to_string(),
            "^" => "Caret".to_string(),
            "~" => "Tilde".to_string(),
            "(" => "LeftParen".to_string(),
            ")" => "RightParen".to_string(),
            "[" => "LeftBracket".to_string(),
            "]" => "RightBracket".to_string(),
            "{" => "LeftBrace".to_string(),
            "}" => "RightBrace".to_string(),
            "'" => "SingleQuote".to_string(),
            "\"" => "DoubleQuote".to_string(),
            "`" => "Backtick".to_string(),
            "$" => "Dollar".to_string(),
            ";" => "Semicolon".to_string(),
            ":" => "Colon".to_string(),
            "," => "Comma".to_string(),
            _ => {
                // For other codes, sanitize by removing/replacing invalid characters
                self.code
                    .chars()
                    .map(|c| match c {
                        'a'..='z' | 'A'..='Z' | '0'..='9' => c.to_string(),
                        '-' | '_' | '.' | ' ' => "-".to_string(), // Convert to dash for splitting
                        _ => format!("_{:02x}", c as u32),        // Convert other characters to hex
                    })
                    .collect::<String>()
            }
        };

        // Convert kebab-case, snake_case, or other formats to PascalCase
        let name = sanitized_code
            .split(&['-', '_', '.', ' '][..])
            .filter(|part| !part.is_empty()) // Filter out empty parts
            .map(|part| {
                let mut chars = part.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                }
            })
            .collect::<String>();

        // Ensure it starts with a letter and is not empty
        if name.is_empty() {
            "Unknown".to_string()
        } else if name.chars().next().unwrap_or('0').is_ascii_digit() {
            format!("Code{name}")
        } else {
            name
        }
    }
}

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

    #[test]
    fn test_generate_enum_name() {
        let manager = ValueSetManager::new();

        assert_eq!(
            manager.generate_enum_name("http://hl7.org/fhir/ValueSet/administrative-gender"),
            "AdministrativeGender"
        );

        assert_eq!(
            manager.generate_enum_name("http://hl7.org/fhir/ValueSet/123-test"),
            "ValueSet123Test"
        );
    }

    #[test]
    fn test_concept_variant_name() {
        let concept = ValueSetConcept::new("male".to_string());
        assert_eq!(concept.to_variant_name(), "Male");

        let concept = ValueSetConcept::new("unknown-gender".to_string());
        assert_eq!(concept.to_variant_name(), "UnknownGender");

        let concept = ValueSetConcept::new("123-code".to_string());
        assert_eq!(concept.to_variant_name(), "Code123Code");
    }
}