summaryrefslogtreecommitdiff
path: root/projects/hack-vm/compare.py
blob: 862281fb348f88bdbd1877920d53917fd4c33f01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from .utils import *

# template for lt, gt, and eq
COMPARE_ASM = """@SP
AM=M-1
D=M
A=A-1
D=M-D
M=0
@END_{tag}
D;{jmp}
@SP
A=M-1
M=-1
(END_{tag})
"""

# exact complement of VM command which leaves top of stack false
JMP = {
    "lt": "JGE",
    "eq": "JNE",
    "gt": "JLE",
}

tag_idx = 0


def translate_compare(command, verbose=False):
    global tag_idx
    asm = f"// {command}\n" if verbose else ""
    asm += COMPARE_ASM.format(tag=f"{command.upper()}_{tag_idx}", jmp=JMP[command])
    tag_idx += 1
    return asm