summaryrefslogtreecommitdiff
path: root/projects/hack-vm/arith_logic.py
blob: a184067447875bcc7b4b113bfc65961928dcea25 (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
from .utils import *

# common preamble to add, sub, and, or
BINARY_COMMON_ASM = """@SP
AM=M-1
D=M
A=A-1
"""

# common preamble to neg and not
UNARY_COMMON_ASM = """@SP
A=M-1
"""

ARITH_LOGIC_ASM = {
    "add": BINARY_COMMON_ASM + "M=D+M\n",
    "sub": BINARY_COMMON_ASM + "M=M-D\n",
    "and": BINARY_COMMON_ASM + "M=D&M\n",
    "or": BINARY_COMMON_ASM + "M=D|M\n",
    "neg": UNARY_COMMON_ASM + "M=-M\n",
    "not": UNARY_COMMON_ASM + "M=!M\n",
}


def translate_arith_logic(command, verbose=False):
    asm = f"// {command}\n" if verbose else ""
    asm += ARITH_LOGIC_ASM[command]
    return asm