Question on compiling 'method' subroutine

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Question on compiling 'method' subroutine

peterxu422
Jack:
class Square {
    field int x, y;
    field int size;
    ...
    method int getX() {return x;}

    ...
}

VM:
function Square.getX 0
push argument 0
pop pointer 0
push this 0
return

I don't understand why in the VM code you have push argument 0, followed by pop pointer 0. I read the part in the book where you treat argument 0 of method subroutines as if it were an implicit object instance, but I don't see how that relates here. Isn't the code here basically setting pointer 0 to argument 0, which is nothing since there is no argument?
Reply | Threaded
Open this post in threaded view
|

Re: Question on compiling 'method' subroutine

ybakos
Every method call has an implicit first argument: this, the object upon which the method is called. In other words, a reference to the object itself. (Note that I don't have my book in front of me.)

When you invoke an object's method, that method might manipulate the state of the object instance. Which instance? The object upon which the method is called. And how do we set the object pointer, this, which points to the base address of the object in memory.

Reply | Threaded
Open this post in threaded view
|

Re: Question on compiling 'method' subroutine

peterxu422
Ah I get it now. I briefly forgot that all parameters before a subroutine call are pushed onto the stack before the it is invoked (in this case since it's a method the first argument, argument 0, already has the object instance pushed onto the stack). Before remembering this, I thought argument 0 was empty or set to some other value and so setting that to 'this' didn't make sense to me. Now I see. Thanks!