Proposal about the "self" keyword

Andrew Whitworth wknight8111 at gmail.com
Mon Feb 2 21:16:54 UTC 2009


Current behavior of IMCC is to allow the "self" keyword in ordinary
subroutines. If "self" is present it's treated like a magical PMC
variable that is given the value of the first passed parameter. If no
parameters are passed, you get the cryptic error about too few
parameters being passed, when it appears that no parameters have been
defined. So this code:

.sub 'mySub'
    $P1 = self
    .return
.end

is valid PIR, even though calling it will likely Do The Wrong Thing.
Instead of getting a helpful error about using "self" where it
probably shouldn't be used, you get an error about how 0 params are
passed but one was expected. This is weird because there are no .param
values declared here, so it seems 0 params were passed and 0 params
were expected.

Of course we can't get rid of this, because subroutines can be
declared as subs but registered as methods on the class object later.
We also can't require that every sub that uses "self" be labeled as
":method", because it's useful in ":vtable" subs as well, and maybe in
other places too that I haven't thought of.

We also have the problem from TT #103, where "self" can't be used from
inside overridden "invoke" vtable subs for a number of reasons. When
we call a line of code like this:

$P0()

IMCC doesn't know at compile time what type of PMC $P0 is, so it can't
know before hand that it's an Object, and can't know that there's
going to be an overridden invoke sub somewhere that's expecting a
"self". IMCC doesn't pass it, and then when "invoke" looks for it you
get the error "0 params passed, (1) param expected". We've mentioned
in various places ways to get around this:

$P0.$P0()

or

$P0($P0)

Neither of which are particularly appealing to me.


My proposal is this: All subs get the "self" keyword, whether they
want it or not. "self" in all subs point to the object that was being
invoked. In an ordinary subroutine, "self" will refer to the Sub PMC
itself. Ignore it if you don't want it, and nothing really changes
from how things are treated now. Objects, when invoked, will have this
"self" if they want it, which they probably always do. This also is
going to help us a lot internally, where we can unify the functions
for calling methods and functions for calling non-method subs. We
simplify a few things in IMCC too, although we do pay because an extra
parameter is being passed in many cases where it's not needed. As part
of this, I may also like to change VTABLE_invoke to take 4 parameters
instead of 3 (adding an optional invocant PMC, if it's different from
the sub object being invoked).

What do people think of this proposal? Any immediate problems come to
mind that would make this a Bad Idea?

--Andrew Whitworth


More information about the parrot-dev mailing list