VMトランスレーター後半 / FibonacciSeries.vm

Chapter 8

今度はフィボナッチ数列を求める。Code_Writer.pyVM_Translator.pyスクリプト本体は前回と同じ。
VM_Translator.py:

from Parser import *
from Code_Writer import *

# .vmファイルを入力して.asmファイルを出力する。
class VM_Translator:
    def __init__(self, vm_file_path):
        self.parser = Parser(vm_file_path)

        asm_file_path = self.__replace_file_extension(vm_file_path, "asm")
        self.code_writer = Code_Writer(asm_file_path)

    def generate_asm(self):
        while self.parser.has_more_lines():
            self.parser.advance()
            
            command_type = self.parser.command_type()
            arg1 = self.parser.arg1()
            arg2 = self.parser.arg2()
            
            if command_type == "C_PUSH" or command_type == "C_POP":
                self.code_writer.write_push_pop(command_type, arg1, arg2)

            elif command_type == "C_ARITHMETIC":
                self.code_writer.write_arithmetic(arg1)

            elif command_type == "C_LABEL":
                self.code_writer.write_label(arg1)

            elif command_type == "C_GOTO":
                self.code_writer.write_goto(arg1)

            elif command_type == "C_IF":
                self.code_writer.write_if(arg1)

        self.code_writer.write_halt()
        self.parser.close()
        self.code_writer.close()

    def __replace_file_extension(self, file_name, new_extension):
        return file_name.split(".")[0] + "." + new_extension
 

############################################################
if __name__ == "__main__":
    # フィボナッチ数列をARG[0]項だけ求めてARG[1]以降に格納する。
    a = VM_Translator("FibonacciSeries\FibonacciSeries.vm")
    a.code_writer.load_ram_address_with_immediate_value(0, 256) # SP。天下り的にセットする。
    a.code_writer.load_ram_address_with_immediate_value(1, 300) # LCL。天下り的にセットする。
    a.code_writer.load_ram_address_with_immediate_value(2, 400) # ARG。天下り的にセットする。
    
    a.code_writer.load_ram_address_with_immediate_value(400+0, 6) # ARG[0]を6にセットする。
    a.code_writer.load_ram_address_with_immediate_value(400+1, 3000) # ARG[1]を3000にセットする。
    a.generate_asm()

正解:

実行結果: