|
All great questions. But, one step at a time. I have a couple suggestions.
You've got the Hack hardware platform, and can write arbitrary assembly language. You can think of the concept of a "virtual machine" as an agreement that we will make about how to use all the memory of the system. For example, we'll agree to use registers 0 - 15 for special purposes; we'll agree to use addresses 16 - 255 for "static" things (you'll discover this later) and addresses 256 - ..., as a "stack," and the rest of memory as a "heap."
To manipulate this virtual machine, we'll rely on an intermediate language: the Hack VM language.
Your goal, for project 7, is to build a program that translates the vm instructions into assembly language. Doing so "realizes" the virtual machine on the hardware platform. It's this "vm translator" program that will enforce the rules like "push 123 means to figure out where the top of the stack is, and put 123 there."
Consider how you built an assembler in the previous project to translate assembly mnemonics into "binary." An asm file was the input, and a hack file was the output. Your vm translator will accept one or more .vm files as input, and generate an .asm file as its output.
As a first step for Project 7, write a Python program, my_translator.py, that allows you to run:
python my_translator.py SimpleAdd/SimpleAdd.vm And, as a first step, this program should just read the lines in SimpleAdd.vm and print them to the console.
Next, modify your program so that it doesn't print the contents of the file, but rather saves the contents of the file in SimpleAdd.asm. You'll know this is right when the contents of SimpleAdd.asm are the same as SimpleAdd/SimpleAdd.vm.
Next, modify your program so that, for each line in SimpleAdd.vm, you translate it into assembly mnemonics, and write that to the SimpleAdd.asm file. One step at a time: handle push constant N.
See if you can get those steps completed, and post back when you're stuck.
To answer some of your questions, yes, R0, aka SP, is the Stack Pointer, and its contents are a number representing the memory address of the top of the stack. An empty stack has a value of 256 in SP. Pushing new values onto the stack should store the new value at the address specified by SP, and then increment SP, placing the top of the stack "on top of" the newly inserted value.
There is just one stack, but as you'll see later, there's a twist when it comes to functions.
C_ARITHMETIC, etc are just constants representing the type of vm command. For example, push constant 0 is a C_PUSH command, and add is a C_ARITHMETIC command. Your translator will need to handle these kinds of commands differently, and therefore need to differentiate between them.
|