TypeScript_Rust_Compiler/
generator.rs

1//! Rust code generator for TypeScript AST
2
3use crate::ast::*;
4use crate::error::{CompilerError, Result};
5use crate::types::TypeMapper;
6
7/// Rust code generator
8pub struct CodeGenerator {
9    type_mapper: TypeMapper,
10    imports: Vec<String>,
11    structs: Vec<String>,
12    traits: Vec<String>,
13    functions: Vec<String>,
14    enums: Vec<String>,
15    modules: Vec<String>,
16    runtime_support: bool,
17}
18
19impl CodeGenerator {
20    /// Create a new code generator
21    pub fn new(runtime: bool) -> Self {
22        Self {
23            type_mapper: TypeMapper::new(runtime),
24            imports: Vec::new(),
25            structs: Vec::new(),
26            traits: Vec::new(),
27            functions: Vec::new(),
28            enums: Vec::new(),
29            modules: Vec::new(),
30            runtime_support: runtime,
31        }
32    }
33
34    /// Generate Rust code from TypeScript program
35    pub fn generate(&mut self, program: &Program) -> Result<String> {
36        let mut rust_code = String::new();
37
38        // Generate imports
39        rust_code.push_str(&self.generate_imports());
40        rust_code.push('\n');
41
42        // Generate runtime support if needed
43        if self.runtime_support {
44            rust_code.push_str(&self.generate_runtime_support());
45            rust_code.push('\n');
46        }
47
48        // Process all statements
49        for statement in &program.statements {
50            match statement {
51                Statement::FunctionDeclaration(func) => {
52                    let func_code = self.generate_function(func)?;
53                    self.functions.push(func_code);
54                }
55                Statement::ClassDeclaration(class) => {
56                    let (struct_code, impl_code) = self.generate_class(class)?;
57                    self.structs.push(struct_code);
58                    self.functions.push(impl_code);
59                }
60                Statement::InterfaceDeclaration(interface) => {
61                    let trait_code = self.generate_interface(interface)?;
62                    self.traits.push(trait_code);
63                }
64                Statement::TypeAlias(type_alias) => {
65                    let type_code = self.generate_type_alias(type_alias)?;
66                    self.structs.push(type_code);
67                }
68                Statement::EnumDeclaration(enum_decl) => {
69                    let enum_code = self.generate_enum(enum_decl)?;
70                    self.enums.push(enum_code);
71                }
72                Statement::VariableDeclaration(var) => {
73                    let var_code = self.generate_variable(var)?;
74                    self.functions.push(var_code);
75                }
76                Statement::ImportDeclaration(import) => {
77                    let import_code = self.generate_import(import)?;
78                    self.imports.push(import_code);
79                }
80                Statement::ExportDeclaration(export) => {
81                    let export_code = self.generate_export(export)?;
82                    self.functions.push(export_code);
83                }
84                Statement::NamespaceDeclaration(namespace) => {
85                    let module_code = self.generate_namespace(namespace)?;
86                    self.modules.push(module_code);
87                }
88                Statement::ModuleDeclaration(module) => {
89                    let module_code = self.generate_module(module)?;
90                    self.modules.push(module_code);
91                }
92                _ => {
93                    // Handle other statement types
94                }
95            }
96        }
97
98        // Combine all generated code
99        rust_code.push_str(&self.functions.join("\n\n"));
100        rust_code.push('\n');
101        rust_code.push_str(&self.structs.join("\n\n"));
102        rust_code.push('\n');
103        rust_code.push_str(&self.traits.join("\n\n"));
104        rust_code.push('\n');
105        rust_code.push_str(&self.enums.join("\n\n"));
106        rust_code.push('\n');
107        rust_code.push_str(&self.modules.join("\n\n"));
108
109        Ok(rust_code)
110    }
111
112    /// Generate imports
113    fn generate_imports(&self) -> String {
114        let mut imports = vec![
115            "use std::collections::HashMap;".to_string(),
116            "use serde::{Deserialize, Serialize};".to_string(),
117        ];
118
119        if self.runtime_support {
120            imports.push("use std::any::Any;".to_string());
121            imports.push("use std::boxed::Box;".to_string());
122            imports.push("use std::rc::Rc;".to_string());
123            imports.push("use std::sync::Arc;".to_string());
124        }
125
126        imports.extend(self.imports.clone());
127        imports.join("\n")
128    }
129
130    /// Generate runtime support code
131    fn generate_runtime_support(&self) -> String {
132        r#"
133// Runtime support for TypeScript semantics
134pub type Any = Box<dyn Any>;
135pub type Unknown = Box<dyn Any>;
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct Symbol {
139    description: Option<String>,
140}
141
142impl Symbol {
143    pub fn new(description: Option<String>) -> Self {
144        Self { description }
145    }
146}
147
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub enum UnionType<T> {
150    Variant1(T),
151    Variant2(T),
152    Variant3(T),
153}
154
155pub trait TypeScriptObject {
156    fn get_property(&self, key: &str) -> Option<Any>;
157    fn set_property(&mut self, key: &str, value: Any);
158    fn has_property(&self, key: &str) -> bool;
159    fn delete_property(&mut self, key: &str) -> bool;
160}
161
162impl TypeScriptObject for HashMap<String, Any> {
163    fn get_property(&self, key: &str) -> Option<Any> {
164        self.get(key).cloned()
165    }
166
167    fn set_property(&mut self, key: &str, value: Any) {
168        self.insert(key.to_string(), value);
169    }
170
171    fn has_property(&self, key: &str) -> bool {
172        self.contains_key(key)
173    }
174
175    fn delete_property(&mut self, key: &str) -> bool {
176        self.remove(key).is_some()
177    }
178}
179"#
180        .to_string()
181    }
182
183    /// Generate function
184    fn generate_function(&mut self, func: &FunctionDeclaration) -> Result<String> {
185        let name = &func.name;
186        let params = self.generate_parameters(&func.parameters)?;
187        let return_type = if let Some(ref t) = func.return_type {
188            format!(" -> {}", self.type_mapper.map_type(t)?)
189        } else {
190            " -> ()".to_string()
191        };
192
193        let body = self.generate_statement(&func.body)?;
194
195        Ok(format!(
196            "pub fn {}({}){}{{\n    {}\n}}",
197            name, params, return_type, body
198        ))
199    }
200
201    /// Generate class
202    fn generate_class(&mut self, class: &ClassDeclaration) -> Result<(String, String)> {
203        let name = &class.name;
204        let mut fields = Vec::new();
205        let mut methods = Vec::new();
206
207        // Process class body
208        for member in &class.body.members {
209            match member {
210                ClassMember::Property(prop) => {
211                    let field_type = if let Some(ref t) = prop.type_ {
212                        self.type_mapper.map_type(t)?
213                    } else {
214                        "Box<dyn Any>".to_string()
215                    };
216
217                    let field_name = &prop.name;
218                    let field_def = if prop.optional {
219                        format!("    pub {}: Option<{}>", field_name, field_type)
220                    } else {
221                        format!("    pub {}: {}", field_name, field_type)
222                    };
223                    fields.push(field_def);
224                }
225                ClassMember::Method(method) => {
226                    let method_code = self.generate_method(method)?;
227                    methods.push(method_code);
228                }
229                _ => {
230                    // Handle other member types
231                }
232            }
233        }
234
235        let struct_code = format!(
236            "#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct {} {{\n{}\n}}",
237            name,
238            fields.join(",\n")
239        );
240
241        let impl_code = format!(
242            "impl {} {{\n{}\n}}",
243            name,
244            methods.join("\n")
245        );
246
247        Ok((struct_code, impl_code))
248    }
249
250    /// Generate interface as trait
251    fn generate_interface(&mut self, interface: &InterfaceDeclaration) -> Result<String> {
252        let name = &interface.name;
253        let mut methods = Vec::new();
254
255        for member in &interface.body.members {
256            match member {
257                ObjectTypeMember::Property(prop) => {
258                    let prop_type = if let Some(ref t) = prop.type_ {
259                        self.type_mapper.map_type(t)?
260                    } else {
261                        "Box<dyn Any>".to_string()
262                    };
263
264                    let getter = format!("    fn get_{}(&self) -> {};", prop.name, prop_type);
265                    let setter = format!("    fn set_{}(&mut self, value: {});", prop.name, prop_type);
266                    methods.push(getter);
267                    methods.push(setter);
268                }
269                ObjectTypeMember::Method(method) => {
270                    let method_sig = self.generate_method_signature(method)?;
271                    methods.push(format!("    {};", method_sig));
272                }
273                _ => {
274                    // Handle other member types
275                }
276            }
277        }
278
279        Ok(format!("pub trait {} {{\n{}\n}}", name, methods.join("\n")))
280    }
281
282    /// Generate type alias
283    fn generate_type_alias(&mut self, type_alias: &TypeAlias) -> Result<String> {
284        let name = &type_alias.name;
285        let type_def = self.type_mapper.map_type(&type_alias.type_definition)?;
286        Ok(format!("pub type {} = {};", name, type_def))
287    }
288
289    /// Generate enum
290    fn generate_enum(&mut self, enum_decl: &EnumDeclaration) -> Result<String> {
291        let name = &enum_decl.name;
292        let mut variants = Vec::new();
293
294        for member in &enum_decl.members {
295            let variant_name = &member.name;
296            let variant_value = if let Some(ref init) = member.initializer {
297                match init {
298                    Expression::Literal(Literal::String(s)) => format!(" = \"{}\"", s),
299                    Expression::Literal(Literal::Number(n)) => format!(" = {}", n),
300                    _ => String::new(),
301                }
302            } else {
303                String::new()
304            };
305            variants.push(format!("    {}{}", variant_name, variant_value));
306        }
307
308        Ok(format!(
309            "#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum {} {{\n{}\n}}",
310            name,
311            variants.join(",\n")
312        ))
313    }
314
315    /// Generate variable
316    fn generate_variable(&mut self, var: &VariableDeclaration) -> Result<String> {
317        let name = &var.name;
318        let var_type = if let Some(ref t) = var.type_annotation {
319            self.type_mapper.map_type(t)?
320        } else {
321            "Box<dyn Any>".to_string()
322        };
323
324        let initializer = if let Some(ref init) = var.initializer {
325            format!(" = {}", self.generate_expression(init)?)
326        } else {
327            String::new()
328        };
329
330        Ok(format!("let {}: {} = {};", name, var_type, initializer))
331    }
332
333    /// Generate import
334    fn generate_import(&mut self, import: &ImportDeclaration) -> Result<String> {
335        let source = &import.source;
336        let mut import_code = format!("use {}::", source);
337
338        for specifier in &import.specifiers {
339            match specifier {
340                ImportSpecifier::Named(named) => {
341                    import_code.push_str(&format!("{} as {}", named.imported, named.name));
342                }
343                ImportSpecifier::Default(default) => {
344                    import_code.push_str(&default.name);
345                }
346                ImportSpecifier::Namespace(namespace) => {
347                    import_code.push_str(&format!("* as {}", namespace.name));
348                }
349            }
350        }
351
352        Ok(import_code)
353    }
354
355    /// Generate export
356    fn generate_export(&mut self, _export: &ExportDeclaration) -> Result<String> {
357        // In Rust, everything is public by default in the module
358        // Exports are handled by the module system
359        Ok(String::new())
360    }
361
362    /// Generate namespace as module
363    fn generate_namespace(&mut self, namespace: &NamespaceDeclaration) -> Result<String> {
364        let name = &namespace.name;
365        let body = self.generate_statement(&namespace.body)?;
366        Ok(format!("pub mod {} {{\n{}\n}}", name, body))
367    }
368
369    /// Generate module
370    fn generate_module(&mut self, module: &ModuleDeclaration) -> Result<String> {
371        let name = &module.name;
372        let body = self.generate_statement(&module.body)?;
373        Ok(format!("pub mod {} {{\n{}\n}}", name, body))
374    }
375
376    /// Generate method
377    fn generate_method(&mut self, method: &MethodDeclaration) -> Result<String> {
378        let name = &method.name;
379        let params = self.generate_parameters(&method.parameters)?;
380        let return_type = if let Some(ref t) = method.return_type {
381            format!(" -> {}", self.type_mapper.map_type(t)?)
382        } else {
383            " -> ()".to_string()
384        };
385
386        let body = if let Some(ref b) = method.body {
387            self.generate_statement(b)?
388        } else {
389            "unimplemented!()".to_string()
390        };
391
392        Ok(format!(
393            "    pub fn {}(&self, {}){}{{\n        {}\n    }}",
394            name, params, return_type, body
395        ))
396    }
397
398    /// Generate method signature
399    fn generate_method_signature(&mut self, method: &MethodSignature) -> Result<String> {
400        let name = &method.name;
401        let params = self.generate_parameters(&method.parameters)?;
402        let return_type = if let Some(ref t) = method.return_type {
403            format!(" -> {}", self.type_mapper.map_type(t)?)
404        } else {
405            " -> ()".to_string()
406        };
407
408        Ok(format!("fn {}(&self, {}){}", name, params, return_type))
409    }
410
411    /// Generate parameters
412    fn generate_parameters(&mut self, parameters: &[Parameter]) -> Result<String> {
413        let mut param_strings = Vec::new();
414
415        for param in parameters {
416            let param_type = if let Some(ref t) = param.type_ {
417                self.type_mapper.map_type(t)?
418            } else {
419                "Box<dyn Any>".to_string()
420            };
421
422            let param_def = if param.optional {
423                format!("{}: Option<{}>", param.name, param_type)
424            } else {
425                format!("{}: {}", param.name, param_type)
426            };
427
428            param_strings.push(param_def);
429        }
430
431        Ok(param_strings.join(", "))
432    }
433
434    /// Generate statement
435    fn generate_statement(&mut self, statement: &Statement) -> Result<String> {
436        match statement {
437            Statement::BlockStatement(block) => {
438                let mut statements = Vec::new();
439                for stmt in &block.statements {
440                    statements.push(self.generate_statement(stmt)?);
441                }
442                Ok(format!("{{\n    {}\n}}", statements.join("\n    ")))
443            }
444            Statement::ExpressionStatement(expr_stmt) => {
445                Ok(self.generate_expression(&expr_stmt.expression)?)
446            }
447            Statement::ReturnStatement(ret) => {
448                if let Some(ref arg) = ret.argument {
449                    Ok(format!("return {};", self.generate_expression(arg)?))
450                } else {
451                    Ok("return;".to_string())
452                }
453            }
454            Statement::VariableDeclaration(var) => {
455                self.generate_variable(var)
456            }
457            _ => {
458                // Handle other statement types
459                Ok("// TODO: Implement statement".to_string())
460            }
461        }
462    }
463
464    /// Generate expression
465    fn generate_expression(&mut self, expression: &Expression) -> Result<String> {
466        match expression {
467            Expression::Literal(literal) => self.generate_literal(literal),
468            Expression::Identifier(ident) => Ok(ident.clone()),
469            Expression::Binary(binary) => self.generate_binary_expression(binary),
470            Expression::Unary(unary) => self.generate_unary_expression(unary),
471            Expression::Call(call) => self.generate_call_expression(call),
472            Expression::Member(member) => self.generate_member_expression(member),
473            Expression::Array(array) => self.generate_array_expression(array),
474            Expression::Object(object) => self.generate_object_expression(object),
475            _ => {
476                // Handle other expression types
477                Ok("// TODO: Implement expression".to_string())
478            }
479        }
480    }
481
482    /// Generate literal
483    fn generate_literal(&self, literal: &Literal) -> Result<String> {
484        match literal {
485            Literal::String(s) => Ok(format!("\"{}\"", s)),
486            Literal::Number(n) => Ok(n.to_string()),
487            Literal::Boolean(b) => Ok(b.to_string()),
488            Literal::Null => Ok("None".to_string()),
489            Literal::Undefined => Ok("None".to_string()),
490            _ => Ok("// TODO: Implement literal".to_string()),
491        }
492    }
493
494    /// Generate binary expression
495    fn generate_binary_expression(&mut self, binary: &BinaryExpression) -> Result<String> {
496        let left = self.generate_expression(&binary.left)?;
497        let right = self.generate_expression(&binary.right)?;
498        let operator = self.map_operator(&binary.operator)?;
499        Ok(format!("({} {} {})", left, operator, right))
500    }
501
502    /// Generate unary expression
503    fn generate_unary_expression(&mut self, unary: &UnaryExpression) -> Result<String> {
504        let argument = self.generate_expression(&unary.argument)?;
505        let operator = self.map_operator(&unary.operator)?;
506        Ok(format!("{}{}", operator, argument))
507    }
508
509    /// Generate call expression
510    fn generate_call_expression(&mut self, call: &CallExpression) -> Result<String> {
511        let callee = self.generate_expression(&call.callee)?;
512        let mut args = Vec::new();
513        for arg in &call.arguments {
514            args.push(self.generate_expression(arg)?);
515        }
516        Ok(format!("{}({})", callee, args.join(", ")))
517    }
518
519    /// Generate member expression
520    fn generate_member_expression(&mut self, member: &MemberExpression) -> Result<String> {
521        let object = self.generate_expression(&member.object)?;
522        let property = self.generate_expression(&member.property)?;
523        
524        if member.computed {
525            Ok(format!("{}[{}]", object, property))
526        } else {
527            Ok(format!("{}.{}", object, property))
528        }
529    }
530
531    /// Generate array expression
532    fn generate_array_expression(&mut self, array: &ArrayExpression) -> Result<String> {
533        let mut elements = Vec::new();
534        for element in &array.elements {
535            if let Some(expr) = element {
536                elements.push(self.generate_expression(expr)?);
537            } else {
538                elements.push("None".to_string());
539            }
540        }
541        Ok(format!("vec![{}]", elements.join(", ")))
542    }
543
544    /// Generate object expression
545    fn generate_object_expression(&mut self, object: &ObjectExpression) -> Result<String> {
546        let mut fields = Vec::new();
547        for property in &object.properties {
548            let key = self.generate_expression(&property.key)?;
549            let value = self.generate_expression(&property.value)?;
550            fields.push(format!("{}: {}", key, value));
551        }
552        Ok(format!("HashMap::from([{}])", fields.join(", ")))
553    }
554
555    /// Map operator
556    fn map_operator(&self, token: &crate::lexer::Token) -> Result<String> {
557        match token {
558            crate::lexer::Token::Plus => Ok("+".to_string()),
559            crate::lexer::Token::Minus => Ok("-".to_string()),
560            crate::lexer::Token::Multiply => Ok("*".to_string()),
561            crate::lexer::Token::Divide => Ok("/".to_string()),
562            crate::lexer::Token::Equal => Ok("==".to_string()),
563            crate::lexer::Token::NotEqual => Ok("!=".to_string()),
564            crate::lexer::Token::LessThan => Ok("<".to_string()),
565            crate::lexer::Token::GreaterThan => Ok(">".to_string()),
566            crate::lexer::Token::LessEqual => Ok("<=".to_string()),
567            crate::lexer::Token::GreaterEqual => Ok(">=".to_string()),
568            crate::lexer::Token::And => Ok("&&".to_string()),
569            crate::lexer::Token::Or => Ok("||".to_string()),
570            crate::lexer::Token::Not => Ok("!".to_string()),
571            crate::lexer::Token::Assign => Ok("=".to_string()),
572            _ => Err(CompilerError::generation_error(format!(
573                "Unsupported operator: {:?}",
574                token
575            ))),
576        }
577    }
578}