labels work im pretty sure

This commit is contained in:
SpookyDervish
2025-09-07 11:58:01 +10:00
parent bee2087ab4
commit cf1ea42232
12 changed files with 87 additions and 44 deletions

View File

@@ -10,6 +10,7 @@ class Generator:
self.output_path = output_path
self.variables = {}
self.constants = {}
self.labels = []
self.constants_reverse = {}
self.constant_counter = 0

View File

@@ -8,7 +8,7 @@ class X86_64Generator(Generator):
self.stack_size = 0
def init(self):
self.lines.append("global _start\n\n")
self.lines.append("global _start\n")
self.lines.append("_start:\n\t")
# generate code
@@ -105,7 +105,6 @@ class X86_64Generator(Generator):
def change_variable(self, var_name: str, new_value):
var_pos = self.get_var_pos(var_name)
print(self.variables[var_name]["type"])
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")
self.variables[var_name]["type"] = IntNode
@@ -135,7 +134,10 @@ class X86_64Generator(Generator):
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")
self.variables[var_name]["type"] = IntNode
print(self.variables[var_name]["type"])
def generate_LabelDecNode(self, node: LabelDecNode):
self.labels.append(node.name)
self.lines.append("." + node.name + ":\n\t")
def generate_InstructionNode(self, node: InstructionNode):
### MISC ###
@@ -409,6 +411,15 @@ class X86_64Generator(Generator):
self.lines.append("mov rdi, 1\n\t") # a file descriptor of 1 is stdout
self.lines.append("syscall\n\t")
elif node.instruction == "jump":
if len(node.arguments) < 1: # example: "jump"
traceback(self.code, "TypeError", "jump expects atleast 1 argument.")
elif len(node.arguments) > 1: # example: "jump %label 123"
traceback(self.code, "TypeError", "jump expects at most 1 argument.")
elif not isinstance(node.arguments[0], LabelRefNode):
traceback(self.code, "TypeError", f"jump expects a label reference as the first argument, not \"{node.arguments[0]}\"")
self.lines.append(f"jmp .{node.arguments[0].name}\n\t")
else:
self.lines.append("; FUCK\n\t")
#raise NotImplementedError(f"A generate method hasn't been made for the \"{node.instruction}\" instruction.")
@@ -431,5 +442,5 @@ class X86_64Generator(Generator):
elif value_type == float or value_type == int:
f.write(f"dq {float(value)}")
f.write("\n")
f.write("\nsection .text\n")
f.write("section .text\n")
f.writelines(self.lines)