3

I am interested in making a stack based interpreter to interpret a dynamic language. I understand how bytecode and the stack works, but I am struggling to implement things such as execution frames and objects.

I know that (correct me if I am wrong) an execution frame will have

  • stack pointer
  • program counter
  • local variable table
  • stack
  • etc..

and an object will have something along the lines of

  • type / super (in Ruby the equivalent would be "klass")
  • variable table
  • method table
  • etc..

but I need help implementing this.

Thanks, Daniel

1
  • 3
    Welcome to StackOverflow! The best way to handle this sort of thing is to give it a stab and ask specific questions about problems you are having. The best SO questions have code, what you expected and what actually happened. Your question is too broad and will have too many differing opinions to be a good fit here. Commented Feb 20, 2014 at 20:10

1 Answer 1

2

For your first experiments, I suggest implementing your stack as a linked list. Each list entry ("frame") represents a function invocation, so it needs;

  • a reference to the callers frame,
  • a reference to the function itself,
  • a program counter inside that function, and
  • the table of variables of the function.

If you know all variables for each function before you invoke it, then each variable can be assigned one slot each, so every invocation for that function allocates a frame of the same size, but the frame sizes of different functions will be different.

This plan is known as a "spaghetti stack". If you want to support continuations, you need to garbage-collect the frames, instead of de-allocating them when the function invocation returns. Although a spaghetti stack is not the path to super high-performance, it's very flexible and might suit you just fine.

For your objects, "super" is a pointer to a klass object, and the method table goes in the klass object. There's no need for methods on non-klass objects; to handle what Ruby calls "singleton" methods, you allocate a separate klass object just for that one instance, whose super is the original declared class. Ruby uses flags on the klass objects to indicate which ones are singleton classes, which are modules added via "extend", and which are the original declared class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.