Let's suppose I have a code file that reads (I'll use Java-ish syntax) and it is being interpreted. Kind of like a ruby script.

class A{
    int fieldName = 4;

    void doSomething(){...}


A instanceOfA = new A();
A.fieldName = 7;

This is what I understand to happen when this file is interpreted.

  1. File is lexed and parsed
  2. AST or Parse tree is generated
  3. Parse tree is walked to generate code in the runtime to represent the class.
  4. Then what happens? How is the definition turned into an instance? And what kind of internal representation is require to represent the class? Does the interpreter keep the AST for the class around for re-processing each time an instance is created or is some other form created?

I've been following the patterns in Terrence Parr's Language Implementations Patterns book. I think understand how to build the symbol table and scope objects. I'm just a little fuzzy on how take a structure like a class and create an instance of it.

1 Answer 1


Step 3 needs to be expanded a little: The parse tree is walked to generate code and metadata. One of the things it generates is information about class A. This generally isn't done by keeping the original code or parse tree, but by storing the data in some sort of struct or object that holds the relevant information.

At the very least, it needs to keep around all of the information that is needed to instantiate a class, such as how large an instance is, (or what a default/new instance will contain, if it's a dynamic language where class instances aren't fixed-size), which it needs to know in order to allocate memory and set up the object. If the language supports some form of reflection, it will keep more than that so that metadata about the class can be accessed at runtime.

In this specific case, you'd need a metadata structure that says that this class has a single int field, and that it's initialized to 4 as a default value. There are several ways you could implement creating an instance. Here's one:

  • Each class type has a metadata table that provides certain information, including the instance size and (optionally) a compiler-generated "secret routine" that initializes the object.
  • The new operator takes the class type and finds its instance size, and allocates memory for it.
  • It then checks to see if the class has an initialization routine, and if so, calls it. (This one does: it sets the value of fieldname to 4.)
  • It then goes through and checks the class's parent class to see if it has an initialization routine, and so on until it's gone all the way up the chain to the base class.
  • Then it calls the constructor with the params you supplied, and returns the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.