CpS 450 Notes

Symbol Table


You should create a SymbolTable class which manages the symbol table. It should manage a stack of Symbol entries (which consist of a scope number, name, and attributes), and keep track of the current scope level (initially 0). It should provide the following interface:

Before trying to use this in your compiler, it would be a good idea to write a small JUnit test to verify that it works properly.

In Eclipse, simply right-click your SymbolTable.java in the Package Explorer, and choose New > JUnit Test from the menu, provide a name (like SymbolTableTest), and click Finish. Write a public void testSymbolTable() method that instantiates a SymbolTable, calls its methods, and asserts that they work properly, then right-click your SymbolTableTest and choose Run > Run As > JUnit Test to run your test program.

Sample SymbolTableTest.java:

import junit.framework.TestCase;

public class SymbolTableTest extends TestCase {
  public void testSymbolTable() {
    SymbolTable table = new SymbolTable();
		
    Symbol s = table.push("x", new VarDecl(Type.INT));
    assertTrue(s.getName().equals("x"));
    // ...
  }

}

 

Declaration

Declaration objects store information about their symbol. You will have a hierarchy of Declaration classes, because there are different kinds of identifiers. I suggest starting with the following class structure:

class Declaration {
  Type type; // all symbols have a Type
}

class VarDecl extends Declaration {
  // more will go here eventually ...
}

class MethodDecl extends Declaration {
  // more will go here eventually ...
}

class ClassDecl extends Declaration {
  // more will go here eventually ...
}