summaryrefslogtreecommitdiff
path: root/projects/hack-vm/branching.py
blob: 684c6e12a281c37a03c43a19609336156468ad0a (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, prog, verbose=False):
    asm = f"// {action} {label}\n" if verbose else ""
    asm += BRANCHING_ASM[action].format(label=f"{prog}${label}")
    return asm