Akuli / jou

Yet another programming language
MIT License
12 stars 4 forks source link

maybe `self.member` instead of `self->member` in class? #439

Closed littlewhitecloud closed 9 months ago

littlewhitecloud commented 10 months ago

Though class is based on the struct.

Akuli commented 10 months ago

self->member is same as (*self).member, where *self takes the value of the self pointer. So using . instead of -> would mean that self is not a pointer. For example, consider this:

class Foo:
    x: int
    def increment(self) -> None:
        self->x++

def main() -> int:
    f = Foo{x=3}
    f.increment()
    printf("%d\n", f.x)  # Output: 4
    return 0

It is basically same as:

class Foo:
    x: int

def Foo_increment(f: Foo*) -> None:
    f->x++

def main() -> int:
    f = Foo{x=3}
    Foo_increment(&f)
    printf("%d\n", x)  # Ouptut: 4
    return 0

But if we did this instead, it would not work:

def Foo_increment(f: Foo) -> None:
    f.x++

Now Foo_increment() gets a copy of a Foo instance, and ++ would only affect the copy. Therefore the instance in main() wouldn't change at all. Basically, passing self as a pointer just works like you would expect things to work.

It would be possible to make self work as expected without making it a pointer, but it would mean doing more magic in the Jou compiler.