package Triangle.ContextualAnalyzer; import java.util.List; import java.util.Map; import java.util.Stack; import Triangle.AbstractSyntaxTrees.Declaration; import java.util.ArrayList; import java.util.HashMap; public final class SymbolTable { private Map> symtab; private List> scopeStack; public SymbolTable () { symtab = new HashMap>(); scopeStack = new ArrayList>(); } // Opens a new level in the identification table, 1 higher than the // current topmost level. public void openScope () { // new empty list scopeStack.add(new ArrayList()); } // Closes the topmost level in the identification table, discarding // all entries belonging to that level. public void closeScope () { //delete from symtab for(int i = 0; i < scopeStack.get(scopeStack.size() -1).size(); i++){ if(symtab.containsKey(scopeStack.get(scopeStack.size() -1).get(i))){ symtab.get(scopeStack.get(scopeStack.size() -1).get(i)).pop(); if(symtab.get(scopeStack.get(scopeStack.size() -1).get(i)).empty()){ symtab.remove(scopeStack.get(scopeStack.size() -1).get(i)); } } } // delete top list scopeStack.remove(scopeStack.size()-1); } // Makes a new entry in the identification table for the given identifier // and attribute. The new entry belongs to the current level. // duplicated is set to to true if there is already an entry for the // same identifier at the current level. public void enter (String id, Declaration attr) { scopeStack.get(scopeStack.size()-1).add(id); if(symtab.containsKey(id)){ symtab.get(id).push(attr); }else{ symtab.put(id, new Stack()); symtab.get(id).push(attr); } } // Finds an entry for the given identifier in the identification table, // if any. If there are several entries for that identifier, finds the // entry at the highest level, in accordance with the scope rules. // Returns null if no entry is found. // otherwise returns the attribute field of the entry found. public Declaration retrieve (String id) { if(symtab.containsKey(id)){ return symtab.get(id).firstElement(); } return null; } }