mrhidee/compiler
0
1import gradio as gr2 3class StackVM:4 def __init__(self):5 self.stack = []6 self.output = []7 8 def reset(self):9 self.stack = []10 self.output = []11 12 def run(self, bytecode):13 self.reset()14 instructions = bytecode.strip().split('\n')15 for line_num, line in enumerate(instructions, start=1):16 parts = line.strip().split()17 if not parts:18 continue19 instr = parts[0].upper()20 try:21 if instr == "PUSH":22 if len(parts) != 2 or not parts[1].lstrip('-').isdigit():23 self.output.append(f"Line {line_num}: Error - Invalid PUSH instruction")24 return25 self.stack.append(int(parts[1]))26 elif instr == "POP":27 if not self.stack:28 self.output.append(f"Line {line_num}: Error - Stack underflow on POP")29 return30 self.stack.pop()31 elif instr in ["ADD", "SUB", "MUL", "DIV"]:32 if len(self.stack) < 2:33 self.output.append(f"Line {line_num}: Error - Not enough values for {instr}")34 return35 b = self.stack.pop()36 a = self.stack.pop()37 if instr == "ADD":38 self.stack.append(a + b)39 elif instr == "SUB":40 self.stack.append(a - b)41 elif instr == "MUL":42 self.stack.append(a * b)43 elif instr == "DIV":44 if b == 0:45 self.output.append(f"Line {line_num}: Error - Division by zero")46 return47 self.stack.append(a // b)48 elif instr == "PRINT":49 if not self.stack:50 self.output.append(f"Line {line_num}: Error - Stack underflow on PRINT")51 return52 self.output.append(f"PRINT: {self.stack[-1]}")53 else:54 self.output.append(f"Line {line_num}: Error - Unknown instruction '{instr}'")55 return56 except Exception as e:57 self.output.append(f"Line {line_num}: Exception - {str(e)}")58 return59 self.output.append(f"Final Stack: {self.stack}")60 return "\n".join(self.output)61 62def run_vm(code):63 vm = StackVM()64 vm.run(code)65 return "\n".join(vm.output)66 67example_code = """PUSH 1068PUSH 2069ADD70PUSH 571MUL72PRINT"""73 74iface = gr.Interface(75 fn=run_vm,76 inputs=gr.Textbox(label="Enter Bytecode", lines=10, value=example_code),77 outputs=gr.Textbox(label="VM Output"),78 title="🧠 Stack-Based Virtual Machine",79 description="Type stack-based bytecode instructions like PUSH, POP, ADD, SUB, MUL, DIV, PRINT. Click Run to execute."80)81 82iface.launch()83 