VMトランスレーター / VMトランスレーターを作る / SimpleAdd.vm
Chapter 7
テキストが用意しているテストファイルで動作確認をする。
まずSimpleAdd.vm (7+8=15)を計算する。
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) 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__": a = VM_Translator("SimpleAdd.vm") a.code_writer.set_pointer("SP", 256) a.generate_asm()
正解:
実行結果: