Spaces:
Build error

Ymc_simple / app.py
farah1's picture
Create app.py
bd242c1 verified
Raw History Blame Contribute Delete
21.3 kB
import csv
import io
import gradio as gr
import pandas as pd
##
# ------------------------------------
# 1) EXTENDED OPCODES + GLOBALS
# ------------------------------------
opcode_map = {
"mov_imm": "01",
"mov_reg": "02",
"add": "11",
"sub": "12",
"mult": "13",
"div": "14",
"addsub": "21",
"subadd": "22",
"multdiv": "23",
"divmult": "24",
"cmp": "3B",
">": "41",
">=": "42",
"<": "43",
"<=": "44",
"!=": "45",
"==": "47",
"jg": "51",
"jge": "52",
"jl": "53",
"jle": "54",
"jne": "55",
"je": "56",
"jmp": "59",
"loop": "71",
# NEW opcodes for memory spill
"store": "E0",
"load": "E1",
}
register_encoding = {
"eax": "00",
"ebx": "01",
"ecx": "02",
"edx": "03",
}
reg_decode = {v: k for k, v in register_encoding.items()}
# Keep track of whether a var is "unsigned"/"signed" or none
var_types = {}
# The 4 hardware registers we can allocate
REGISTER_POOL = ["eax", "ebx", "ecx", "edx"]
# Maps var_name -> currently allocated register
var_to_reg = {}
# Which registers are in use
used_regs = set()
# ------------------------------------
# SPILL SUPPORT
# ------------------------------------
# We'll assign memory addresses to variables if spilled, starting at 100
var_memory = {}
memory_counter = 100
def create_instr(opcode, operands, hlc=""):
"""Utility to create an IR instruction dict."""
return {
'label': None,
'opcode': opcode,
'operands': operands, # e.g. [reg, imm_addr] or [reg1, reg2]
'hlc': hlc,
'address': None,
'machine': ""
}
def spill_register(instructions):
"""
Super-naive: pick the first variable in var_to_reg to spill to memory.
"""
victim_var, victim_reg = next(iter(var_to_reg.items()))
ensure_in_memory(victim_var, instructions)
return victim_var, victim_reg
def ensure_in_memory(var_name, instructions):
"""
Generate a 'store' instruction so we don't lose var_name's value.
Then unassign that register from var_name.
"""
global var_memory, memory_counter, var_to_reg, used_regs
# If it doesn't have a memory slot yet, assign one
if var_name not in var_memory:
var_memory[var_name] = memory_counter
memory_counter += 1
mem_addr = var_memory[var_name]
victim_reg = var_to_reg[var_name]
# store victim_reg -> mem_addr
instr = create_instr("store", [victim_reg, str(mem_addr)], hlc=f"spill {var_name}")
instructions.append(instr)
# Remove the mapping from var -> reg
del var_to_reg[var_name]
used_regs.remove(victim_reg)
def allocate_register_for_write(var_name, instructions):
"""
For writing to var_name, we don't need the old value, so no load needed.
If no free reg, we spill another variable.
"""
if var_name in var_to_reg:
return var_to_reg[var_name]
# find a free register
for r in REGISTER_POOL:
if r not in used_regs:
used_regs.add(r)
var_to_reg[var_name] = r
return r
# If no free register, spill
spill_var, spill_reg = spill_register(instructions)
used_regs.add(spill_reg)
var_to_reg[var_name] = spill_reg
return spill_reg
def load_if_spilled(var_name, instructions):
"""
For reading from var_name. If it's not in a register, but we have a mem
address, do a 'load' instruction. If it doesn't exist at all, we allocate fresh.
"""
if var_name in var_to_reg:
# It's already in a register
return var_to_reg[var_name]
# If we've assigned it a memory address, that means it might be spilled
if var_name in var_memory:
# we need a register. Possibly spill something else
for r in REGISTER_POOL:
if r not in used_regs:
used_regs.add(r)
var_to_reg[var_name] = r
mem_addr = var_memory[var_name]
instructions.append(create_instr("load", [r, str(mem_addr)], hlc=f"reload {var_name}"))
return r
# or spill a register
spill_var, spill_reg = spill_register(instructions)
used_regs.add(spill_reg)
var_to_reg[var_name] = spill_reg
mem_addr = var_memory[var_name]
instructions.append(create_instr("load", [spill_reg, str(mem_addr)], hlc=f"reload {var_name}"))
return spill_reg
# If var_name not in var_memory, treat it as new (never assigned)
return allocate_register_for_write(var_name, instructions)
# ------------------------------------
# PARSER
# ------------------------------------
def parse_hlc_lines(hlc_lines):
"""
We reset global state, then parse line-by-line.
For each variable read, call load_if_spilled.
For each variable write, call allocate_register_for_write.
"""
global var_types, var_to_reg, used_regs, var_memory, memory_counter
var_types.clear()
var_to_reg.clear()
used_regs.clear()
var_memory.clear()
memory_counter = 100
instructions = []
loop_stack = []
line_idx = 0
while line_idx < len(hlc_lines):
line = hlc_lines[line_idx].strip()
if not line or line.startswith("//"):
line_idx += 1
continue
if line.startswith("unsigned") or line.startswith("signed"):
tokens = line.split()
kind = tokens[0]
for varname in tokens[1:]:
var_types[varname] = kind
line_idx += 1
continue
if line.startswith("while"):
label_start = f"LOOP_START_{line_idx}"
label_end = f"LOOP_END_{line_idx}"
loop_stack.append((label_start, label_end))
start_instr = create_instr(None, [], hlc=line)
start_instr['label'] = label_start
instructions.append(start_instr)
tokens = line.split()
varname = tokens[1] # e.g. while x < 0
imm_val = tokens[3]
# We'll read x
reg_var = load_if_spilled(varname, instructions)
if imm_val.lstrip("-").isdigit():
# immediate
tmp_reg = load_if_spilled(f"const_{imm_val}", instructions)
instructions.append(create_instr("mov_imm", [tmp_reg, imm_val], hlc=line))
instructions.append(create_instr("cmp", [reg_var, tmp_reg], hlc=line))
else:
reg_imm = load_if_spilled(imm_val, instructions)
instructions.append(create_instr("cmp", [reg_var, reg_imm], hlc=line))
jge_instr = create_instr("jge", [label_end], hlc=line)
instructions.append(jge_instr)
line_idx += 1
continue
if line.strip() == "}":
# End of while
if loop_stack:
label_start, label_end = loop_stack.pop()
jmp_instr = create_instr("jmp", [label_start], hlc=line)
instructions.append(jmp_instr)
end_instr = create_instr(None, [], hlc=line)
end_instr['label'] = label_end
instructions.append(end_instr)
line_idx += 1
continue
if line.startswith("print"):
tokens = line.split()
to_print = tokens[1] if len(tokens) > 1 else ""
# read to_print
_ = load_if_spilled(to_print, instructions)
instr = create_instr("print", [to_print], hlc=line)
instructions.append(instr)
line_idx += 1
continue
if "=" in line:
lhs, rhs = line.split("=")
lhs = lhs.strip()
rhs = rhs.strip()
reg_lhs = allocate_register_for_write(lhs, instructions)
if rhs.lstrip("-").isdigit():
imm_val = int(rhs)
if var_types.get(lhs, "unsigned") == "signed":
imm_val = imm_val & 0xFF
instr = create_instr("mov_imm", [reg_lhs, str(imm_val)], hlc=line)
instr["dest_type"] = var_types.get(lhs, "unsigned")
instructions.append(instr)
elif "+" in rhs:
parts = rhs.split("+")
r1 = parts[0].strip()
r2 = parts[1].strip()
reg_r1 = load_if_spilled(r1, instructions)
if r2.lstrip("-").isdigit():
tmp_reg = allocate_register_for_write(f"const_{r2}", instructions)
instructions.append(create_instr("mov_imm", [tmp_reg, r2], hlc=line))
instructions.append(create_instr("add", [reg_lhs, reg_r1, tmp_reg], hlc=line))
else:
reg_r2 = load_if_spilled(r2, instructions)
instructions.append(create_instr("add", [reg_lhs, reg_r1, reg_r2], hlc=line))
elif "-" in rhs:
parts = rhs.split("-")
if parts[0].strip() == "":
# negative literal, handled as above
pass
else:
r1 = parts[0].strip()
r2 = parts[1].strip()
reg_r1 = load_if_spilled(r1, instructions)
if r2.lstrip("-").isdigit():
tmp_reg = allocate_register_for_write(f"const_{r2}", instructions)
instructions.append(create_instr("mov_imm", [tmp_reg, r2], hlc=line))
instructions.append(create_instr("sub", [reg_lhs, reg_r1, tmp_reg], hlc=line))
else:
reg_r2 = load_if_spilled(r2, instructions)
instructions.append(create_instr("sub", [reg_lhs, reg_r1, reg_r2], hlc=line))
else:
# e.g. x = y
reg_rhs = load_if_spilled(rhs, instructions)
instructions.append(create_instr("mov_reg", [reg_lhs, reg_rhs], hlc=line))
line_idx += 1
continue
line_idx += 1
return instructions
# ------------------------------------
# SIZES, ADDRESSES, LABELS, ENCODING
# ------------------------------------
def instruction_size(instr):
op = instr['opcode']
if op in [None, "print"]:
return 0
if op in ["mov_imm", "mov_reg", "cmp", "store", "load"]:
return 3
if op in ["add", "sub", "mult", "div"]:
return 4
if op in ["jmp", "jg", "jge", "jl", "jle", "jne", "je"]:
return 3
return 3
def assign_addresses(ymc_instructions, start=0):
addr = start
for instr in ymc_instructions:
instr['address'] = addr
sz = instruction_size(instr)
addr += sz
def build_label_map(ymc_instructions):
label_map = {}
for instr in ymc_instructions:
if instr['label'] is not None:
label_map[instr['label']] = instr['address']
return label_map
def fixup_jumps(ymc_instructions, label_map):
jump_ops = {"jmp", "jg", "jge", "jl", "jle", "jne", "je"}
for instr in ymc_instructions:
if instr['opcode'] in jump_ops:
target = instr['operands'][0]
if target in label_map:
instr['operands'][0] = label_map[target]
def to_hex8(val):
val = int(val) & 0xFF
return f"{val:02X}"
def encode_instruction(instr):
op = instr['opcode']
if op is None:
return ""
if op == "print":
operand = instr['operands'][0]
return f"FF {operand}"
if op not in opcode_map:
return f"?? ; unknown opcode {op}"
opcode_hex = opcode_map[op]
code_bytes = [opcode_hex]
if op == "mov_imm":
dest_reg = instr['operands'][0]
imm = instr['operands'][1]
code_bytes.append(register_encoding[dest_reg])
code_bytes.append(to_hex8(imm))
elif op == "mov_reg":
dr = instr['operands'][0]
sr = instr['operands'][1]
code_bytes.append(register_encoding[dr])
code_bytes.append(register_encoding[sr])
elif op in ["add", "sub", "mult", "div"]:
dr = instr['operands'][0]
r1 = instr['operands'][1]
r2 = instr['operands'][2]
code_bytes.append(register_encoding[dr])
code_bytes.append(register_encoding[r1])
code_bytes.append(register_encoding[r2])
elif op == "cmp":
r1 = instr['operands'][0]
r2 = instr['operands'][1]
code_bytes.append(register_encoding[r1])
code_bytes.append(register_encoding[r2])
elif op in ["jmp", "jg", "jge", "jl", "jle", "jne", "je"]:
addr = int(instr['operands'][0])
high = (addr >> 8) & 0xFF
low = addr & 0xFF
code_bytes.append(to_hex8(high))
code_bytes.append(to_hex8(low))
elif op == "store":
reg = instr['operands'][0]
mem_str = instr['operands'][1]
code_bytes.append(register_encoding[reg])
code_bytes.append(to_hex8(mem_str))
elif op == "load":
reg = instr['operands'][0]
mem_str = instr['operands'][1]
code_bytes.append(register_encoding[reg])
code_bytes.append(to_hex8(mem_str))
return " ".join(code_bytes)
def encode_all(ymc_instructions):
for instr in ymc_instructions:
mc = encode_instruction(instr)
instr['machine'] = mc
def to_signed8(x):
x = x & 0xFF
return x - 256 if x & 0x80 else x
# ------------------------------------
# ENHANCED CPU with store/load
# ------------------------------------
class TinyCPU:
def __init__(self):
self.regs = {"eax": 0, "ebx": 0, "ecx": 0, "edx": 0}
self.flags = {"ZF": 0, "SF": 0, "CF": 0, "OF": 0}
self.pc = 0 # Program Counter
# Simple memory model: address -> integer
self.memory = {}
def get_state(self):
return (dict(self.regs), dict(self.flags), self.pc)
def execute(self, instr):
self.pc = instr['address']
op = instr['opcode']
if op is None:
self.pc += instruction_size(instr)
return
if op == "print":
self.pc += instruction_size(instr)
# (No real printing here)
return
if op == "mov_imm":
reg = instr['operands'][0]
imm = int(instr['operands'][1])
self.regs[reg] = imm & 0xFF
elif op == "mov_reg":
dr = instr['operands'][0]
sr = instr['operands'][1]
self.regs[dr] = self.regs[sr]
elif op == "add":
dr, r1, r2 = instr['operands']
v1 = self.regs[r1]
v2 = self.regs[r2]
full_result = v1 + v2
res = full_result & 0xFF
self.regs[dr] = res
self.flags["ZF"] = 1 if res == 0 else 0
self.flags["SF"] = 1 if (res & 0x80) else 0
self.flags["CF"] = 1 if full_result > 0xFF else 0
signed_v1 = to_signed8(v1)
signed_v2 = to_signed8(v2)
signed_res = to_signed8(res)
# Overflow detection
if (signed_v1 >= 0 and signed_v2 >= 0 and signed_res < 0) or (signed_v1 < 0 and signed_v2 < 0 and signed_res >= 0):
self.flags["OF"] = 1
else:
self.flags["OF"] = 0
elif op == "sub":
dr, r1, r2 = instr['operands']
v1 = self.regs[r1]
v2 = self.regs[r2]
full_result = v1 - v2
res = full_result & 0xFF
self.regs[dr] = res
self.flags["ZF"] = 1 if res == 0 else 0
self.flags["SF"] = 1 if (res & 0x80) else 0
self.flags["CF"] = 1 if v1 < v2 else 0
if (((v1 ^ v2) & (v1 ^ res)) & 0x80) != 0:
self.flags["OF"] = 1
else:
self.flags["OF"] = 0
elif op == "cmp":
r1, r2 = instr['operands']
v1 = self.regs[r1]
v2 = self.regs[r2]
result = (v1 - v2) & 0xFF
self.flags["ZF"] = 1 if result == 0 else 0
self.flags["SF"] = 1 if (result & 0x80) else 0
self.flags["CF"] = 1 if v1 < v2 else 0
if (((v1 ^ v2) & (v1 ^ result)) & 0x80) != 0:
self.flags["OF"] = 1
else:
self.flags["OF"] = 0
elif op == "store":
reg = instr['operands'][0]
mem_addr = int(instr['operands'][1])
self.memory[mem_addr] = self.regs[reg]
elif op == "load":
reg = instr['operands'][0]
mem_addr = int(instr['operands'][1])
val = self.memory.get(mem_addr, 0)
self.regs[reg] = val
# We do not do actual branching in the CPU for the CSV trace:
# just increment PC by the instruction size
sz = instruction_size(instr)
self.pc += sz
def diff_states(self, before, after):
changed_regs = []
changed_flags = []
before_regs, before_f, _ = before
after_regs, after_f, _ = after
for r in after_regs:
if after_regs[r] != before_regs[r]:
changed_regs.append(f"{r}={after_regs[r]}")
for f in after_f:
if after_f[f] != before_f[f]:
changed_flags.append(f"{f}={after_f[f]}")
return (" ".join(changed_regs), " ".join(changed_flags))
# Display jump addresses in decimal + hex
def assemble_text(instr):
if instr['opcode'] is None:
if instr['label'] is not None:
return f"<LABEL {instr['label']}>"
return ""
op = instr['opcode']
jump_ops = {"jmp", "jg", "jge", "jl", "jle", "jne", "je"}
if op in jump_ops:
addr_int = int(instr['operands'][0])
return f"{op} {addr_int} (0x{addr_int:02X})"
# otherwise
ops = ", ".join(str(o) for o in instr['operands'])
return f"{op} {ops}"
# ------------------------------------
# HELPER: Build an in-memory CSV
# ------------------------------------
def build_csv_trace(ymc_instructions):
cpu = TinyCPU()
output = io.StringIO()
fieldnames = [
"PC_Before",
"PC_After",
"Address",
"HLC",
"YMC Assembly",
"Machine Code",
"Modified Registers",
"Registers",
"Flags"
]
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
for instr in ymc_instructions:
before_state = cpu.get_state()
cpu.execute(instr)
after_state = cpu.get_state()
changed_regs, _ = cpu.diff_states(before_state, after_state)
regs_status = " ".join(f"{r}={v}" for r, v in after_state[0].items())
flags_status = " ".join(f"{flag}={value}" for flag, value in after_state[1].items())
row = {
"PC_Before": f"{before_state[2]:04X}",
"PC_After": f"{after_state[2]:04X}",
"Address": f"{instr['address']:04X}",
"HLC": instr['hlc'],
"YMC Assembly": assemble_text(instr),
"Machine Code": instr['machine'],
"Modified Registers": changed_regs,
"Registers": regs_status,
"Flags": flags_status
}
writer.writerow(row)
return output.getvalue()
# ------------------------------------
# 2) Gradio Methods
# ------------------------------------
def process_hlc_to_csv(hlc_text: str):
hlc_program = hlc_text.splitlines()
ymc_instructions = parse_hlc_lines(hlc_program)
assign_addresses(ymc_instructions, start=0)
label_map = build_label_map(ymc_instructions)
fixup_jumps(ymc_instructions, label_map)
encode_all(ymc_instructions)
csv_text = build_csv_trace(ymc_instructions)
return csv_text
def process_and_get_dataframe(hlc_text: str):
csv_text = process_hlc_to_csv(hlc_text)
df = pd.read_csv(io.StringIO(csv_text))
return df, csv_text
# ------------------------------------
# 3) Gradio UI
# ------------------------------------
with gr.Blocks() as demo:
gr.Markdown("## YMC with Register Spilling + Decimal/Hex Jump Addresses")
gr.Markdown(
"Paste your HLC code below. This version implements naive register spilling:\n"
"- Only 4 registers: eax, ebx, ecx, edx.\n"
"- If they're all full, we 'spill' a random variable to memory with 'store'.\n"
"- If we need a spilled variable, we 'load' it back.\n\n"
"We also display jumps in both decimal & hex, e.g. `jge 28 (0x1C)`."
)
input_hlc = gr.Textbox(
label="Enter HLC Program",
lines=15,
placeholder=(
"unsigned a b\n"
"signed x y\n\n"
"a = 10\n"
"b = 2\n"
"x = -10\n"
"y = 1\n\n"
"while x < 0\n"
" print x\n"
" print \\n\n"
" x = x + y\n"
"}\n\n"
"while a > 0\n"
" print a\n"
" print \\n\n"
" a = a - b\n"
"} "
)
)
output_table = gr.Dataframe(label="CSV Trace (Execution)", type="pandas")
csv_output = gr.Textbox(label="CSV Output (raw text)", lines=10)
run_button = gr.Button("Assemble & Run")
run_button.click(fn=process_and_get_dataframe, inputs=input_hlc, outputs=[output_table, csv_output])
demo.launch()