7.7.函数抽象
Function: Abstraction
1.Function in VM language
The VM language features:
- primitive operation(fixed):
add
,sub
- abstract operation(extensible):
mutiple
- primitive operation(fixed):
When we want to call a function, we:
- push the required argument onto the stack.
- call the function. Then the result of function will replace the argument you push earlier.
Take this simple funtion call sqrt(x-17+x*5)
as
example, it can be translated into:
1 | push x |
2.Function definition
Take the previous function as example:
1 | // returns x"y |
As is discussed before, it's pseudo VM code is as below:
1 | function mult(x,y) |
In fact, it can be translated into this VM code:
1 | function mult 2 |
Let's discuss the implementation in detail:
Function declaration:
Function
: function declaration.mult
: the name of the function.2
: use 2 local variables in the function.
Function body:
- branching.
- the variable declared within the body should be stored in
local
. - the assignment of variables can be done through
push constant
andpop local
.
Return value
push
the to-return value in the stack.return
statement at the end of program.
3.Function execution
We can execute a function in a Main
function:
1 | function main 0 |
- the
2
next tomult
indicates that the funtion takes in 2 arguments. - the whole process can be described through these diagrams:
for each function call
during run-time, the
implementation of the call
command should :
Pass parameters from the calling function to the called function;
Determine the return address within the caller's code;
Save the caller's return address, stack and memory segments;
- so that when we return to the
main
, we will be able to recreate the private world ofmain
.
- so that when we return to the
Jump to execute the called fiunction:
And for each function return
during run-time, the
impletation has to:
Return to the caller the value computed by the called function;
- The implementation knows that the topmost value on the stack must be the return value, so it returns the value.
Recycle the memory resources used by the called funetion;
Reinstate the caller's stack and memory segments;
Jump to the return address in the caller's code.
Related Issues not found
Please contact @fyerfyer to initialize the comment