def _return(): # FLAME=*LCL asm.set_areg('LCL') # @LCL asm.set_dreg_from_sgm() # D=M asm.set_areg('FRAME') # @FRAME asm.set_sgm_from_dreg() # M=D # RET=*(FRAME-5) _set_return() # *ARG=pop() cs.dec_sp() # Mem[SP] = Mem[SP] - 1 asm.set_areg_from_sgm() # A=M asm.set_dreg_from_sgm() # D=M asm.set_areg('ARG') # @ARG asm.set_areg_from_sgm() # A=M asm.set_sgm_from_dreg() # M=D # SP=ARG+1 asm.set_areg('ARG') # @ARG asm.set_dreg_from_sgm() # D=M asm.append_lines('D=D+1') # D=D+1 asm.set_areg('SP') # @SP asm.set_sgm_from_dreg() # M=D _set_return_segment('THAT', 1) # THAT=*(FRAME-1) _set_return_segment('THIS', 2) # THIS=*(FRAME-2) _set_return_segment('ARG', 3) # ARG=*(FRAME-3) _set_return_segment('LCL', 4) # LCL=*(FRAME-4) # GOTO RET. asm.set_areg('RETURN') # @RETURN asm.set_areg_from_sgm() # A=M asm.append_lines('0;JMP')
def _unary(compute): # compute Example: 'M=-D', 'M=!D'' cs.dec_sp() cs.st_2_dreg() asm.append_lines(compute) cs.inc_sp() return
def _set_bool(bool): asm.set_areg('SP') asm.set_areg_from_sgm() if bool == 'TRUE': asm.append_lines('M=-1') elif bool == 'FALSE': asm.append_lines('M=0')
def _binary(compute): # compute Example: 'M=M+D', 'M=M-D', 'M=M&D', 'M=M|D' asm.dec_sp() asm.st_2_dreg() asm.dec_sp() asm.st_2_areg() asm.append_lines(compute) asm.inc_sp()
def _comp(jump): # jmp Example: 'JEQ', 'JGT', 'JLT' asm.dec_sp() asm.st_2_dreg() asm.dec_sp() asm.st_2_areg() asm.append_lines('D=M-D') asm.set_areg(str(len(asm.asmLines) + 7)) # 1Line # 7 = 1 + 3 + 1 + 1 + 1 asm.append_lines('D;' + jump) # 1Line asm.set_bool('FALSE') # 3Lines asm.set_areg(str(len(asm.asmLines) + 5)) # 1Line # 5 = 1 + 3 + 1 asm.append_lines('0;JMP') # 1Line asm.set_bool('TRUE') # 3Lines asm.inc_sp()
def _comp(jump): # TODO use Label! # jmp Example: 'JEQ', 'JGT', 'JLT' cs.dec_sp() cs.st_2_dreg() cs.dec_sp() cs.st_2_areg() asm.append_lines('D=M-D') #asm.set_areg(str(len(asm.asmLines) + 7)) # 1Line # 7 = 1 + 3 + 1 + 1 + 1 asm.set_areg(str(_count_unlabeld_line() + 7)) asm.append_lines('D;' + jump) # 1Line _set_bool('FALSE') # 3Lines #asm.set_areg(str(len(asm.asmLines) + 5)) # 1Line # 5 = 1 + 3 + 1 asm.set_areg(str(_count_unlabeld_line() + 5)) asm.append_lines('0;JMP') # 1Line _set_bool('TRUE') # 3Lines cs.inc_sp() return
def _set_if_goto(label): cs.dec_sp() # SP-- cs.st_2_dreg() # A=M, D=A asm.set_areg(label) # A=Label asm.append_lines('D;JNE') # If D != 0; then goto label.
def _set_label(label, funcName): if funcName: asm.append_lines('(' + funcName + '$' + label + ')') else: asm.append_lines('(' + label + ')')
def _set_goto(label, funcName): if funcName: asm.set_areg(funcName + '$' + label) else: asm.set_areg(label) asm.append_lines('0;JMP')
def st_2_areg(): asm.append_lines('@SP', 'A=M')
def st_2_dreg(): asm.append_lines('@SP', 'A=M', 'D=M')
def inc_sp(): asm.append_lines('@SP', 'M=M+1')
def dec_sp(): asm.append_lines('@SP', 'M=M-1')
def _unary(compute): # compute Example: 'M=-D', 'M=!D'' asm.dec_sp() asm.st_2_dreg() asm.append_lines(compute) asm.inc_sp()