Home > Net >  implementing "this" / "self" in a custom interpreted programming language
implementing "this" / "self" in a custom interpreted programming language

Time:06-26

I'm working on a custom interpreter for fun ;) What I have so far is assigning variables, defining and calling functions, arrays, loops, if blocks etc... I've started adding OOP elements to my language and I'm having trouble implementing the "this" / "self" keyword. I just cannot figure out a solution to this problem. I've thought about a few solutions:

  1. a class stores it's instances (as a dictionary) and when the "this" keyword appears, the interpreter ignores "private" and "public" keywords (to call a private method from a public one), creates a call to the method referenced by "this" and returns.
  2. the "this" keyword is a reference which under the hood is the instance itself, but the method access modifiers are dropped for that call. this is similar to the first one, but I cannot think of anything better.

Also it would be nice if you knew C# (primarly) or C , since I'm heavily relying on OOP to create my interpreter.

heres a small sample of code that I would like to implement:

struct Dog has
    pub prop age;

    prv def bark() do
        println "woof woof";
    end

    pub def run(dist) do
        loop 0 to $dist with "d" do
            println ("the dog ran "   string $d)   " meters";
            $self.bark();
        end
    end
end

def main(args) do
    new Dog -> $dog;

    7 -> $dog.age;

    println $dog.age;

    $dog.run 30;
end

notice that the bark() method is "prv" (private). I would like to know how can I make the struct be aware of it's instances so I can make the dog bark each time it runs (calling a private method from a public method).

Thanks in advance

CodePudding user response:

Your interpreter is going to need to keep an execution stack and environment (otherwise you wouldn't know where to return to after a method is finished, etc.).

In this execution stack/env, apart from a function pointer/signature, you'd also keep the object the method is being invoked on (if any, remember about static-like functions).

This reference that you'd store would then be also accessed when de-referencing $this. And actually this is both part 1 and 2 of your idea - you could put some kind of checks like visibility of methods etc. there.

Good luck, sounds like a fun project!

  • Related