Files
overcode/over_interpreter.py

723 lines
23 KiB
Python

#!/usr/bin/env python3
"""
OverCode Interpreter - Enhanced Polyglot Execution Engine
Supports 15+ programming languages with advanced features
"""
import re
import subprocess
import tempfile
import os
import sys
import json
import time
from pathlib import Path
from colorama import Fore, Style, init
# Import progress bars
try:
from utils.progress import ProgressBar, SpinnerProgress
except ImportError:
# Fallback if utils not available
class ProgressBar:
def __init__(self, *args, **kwargs): pass
def update(self, *args, **kwargs): pass
class SpinnerProgress:
def __init__(self, *args, **kwargs): pass
def start(self): pass
def stop(self, *args): pass
init(autoreset=True)
class OverCodeInterpreter:
"""Advanced polyglot code interpreter"""
def __init__(self):
self.supported_languages = {
'py': 'Python',
'js': 'JavaScript',
'ts': 'TypeScript',
'php': 'PHP',
'rb': 'Ruby',
'go': 'Go',
'rs': 'Rust',
'java': 'Java',
'cpp': 'C++',
'c': 'C',
'cs': 'C#',
'lua': 'Lua',
'perl': 'Perl',
'r': 'R',
'swift': 'Swift',
'kotlin': 'Kotlin',
'dart': 'Dart',
'julia': 'Julia',
'bash': 'Bash',
'ps': 'PowerShell'
}
self.outputs = []
self.execution_times = {}
self.errors = []
def interpret(self, source_code, verbose=False):
"""Main interpretation method with progress bars"""
print(Fore.CYAN + "🚀 OverCode Interpreter v2.0" + Style.RESET_ALL)
print(Fore.YELLOW + "" * 50)
start_time = time.time()
# Count total language blocks to process
total_blocks = 0
for lang_key in self.supported_languages.keys():
pattern = f'<\\?{lang_key}(.*?)\\?>'
segments = re.findall(pattern, source_code, re.DOTALL)
total_blocks += len([s for s in segments if s.strip()])
if total_blocks > 0:
# Create progress bar for execution
progress = ProgressBar(total_blocks, style='fire', color='green')
current_block = 0
# Process each language block
for lang_key, lang_name in self.supported_languages.items():
current_block = self._process_language_with_progress(
source_code, lang_key, lang_name, verbose, progress, current_block
)
else:
print(Fore.YELLOW + "No executable code blocks found.")
# Display results
self._display_results()
total_time = time.time() - start_time
print(Fore.GREEN + f"\n✓ Total execution time: {total_time:.3f}s" + Style.RESET_ALL)
return '\n'.join(self.outputs)
def _process_language_with_progress(self, source, lang_key, lang_name, verbose, progress, current_block):
"""Process language blocks with progress tracking"""
pattern = f'<\\?{lang_key}(.*?)\\?>'
segments = re.findall(pattern, source, re.DOTALL)
if not segments:
return current_block
for i, segment in enumerate(segments):
code = segment.strip()
if not code:
continue
# Update progress
progress.update(current_block + 1, f"Executing {lang_name} block {i+1}")
start = time.time()
output = self._execute_code(lang_key, code, verbose)
exec_time = time.time() - start
if output:
self.outputs.append(f"[{lang_name} Block {i+1}]\n{output}")
self.execution_times[f"{lang_name}_{i+1}"] = exec_time
current_block += 1
time.sleep(0.1) # Small delay to show progress
return current_block
def _process_language(self, source, lang_key, lang_name, verbose):
"""Process code blocks for a specific language"""
pattern = f'<\\?{lang_key}(.*?)\\?>'
segments = re.findall(pattern, source, re.DOTALL)
if not segments:
return
if verbose:
print(Fore.BLUE + f"📦 Processing {lang_name} blocks..." + Style.RESET_ALL)
for i, segment in enumerate(segments):
code = segment.strip()
if not code:
continue
start = time.time()
output = self._execute_code(lang_key, code, verbose)
exec_time = time.time() - start
if output:
self.outputs.append(f"[{lang_name} Block {i+1}]\n{output}")
self.execution_times[f"{lang_name}_{i+1}"] = exec_time
def _execute_code(self, lang, code, verbose):
"""Execute code for a specific language"""
try:
if lang == 'py':
return self._run_python(code)
elif lang == 'js':
return self._run_javascript(code)
elif lang == 'ts':
return self._run_typescript(code)
elif lang == 'php':
return self._run_php(code)
elif lang == 'rb':
return self._run_ruby(code)
elif lang == 'go':
return self._run_go(code)
elif lang == 'rs':
return self._run_rust(code)
elif lang == 'java':
return self._run_java(code)
elif lang == 'cpp':
return self._run_cpp(code)
elif lang == 'c':
return self._run_c(code)
elif lang == 'cs':
return self._run_csharp(code)
elif lang == 'lua':
return self._run_lua(code)
elif lang == 'perl':
return self._run_perl(code)
elif lang == 'r':
return self._run_r(code)
elif lang == 'swift':
return self._run_swift(code)
elif lang == 'kotlin':
return self._run_kotlin(code)
elif lang == 'dart':
return self._run_dart(code)
elif lang == 'julia':
return self._run_julia(code)
elif lang == 'bash':
return self._run_bash(code)
elif lang == 'ps':
return self._run_powershell(code)
else:
return f"Language {lang} not yet implemented"
except Exception as e:
error_msg = f"Error executing {lang}: {str(e)}"
self.errors.append(error_msg)
return error_msg if verbose else ""
def _run_python(self, code):
"""Execute Python code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.py') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['python', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout + (result.stderr if result.stderr else "")
finally:
os.unlink(path)
def _run_javascript(self, code):
"""Execute JavaScript code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.js') as f:
f.write(code)
path = f.name
try:
# Try node first, then fallback to other JS engines
for cmd in ['node', 'nodejs', 'deno', 'bun']:
if self._command_exists(cmd):
result = subprocess.run(
[cmd, path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout + (result.stderr if result.stderr else "")
return "JavaScript runtime not found (install Node.js)"
finally:
os.unlink(path)
def _run_typescript(self, code):
"""Execute TypeScript code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.ts') as f:
f.write(code)
path = f.name
try:
if self._command_exists('ts-node'):
result = subprocess.run(
['ts-node', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
elif self._command_exists('deno'):
result = subprocess.run(
['deno', 'run', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
return "TypeScript runtime not found (install ts-node or deno)"
finally:
os.unlink(path)
def _run_php(self, code):
"""Execute PHP code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.php') as f:
f.write("<?php\n" + code + "\n?>")
path = f.name
try:
result = subprocess.run(
['php', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_ruby(self, code):
"""Execute Ruby code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.rb') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['ruby', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_go(self, code):
"""Execute Go code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.go') as f:
# Wrap in main function if not present
if 'func main()' not in code:
code = f'package main\nimport "fmt"\nfunc main() {{\n{code}\n}}'
f.write(code)
path = f.name
try:
result = subprocess.run(
['go', 'run', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_rust(self, code):
"""Execute Rust code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.rs') as f:
# Wrap in main function if not present
if 'fn main()' not in code:
code = f'fn main() {{\n{code}\n}}'
f.write(code)
path = f.name
try:
exe_path = path.replace('.rs', '')
compile_result = subprocess.run(
['rustc', path, '-o', exe_path],
capture_output=True,
text=True,
timeout=10
)
if os.path.exists(exe_path):
run_result = subprocess.run(
[exe_path],
capture_output=True,
text=True,
timeout=10
)
os.unlink(exe_path)
return run_result.stdout
return compile_result.stderr
finally:
os.unlink(path)
def _run_java(self, code):
"""Execute Java code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.java') as f:
# Wrap in class if not present
if 'class' not in code:
code = f'''
public class TempClass {{
public static void main(String[] args) {{
{code}
}}
}}'''
f.write(code)
path = f.name
try:
# Extract class name
class_name = re.search(r'class\s+(\w+)', code)
if class_name:
class_name = class_name.group(1)
else:
class_name = 'TempClass'
# Compile
subprocess.run(['javac', path], capture_output=True, timeout=10)
# Run
class_file = os.path.join(os.path.dirname(path), f'{class_name}.class')
if os.path.exists(class_file):
result = subprocess.run(
['java', '-cp', os.path.dirname(path), class_name],
capture_output=True,
text=True,
timeout=10
)
os.unlink(class_file)
return result.stdout
return "Compilation failed"
finally:
os.unlink(path)
def _run_cpp(self, code):
"""Execute C++ code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.cpp') as f:
# Add necessary includes if not present
if '#include' not in code:
code = '#include <iostream>\nusing namespace std;\n' + code
if 'int main()' not in code:
code = f'{code}\nint main() {{ return 0; }}'
f.write(code)
path = f.name
try:
exe_path = path.replace('.cpp', '.exe' if os.name == 'nt' else '')
compile_result = subprocess.run(
['g++', path, '-o', exe_path],
capture_output=True,
text=True,
timeout=10
)
if os.path.exists(exe_path):
run_result = subprocess.run(
[exe_path],
capture_output=True,
text=True,
timeout=10
)
os.unlink(exe_path)
return run_result.stdout
return compile_result.stderr
finally:
os.unlink(path)
def _run_c(self, code):
"""Execute C code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.c') as f:
if '#include' not in code:
code = '#include <stdio.h>\n' + code
if 'int main()' not in code:
code = f'{code}\nint main() {{ return 0; }}'
f.write(code)
path = f.name
try:
exe_path = path.replace('.c', '.exe' if os.name == 'nt' else '')
compile_result = subprocess.run(
['gcc', path, '-o', exe_path],
capture_output=True,
text=True,
timeout=10
)
if os.path.exists(exe_path):
run_result = subprocess.run(
[exe_path],
capture_output=True,
text=True,
timeout=10
)
os.unlink(exe_path)
return run_result.stdout
return compile_result.stderr
finally:
os.unlink(path)
def _run_csharp(self, code):
"""Execute C# code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.cs') as f:
if 'class' not in code:
code = f'''
using System;
class Program {{
static void Main() {{
{code}
}}
}}'''
f.write(code)
path = f.name
try:
exe_path = path.replace('.cs', '.exe')
compile_result = subprocess.run(
['csc', '/nologo', f'/out:{exe_path}', path],
capture_output=True,
text=True,
timeout=10
)
if os.path.exists(exe_path):
run_result = subprocess.run(
[exe_path],
capture_output=True,
text=True,
timeout=10
)
os.unlink(exe_path)
return run_result.stdout
return "C# compiler not found or compilation failed"
finally:
os.unlink(path)
def _run_lua(self, code):
"""Execute Lua code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.lua') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['lua', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_perl(self, code):
"""Execute Perl code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.pl') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['perl', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_r(self, code):
"""Execute R code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.r') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['Rscript', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_swift(self, code):
"""Execute Swift code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.swift') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['swift', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_kotlin(self, code):
"""Execute Kotlin code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.kt') as f:
if 'fun main()' not in code:
code = f'fun main() {{\n{code}\n}}'
f.write(code)
path = f.name
try:
jar_path = path.replace('.kt', '.jar')
subprocess.run(
['kotlinc', path, '-d', jar_path],
capture_output=True,
timeout=10
)
if os.path.exists(jar_path):
result = subprocess.run(
['java', '-jar', jar_path],
capture_output=True,
text=True,
timeout=10
)
os.unlink(jar_path)
return result.stdout
return "Kotlin compiler not found"
finally:
os.unlink(path)
def _run_dart(self, code):
"""Execute Dart code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.dart') as f:
if 'void main()' not in code:
code = f'void main() {{\n{code}\n}}'
f.write(code)
path = f.name
try:
result = subprocess.run(
['dart', 'run', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_julia(self, code):
"""Execute Julia code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.jl') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['julia', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_bash(self, code):
"""Execute Bash code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.sh') as f:
f.write(code)
path = f.name
try:
if os.name == 'nt':
# On Windows, try WSL or Git Bash
for shell in ['bash', 'sh']:
if self._command_exists(shell):
result = subprocess.run(
[shell, path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
return "Bash not available on Windows (install WSL or Git Bash)"
else:
result = subprocess.run(
['bash', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _run_powershell(self, code):
"""Execute PowerShell code"""
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.ps1') as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
['powershell', '-ExecutionPolicy', 'Bypass', '-File', path],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
finally:
os.unlink(path)
def _command_exists(self, command):
"""Check if a command exists"""
try:
subprocess.run(
['which' if os.name != 'nt' else 'where', command],
capture_output=True,
check=False
)
return True
except:
return False
def _display_results(self):
"""Display execution results"""
if self.outputs:
print(Fore.GREEN + "\n📋 Output:" + Style.RESET_ALL)
print("" * 50)
for output in self.outputs:
print(output)
if self.errors:
print(Fore.RED + "\n❌ Errors:" + Style.RESET_ALL)
for error in self.errors:
print(f"{error}")
if self.execution_times:
print(Fore.CYAN + "\n⏱️ Execution Times:" + Style.RESET_ALL)
for lang, exec_time in self.execution_times.items():
print(f"{lang}: {exec_time:.3f}s")
def interpret_file(filepath, verbose=False):
"""Interpret an OverCode file"""
interpreter = OverCodeInterpreter()
try:
with open(filepath, 'r', encoding='utf-8') as f:
source_code = f.read()
return interpreter.interpret(source_code, verbose)
except FileNotFoundError:
print(Fore.RED + f"Error: File '{filepath}' not found" + Style.RESET_ALL)
return None
except Exception as e:
print(Fore.RED + f"Error: {str(e)}" + Style.RESET_ALL)
return None
if __name__ == "__main__":
if len(sys.argv) > 1:
interpret_file(sys.argv[1], verbose=True)
else:
print("Usage: python over_interpreter.py <file.ovc>")