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.

  1. We push the object into the stack.
  2. We push enough arguments into the stack.
  3. 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:

  1. 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.
  2. 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.
  3. 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 do push argument 0 and pop pointer 0 to let THIS 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:

  1. To obey the rule, we generate code at the end of each method that returns a value.
  2. Since we have nothing to return, we push constant 0, which is a dummy value and then return.

  But now the compiled code faces a slight problem: the stack contains uncessary value and we want to get rid of it.

  1. To do this, we simply pop temp 0.