File size: 4,065 Bytes
cff74af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Dict, List, Optional
import random

class CodeGenerator:
    """A class to generate function code in multiple programming languages."""
    
    # Supported languages and their templates with proper indentation
    TEMPLATES: Dict[str, str] = {
        "python": "def {func_name}({params}):\n    {body}",
        "javascript": "function {func_name}({params}) {{\n    {body}\n}}",
        "cpp": "{ret_type} {func_name}({params}) {{\n    {body}\n}}",
        "java": "public class Main {{\n    public static {ret_type} {func_name}({params}) {{\n        {body}\n    }}\n}}",
        "csharp": "public class Program {{\n    public static {ret_type} {func_name}({params}) {{\n        {body}\n    }}\n}}"
    }

    # Configuration data
    FUNCTION_NAMES: List[str] = ["calculate", "processData", "computeValue", "generateOutput"]
    DEFAULT_PARAMS: Dict[str, str] = {
        "python": "x: int, y: int",
        "javascript": "x, y",
        "cpp": "int x, int y",
        "java": "int x, int y",
        "csharp": "int x, int y"
    }
    RETURN_TYPES: Dict[str, str] = {
        "cpp": "int",
        "java": "int",
        "csharp": "int",
        "python": " -> int",  # Type hint for Python
        "javascript": ""      # No explicit return type
    }
    DEFAULT_BODY: str = "return x + y;"
    
    def __init__(self, seed: Optional[int] = None):
        """Initialize generator with optional random seed."""
        if seed is not None:
            random.seed(seed)

    def get_supported_languages(self) -> List[str]:
        """Return list of supported languages."""
        return list(self.TEMPLATES.keys())

    def generate_code(
        self,
        language: str,
        func_name: Optional[str] = None,
        params: Optional[str] = None,
        body: Optional[str] = None,
        ret_type: Optional[str] = None
    ) -> Optional[str]:
        """
        Generate code for the specified language with customizable components.
        
        Args:
            language: Target programming language
            func_name: Optional custom function name
            params: Optional custom parameters
            body: Optional custom function body
            ret_type: Optional custom return type
            
        Returns:
            Generated code string or None if language is unsupported
        """
        if language not in self.TEMPLATES:
            return None

        # Use provided values or defaults
        selected_func_name = func_name or random.choice(self.FUNCTION_NAMES)
        selected_params = params or self.DEFAULT_PARAMS.get(language, "")
        selected_body = self._normalize_body(body or self.DEFAULT_BODY, language)
        selected_ret_type = ret_type or self.RETURN_TYPES.get(language, "")

        try:
            return self.TEMPLATES[language].format(
                func_name=selected_func_name,
                params=selected_params,
                body=selected_body,
                ret_type=selected_ret_type
            )
        except KeyError as e:
            raise ValueError(f"Missing template component: {str(e)}")
        except Exception as e:
            raise RuntimeError(f"Code generation failed: {str(e)}")

    def _normalize_body(self, body: str, language: str) -> str:
        """Normalize function body based on language requirements."""
        body = body.strip()
        if language in {"cpp", "java", "csharp"} and not body.endswith(";"):
            return body + ";"
        if language == "python":
            return body.replace(";", "")  # Python doesn't use semicolons
        return body

def main():
    """Demonstrate code generation for all supported languages."""
    generator = CodeGenerator(seed=42)  # Fixed seed for reproducibility
    
    print("Supported languages:", generator.get_supported_languages())
    print("\nGenerated code examples:")
    
    for lang in generator.get_supported_languages():
        code = generator.generate_code(lang)
        print(f"\n{lang.upper()}:\n{code}")

if __name__ == "__main__":
    main()