Skip to main content

oxirs_samm/generators/
python.rs

1//! SAMM to Python Dataclass Generator
2//!
3//! Generates Python dataclasses with type hints from SAMM Aspect models.
4//! Supports typing module, Enum classes, and validation.
5
6use crate::error::SammError;
7use crate::metamodel::{Aspect, CharacteristicKind, ModelElement};
8use std::collections::HashSet;
9
10/// Python generation options
11#[derive(Debug, Clone)]
12pub struct PythonOptions {
13    /// Use pydantic for validation
14    pub use_pydantic: bool,
15    /// Add __post_init__ validation
16    pub add_validation: bool,
17    /// Generate docstrings
18    pub generate_docstrings: bool,
19    /// Use snake_case for field names
20    pub snake_case_fields: bool,
21}
22
23impl Default for PythonOptions {
24    fn default() -> Self {
25        Self {
26            use_pydantic: false,
27            add_validation: true,
28            generate_docstrings: true,
29            snake_case_fields: true,
30        }
31    }
32}
33
34/// Generate Python dataclasses from SAMM Aspect
35pub fn generate_python(aspect: &Aspect, options: PythonOptions) -> Result<String, SammError> {
36    let mut python = String::new();
37    let mut enum_classes = Vec::new();
38    let mut nested_classes = HashSet::new();
39
40    // Header imports
41    python.push_str("\"\"\"Generated Python dataclasses from SAMM model\"\"\"\n\n");
42
43    if options.use_pydantic {
44        python.push_str("from pydantic import BaseModel, Field\n");
45    } else {
46        python.push_str("from dataclasses import dataclass, field\n");
47    }
48
49    python.push_str("from typing import Optional, List\n");
50    python.push_str("from enum import Enum\n");
51    python.push_str("from datetime import datetime, date, time\n");
52    python.push('\n');
53
54    // Collect enum classes and nested types
55    for prop in aspect.properties() {
56        if let Some(char) = &prop.characteristic {
57            // Collect enum classes
58            if let CharacteristicKind::Enumeration { values } = char.kind() {
59                let enum_name = to_pascal_case(&prop.name());
60                let enum_def = generate_enum_class(&enum_name, values, &options);
61                enum_classes.push(enum_def);
62            }
63
64            // Collect state classes
65            if let CharacteristicKind::State {
66                values,
67                default_value: _,
68            } = char.kind()
69            {
70                let enum_name = to_pascal_case(&prop.name());
71                let enum_def = generate_enum_class(&enum_name, values, &options);
72                enum_classes.push(enum_def);
73            }
74
75            // Collect entity types
76            if let CharacteristicKind::SingleEntity { entity_type } = char.kind() {
77                let entity_name = entity_type.split('#').next_back().unwrap_or(entity_type);
78                nested_classes.insert(to_pascal_case(entity_name));
79            }
80        }
81    }
82
83    // Generate enum classes
84    for enum_def in &enum_classes {
85        python.push_str(enum_def);
86        python.push_str("\n\n");
87    }
88
89    // Generate nested class stubs
90    for nested_class in &nested_classes {
91        python.push_str(&generate_nested_class_stub(nested_class, &options));
92        python.push_str("\n\n");
93    }
94
95    // Generate main dataclass
96    let main_class = generate_main_dataclass(aspect, &options)?;
97    python.push_str(&main_class);
98
99    Ok(python)
100}
101
102/// Generate enum class
103fn generate_enum_class(name: &str, values: &[String], options: &PythonOptions) -> String {
104    let mut enum_def = String::new();
105
106    if options.generate_docstrings {
107        enum_def.push_str(&format!("class {}(Enum):\n", name));
108        enum_def.push_str(&format!("    \"\"\"Enumeration: {}\"\"\"\n", name));
109    } else {
110        enum_def.push_str(&format!("class {}(Enum):\n", name));
111    }
112
113    for value in values {
114        // A bare Python class attribute name cannot start with a digit or
115        // contain symbol characters — see `super::ensure_valid_identifier`.
116        let member_name = super::ensure_valid_identifier(
117            &value.to_uppercase().replace(['-', ' '], "_"),
118            "VALUE_",
119        );
120        enum_def.push_str(&format!("    {} = \"{}\"\n", member_name, value));
121    }
122
123    enum_def
124}
125
126/// Generate nested class stub
127fn generate_nested_class_stub(name: &str, options: &PythonOptions) -> String {
128    let mut class_def = String::new();
129
130    if options.use_pydantic {
131        class_def.push_str(&format!("class {}(BaseModel):\n", name));
132    } else {
133        class_def.push_str("@dataclass\n");
134        class_def.push_str(&format!("class {}:\n", name));
135    }
136
137    if options.generate_docstrings {
138        class_def.push_str(&format!("    \"\"\"Referenced entity: {}\"\"\"\n", name));
139    }
140
141    class_def.push_str("    id: str\n");
142    class_def.push_str("    # Add other fields as needed\n");
143
144    class_def
145}
146
147/// Generate main dataclass
148fn generate_main_dataclass(aspect: &Aspect, options: &PythonOptions) -> Result<String, SammError> {
149    let class_name = to_pascal_case(&aspect.name());
150    let mut class_def = String::new();
151
152    // Decorator and class definition
153    if options.use_pydantic {
154        class_def.push_str(&format!("class {}(BaseModel):\n", class_name));
155    } else {
156        class_def.push_str("@dataclass\n");
157        class_def.push_str(&format!("class {}:\n", class_name));
158    }
159
160    // Docstring
161    if options.generate_docstrings {
162        class_def.push_str(&format!("    \"\"\"{}\n", class_name));
163        if let Some(desc) = aspect.metadata().get_description("en") {
164            class_def.push_str(&format!("    \n    {}\n", desc));
165        }
166        class_def.push_str("    \n    Generated from SAMM model\n");
167        class_def.push_str(&format!("    URN: {}\n", aspect.metadata().urn));
168        class_def.push_str("    \"\"\"\n");
169    }
170
171    // Always add id field
172    class_def.push_str("    id: str\n");
173
174    // Add properties
175    for prop in aspect.properties() {
176        let field_name = if options.snake_case_fields {
177            to_snake_case(&prop.name())
178        } else {
179            prop.name().to_string()
180        };
181
182        let field_type = get_python_type(prop, options)?;
183
184        // Add docstring comment
185        if options.generate_docstrings {
186            if let Some(desc) = prop.metadata().get_description("en") {
187                class_def.push_str(&format!("    # {}\n", desc));
188            }
189        }
190
191        class_def.push_str(&format!("    {}: {}\n", field_name, field_type));
192    }
193
194    // Add metadata fields
195    class_def.push_str("    created_at: datetime\n");
196    class_def.push_str("    updated_at: datetime\n");
197
198    // Add __post_init__ validation if requested
199    if options.add_validation && !options.use_pydantic {
200        class_def.push('\n');
201        class_def.push_str("    def __post_init__(self):\n");
202        class_def.push_str("        \"\"\"Validate field values\"\"\"\n");
203
204        // Add validation for required fields
205        for prop in aspect.properties() {
206            if !prop.optional {
207                let field_name = if options.snake_case_fields {
208                    to_snake_case(&prop.name())
209                } else {
210                    prop.name().to_string()
211                };
212                class_def.push_str(&format!("        if self.{} is None:\n", field_name));
213                class_def.push_str(&format!(
214                    "            raise ValueError(\"Field '{}' is required\")\n",
215                    field_name
216                ));
217            }
218        }
219    }
220
221    Ok(class_def)
222}
223
224/// Get Python type for a property
225fn get_python_type(
226    prop: &crate::metamodel::Property,
227    options: &PythonOptions,
228) -> Result<String, SammError> {
229    if let Some(char) = &prop.characteristic {
230        let base_type = match char.kind() {
231            CharacteristicKind::Enumeration { .. } | CharacteristicKind::State { .. } => {
232                // Use the property name as the enum class name
233                to_pascal_case(&prop.name())
234            }
235            CharacteristicKind::Collection { .. } | CharacteristicKind::List { .. } => {
236                // List type
237                if let Some(dt) = &char.data_type {
238                    let element_type = map_xsd_to_python(dt);
239                    format!("List[{}]", element_type)
240                } else {
241                    "List[str]".to_string()
242                }
243            }
244            CharacteristicKind::Set { .. } | CharacteristicKind::SortedSet { .. } => {
245                // Set type (represented as List in Python for JSON serialization)
246                if let Some(dt) = &char.data_type {
247                    let element_type = map_xsd_to_python(dt);
248                    format!("List[{}]", element_type)
249                } else {
250                    "List[str]".to_string()
251                }
252            }
253            CharacteristicKind::SingleEntity { entity_type } => {
254                // Object reference - extract entity name
255                let entity_name = entity_type.split('#').next_back().unwrap_or(entity_type);
256                to_pascal_case(entity_name)
257            }
258            CharacteristicKind::TimeSeries { .. } => {
259                // Time series as list of dicts
260                "List[dict]".to_string()
261            }
262            _ => {
263                // Default: use data type
264                if let Some(dt) = &char.data_type {
265                    map_xsd_to_python(dt)
266                } else {
267                    "str".to_string()
268                }
269            }
270        };
271
272        // Add Optional for optional fields
273        if prop.optional {
274            Ok(format!("Optional[{}]", base_type))
275        } else {
276            Ok(base_type)
277        }
278    } else {
279        // No characteristic, default to str
280        if prop.optional {
281            Ok("Optional[str]".to_string())
282        } else {
283            Ok("str".to_string())
284        }
285    }
286}
287
288/// Map XSD types to Python types
289fn map_xsd_to_python(xsd_type: &str) -> String {
290    match xsd_type {
291        t if t.ends_with("string") => "str".to_string(),
292        t if t.ends_with("int") | t.ends_with("integer") => "int".to_string(),
293        t if t.ends_with("long") => "int".to_string(),
294        t if t.ends_with("short") | t.ends_with("byte") => "int".to_string(),
295        t if t.ends_with("decimal") => "float".to_string(),
296        t if t.ends_with("float") => "float".to_string(),
297        t if t.ends_with("double") => "float".to_string(),
298        t if t.ends_with("boolean") => "bool".to_string(),
299        t if t.ends_with("date") => "date".to_string(),
300        t if t.ends_with("dateTime") | t.ends_with("dateTimeStamp") => "datetime".to_string(),
301        t if t.ends_with("time") => "time".to_string(),
302        t if t.ends_with("duration") => "str".to_string(),
303        t if t.ends_with("anyURI") => "str".to_string(),
304        _ => "str".to_string(),
305    }
306}
307
308/// Convert PascalCase/camelCase to snake_case
309fn to_snake_case(s: &str) -> String {
310    let mut result = String::new();
311    for (i, ch) in s.chars().enumerate() {
312        if ch.is_uppercase() {
313            if i > 0 {
314                result.push('_');
315            }
316            result.push(
317                ch.to_lowercase()
318                    .next()
319                    .expect("lowercase should produce a character"),
320            );
321        } else {
322            result.push(ch);
323        }
324    }
325    result
326}
327
328/// Convert snake_case or camelCase to PascalCase
329fn to_pascal_case(s: &str) -> String {
330    let mut result = String::new();
331    let mut capitalize_next = true;
332
333    for ch in s.chars() {
334        if ch == '_' || ch == '-' || ch == ' ' {
335            capitalize_next = true;
336        } else if capitalize_next {
337            result.push(ch.to_ascii_uppercase());
338            capitalize_next = false;
339        } else {
340            result.push(ch);
341        }
342    }
343
344    result
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn test_xsd_to_python_mapping() {
353        assert_eq!(
354            map_xsd_to_python("http://www.w3.org/2001/XMLSchema#string"),
355            "str"
356        );
357        assert_eq!(
358            map_xsd_to_python("http://www.w3.org/2001/XMLSchema#int"),
359            "int"
360        );
361        assert_eq!(
362            map_xsd_to_python("http://www.w3.org/2001/XMLSchema#boolean"),
363            "bool"
364        );
365        assert_eq!(
366            map_xsd_to_python("http://www.w3.org/2001/XMLSchema#float"),
367            "float"
368        );
369        assert_eq!(
370            map_xsd_to_python("http://www.w3.org/2001/XMLSchema#dateTime"),
371            "datetime"
372        );
373    }
374
375    #[test]
376    fn test_case_conversion() {
377        assert_eq!(to_snake_case("MovementAspect"), "movement_aspect");
378        assert_eq!(to_snake_case("currentSpeed"), "current_speed");
379        assert_eq!(to_pascal_case("movement_aspect"), "MovementAspect");
380        assert_eq!(to_pascal_case("currentSpeed"), "CurrentSpeed");
381    }
382
383    #[test]
384    fn test_python_options_default() {
385        let options = PythonOptions::default();
386        assert!(!options.use_pydantic);
387        assert!(options.add_validation);
388        assert!(options.generate_docstrings);
389        assert!(options.snake_case_fields);
390    }
391
392    #[test]
393    fn test_enum_generation() {
394        let values = vec!["green".to_string(), "yellow".to_string(), "red".to_string()];
395        let options = PythonOptions::default();
396        let enum_def = generate_enum_class("TrafficLight", &values, &options);
397
398        assert!(enum_def.contains("class TrafficLight(Enum)"));
399        assert!(enum_def.contains("GREEN = \"green\""));
400        assert!(enum_def.contains("YELLOW = \"yellow\""));
401        assert!(enum_def.contains("RED = \"red\""));
402    }
403
404    #[test]
405    fn regression_enum_generation_numeric_values_produce_valid_identifiers() {
406        let values = vec!["1".to_string(), "2".to_string(), "3".to_string()];
407        let options = PythonOptions::default();
408        let enum_def = generate_enum_class("StatusCode", &values, &options);
409
410        assert!(
411            !enum_def.contains("    1 = \"1\""),
412            "a bare numeric literal is not a legal Python class attribute name: {enum_def}"
413        );
414        assert!(enum_def.contains("VALUE_1 = \"1\""), "{enum_def}");
415        assert!(enum_def.contains("VALUE_2 = \"2\""), "{enum_def}");
416        assert!(enum_def.contains("VALUE_3 = \"3\""), "{enum_def}");
417    }
418}