from generators.generator import Generator from ground_ast import * from error import traceback class X86_64Generator(Generator): def __init__(self, ast, code, output_path): super().__init__(ast, code, output_path) self.stack_size = 0 def init(self): self.lines.append("global _start\n\n") self.lines.append("_start:\n\t") # generate code self.generate() self.write() def push(self, reg: str): self.lines.append("push " + reg + "\n\t") self.stack_size += 1 def pop(self, reg: str): self.lines.append("pop " + reg + "\n\t") self.stack_size -= 1 def get_variable(self, var_name: str, reg: str, float: bool = False): var = self.variables.get(var_name, None) var_pos = self.get_var_pos(var_name) try: #print(var["type"]) if var["type"] == FloatNode or float: conversion = { "rax": "xmm0", "rbx": "xmm1", "rdi": "xmm0" # ... } self.lines.append(f"movsd {conversion[reg]}, [rsp + {var_pos}]\n\t") self.lines.append("add rsp, 8\n\t") #self.stack_size -= 1 elif var["type"] == IntNode: self.push( f"QWORD [rsp + {var_pos}]" ) self.pop(reg) except TypeError: # variable doesnt exist traceback(self.code, "NameError", f"\"{var_name}\" is not defined.") return var["type"] def get_var_pos(self, var_name: str): return (self.stack_size - self.variables.get(var_name)['stack_loc'] - 1) * 8 def create_variable(self, var_name: str, starting_value, var_type: Any = None): if var_type == None: var_type = type(starting_value) stack_location = self.stack_size if type(starting_value) == IntNode: self.lines.append(f"mov rax, {starting_value.value}\n\t") self.push("rax") elif type(starting_value) == VarRefNode: var_type = self.get_variable(starting_value.var_name, "rax") if var_type == FloatNode: self.lines.append("sub rsp, 8\n\t") self.lines.append("movsd [rsp], xmm0\n\t") else: self.push("rax") elif type(starting_value) == FloatNode: name = self.add_constant(starting_value.value) self.lines.append("sub rsp, 8\n\t") # make space on the stack self.lines.append(f"movsd xmm0, {name}\n\t") self.lines.append("movsd [rsp], xmm0\n\t") self.stack_size += 1 elif type(starting_value) == str: if starting_value.startswith("xmm"): # floating point stuff self.lines.append("sub rsp, 8\n\t") # make space self.lines.append(f"movsd [rsp], {starting_value}\n\t") self.stack_size += 1 else: self.push(starting_value) self.variables[var_name] = {"stack_loc": stack_location, "type": var_type} def change_variable(self, var_name: str, new_value): var_pos = self.get_var_pos(var_name) if type(new_value) == IntNode: # we're changing a variable to a number self.lines.append(f"mov QWORD [rsp + {var_pos}], {new_value.value}\n\t") elif type(new_value) == VarRefNode: # we're changing a variable to the value of another variable self.get_variable(new_value.var_name, "rax") self.lines.append(f"mov QWORD [rsp + {var_pos}], rax\n\t") elif type(new_value) == str: # we're changing a variable to the value of a register self.lines.append(f"mov QWORD [rsp + {var_pos}], {new_value}\n\t") def generate_InstructionNode(self, node: InstructionNode): if node.instruction == "end": if len(node.arguments) == 0: # example: "end" traceback(self.code, "TypeError", "end expects atleast 1 argument.") elif len(node.arguments) > 1: # example: "end 1 1" traceback(self.code, "TypeError", "end expects only 1 argument.") if not type(node.arguments[0]) in [IntNode, VarRefNode]: # example: "end true" traceback(self.code, "TypeError", f"end expects an integer, not {node.arguments[0]}") self.lines.append("mov rax, 60\n\t") if isinstance(node.arguments[0], IntNode): self.lines.append("mov rdi, " + str(node.arguments[0].value) + "\n\t") elif isinstance(node.arguments[0], VarRefNode): var_type = self.get_variable(node.arguments[0].var_name, "rdi") if var_type == FloatNode: self.lines.append("cvttsd2si rdi, xmm0\n\t") else: if var_type != IntNode: traceback(self.code, "TypeError", f"end expects an integer, not \"{var_type}\"") #self.lines.append("mov rdi, " + str(self.get_variable(node.arguments[0].var_name)) + "\n\t") self.lines.append("syscall\n\t") elif node.instruction == "set": if len(node.arguments) < 2: # example: "set" or "set &hi" traceback(self.code, "TypeError", "set expects atleast 2 arguments.") elif len(node.arguments) > 2: # example: "set &hi 0 123" traceback(self.code, "TypeError", "set expects only 2 arguments.") if not isinstance(node.arguments[0], VarPointerNode): traceback(self.code, "TypeError", f"the first argument of set should be a variable pointer, not \"{node.arguments[0]}\"") if type(node.arguments[1]) not in [IntNode, VarRefNode, FloatNode]: traceback(self.code, "TypeError", f"variables can't be of type \"{type(node.arguments[1])}\"") variable_exists = self.variables.get(node.arguments[0].var_name, None) != None if not variable_exists: # create a new variable self.create_variable(node.arguments[0].var_name, node.arguments[1]) else: # modify the existing one self.change_variable(node.arguments[0].var_name, node.arguments[1]) elif node.instruction == "add": if len(node.arguments) < 3: # example: "add" or "add 1" or "add 1 2" traceback(self.code, "TypeError", "add expects atleast 3 arguments.") elif len(node.arguments) > 3: # example: "add 1 2 3 4" traceback(self.code, "TypeError", "add expects only 3 arguments.") elif type(node.arguments[2]) != VarPointerNode: traceback(self.code, "TypeError", f"the destination of the add command must be a variable pointer, not \"{node.arguments[2]}\"") # bro this entire god damn instruction is just error handling 😔 number1_type = None number2_type = None arg2 = "rbx" if isinstance(node.arguments[0], VarRefNode): number1_type = self.get_variable(node.arguments[0].var_name, "rax") elif isinstance(node.arguments[0], FloatNode) or isinstance(node.arguments[1], FloatNode): number1_type = FloatNode constant_name = self.add_constant(node.arguments[0].value) self.lines.append(f"movsd xmm0, {constant_name}\n\t") elif isinstance(node.arguments[0], IntNode): number1_type = IntNode #arg1 = node.arguments[0].value self.lines.append(f"mov rax, {node.arguments[0].value}\n\t") else: traceback(self.code, "TypeError", f"expected a variable reference or number for argument 1 of add, got {node.arguments[0]}") if isinstance(node.arguments[1], VarRefNode): number2_type = self.get_variable(node.arguments[1].var_name, "rbx") elif number1_type == FloatNode or isinstance(node.arguments[1], FloatNode): number2_type = FloatNode constant_name = self.add_constant(node.arguments[1].value) self.lines.append(f"movsd xmm1, {constant_name}\n\t") elif isinstance(node.arguments[1], IntNode): number2_type = IntNode arg2 = node.arguments[1].value #self.lines.append(f"mov rbx, {node.arguments[1].value}\n\t") else: traceback(self.code, "TypeError", f"expected a variable reference or number for argument 2 of add, got {node.arguments[1]}") # TODO: numbers can be added to numbers, but numbers cant be added to strings. but strings can be added to strings, etc... if number1_type not in [IntNode, FloatNode] or number2_type not in [IntNode, FloatNode]: traceback(self.code, "TypeError", f"Unsupported operation \"add\" for \"{node.arguments[0]}\" and \"{node.arguments[1]}\".") if number1_type == IntNode and number2_type == IntNode: self.lines.append(f"add rax, {arg2}\n\t") else: self.lines.append(f"addsd xmm0, xmm1\n\t") is_integer = number1_type == IntNode and number2_type == IntNode starting_reg = "rax" if is_integer else "xmm0" if self.variables.get(node.arguments[2].var_name, None) == None: # we need to create a variable for the destination self.create_variable(node.arguments[2].var_name, starting_reg, IntNode if is_integer else FloatNode) else: self.change_variable(node.arguments[2].var_name, starting_reg) elif node.instruction == "subtract": if len(node.arguments) < 3: # example: "subtract" or "subtract 1" or "subtract 1 2" traceback(self.code, "TypeError", "subtract expects atleast 3 arguments.") elif len(node.arguments) > 3: # example: "subtract 1 2 3 4" traceback(self.code, "TypeError", "subtract expects only 3 arguments.") elif type(node.arguments[2]) != VarPointerNode: traceback(self.code, "TypeError", f"the destination of the subtract command must be a variable pointer, not \"{node.arguments[2]}\"") # bro this entire god damn instruction is just error handling 😔 number1_type = None number2_type = None arg2 = "rbx" if isinstance(node.arguments[0], VarRefNode): number1_type = self.get_variable(node.arguments[0].var_name, "rax", isinstance(node.arguments[1], FloatNode)) elif isinstance(node.arguments[0], FloatNode) or isinstance(node.arguments[1], FloatNode): number1_type = FloatNode constant_name = self.add_constant(node.arguments[0].value) self.lines.append(f"movsd xmm0, {constant_name}\n\t") elif isinstance(node.arguments[0], IntNode): number1_type = IntNode #arg1 = node.arguments[0].value self.lines.append(f"mov rax, {node.arguments[0].value}\n\t") else: traceback(self.code, "TypeError", f"expected a variable reference or number for argument 1 of subtract, got {node.arguments[0]}") if isinstance(node.arguments[1], VarRefNode): number2_type = self.get_variable(node.arguments[1].var_name, "rbx", number1_type == FloatNode) elif number1_type == FloatNode or isinstance(node.arguments[1], FloatNode): number2_type = FloatNode constant_name = self.add_constant(node.arguments[1].value) self.lines.append(f"movsd xmm1, {constant_name}\n\t") elif isinstance(node.arguments[1], IntNode): number2_type = IntNode arg2 = node.arguments[1].value #self.lines.append(f"mov rbx, {node.arguments[1].value}\n\t") else: traceback(self.code, "TypeError", f"expected a variable reference or number for argument 2 of subtract, got {node.arguments[1]}") # TODO: numbers can be added to numbers, but numbers cant be added to strings. but strings can be added to strings, etc... if number1_type not in [IntNode, FloatNode] or number2_type not in [IntNode, FloatNode]: traceback(self.code, "TypeError", f"Unsupported operation \"subtract\" for \"{node.arguments[0]}\" and \"{node.arguments[1]}\".") if number1_type == IntNode and number2_type == IntNode: self.lines.append(f"sub rax, {arg2}\n\t") else: self.lines.append(f"subsd xmm0, xmm1\n\t") is_integer = number1_type == IntNode and number2_type == IntNode starting_reg = "rax" if is_integer else "xmm0" if self.variables.get(node.arguments[2].var_name, None) == None: # we need to create a variable for the destination self.create_variable(node.arguments[2].var_name, starting_reg, IntNode if is_integer else FloatNode) else: self.change_variable(node.arguments[2].var_name, starting_reg) else: self.lines.append("; FUCK\n\t") #raise NotImplementedError(f"A generate method hasn't been made for the \"{node.instruction}\" instruction.") def write(self): with open(self.output_path + ".asm", "w") as f: f.write("section .data\n") for name, value in self.constants.items(): f.write("." + name + ": ") value_type = type(value) if value_type == str: f.write(f"db \"{value}\", 0") elif value_type == float or value_type == int: f.write(f"dq {float(value)}") f.write("\n") f.write("\nsection .text\n") f.writelines(self.lines)