From 56bcad6fc1413b9e69f6f88e6a7f69ef13b5ee64 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 29 Apr 2024 17:03:51 +0300 Subject: [PATCH] Generated code is now kept as list of instructions --- 04_semantics_and_running/main.py | 323 ++++++++++++++++--------------- 1 file changed, 163 insertions(+), 160 deletions(-) diff --git a/04_semantics_and_running/main.py b/04_semantics_and_running/main.py index b2a9450..c0048d7 100644 --- a/04_semantics_and_running/main.py +++ b/04_semantics_and_running/main.py @@ -276,75 +276,31 @@ def semantic_check(node: ASTnode, sem_data: SemData) -> None | ASTnode: case _: print_todo(f'Semantic check type \'{node.nodetype}\'', node) +class Instruction: + def __init__(self, opcode: str, operands: list[str] = []): + self.opcode = opcode + self.operands = operands + + def __str__(self): + return f'{self.opcode} {', '.join(self.operands)}' + class CompileData: def __init__(self, sem_data: SemData): self.sem_data = sem_data self.date_buffer_size = 128 - self.string_literals = [] self.label_counter = 0 - self.callables = {} - self.scope = None - self.code = '' - - self.callables['__builtin_today'] = '''\ - pushq %rbp - movq %rsp, %rbp - xorq %rdi, %rdi - call time - movq %rax, %rdi - movq $86400, %rcx - xorq %rdx, %rdx - divq %rcx - movq %rdi, %rax - subq %rdx, %rax - popq %rbp - ret - ''' - - self.callables['__builtin_print_date'] = f'''\ - pushq %rbp - movq %rsp, %rbp - subq $16, %rsp - movq %rdi, 0(%rsp) - leaq 0(%rsp), %rdi - call localtime - movq $.date_buffer, %rdi - movq ${self.date_buffer_size}, %rsi - movq $.date_format, %rdx - movq %rax, %rcx - call strftime - movq $.str_format, %rdi - movq $.date_buffer, %rsi - call printf - leave - ret - ''' - - self.callables['__builtin_get_day_attr'] = f'''\ - pushq %rbp - movq %rsp, %rbp - subq $16, %rsp - movq %rdi, 0(%rsp) - movq %rsi, 8(%rsp) - leaq 0(%rsp), %rdi - call localtime - movq $.date_buffer, %rdi - movq ${self.date_buffer_size}, %rsi - movq 8(%rsp), %rdx - movq %rax, %rcx - call strftime - movq $.date_buffer, %rdi - call atoi - leave - ret - ''' + self.string_literals: list[str] = [] + self.callables: dict[str, list[Instruction]] = {} + self.scope: ASTnode = None + self.code: list[Instruction] = [] + self.add_builtin_functions() def get_label(self) -> str: self.label_counter += 1 return f'.L{self.label_counter - 1}' def insert_label(self, label) -> None: - self.code += f'{label}:\n' + self.code.append(Instruction('