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

LABEL_ASM = "({label})\n"

GOTO_ASM = """@{label}
0;JMP
"""

IF_GOTO_ASM = """@SP
AM=M-1
D=M
@{label}
D;JNE
"""

BRANCHING_ASM = {
    "label": LABEL_ASM,
    "goto": GOTO_ASM,
    "if-goto": IF_GOTO_ASM,
}


def translate_branching(action, label, verbose=False):
    asm = f"// {action} {label}\n" if verbose else ""
    asm += BRANCHING_ASM[action].format(label=label)
    return asm