help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
code-assistant-bot
/
utils
RSK World
code-assistant-bot
Code Assistant Bot - Python + Flask + OpenAI API + Code Generation + Debugging + Code Analysis + GitHub Integration
utils
  • __pycache__
  • __init__.py874 B
  • code_analyzer.py14.1 KB
  • code_comparator.py6 KB
  • code_converter.py15.4 KB
  • code_documenter.py12.8 KB
  • code_formatter.py10.3 KB
  • code_optimizer.py12.6 KB
  • code_reviewer.py11.7 KB
  • code_tester.py20.8 KB
  • github_integration.py14.4 KB
  • syntax_checker.py24.3 KB
__init__.pysyntax_checker.pycode_reviewer.pycode_converter.py
utils/__init__.py
Raw Download
Find: Go to:
"""
Utils package for Code Assistant Bot
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

from .code_analyzer import CodeAnalyzer
from .github_integration import GitHubIntegration
from .syntax_checker import SyntaxChecker
from .code_optimizer import CodeOptimizer
from .code_converter import CodeConverter
from .code_tester import CodeTester
from .code_formatter import CodeFormatter
from .code_documenter import CodeDocumenter
from .code_reviewer import CodeReviewer
from .code_comparator import CodeComparator

__all__ = [
    'CodeAnalyzer', 
    'GitHubIntegration', 
    'SyntaxChecker',
    'CodeOptimizer',
    'CodeConverter',
    'CodeTester',
    'CodeFormatter',
    'CodeDocumenter',
    'CodeReviewer',
    'CodeComparator'
]
33 lines•874 B
python
utils/syntax_checker.py
Raw Download
Find: Go to:
"""
Syntax Checker Utility for Code Assistant Bot
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import ast
import re
import subprocess
import tempfile
import os
from typing import Dict, List, Any, Tuple

class SyntaxChecker:
    """
    Utility class for checking syntax errors in various programming languages
    """
    
    def __init__(self):
        self.supported_languages = [
            'python', 'javascript', 'java', 'cpp', 'c', 'csharp',
            'php', 'ruby', 'go', 'rust', 'typescript', 'html', 'css'
        ]
    
    def check_syntax(self, code: str, language: str) -> Dict[str, Any]:
        """
        Check syntax for the given code and language
        """
        try:
            if language not in self.supported_languages:
                return {
                    'valid': False,
                    'error': f'Language {language} is not supported',
                    'errors': [],
                    'warnings': []
                }
            
            # Language-specific syntax checking
            if language == 'python':
                return self._check_python_syntax(code)
            elif language in ['javascript', 'typescript']:
                return self._check_javascript_syntax(code, language)
            elif language == 'java':
                return self._check_java_syntax(code)
            elif language in ['cpp', 'c']:
                return self._check_cpp_syntax(code, language)
            elif language == 'csharp':
                return self._check_csharp_syntax(code)
            elif language == 'php':
                return self._check_php_syntax(code)
            elif language == 'ruby':
                return self._check_ruby_syntax(code)
            elif language == 'go':
                return self._check_go_syntax(code)
            elif language == 'rust':
                return self._check_rust_syntax(code)
            elif language == 'html':
                return self._check_html_syntax(code)
            elif language == 'css':
                return self._check_css_syntax(code)
            else:
                return {
                    'valid': True,
                    'error': None,
                    'errors': [],
                    'warnings': ['Syntax checking not implemented for this language']
                }
                
        except Exception as e:
            return {
                'valid': False,
                'error': f'Syntax checking failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_python_syntax(self, code: str) -> Dict[str, Any]:
        """Check Python syntax using AST"""
        try:
            # Parse the code
            ast.parse(code)
            
            # Additional checks
            warnings = self._check_python_style(code)
            
            return {
                'valid': True,
                'error': None,
                'errors': [],
                'warnings': warnings
            }
            
        except SyntaxError as e:
            return {
                'valid': False,
                'error': 'Syntax error detected',
                'errors': [{
                    'line': e.lineno or 0,
                    'column': e.offset or 0,
                    'message': e.msg or 'Unknown syntax error'
                }],
                'warnings': []
            }
        except Exception as e:
            return {
                'valid': False,
                'error': f'Parse error: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_javascript_syntax(self, code: str, language: str) -> Dict[str, Any]:
        """Check JavaScript/TypeScript syntax"""
        try:
            # Basic syntax checks using regex patterns
            errors = []
            warnings = []
            
            # Check for unmatched brackets
            bracket_pairs = {'(': ')', '[': ']', '{': '}'}
            stack = []
            
            for i, char in enumerate(code):
                if char in bracket_pairs:
                    stack.append((char, i))
                elif char in bracket_pairs.values():
                    if not stack:
                        errors.append({
                            'line': code[:i].count('\n') + 1,
                            'column': i - code.rfind('\n', 0, i) - 1,
                            'message': f'Unmatched closing bracket: {char}'
                        })
                    else:
                        open_bracket, _ = stack.pop()
                        expected_close = bracket_pairs[open_bracket]
                        if char != expected_close:
                            errors.append({
                                'line': code[:i].count('\n') + 1,
                                'column': i - code.rfind('\n', 0, i) - 1,
                                'message': f'Expected {expected_close} but found {char}'
                            })
            
            # Check for unclosed brackets
            for open_bracket, pos in stack:
                errors.append({
                    'line': code[:pos].count('\n') + 1,
                    'column': pos - code.rfind('\n', 0, pos) - 1,
                    'message': f'Unclosed bracket: {open_bracket}'
                })
            
            # Check for common issues
            if '==' in code and '===' not in code:
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'Consider using === instead of == for strict equality'
                })
            
            # Check for missing semicolons (basic check)
            lines = code.split('\n')
            for i, line in enumerate(lines):
                stripped = line.strip()
                if (stripped and 
                    not stripped.endswith(('{', '}', ';', ',', '(', ')', '[', ']')) and
                    not any(keyword in stripped for keyword in ['if', 'for', 'while', 'function', 'else', 'try', 'catch', 'finally', 'class', 'return', 'break', 'continue']) and
                    not stripped.startswith('//') and
                    not stripped.startswith('/*')):
                    warnings.append({
                        'line': i + 1,
                        'column': len(line),
                        'message': 'Missing semicolon at end of line'
                    })
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'JavaScript syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_java_syntax(self, code: str) -> Dict[str, Any]:
        """Check Java syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for class declaration
            if not re.search(r'\bclass\s+\w+', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No class declaration found'
                })
            
            # Check for main method
            if not re.search(r'public\s+static\s+void\s+main\s*\(\s*String\s*\[\s*\]\s*\w+\s*\)', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No main method found'
                })
            
            # Check for unmatched brackets
            bracket_errors = self._check_brackets(code)
            errors.extend(bracket_errors)
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'Java syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_cpp_syntax(self, code: str, language: str) -> Dict[str, Any]:
        """Check C/C++ syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for main function
            if not re.search(r'int\s+main\s*\(', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No main function found'
                })
            
            # Check for include statements
            if not re.search(r'#include\s*<[^>]+>', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No include statements found'
                })
            
            # Check for unmatched brackets
            bracket_errors = self._check_brackets(code)
            errors.extend(bracket_errors)
            
            # Check for missing semicolons
            lines = code.split('\n')
            for i, line in enumerate(lines):
                stripped = line.strip()
                if (stripped and 
                    not stripped.endswith(('{', '}', ';', ',', '(', ')', '[', ']', ':', '//')) and
                    not any(keyword in stripped for keyword in ['if', 'for', 'while', 'else', 'switch', 'case', 'default', 'return', 'break', 'continue', 'using', 'namespace']) and
                    not stripped.startswith('#') and
                    not stripped.startswith('//')):
                    warnings.append({
                        'line': i + 1,
                        'column': len(line),
                        'message': 'Missing semicolon at end of line'
                    })
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'C/C++ syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_csharp_syntax(self, code: str) -> Dict[str, Any]:
        """Check C# syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for class declaration
            if not re.search(r'\bclass\s+\w+', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No class declaration found'
                })
            
            # Check for Main method
            if not re.search(r'static\s+void\s+Main\s*\(', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No Main method found'
                })
            
            # Check for using statements
            if not re.search(r'using\s+\w+(?:\.\w+)*\s*;', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No using statements found'
                })
            
            # Check for unmatched brackets
            bracket_errors = self._check_brackets(code)
            errors.extend(bracket_errors)
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'C# syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_php_syntax(self, code: str) -> Dict[str, Any]:
        """Check PHP syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for PHP tags
            if not re.search(r'<\?php', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No PHP opening tag found'
                })
            
            # Check for unmatched brackets
            bracket_errors = self._check_brackets(code)
            errors.extend(bracket_errors)
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'PHP syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_ruby_syntax(self, code: str) -> Dict[str, Any]:
        """Check Ruby syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for unmatched brackets
            bracket_errors = self._check_brackets(code)
            errors.extend(bracket_errors)
            
            # Check for end statements
            do_count = len(re.findall(r'\bdo\b', code))
            end_count = len(re.findall(r'\bend\b', code))
            
            if do_count != end_count:
                errors.append({
                    'line': 0,
                    'column': 0,
                    'message': f'Mismatched do/end blocks: {do_count} do, {end_count} end'
                })
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'Ruby syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_go_syntax(self, code: str) -> Dict[str, Any]:
        """Check Go syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for package declaration
            if not re.search(r'package\s+\w+', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No package declaration found'
                })
            
            # Check for main function
            if not re.search(r'func\s+main\s*\(', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No main function found'
                })
            
            # Check for unmatched brackets
            bracket_errors = self._check_brackets(code)
            errors.extend(bracket_errors)
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'Go syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_rust_syntax(self, code: str) -> Dict[str, Any]:
        """Check Rust syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for fn main
            if not re.search(r'fn\s+main\s*\(', code):
                warnings.append({
                    'line': 0,
                    'column': 0,
                    'message': 'No main function found'
                })
            
            # Check for unmatched brackets
            bracket_errors = self._check_brackets(code)
            errors.extend(bracket_errors)
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'Syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'Rust syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_html_syntax(self, code: str) -> Dict[str, Any]:
        """Check HTML syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for unmatched tags
            tag_pattern = r'<(/?)([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>'
            tags = re.finditer(tag_pattern, code)
            
            stack = []
            for match in tags:
                is_closing = match.group(1) == '/'
                tag_name = match.group(2).lower()
                position = match.start()
                
                # Skip self-closing tags
                if match.group(0).endswith('/>') or tag_name in ['br', 'hr', 'img', 'meta', 'link', 'input']:
                    continue
                
                if is_closing:
                    if not stack or stack[-1] != tag_name:
                        errors.append({
                            'line': code[:position].count('\n') + 1,
                            'column': position - code.rfind('\n', 0, position) - 1,
                            'message': f'Unexpected closing tag: {tag_name}'
                        })
                    else:
                        stack.pop()
                else:
                    stack.append(tag_name)
            
            # Check for unclosed tags
            for tag in stack:
                errors.append({
                    'line': 0,
                    'column': 0,
                    'message': f'Unclosed tag: {tag}'
                })
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'HTML syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'HTML syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_css_syntax(self, code: str) -> Dict[str, Any]:
        """Check CSS syntax (basic checks)"""
        try:
            errors = []
            warnings = []
            
            # Check for unmatched braces
            open_braces = code.count('{')
            close_braces = code.count('}')
            
            if open_braces != close_braces:
                errors.append({
                    'line': 0,
                    'column': 0,
                    'message': f'Unmatched braces: {open_braces} opening, {close_braces} closing'
                })
            
            # Check for invalid selectors (basic check)
            selector_pattern = r'([^{]+)\s*\{'
            matches = re.finditer(selector_pattern, code)
            
            for match in matches:
                selector = match.group(1).strip()
                if not selector:
                    errors.append({
                        'line': code[:match.start()].count('\n') + 1,
                        'column': match.start() - code.rfind('\n', 0, match.start()) - 1,
                        'message': 'Empty selector found'
                    })
            
            return {
                'valid': len(errors) == 0,
                'error': None if len(errors) == 0 else 'CSS syntax errors detected',
                'errors': errors,
                'warnings': warnings
            }
            
        except Exception as e:
            return {
                'valid': False,
                'error': f'CSS syntax check failed: {str(e)}',
                'errors': [{'line': 0, 'column': 0, 'message': str(e)}],
                'warnings': []
            }
    
    def _check_brackets(self, code: str) -> List[Dict[str, Any]]:
        """Check for unmatched brackets"""
        errors = []
        bracket_pairs = {'(': ')', '[': ']', '{': '}'}
        stack = []
        
        for i, char in enumerate(code):
            if char in bracket_pairs:
                stack.append((char, i))
            elif char in bracket_pairs.values():
                if not stack:
                    errors.append({
                        'line': code[:i].count('\n') + 1,
                        'column': i - code.rfind('\n', 0, i) - 1,
                        'message': f'Unmatched closing bracket: {char}'
                    })
                else:
                    open_bracket, _ = stack.pop()
                    expected_close = bracket_pairs[open_bracket]
                    if char != expected_close:
                        errors.append({
                            'line': code[:i].count('\n') + 1,
                            'column': i - code.rfind('\n', 0, i) - 1,
                            'message': f'Expected {expected_close} but found {char}'
                        })
        
        # Check for unclosed brackets
        for open_bracket, pos in stack:
            errors.append({
                'line': code[:pos].count('\n') + 1,
                'column': pos - code.rfind('\n', 0, pos) - 1,
                'message': f'Unclosed bracket: {open_bracket}'
            })
        
        return errors
    
    def _check_python_style(self, code: str) -> List[Dict[str, Any]]:
        """Check Python code style issues"""
        warnings = []
        lines = code.split('\n')
        
        for i, line in enumerate(lines):
            stripped = line.strip()
            
            # Check line length
            if len(line) > 79:
                warnings.append({
                    'line': i + 1,
                    'column': 80,
                    'message': f'Line too long ({len(line)} > 79 characters)'
                })
            
            # Check for trailing whitespace
            if line.endswith(' ') or line.endswith('\t'):
                warnings.append({
                    'line': i + 1,
                    'column': len(line),
                    'message': 'Trailing whitespace'
                })
            
            # Check for missing docstring in functions
            if stripped.startswith('def ') and ':' in stripped:
                next_line = lines[i + 1] if i + 1 < len(lines) else ''
                if not next_line.strip().startswith('"""') and not next_line.strip().startswith("'''"):
                    warnings.append({
                        'line': i + 1,
                        'column': len(stripped),
                        'message': 'Missing docstring in function'
                    })
        
        return warnings
652 lines•24.3 KB
python
utils/code_reviewer.py
Raw Download
Find: Go to:
"""
Code Reviewer Utility for Code Assistant Bot
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import re
import ast
from typing import Dict, List, Any, Optional

class CodeReviewer:
    """
    Utility class for code review and suggestions
    """
    
    def __init__(self):
        self.review_rules = {
            'python': self._review_python,
            'javascript': self._review_javascript,
            'typescript': self._review_javascript,
            'java': self._review_java,
            'cpp': self._review_cpp,
            'c': self._review_cpp
        }
    
    def review_code(self, code: str, language: str) -> Dict[str, Any]:
        """
        Review code and provide suggestions
        """
        try:
            review_function = self.review_rules.get(language, self._review_generic)
            return review_function(code, language)
        except Exception as e:
            return {
                'success': False,
                'error': f'Code review failed: {str(e)}',
                'issues': [],
                'suggestions': []
            }
    
    def _review_python(self, code: str, language: str) -> Dict[str, Any]:
        """Review Python code"""
        issues = []
        suggestions = []
        
        try:
            # Parse code
            tree = ast.parse(code)
            lines = code.split('\n')
            
            # Check for PEP 8 violations
            for i, line in enumerate(lines, 1):
                # Line length
                if len(line) > 79:
                    issues.append({
                        'type': 'style',
                        'severity': 'low',
                        'line': i,
                        'message': f'Line {i} exceeds 79 characters (PEP 8)',
                        'suggestion': 'Break long lines into multiple lines'
                    })
                
                # Trailing whitespace
                if line.rstrip() != line:
                    issues.append({
                        'type': 'style',
                        'severity': 'low',
                        'line': i,
                        'message': f'Line {i} has trailing whitespace',
                        'suggestion': 'Remove trailing whitespace'
                    })
            
            # Check for missing docstrings
            for node in ast.walk(tree):
                if isinstance(node, ast.FunctionDef):
                    if not ast.get_docstring(node):
                        suggestions.append({
                            'type': 'documentation',
                            'severity': 'medium',
                            'line': node.lineno,
                            'message': f'Function "{node.name}" is missing a docstring',
                            'suggestion': 'Add a docstring describing the function'
                        })
                
                elif isinstance(node, ast.ClassDef):
                    if not ast.get_docstring(node):
                        suggestions.append({
                            'type': 'documentation',
                            'severity': 'medium',
                            'line': node.lineno,
                            'message': f'Class "{node.name}" is missing a docstring',
                            'suggestion': 'Add a docstring describing the class'
                        })
            
            # Check for bare except
            for node in ast.walk(tree):
                if isinstance(node, ast.ExceptHandler):
                    if node.type is None:
                        issues.append({
                            'type': 'error_handling',
                            'severity': 'high',
                            'line': node.lineno,
                            'message': 'Bare except clause found',
                            'suggestion': 'Specify exception types instead of bare except'
                        })
            
            # Check for unused imports (basic)
            imports = []
            for node in ast.walk(tree):
                if isinstance(node, ast.Import):
                    for alias in node.names:
                        imports.append(alias.name)
                elif isinstance(node, ast.ImportFrom):
                    if node.module:
                        imports.append(node.module)
            
            # Check for potential bugs
            code_str = code.lower()
            if 'eval(' in code_str:
                issues.append({
                    'type': 'security',
                    'severity': 'critical',
                    'line': 0,
                    'message': 'Use of eval() detected',
                    'suggestion': 'Avoid eval() - it can be a security risk'
                })
            
            if 'exec(' in code_str:
                issues.append({
                    'type': 'security',
                    'severity': 'critical',
                    'line': 0,
                    'message': 'Use of exec() detected',
                    'suggestion': 'Avoid exec() - it can be a security risk'
                })
            
        except SyntaxError as e:
            issues.append({
                'type': 'syntax',
                'severity': 'critical',
                'line': e.lineno or 0,
                'message': f'Syntax error: {str(e)}',
                'suggestion': 'Fix syntax errors before reviewing'
            })
        
        return {
            'success': True,
            'issues': issues,
            'suggestions': suggestions,
            'summary': {
                'total_issues': len(issues),
                'total_suggestions': len(suggestions),
                'critical': len([i for i in issues if i['severity'] == 'critical']),
                'high': len([i for i in issues if i['severity'] == 'high']),
                'medium': len([i for i in issues if i['severity'] == 'medium']),
                'low': len([i for i in issues if i['severity'] == 'low'])
            }
        }
    
    def _review_javascript(self, code: str, language: str) -> Dict[str, Any]:
        """Review JavaScript/TypeScript code"""
        issues = []
        suggestions = []
        lines = code.split('\n')
        
        # Check for var usage
        for i, line in enumerate(lines, 1):
            if re.search(r'\bvar\s+', line):
                suggestions.append({
                    'type': 'best_practice',
                    'severity': 'medium',
                    'line': i,
                    'message': 'Use of var detected',
                    'suggestion': 'Use let or const instead of var for better scoping'
                })
            
            # Check for == instead of ===
            if '==' in line and '===' not in line and '!=' not in line:
                suggestions.append({
                    'type': 'best_practice',
                    'severity': 'low',
                    'line': i,
                    'message': 'Use of == instead of ===',
                    'suggestion': 'Use === for strict equality comparison'
                })
            
            # Check for missing semicolons
            stripped = line.strip()
            if (stripped and 
                not stripped.endswith(('{', '}', ';', ',', '(', ')', '[', ']')) and
                not any(keyword in stripped for keyword in ['if', 'for', 'while', 'function', 'else', 'try', 'catch'])):
                suggestions.append({
                    'type': 'style',
                    'severity': 'low',
                    'line': i,
                    'message': 'Missing semicolon',
                    'suggestion': 'Add semicolon at end of statement'
                })
        
        # Check for eval usage
        if 'eval(' in code:
            issues.append({
                'type': 'security',
                'severity': 'critical',
                'line': 0,
                'message': 'Use of eval() detected',
                'suggestion': 'Avoid eval() - it can be a security risk'
            })
        
        return {
            'success': True,
            'issues': issues,
            'suggestions': suggestions,
            'summary': {
                'total_issues': len(issues),
                'total_suggestions': len(suggestions),
                'critical': len([i for i in issues if i['severity'] == 'critical']),
                'high': len([i for i in issues if i['severity'] == 'high']),
                'medium': len([i for i in issues if i['severity'] == 'medium']),
                'low': len([i for i in issues if i['severity'] == 'low'])
            }
        }
    
    def _review_java(self, code: str, language: str) -> Dict[str, Any]:
        """Review Java code"""
        issues = []
        suggestions = []
        lines = code.split('\n')
        
        # Check for missing JavaDoc
        for i, line in enumerate(lines, 1):
            if re.search(r'(public|private|protected)\s+\w+\s+\w+\s*\(', line):
                # Check if previous lines have JavaDoc
                if i > 1 and not lines[i-2].strip().startswith('/**'):
                    suggestions.append({
                        'type': 'documentation',
                        'severity': 'medium',
                        'line': i,
                        'message': 'Method missing JavaDoc comment',
                        'suggestion': 'Add JavaDoc comment above method'
                    })
        
        return {
            'success': True,
            'issues': issues,
            'suggestions': suggestions,
            'summary': {
                'total_issues': len(issues),
                'total_suggestions': len(suggestions),
                'critical': 0,
                'high': 0,
                'medium': len(suggestions),
                'low': 0
            }
        }
    
    def _review_cpp(self, code: str, language: str) -> Dict[str, Any]:
        """Review C/C++ code"""
        issues = []
        suggestions = []
        
        # Check for memory leaks (basic)
        if 'malloc(' in code and 'free(' not in code:
            suggestions.append({
                'type': 'memory',
                'severity': 'high',
                'line': 0,
                'message': 'Potential memory leak',
                'suggestion': 'Ensure all malloc() calls have corresponding free() calls'
            })
        
        return {
            'success': True,
            'issues': issues,
            'suggestions': suggestions,
            'summary': {
                'total_issues': len(issues),
                'total_suggestions': len(suggestions),
                'critical': 0,
                'high': len(suggestions),
                'medium': 0,
                'low': 0
            }
        }
    
    def _review_generic(self, code: str, language: str) -> Dict[str, Any]:
        """Generic code review"""
        return {
            'success': True,
            'issues': [],
            'suggestions': [{
                'type': 'info',
                'severity': 'low',
                'line': 0,
                'message': f'Generic review for {language}',
                'suggestion': 'Consider using language-specific review tools'
            }],
            'summary': {
                'total_issues': 0,
                'total_suggestions': 1,
                'critical': 0,
                'high': 0,
                'medium': 0,
                'low': 1
            }
        }
310 lines•11.7 KB
python
utils/code_converter.py
Raw Download
Find: Go to:
"""
Code Converter Utility for Code Assistant Bot
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import re
import json
from typing import Dict, List, Any, Optional

class CodeConverter:
    """
    Advanced code conversion between programming languages
    """
    
    def __init__(self):
        self.supported_conversions = {
            'python': ['javascript', 'java', 'cpp', 'csharp'],
            'javascript': ['python', 'typescript', 'java'],
            'java': ['python', 'cpp', 'csharp'],
            'cpp': ['python', 'java', 'c'],
            'csharp': ['python', 'java', 'cpp'],
            'typescript': ['javascript', 'python'],
            'php': ['python', 'javascript'],
            'go': ['python', 'cpp'],
            'rust': ['cpp', 'python']
        }
        
        self.language_mappings = {
            'python': {
                'keywords': {
                    'def': 'function',
                    'class': 'class',
                    'if': 'if',
                    'else': 'else',
                    'elif': 'else if',
                    'for': 'for',
                    'while': 'while',
                    'try': 'try',
                    'except': 'catch',
                    'finally': 'finally',
                    'import': 'import',
                    'from': 'import',
                    'return': 'return',
                    'break': 'break',
                    'continue': 'continue',
                    'pass': 'pass',
                    'None': 'null',
                    'True': 'true',
                    'False': 'false',
                    'and': '&&',
                    'or': '||',
                    'not': '!'
                },
                'data_types': {
                    'str': 'string',
                    'int': 'number',
                    'float': 'number',
                    'bool': 'boolean',
                    'list': 'Array',
                    'dict': 'Object',
                    'tuple': 'Array'
                }
            },
            'javascript': {
                'keywords': {
                    'function': 'def',
                    'class': 'class',
                    'if': 'if',
                    'else': 'else',
                    'for': 'for',
                    'while': 'while',
                    'try': 'try',
                    'catch': 'except',
                    'finally': 'finally',
                    'import': 'import',
                    'return': 'return',
                    'break': 'break',
                    'continue': 'continue',
                    'null': 'None',
                    'true': 'True',
                    'false': 'False',
                    '&&': 'and',
                    '||': 'or',
                    '!': 'not'
                },
                'data_types': {
                    'string': 'str',
                    'number': 'int',
                    'boolean': 'bool',
                    'Array': 'list',
                    'Object': 'dict'
                }
            }
        }
    
    def convert_code(self, code: str, from_lang: str, to_lang: str) -> Dict[str, Any]:
        """
        Convert code from one language to another
        """
        try:
            if from_lang not in self.supported_conversions:
                return {
                    'success': False,
                    'error': f'Source language {from_lang} not supported',
                    'converted_code': ''
                }
            
            if to_lang not in self.supported_conversions[from_lang]:
                return {
                    'success': False,
                    'error': f'Conversion from {from_lang} to {to_lang} not supported',
                    'converted_code': ''
                }
            
            # Perform conversion based on language pair
            conversion_method = f'_convert_{from_lang}_to_{to_lang}'
            if hasattr(self, conversion_method):
                result = getattr(self, conversion_method)(code)
            else:
                # Use generic conversion
                result = self._generic_convert(code, from_lang, to_lang)
            
            return {
                'success': True,
                'converted_code': result['code'],
                'changes_made': result['changes'],
                'warnings': result.get('warnings', []),
                'from_language': from_lang,
                'to_language': to_lang
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': f'Conversion failed: {str(e)}',
                'converted_code': ''
            }
    
    def _convert_python_to_javascript(self, code: str) -> Dict[str, Any]:
        """Convert Python code to JavaScript"""
        changes = []
        warnings = []
        js_code = code
        
        # Convert function definitions
        js_code = re.sub(r'def\s+(\w+)\s*\(([^)]*)\):', r'function \1(\2) {', js_code)
        changes.append('Function definitions converted')
        
        # Convert class definitions
        js_code = re.sub(r'class\s+(\w+)(?:\([^)]*\))?:', r'class \1 {', js_code)
        changes.append('Class definitions converted')
        
        # Convert if/elif/else
        js_code = re.sub(r'elif\s+', 'else if ', js_code)
        changes.append('elif converted to else if')
        
        # Convert boolean values
        js_code = js_code.replace('True', 'true').replace('False', 'false')
        js_code = js_code.replace('None', 'null')
        changes.append('Boolean and null values converted')
        
        # Convert logical operators
        js_code = js_code.replace(' and ', ' && ').replace(' or ', ' || ')
        js_code = js_code.replace(' not ', ' !')
        changes.append('Logical operators converted')
        
        # Convert print statements
        js_code = re.sub(r'print\s*\(([^)]+)\)', r'console.log(\1)', js_code)
        changes.append('print statements converted to console.log')
        
        # Convert list/dict literals
        js_code = js_code.replace('[', '[').replace(']', ']')  # Keep as is
        js_code = js_code.replace('{', '{').replace('}', '}')    # Keep as is
        
        # Convert indentation to braces (basic)
        lines = js_code.split('\n')
        brace_lines = []
        indent_stack = [0]
        
        for line in lines:
            stripped = line.strip()
            if not stripped:
                brace_lines.append('')
                continue
            
            current_indent = len(line) - len(line.lstrip())
            
            # Close braces for reduced indentation
            while current_indent < indent_stack[-1]:
                brace_lines.append(' ' * indent_stack[-2] + '}')
                indent_stack.pop()
            
            # Add the current line
            if stripped.endswith(':'):
                brace_lines.append(line.rstrip(':') + ' {')
                indent_stack.append(current_indent + 4)
            else:
                brace_lines.append(line + ';')
        
        # Close remaining braces
        while len(indent_stack) > 1:
            brace_lines.append(' ' * indent_stack[-2] + '}')
            indent_stack.pop()
        
        js_code = '\n'.join(brace_lines)
        changes.append('Python indentation converted to JavaScript braces')
        
        # Add warnings for unsupported features
        if 'import ' in js_code:
            warnings.append('Python imports may need manual conversion to ES6 imports')
        
        if '__' in js_code:
            warnings.append('Python dunder methods may need manual conversion')
        
        return {
            'code': js_code,
            'changes': changes,
            'warnings': warnings
        }
    
    def _convert_javascript_to_python(self, code: str) -> Dict[str, Any]:
        """Convert JavaScript code to Python"""
        changes = []
        warnings = []
        py_code = code
        
        # Convert function definitions
        py_code = re.sub(r'function\s+(\w+)\s*\(([^)]*)\)\s*{', r'def \1(\2):', py_code)
        py_code = re.sub(r'const\s+(\w+)\s*=\s*\(([^)]*)\)\s*=>', r'def \1(\2):', py_code)
        changes.append('Function definitions converted')
        
        # Convert class definitions
        py_code = re.sub(r'class\s+(\w+)\s*{', r'class \1:', py_code)
        changes.append('Class definitions converted')
        
        # Convert else if to elif
        py_code = py_code.replace('else if', 'elif')
        changes.append('else if converted to elif')
        
        # Convert boolean values
        py_code = py_code.replace('true', 'True').replace('false', 'False')
        py_code = py_code.replace('null', 'None')
        changes.append('Boolean and None values converted')
        
        # Convert logical operators
        py_code = py_code.replace(' && ', ' and ').replace(' || ', ' or ')
        py_code = re.sub(r'\s*!\s*', ' not ', py_code)
        changes.append('Logical operators converted')
        
        # Convert console.log to print
        py_code = re.sub(r'console\.log\s*\(([^)]+)\)', r'print(\1)', py_code)
        changes.append('console.log converted to print')
        
        # Convert braces to indentation (basic)
        lines = py_code.split('\n')
        indent_lines = []
        indent_level = 0
        
        for line in lines:
            stripped = line.strip()
            if not stripped:
                indent_lines.append('')
                continue
            
            # Handle closing braces
            if stripped == '}':
                indent_level = max(0, indent_level - 1)
                continue
            
            # Handle opening braces
            if stripped.endswith('{'):
                indent_lines.append('    ' * indent_level + stripped[:-1].strip() + ':')
                indent_level += 1
            else:
                # Remove semicolons and add proper indentation
                clean_line = stripped.rstrip(';')
                indent_lines.append('    ' * indent_level + clean_line)
        
        py_code = '\n'.join(indent_lines)
        changes.append('JavaScript braces converted to Python indentation')
        
        # Add warnings for unsupported features
        if 'var ' in py_code:
            warnings.append('var declarations converted to let - consider scope')
        
        if '=>' in py_code:
            warnings.append('Arrow functions may need manual review')
        
        return {
            'code': py_code,
            'changes': changes,
            'warnings': warnings
        }
    
    def _convert_python_to_java(self, code: str) -> Dict[str, Any]:
        """Convert Python code to Java"""
        changes = []
        warnings = []
        java_code = code
        
        # Convert function definitions
        java_code = re.sub(r'def\s+(\w+)\s*\(([^)]*)\):', r'public static \1(\2) {', java_code)
        changes.append('Function definitions converted to static methods')
        
        # Convert class definitions
        java_code = re.sub(r'class\s+(\w+)(?:\([^)]*\))?:', r'public class \1 {', java_code)
        changes.append('Class definitions converted')
        
        # Convert data types
        java_code = java_code.replace('True', 'true').replace('False', 'false')
        java_code = java_code.replace('None', 'null')
        changes.append('Boolean and null values converted')
        
        # Convert print statements
        java_code = re.sub(r'print\s*\(([^)]+)\)', r'System.out.println(\1)', java_code)
        changes.append('print statements converted to System.out.println')
        
        # Add type declarations (basic)
        java_code = re.sub(r'(\w+)\s*=', 'Object ', java_code)
        changes.append('Variable declarations added (Object type)')
        
        # Add warnings
        warnings.append('Java conversion requires manual type declarations')
        warnings.append('Python dynamic typing may need explicit Java types')
        warnings.append('Consider adding proper package and import statements')
        
        return {
            'code': java_code,
            'changes': changes,
            'warnings': warnings
        }
    
    def _generic_convert(self, code: str, from_lang: str, to_lang: str) -> Dict[str, Any]:
        """Generic conversion using keyword mappings"""
        changes = []
        warnings = []
        converted_code = code
        
        # Get keyword mappings
        from_mapping = self.language_mappings.get(from_lang, {}).get('keywords', {})
        to_mapping = self.language_mappings.get(to_lang, {}).get('keywords', {})
        
        # Apply keyword conversions
        for from_keyword, to_keyword in from_mapping.items():
            if from_keyword in converted_code:
                # Use word boundaries to avoid partial matches
                pattern = r'\b' + re.escape(from_keyword) + r'\b'
                converted_code = re.sub(pattern, to_keyword, converted_code)
                changes.append(f'Converted {from_keyword} to {to_keyword}')
        
        # Add generic warnings
        warnings.append(f'Generic conversion from {from_lang} to {to_lang} - manual review recommended')
        warnings.append('Language-specific features may need manual adjustment')
        
        return {
            'code': converted_code,
            'changes': changes,
            'warnings': warnings
        }
    
    def get_supported_conversions(self) -> Dict[str, List[str]]:
        """Get all supported language conversions"""
        return self.supported_conversions
    
    def detect_language(self, code: str) -> Optional[str]:
        """Detect the programming language of the code"""
        language_patterns = {
            'python': [r'def\s+\w+\s*\(', r'import\s+\w+', r'from\s+\w+\s+import', r'print\s*\('],
            'javascript': [r'function\s+\w+\s*\(', r'const\s+\w+\s*=', r'let\s+\w+\s*=', r'console\.log'],
            'java': [r'public\s+class\s+\w+', r'public\s+static\s+void\s+main', r'System\.out\.println'],
            'cpp': [r'#include\s*<[^>]+>', r'int\s+main\s*\(', r'cout\s*<<', r'cin\s*>>'],
            'csharp': [r'using\s+\w+', r'public\s+class\s+\w+', r'Console\.WriteLine'],
            'php': [r'<\?php', r'\$\w+\s*=', r'echo\s+', r'function\s+\w+\s*\('],
            'ruby': [r'def\s+\w+', r'puts\s+', r'end\s*$', r'@\w+'],
            'go': [r'package\s+\w+', r'func\s+\w+\s*\(', r'fmt\.Print'],
            'rust': [r'fn\s+\w+\s*\(', r'let\s+mut\s+\w+', r'println!'],
            'typescript': [r'interface\s+\w+', r'type\s+\w+', r':\s*\w+\[\]']
        }
        
        scores = {}
        for lang, patterns in language_patterns.items():
            score = 0
            for pattern in patterns:
                if re.search(pattern, code, re.IGNORECASE):
                    score += 1
            scores[lang] = score
        
        # Return language with highest score
        if scores:
            best_lang = max(scores, key=scores.get)
            if scores[best_lang] > 0:
                return best_lang
        
        return None
399 lines•15.4 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer