devoured elysium
devoured elysium

Reputation: 105027

Simple question about a Compiler's Symbol Table

I am developing a small object-based programming language.

I am a bit lost on a simple thing, though. I have implemented a couple of visitors that collect the names, types and parameters of classes, method headers and fields off the AST.

My problem is on what to do now with the body of my methods. Should I add the local variables to the Symbol Table?

It could look like a nice idea at first, until one thinks of a case such as:

void myMethod() {
    int i;

    while (something) {
        int y;
    }

    while (something) {
        int y;
    }   
}

Were I just to add the i and y variables to the Symbol Table, and I'd get that y is a duplicated variable.

Keep in mind I know about Symbol Table Scopes. What I fail to grasp is whether one should add and delete info on the fly on the Symbols Table while inside a method, or if I should add data permanently to the Symbol Table when visiting a method (like I did with the class+fields+methodsheader).

Restating the question: when visiting a method body, should I let the Symbol Table, at the end of the visit, just as it was before the visit?

Thanks!

Upvotes: 4

Views: 1073

Answers (2)

Ira Baxter
Ira Baxter

Reputation: 95306

You have an AST representing the program structure. Certain nodes in the AST represent new scopes (method entry, block bodies, ...).

You could build a symbol table that has the same shape as your AST: whereever you have an AST node that represents a scope introduction, build an associated map from symbols to their declarations.

You'll have to search the scopes in an order determined by your language semantics, but at least you'll know where to look for each scope.

Upvotes: 2

Lindydancer
Lindydancer

Reputation: 26094

Why don't you model the blocks of the program, that way you could let a block own a symbol table. In that scenario y could be alive in two different blocks, as the two instances would be placed in two different symbol tables.

Upvotes: 1

Related Questions