class Parser: def __init__(self, file_path): self.file = open(file_path, "r") self.file.seek(0, 2) self.EOF_POS = self.file.tell() self.file.seek(0) self.current_line = "" def has_more_lines(self): return self.file.tell() != self.EOF_POS def __readline_scrapeoff(self): line = self.file.readline() # 先頭の空白と末尾の改行記号とを削除する。 line = line.strip() # コメントを削除する line = line.split("//")[0] # 文字列中のスペースを削除する。 line = line.replace(" ", "") # 文字列中のタブ文字を削除する。 line = line.replace("\t", "") return line def advance(self): self.current_line = self.__readline_scrapeoff() def instruction_type(self): # @があったらA命令。 if "@" in self.current_line: return "A_INSTRUCTION" # (~)があったらL命令。 elif ("(" in self.current_line) and (")" in self.current_line): return "L_INSTRUCTION" # 空行ならNoneを返す。 elif self.current_line == "": return None # それ以外ならC命令。 else: return "C_INSTRUCTION" def close(self): self.file.close() ################################################### if __name__ == "__main__": s = Parser("test.asm") while (s.has_more_lines()): s.advance() print(s.current_line) print(s.instruction_type()) s.close()
テストファイル:
// This file is part/ / of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/06/add/Add.asm // Computes R0 = 2 + 3 (R0 refers to RAM[0]) @ 2//////////////////////*************************** D = A @3 D = D + A (LOOP) @ 0 M =D // @LOOP 0;JMP ////////
実行結果: