-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSymbolTable.java
More file actions
97 lines (80 loc) · 2.35 KB
/
Copy pathSymbolTable.java
File metadata and controls
97 lines (80 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package cop5556sp17;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
import java.util.Stack;
import cop5556sp17.AST.Dec;
public class SymbolTable {
public class SymbolTableEntry {
int scope;
Dec dec;
public SymbolTableEntry(int scope, Dec dec) {
this.scope = scope;
this.dec = dec;
}
@Override
public String toString() {
return Integer.toString(this.scope);
}
}
int currentScope, nextScope;
Map<String, LinkedList<SymbolTableEntry>> symbolTableMap;
Stack<Integer> scopeStack;
/**
* to be called when block entered
*/
public void enterScope() {
currentScope = ++ nextScope;
scopeStack.push(currentScope);
}
/**
* leaves scope
*/
public void leaveScope(){
scopeStack.pop();
currentScope = scopeStack.peek();
}
public boolean insert(String ident, Dec dec) {
// list empty for this ident - add a new entry to the list
if(symbolTableMap.get(ident) == null) {
LinkedList<SymbolTableEntry> symbolTableEntries = new LinkedList<SymbolTableEntry>();
symbolTableEntries.addFirst(new SymbolTableEntry(currentScope, dec));
symbolTableMap.put(ident, symbolTableEntries);
}
// list not empty - iterate through the list to see if variable redeclared
else {
LinkedList<SymbolTableEntry> symbolTableEntries = symbolTableMap.get(ident);
for(SymbolTableEntry entry : symbolTableEntries) {
if(entry.scope == currentScope)
return false;
}
symbolTableEntries.addFirst(new SymbolTableEntry(currentScope, dec));
symbolTableMap.put(ident, symbolTableEntries);
}
return true;
}
public Dec lookup(String ident) {
if(symbolTableMap.get(ident) != null){
LinkedList<SymbolTableEntry> symbolTableEntries = symbolTableMap.get(ident);
for(SymbolTableEntry entry : symbolTableEntries){
for (ListIterator<Integer> iterator = scopeStack.listIterator(scopeStack.size()); iterator.hasPrevious();) {
if(entry.scope == iterator.previous()) {
return entry.dec;
}
}
}
}
return null;
}
public SymbolTable() {
scopeStack = new Stack<Integer>();
scopeStack.push(0);
symbolTableMap = new HashMap<String, LinkedList<SymbolTableEntry>>();
}
@Override
public String toString() {
//TODO: IMPLEMENT THIS
return "";
}
}