I'm reading a compiler textbook that compiles to some form of assembly. Since I don't know this assembly language I decided to invent my own simple "assembly language" and implement a basic "virtual machine" which will execute these instructions.
Currently I'm thinking how I can implement function decleration and function calling in the language and VM.
I had the following idea, please tell me what you think:
Function declerations would look like simple labels. At the end of a function there's an
end statement. The 'main program' is a function by itself. For examle:
main: // some logic CALL funcA // more logic END funcA: // .. some logic END
However the difference between
call <function> and
goto <label> is this:
goto simply sets the 'instruction pointer' (the register that holds the number of the next line to be executed) to the line number of the label.
call does what
goto does, but before jumping it pushes the current line number (plus 1) onto a stack.
end is reached, the VM pops the top of the stack and jumps to this line number. If there is nothing in the stack, the program terminates.
So for example, for the code above this is what happens:
main: // this is where the VM starts // some logic CALL funcA // push onto the stack the number 4 (3+1), and jump to the label funcA // more logic .. this is where we return to from funcA END // pop the top of the stack and jump to this line number. nothing -> terminate funcA: // .. some logic END // pop the top of the stack (the number 4), and jump to this line number
What do you think of this approach?