summaryrefslogtreecommitdiff
path: root/projects/hack-vm/memory.py
diff options
context:
space:
mode:
Diffstat (limited to 'projects/hack-vm/memory.py')
-rw-r--r--projects/hack-vm/memory.py16
1 files changed, 9 insertions, 7 deletions
diff --git a/projects/hack-vm/memory.py b/projects/hack-vm/memory.py
index 84f4a53..a8e2765 100644
--- a/projects/hack-vm/memory.py
+++ b/projects/hack-vm/memory.py
@@ -77,7 +77,7 @@ SEGMENT_SIZE = {
}
-def translate_memory(action, segment, index, prog):
+def translate_memory(action, segment, index, prog, verbose=False):
try:
index = int(index)
except ValueError:
@@ -90,11 +90,11 @@ def translate_memory(action, segment, index, prog):
f"Address error: negative segment index {index}", EXIT_CODE_ADDR_ERROR
)
- asm = ""
+ asm = f"// {action} {segment} {index}\n" if verbose else ""
if segment in ["local", "argument", "this", "that"]:
# these segments are dynamic
- asm = PUSH_ASM if action == "push" else POP_ASM
- return asm.format(segment=SEGMENT_PTR[segment], index=index)
+ asm += PUSH_ASM if action == "push" else POP_ASM
+ asm = asm.format(segment=SEGMENT_PTR[segment], index=index)
elif segment in ["static", "temp", "pointer"]:
# these segments have a fixed location and size on memory
if index >= SEGMENT_SIZE[segment]:
@@ -113,15 +113,17 @@ def translate_memory(action, segment, index, prog):
# "pointer 0" is THIS, "pointer 1" is THAT
addr = "THIS" if index == 0 else "THAT"
- asm = PUSH_FIXED_ASM if action == "push" else POP_FIXED_ASM
- return asm.format(addr=addr)
+ asm += PUSH_FIXED_ASM if action == "push" else POP_FIXED_ASM
+ asm = asm.format(addr=addr)
elif segment == "constant":
if action == "pop":
exit_on_error(
f"Syntax error: popping to constant not allowed", EXIT_CODE_SYNTAX_ERROR
)
- return PUSH_CONSTANT_ASM.format(constant=index)
+ asm += PUSH_CONSTANT_ASM.format(constant=index)
else:
exit_on_error(
f"Syntax error: invalid memory segment {segment}", EXIT_CODE_SYNTAX_ERROR
)
+
+ return asm