アセンブラを作る / has_more_lines() / 読み込むべき行がまだ残っているかどうかを確かめる

pp.109ff.
ここからは未知の領域である。

テキストどおりParserクラスを設けてそこに各メソッドを作り込む。メソッドごとの担当もテキストどおりに切り分ける。まず、読み込むべき行が残っているかどうかを確認できるようにする。

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)
       
    # 今の位置がファイル末尾でないならTrueを返す。
    def has_more_lines(self):
        return self.file.tell() != self.EOF_POS

    def close(self):
        self.file.close()

###################################################
if __name__ == "__main__":
    s = Parser("Add.asm")

    while (tf := s.has_more_lines()):
        print(tf)
        print(s.file.readline())
        
    print(s.has_more_lines())
    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
@ 0
M =D    //


////////

実行結果: