10.7.对对象的处理——操纵对象
\(10.7.\)Handling Objects: Manipulation
1.Compiling method calls
- In compiler, we are going to translate the OO method calls into procedural style language like VM language or machine language, they don't understand what an object is.
In order to do this:
- We can treat the object as the first, implicit argument. We push it onto the stack, because we want it to be the first argument on which the method is going to operate.
- We
push
the object into the stack. - We
push
enough arguments into the stack. - We
call
the method.
When we say "put the object onto the stack", we don't care what the object is, we are only interested in its base address.
2.Compiling methods
Methods are used to operate on the object which refers to as
THIS
. Therefore, each method's code needs to access
to the object's field
variables.
In the previous unit, we know that we can access the \(ith\) field
by
THIS i
. However, before we use THIS
, we have
to anchor it on the proper address on the RAM first, so we also need
pointer
.
Let's take the distance
method as an example:
- The method is compiled within a class, so we will compile
the class variables, namely
x, y, pointCount
. This will end up generating no code. - Both the method declaration and variable declaration generate no
code, either. Instead, the compiler creates the symbol table of
the subroutine and populates it within the
this
object as well as the explicit variables that is found in the parameter list and the variable declaration. - We can anticipate that the method will want to operate on the
current object, so we need to generate code that will anchor
this on the correct address in memory. And we know that the
current object address is
argument 0
, so we dopush argument 0
andpop pointer 0
to letTHIS
pointer to contain the address of the current object.
When the distance
method completes execution and
terminates, control will return to the caller. The compiled code of the
caller is as below:
- We know that the method returns a value on the top of stack, so we
remove it and put it into
d
.
3.void
method
compilation
The void
doesn't expect to get a return value, while
according to the rules of the game, we must return a value. As a result,
we:
- To obey the rule, we generate code at the end of each method that returns a value.
- Since we have nothing to return, we
push constant 0
, which is a dummy value and thenreturn
.
But now the compiled code faces a slight problem: the stack contains uncessary value and we want to get rid of it.
- To do this, we simply
pop temp 0
.