A simple question about the compiler symbol table

I am developing a small object-based programming language.

I lost a little simple thing. I implemented a couple of visitors who collect the names, types and parameters of classes, method headers and fields from the AST.

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

At first, this may seem like a good idea until you think about a case such as:

void myMethod() { int i; while (something) { int y; } while (something) { int y; } } 

If I just added the variables i and y to the character table, and I would understand that y is a duplicate variable.

Keep in mind that I know about symbol table clouds. What I don’t understand is whether to add and remove information on the fly in the Symbols table while inside the method, or if I have to constantly add data to the symbol table when visiting the method (for example, I did this with fields of class + methodsheader).

Repeat question: when visiting the body of the method, should I leave the Symbol Table at the end of the visit in the same way as it was before the visit?

Thanks!

+4
source share
2 answers

Why don't you simulate program blocks, so you could let the block create a symbol table. In this scenario, y can be live in two different blocks, since two instances will be placed in two different symbol tables.

0
source

You have an AST representing the structure of the program. Some nodes in AST represent new applications (method input, block body, ...).

You can create a symbol table that has the same shape as your AST: if you have an AST node that represents an introduction to the area, create a linked map from the symbols in your declarations.

You will need to search for areas in the order defined by your langauge semantics, but at least you will know where to look for each area.

0
source

All Articles