Alex0105 wrote
Hi there,
How can we implement the Hack Virtual Machine Language operations in the Hack Assembly Language?
Like
1.push constant 13
2.lt
3.pop local 3
4.push argument 0
Cheers,
Alex
As shown in figure 7.2, push needs to put a value in RAM[SP] and then increment SP. Since all push operations need to do this, it would make sense to have a subroutine that does this. Since data is generally only useful if it is in the D register, the general pattern for all the pushes becomes something like
call writeConstToD(13);
call writePushD();
or
call writeSegmentToD("ARG", 0);
call writePushD();
This way you break the job down into little steps that should be easier to figure out.
The compares could be something like
call writePopToD();
call writeSubTopFromD(); // D = D - RAM[SP-1]; SP unchanged
call writeCmpResult("lt"); // set D to 0 or -1 depending on comparison type and D value.
call writeDtoTop(); // RAM[SP-1] = D; SP unchanged
Some of these subroutines are trivial and you will probably just want to write them inline -- for example, writeConstToD(int n) obviously just writes
@n
D=A
Don't worry too much about size of your generated ASM code or the efficiency of your code generator. You can come back later and make improvements to both after you get done with chapter 8. (You will learn more ASM tricks as you write the various code generators.)
--Mark