Overview
The VM Translator is a program that translates programs written in the VM language into programs written in the Hack assembly language. The VM language is a high-level language that is designed to be easy to read and write, while the Hack assembly language is a low-level language that is specifically designed for the Hack computer.
Implementation
The VM Translator is implemented in two stages. The first stage implements the nine arithmetic and logical commands of the VM language, as well as the push constant command. The second stage implements the push and pop commands, handling the eight memory segments.
The following example shows the translation from a VM file to an ASM file:
@17
D=A
@SP
A=M
M=D
@SP
M=M+1
@17
D=A
@SP
A=M
M=D
@SP
M=M+1
@SP
A=M
A=A-1
D=M
A=A-1
D=D-M
@IS_EQUAL
D;JEQ
@SP
A=M
A=A-1
D=A
A=A-1
M=0
@SP
M=D
(IS_EQUAL)
@SP
A=M
A=A-1
D=A
A=A-1
M=-1
@SP
M=D
@892
D=A
@SP
A=M
M=D
@SP
M=M+1
@891
D=A
@SP
A=M
M=D
@SP
M=M+1
@SP
A=M
A=A-1
D=M
A=A-1
D=D-M
@IS_EQUAL
D;JLT
@SP
A=M
A=A-1
D=A
A=A-1
M=0
@SP
M=D
(IS_EQUAL)
@SP
A=M
A=A-1
D=A
A=A-1
M=-1
@SP
M=D
@32767
D=A
@SP
A=M
M=D
@SP
M=M+1
@32766
D=A
@SP
A=M
M=D
@SP
M=M+1
@SP
A=M
A=A-1
D=M
A=A-1
D=D-M
@IS_EQUAL
D;JGT
@SP
A=M
A=A-1
D=A
A=A-1
M=0
@SP
M=D
(IS_EQUAL)
@SP
A=M
A=A-1
D=A
A=A-1
M=-1
@SP
M=D
@56
D=A
@SP
A=M
M=D
@SP
M=M+1
@31
D=A
@SP
A=M
M=D
@SP
M=M+1
@53
D=A
@SP
A=M
M=D
@SP
M=M+1
@SP
M=M-1
A=M
D=M
A=A-1
D=D+M
M=D
@112
D=A
@SP
A=M
M=D
@SP
M=M+1
@SP
M=M-1
A=M
D=M
A=A-1
D=M-D
M=D
@SP
A=M
A=A-1
M=-M
@SP
M=M-1
A=M
D=M
A=A-1
D=D&M
M=D
@82
D=A
@SP
A=M
M=D
@SP
M=M+1
@SP
M=M-1
A=M
D=M
A=A-1
D=D|M
M=D