73 lines
2.3 KiB
Java
73 lines
2.3 KiB
Java
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<String, Stack<Declaration>> symtab;
|
|
private List<List<String>> scopeStack;
|
|
|
|
public SymbolTable () {
|
|
symtab = new HashMap<String, Stack<Declaration>>();
|
|
scopeStack = new ArrayList<List<String>>();
|
|
}
|
|
|
|
// 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<String>());
|
|
}
|
|
|
|
// 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<Declaration>());
|
|
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;
|
|
}
|
|
|
|
}
|