digitaladdictions wrote
I am working on the project for chapter 7. I have managed to get the framework in place and can generate asm for pushing two constants and adding, subtracting, or'ing, and'ing, and negating them. I am now working on the eq, gt, lt operations which gave me pause. I think I have a working assembly instruction set for eq but I just want to make sure I am on the right track.
Does it make sense that my VMTranslator would need to dynamically create labels?
Yes, you will need to dynamically create labels. I have a uniqueLabel(prefix) function that creates a guaranteed unique label using an incrementing serial number. The prefix and the s/n are concatenated with a '$', as in "RET$123". The '$' character is a legal symbol character in Hack Assembly that is not leval in VM commands, so my dynamic labels cannot collide with any function names or goto labels used in the VM files.
Does it make sense that the code that my conditional jump executes gets repeated every time the VMTranslator encounters an eq? The only thing that should change is the return address but I don't know how to figure out the return address to push it to the stack so the code could retrieve it and unconditionally jump back to the correct place. As a result, the only thing I can think to do is repeat the whole thing each time and use dynamically created labels.
Registers R13-R15 are available for your generated code to use. You can reserve one of them as a return address register and do one level ASM subroutine calling like this:
@RET$123
D=A
@EQ$SUB
0;JMP
(RET$123)
Somewhere, of course, you need to write the subroutine. One option is to them to an in memory list that gets appended to the end of the translation.
(EQ$SUB)
@R15 // Save return address
M=D
...
@R15 // Return to caller
A=M
0;JMP
My asm is 26 lines long. I feel like it might be more complex than what would be expected at this point. It also uses some stack based gymnastics that were not explicitly demonstrated up to this point. Then again they did say Chapters 7-12 were going to be significantly more difficult than 1-6 so maybe not.
Thanks
-- Justin
One thing that will help quite a bit as you debug your generated code is to write the source VM commands in the output ASM as comments:
// push constant 42
@42
D=A
@SP
...
// add
If you want to email me your generated code, I'll be happy to comment on it.
--Mark