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                Statement::ExpressionStatement(expr_stmt) => {
93                    let expr_code = self.generate_expression(&expr_stmt.expression)?;
94                    self.functions.push(expr_code);
95                }
96                _ => {
97                    // Handle other statement types
98                }
99            }
100        }
101
102        // Combine all generated code
103        rust_code.push_str(&self.functions.join("\n\n"));
104        rust_code.push('\n');
105        rust_code.push_str(&self.structs.join("\n\n"));
106        rust_code.push('\n');
107        rust_code.push_str(&self.traits.join("\n\n"));
108        rust_code.push('\n');
109        rust_code.push_str(&self.enums.join("\n\n"));
110        rust_code.push('\n');
111        rust_code.push_str(&self.modules.join("\n\n"));
112
113        Ok(rust_code)
114    }
115
116    /// Generate imports
117    fn generate_imports(&self) -> String {
118        let mut imports = vec![
119            "use std::collections::HashMap;".to_string(),
120            "use serde::{Deserialize, Serialize};".to_string(),
121        ];
122
123        if self.runtime_support {
124            imports.push("use std::any::Any;".to_string());
125            imports.push("use std::boxed::Box;".to_string());
126            imports.push("use std::rc::Rc;".to_string());
127            imports.push("use std::sync::Arc;".to_string());
128        }
129
130        imports.extend(self.imports.clone());
131        imports.join("\n")
132    }
133
134    /// Generate runtime support code
135    fn generate_runtime_support(&self) -> String {
136        r#"
137// Runtime support for TypeScript semantics
138pub type Any = Box<dyn Any>;
139pub type Unknown = Box<dyn Any>;
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct Symbol {
143    description: Option<String>,
144}
145
146impl Symbol {
147    pub fn new(description: Option<String>) -> Self {
148        Self { description }
149    }
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub enum UnionType<T> {
154    Variant1(T),
155    Variant2(T),
156    Variant3(T),
157}
158
159pub trait TypeScriptObject {
160    fn get_property(&self, key: &str) -> Option<Any>;
161    fn set_property(&mut self, key: &str, value: Any);
162    fn has_property(&self, key: &str) -> bool;
163    fn delete_property(&mut self, key: &str) -> bool;
164}
165
166impl TypeScriptObject for HashMap<String, Any> {
167    fn get_property(&self, key: &str) -> Option<Any> {
168        self.get(key).cloned()
169    }
170
171    fn set_property(&mut self, key: &str, value: Any) {
172        self.insert(key.to_string(), value);
173    }
174
175    fn has_property(&self, key: &str) -> bool {
176        self.contains_key(key)
177    }
178
179    fn delete_property(&mut self, key: &str) -> bool {
180        self.remove(key).is_some()
181    }
182}
183"#
184        .to_string()
185    }
186
187    /// Generate function
188    fn generate_function(&mut self, func: &FunctionDeclaration) -> Result<String> {
189        let name = &func.name;
190        let params = self.generate_parameters(&func.parameters)?;
191        let return_type = if let Some(ref t) = func.return_type {
192            format!(" -> {}", self.type_mapper.map_type(t)?)
193        } else {
194            " -> ()".to_string()
195        };
196
197        let body = self.generate_statement(&func.body)?;
198
199        Ok(format!(
200            "pub fn {}({}){}{{\n    {}\n}}",
201            name, params, return_type, body
202        ))
203    }
204
205    /// Generate class
206    fn generate_class(&mut self, class: &ClassDeclaration) -> Result<(String, String)> {
207        let name = &class.name;
208        let mut fields = Vec::new();
209        let mut methods = Vec::new();
210
211        // Process class body
212        for member in &class.body.members {
213            match member {
214                ClassMember::Property(prop) => {
215                    let field_type = if let Some(ref t) = prop.type_ {
216                        self.type_mapper.map_type(t)?
217                    } else {
218                        "Box<dyn Any>".to_string()
219                    };
220
221                    let field_name = &prop.name;
222                    let field_def = if prop.optional {
223                        format!("    pub {}: Option<{}>", field_name, field_type)
224                    } else {
225                        format!("    pub {}: {}", field_name, field_type)
226                    };
227                    fields.push(field_def);
228                }
229                ClassMember::Method(method) => {
230                    let method_code = self.generate_method(method)?;
231                    methods.push(method_code);
232                }
233                _ => {
234                    // Handle other member types
235                }
236            }
237        }
238
239        let struct_code = format!(
240            "#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct {} {{\n{}\n}}",
241            name,
242            fields.join(",\n")
243        );
244
245        let impl_code = format!("impl {} {{\n{}\n}}", name, methods.join("\n"));
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 =
266                        format!("    fn set_{}(&mut self, value: {});", prop.name, prop_type);
267                    methods.push(getter);
268                    methods.push(setter);
269                }
270                ObjectTypeMember::Method(method) => {
271                    let method_sig = self.generate_method_signature(method)?;
272                    methods.push(format!("    {};", method_sig));
273                }
274                _ => {
275                    // Handle other member types
276                }
277            }
278        }
279
280        Ok(format!("pub trait {} {{\n{}\n}}", name, methods.join("\n")))
281    }
282
283    /// Generate type alias
284    fn generate_type_alias(&mut self, type_alias: &TypeAlias) -> Result<String> {
285        let name = &type_alias.name;
286        let type_def = self.type_mapper.map_type(&type_alias.type_definition)?;
287        Ok(format!("pub type {} = {};", name, type_def))
288    }
289
290    /// Generate enum
291    fn generate_enum(&mut self, enum_decl: &EnumDeclaration) -> Result<String> {
292        let name = &enum_decl.name;
293        let mut variants = Vec::new();
294
295        for member in &enum_decl.members {
296            let variant_name = &member.name;
297            let variant_value = if let Some(ref init) = member.initializer {
298                match init {
299                    Expression::Literal(Literal::String(s)) => format!(" = \"{}\"", s),
300                    Expression::Literal(Literal::Number(n)) => format!(" = {}", n),
301                    _ => String::new(),
302                }
303            } else {
304                String::new()
305            };
306            variants.push(format!("    {}{}", variant_name, variant_value));
307        }
308
309        Ok(format!(
310            "#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum {} {{\n{}\n}}",
311            name,
312            variants.join(",\n")
313        ))
314    }
315
316    /// Generate variable
317    fn generate_variable(&mut self, var: &VariableDeclaration) -> Result<String> {
318        let name = &var.name;
319        let var_type = if let Some(ref t) = var.type_annotation {
320            self.type_mapper.map_type(t)?
321        } else {
322            "Box<dyn Any>".to_string()
323        };
324
325        let initializer = if let Some(ref init) = var.initializer {
326            format!(" = {}", self.generate_expression(init)?)
327        } else {
328            String::new()
329        };
330
331        Ok(format!("let {}: {}{};", name, var_type, initializer))
332    }
333
334    /// Generate import
335    fn generate_import(&mut self, import: &ImportDeclaration) -> Result<String> {
336        let source = &import.source;
337        let mut import_code = format!("use {}::", source);
338
339        for specifier in &import.specifiers {
340            match specifier {
341                ImportSpecifier::Named(named) => {
342                    import_code.push_str(&format!("{} as {}", named.imported, named.name));
343                }
344                ImportSpecifier::Default(default) => {
345                    import_code.push_str(&default.name);
346                }
347                ImportSpecifier::Namespace(namespace) => {
348                    import_code.push_str(&format!("* as {}", namespace.name));
349                }
350            }
351        }
352
353        Ok(import_code)
354    }
355
356    /// Generate export
357    fn generate_export(&mut self, _export: &ExportDeclaration) -> Result<String> {
358        // In Rust, everything is public by default in the module
359        // Exports are handled by the module system
360        Ok(String::new())
361    }
362
363    /// Generate namespace as module
364    fn generate_namespace(&mut self, namespace: &NamespaceDeclaration) -> Result<String> {
365        let name = &namespace.name;
366        let body = self.generate_statement(&namespace.body)?;
367        Ok(format!("pub mod {} {{\n{}\n}}", name, body))
368    }
369
370    /// Generate module
371    fn generate_module(&mut self, module: &ModuleDeclaration) -> Result<String> {
372        let name = &module.name;
373        let body = self.generate_statement(&module.body)?;
374        Ok(format!("pub mod {} {{\n{}\n}}", name, body))
375    }
376
377    /// Generate method
378    fn generate_method(&mut self, method: &MethodDeclaration) -> Result<String> {
379        let name = &method.name;
380        let params = self.generate_parameters(&method.parameters)?;
381        let return_type = if let Some(ref t) = method.return_type {
382            format!(" -> {}", self.type_mapper.map_type(t)?)
383        } else {
384            " -> ()".to_string()
385        };
386
387        let body = if let Some(ref b) = method.body {
388            self.generate_statement(b)?
389        } else {
390            "unimplemented!()".to_string()
391        };
392
393        Ok(format!(
394            "    pub fn {}(&self, {}){}{{\n        {}\n    }}",
395            name, params, return_type, body
396        ))
397    }
398
399    /// Generate method signature
400    fn generate_method_signature(&mut self, method: &MethodSignature) -> Result<String> {
401        let name = &method.name;
402        let params = self.generate_parameters(&method.parameters)?;
403        let return_type = if let Some(ref t) = method.return_type {
404            format!(" -> {}", self.type_mapper.map_type(t)?)
405        } else {
406            " -> ()".to_string()
407        };
408
409        Ok(format!("fn {}(&self, {}){}", name, params, return_type))
410    }
411
412    /// Generate parameters
413    fn generate_parameters(&mut self, parameters: &[Parameter]) -> Result<String> {
414        let mut param_strings = Vec::new();
415
416        for param in parameters {
417            let param_type = if let Some(ref t) = param.type_ {
418                self.type_mapper.map_type(t)?
419            } else {
420                "Box<dyn Any>".to_string()
421            };
422
423            let param_def = if param.optional {
424                format!("{}: Option<{}>", param.name, param_type)
425            } else {
426                format!("{}: {}", param.name, param_type)
427            };
428
429            param_strings.push(param_def);
430        }
431
432        Ok(param_strings.join(", "))
433    }
434
435    /// Generate statement
436    fn generate_statement(&mut self, statement: &Statement) -> Result<String> {
437        match statement {
438            Statement::BlockStatement(block) => {
439                let mut statements = Vec::new();
440                for stmt in &block.statements {
441                    statements.push(self.generate_statement(stmt)?);
442                }
443                Ok(statements.join("\n    "))
444            }
445            Statement::ExpressionStatement(expr_stmt) => {
446                let expr = self.generate_expression(&expr_stmt.expression)?;
447                // Add semicolon for all statements
448                Ok(format!("{};", expr))
449            }
450            Statement::ReturnStatement(ret) => {
451                if let Some(ref arg) = ret.argument {
452                    Ok(format!("return {};", self.generate_expression(arg)?))
453                } else {
454                    Ok("return;".to_string())
455                }
456            }
457            Statement::VariableDeclaration(var) => self.generate_variable(var),
458            _ => {
459                // Handle other statement types
460                Ok("// TODO: Implement statement".to_string())
461            }
462        }
463    }
464
465    /// Generate expression
466    fn generate_expression(&mut self, expression: &Expression) -> Result<String> {
467        match expression {
468            Expression::Literal(literal) => self.generate_literal(literal),
469            Expression::Identifier(ident) => Ok(ident.clone()),
470            Expression::Binary(binary) => self.generate_binary_expression(binary),
471            Expression::Unary(unary) => self.generate_unary_expression(unary),
472            Expression::Call(call) => self.generate_call_expression(call),
473            Expression::Member(member) => self.generate_member_expression(member),
474            Expression::Array(array) => self.generate_array_expression(array),
475            Expression::Object(object) => self.generate_object_expression(object),
476            Expression::Template(template) => self.generate_template_literal(template),
477            Expression::New(new_expr) => self.generate_new_expression(new_expr),
478            _ => {
479                // Handle other expression types
480                Ok("// TODO: Implement expression".to_string())
481            }
482        }
483    }
484
485    /// Generate literal
486    fn generate_literal(&self, literal: &Literal) -> Result<String> {
487        match literal {
488            Literal::String(s) => Ok(format!("\"{}\"", s)),
489            Literal::Number(n) => Ok(n.to_string()),
490            Literal::Boolean(b) => Ok(b.to_string()),
491            Literal::Null => Ok("None".to_string()),
492            Literal::Undefined => Ok("None".to_string()),
493            _ => Ok("// TODO: Implement literal".to_string()),
494        }
495    }
496
497    /// Generate binary expression
498    fn generate_binary_expression(&mut self, binary: &BinaryExpression) -> Result<String> {
499        let left = self.generate_expression(&binary.left)?;
500        let right = self.generate_expression(&binary.right)?;
501        let operator = self.map_operator(&binary.operator)?;
502        Ok(format!("({} {} {})", left, operator, right))
503    }
504
505    /// Generate unary expression
506    fn generate_unary_expression(&mut self, unary: &UnaryExpression) -> Result<String> {
507        let argument = self.generate_expression(&unary.argument)?;
508        let operator = self.map_operator(&unary.operator)?;
509        Ok(format!("{}{}", operator, argument))
510    }
511
512    /// Generate call expression
513    fn generate_call_expression(&mut self, call: &CallExpression) -> Result<String> {
514        let callee = self.generate_expression(&call.callee)?;
515        let mut args = Vec::new();
516        for arg in &call.arguments {
517            args.push(self.generate_expression(arg)?);
518        }
519        
520        // Special handling for console.log
521        if callee == "console.log" {
522            if args.len() == 1 {
523                Ok(format!("println!(\"{{}}\", {})", args[0]))
524            } else {
525                let format_string = args.iter().map(|_| "{}").collect::<Vec<_>>().join(" ");
526                Ok(format!("println!(\"{}\", {})", format_string, args.join(", ")))
527            }
528        } else {
529            Ok(format!("{}({})", callee, args.join(", ")))
530        }
531    }
532
533    /// Generate member expression
534    fn generate_member_expression(&mut self, member: &MemberExpression) -> Result<String> {
535        let object = self.generate_expression(&member.object)?;
536        let property = self.generate_expression(&member.property)?;
537
538        if member.computed {
539            Ok(format!("{}[{}]", object, property))
540        } else {
541            Ok(format!("{}.{}", object, property))
542        }
543    }
544
545    /// Generate array expression
546    fn generate_array_expression(&mut self, array: &ArrayExpression) -> Result<String> {
547        let mut elements = Vec::new();
548        for element in &array.elements {
549            if let Some(expr) = element {
550                elements.push(self.generate_expression(expr)?);
551            } else {
552                elements.push("None".to_string());
553            }
554        }
555        Ok(format!("vec![{}]", elements.join(", ")))
556    }
557
558    /// Generate object expression
559    fn generate_object_expression(&mut self, object: &ObjectExpression) -> Result<String> {
560        let mut fields = Vec::new();
561        for property in &object.properties {
562            let key = self.generate_expression(&property.key)?;
563            let value = self.generate_expression(&property.value)?;
564            fields.push(format!("{}: {}", key, value));
565        }
566        Ok(format!("{{\n        {}\n    }}", fields.join(",\n        ")))
567    }
568
569    /// Generate template literal
570    fn generate_template_literal(&mut self, template: &TemplateLiteral) -> Result<String> {
571        // For simple template literals, just return the string with proper escaping
572        let raw_string = template.quasis[0].value.replace("${name}", "{}");
573        Ok(format!("\"{}\"", raw_string))
574    }
575
576    /// Generate new expression
577    fn generate_new_expression(&mut self, new_expr: &NewExpression) -> Result<String> {
578        let callee = self.generate_expression(&new_expr.callee)?;
579        let mut args = Vec::new();
580        for arg in &new_expr.arguments {
581            args.push(self.generate_expression(arg)?);
582        }
583        Ok(format!("{}::new({})", callee, args.join(", ")))
584    }
585
586    /// Map operator
587    fn map_operator(&self, token: &crate::lexer::Token) -> Result<String> {
588        match token {
589            crate::lexer::Token::Plus => Ok("+".to_string()),
590            crate::lexer::Token::Minus => Ok("-".to_string()),
591            crate::lexer::Token::Multiply => Ok("*".to_string()),
592            crate::lexer::Token::Divide => Ok("/".to_string()),
593            crate::lexer::Token::Equal => Ok("==".to_string()),
594            crate::lexer::Token::NotEqual => Ok("!=".to_string()),
595            crate::lexer::Token::LessThan => Ok("<".to_string()),
596            crate::lexer::Token::GreaterThan => Ok(">".to_string()),
597            crate::lexer::Token::LessEqual => Ok("<=".to_string()),
598            crate::lexer::Token::GreaterEqual => Ok(">=".to_string()),
599            crate::lexer::Token::And => Ok("&&".to_string()),
600            crate::lexer::Token::Or => Ok("||".to_string()),
601            crate::lexer::Token::Not => Ok("!".to_string()),
602            crate::lexer::Token::Assign => Ok("=".to_string()),
603            _ => Err(CompilerError::generation_error(format!(
604                "Unsupported operator: {:?}",
605                token
606            ))),
607        }
608    }
609}