diff options
Diffstat (limited to 'projects/hack-vm/compare.py')
-rw-r--r-- | projects/hack-vm/compare.py | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/projects/hack-vm/compare.py b/projects/hack-vm/compare.py new file mode 100644 index 0000000..1565b11 --- /dev/null +++ b/projects/hack-vm/compare.py @@ -0,0 +1,32 @@ +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): + global tag_idx + asm = COMPARE_ASM.format(tag=f"{command.upper()}_{tag_idx}", jmp=JMP[command]) + tag_idx += 1 + return asm |