Section Notes: 10/8

Symbol Table implementation:

Symbol tables contain mapping between a name and its all of the attributes the program. Every namable object in the program (variables, functions, classes, methods) has an entry in the symbol table. Symbol tables also need to solve one other problem with names, which is that of resolving which the scopes in which a name is valid.

There are two ways of implementing the symbol table during name analysis, one with a list of hash tables, the other with a hash table of lists. Name analysis is the process in which the duplicate, or missing declarations of variables are detected, and where AST nodes for the variables are decorated with their symbol table entries.

List of Symbol Tables

With a list of hash tables implementation, each variable scope in the program is represented with a hash table. The hash table at the head of the list is the current scope we are in, and each subsequent hash table linked represents enclosing scopes.

int a;

f() {
      int b;
      while(true) {
            bool c;
            int  d;
      }
}
Event Action
Enter a new scope Push a new symbol table to the front of the list.
Exit a scope Remove the current symbol table at the front of the list.
Variable declaration Check to see if the variable has already been declared in the current symbol table. If not, add the mapping to the current top symbol table.
Variable use Check to see if the variable exists in the current scope or any containing scopes, iterating through the symbol tables stored in the list.

Symbol Table of Lists

With this scheme, we keep a single symbol table, with mapping from names to a list of symbol table entries, one entry per variable defined in each scope.

int a;

f() {
      int b;
      int c;

      while(true) {
            bool c;
            int  d;
      }
}

1 - global scope
2 - f() scope
3 - while scope

Event Action
Enter a new scope Increment scope counter.
Exit a scope Decrement scope counter. Remove all symbol table entries at the front of the list that belonged to this scope number.
Variable declaration Check if a duplicate entry exists, and then add the variable to the front of the list.
Variable use Check the list for a variable if an matching entry exists.

After Name Analysis:

When traversing AST during name analysis, each time you visit a node corresponding to a variable, add a reference to the symbol table entry. In the end of name analysis, every variable reference in your AST should be decorated with their appropriate symbol table entries.