6. Symbol table
Once completed the syntax analysis, we can start to develop the semantic analysis phase. First of all we have to design the symbol table organization, in order to hold information about source-program constructs. Information will be collected incrementally by the analysis phase and used by the synthesis phase to generate the code. Entries in the symbol table will contain information about every identifier, such as its lexeme, its type, its position in storage, and any other information relevant to the translation process. Since mjava admits nested environments, where identifiers can be redeclared, we support multiple declarations of a same identifier by setting up a separate symbol table for each scope. The most-closely nested rule will be implemented by chaining the symbol tables so that the table for a nested scope points to the table for its enclosing scope. An example of multiple declarations, their scopes, and the corresponding chained symbol tables is shown in the figure:
The implementation of chained symbol tables is defined by the class Env in Env.java. This class models an environment by means of an HashMap (table) and a reference (prev) to the table of the enclosing scope; the static variables top and root maintain the references to the current environment and to the root environment respectively. Entries in a table are key-value pairs, where the key is the lexeme of an identifier and the value is an instance of the class Symb, declared in Symb.java, that will contain information about the identifier (in this first implementation Symb is empty). The following static methods are declared in class Env : · put adds a new entry in the current environment if its lexeme is not already there · get retrieves an entry in the chain of tables starting from the current environment · putClass adds a new entry in the root environment if its lexeme (a class name) is not already there and its super class (if any) has already been declared · push creates a new environment and makes it the current environment · pop restores the previous environment. The current environment is printed on the Java console anytime it is modified.
The construction of symbol tables for mjava is specified in mjava.cup. You can generate the parser and run it on the input program SampleProgram.mjava by means of mjava.bat or mjava.spt (Env.java and Symb.java should be stored in a subdirectory named symtab). The output reported in SymbolTableResult.txt will be printed on the Java console.
|