-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSymbolTable.java
More file actions
129 lines (105 loc) · 2.49 KB
/
SymbolTable.java
File metadata and controls
129 lines (105 loc) · 2.49 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package cop5556sp17;
import cop5556sp17.AST.Dec;
import java.util.HashMap;
import java.util.Stack;
import java.util.Map.Entry;
import java.util.Set;
public class SymbolTable {
//TODO add fields
/**
* to be called when block entered
*/
static class SymbolNode{
public SymbolNode(Dec dec,int scope,SymbolNode next)
{
super();
this.dec = dec;
this.next = next;
this.scope = scope;
}
int scope;
Dec dec;
SymbolNode next = null;
}
HashMap<String, SymbolNode> symbolTable;
Stack<Integer> scopeStack;
int currScope;
int nextscope;
public void enterScope(){
//TODO: IMPLEMENT THIS
currScope = ++nextscope;
scopeStack.push(currScope);
}
/**
* leaves scope
*/
public void leaveScope(){
//TODO: IMPLEMENT THIS
if(scopeStack.size()>0)
{
scopeStack.pop();
currScope = (int)scopeStack.peek();
}
}
public boolean insert(String ident, Dec dec){
//TODO: IMPLEMENT THIS
SymbolNode node = symbolTable.get(ident);
while(node !=null)
{
if(node.scope == currScope){return false;}
node = node.next;
}
symbolTable.put(ident,new SymbolNode(dec,currScope,symbolTable.get(ident)));
return true;
}
public Dec lookup(String ident){
//TODO: IMPLEMENT THIS
SymbolNode node = symbolTable.get(ident);
if(node == null)
{
return null;
}
SymbolNode temp;
temp = node;
int scope = currScope;
while(temp != null)
{
if(temp.scope <= scope)
{
return temp.dec;
}
temp = temp.next;
}
return null;
}
public SymbolTable() {
//TODO: IMPLEMENT THIS
currScope = 0;
nextscope =0;
symbolTable = new HashMap<String,SymbolNode>();
scopeStack = new Stack<Integer>();
scopeStack.push(currScope);
}
@Override
public String toString() {
//TODO: IMPLEMENT THIS
StringBuilder sb = new StringBuilder();
sb.append("ScopeStack: \n");
for(int i : scopeStack)
{
sb.append(i).append('\n');
}
sb.append("SymbolEntries: \n");
Set<Entry<String, SymbolNode>> symEntries = symbolTable.entrySet();
for (Entry<String, SymbolNode> symEntry: symEntries){
sb.append(symEntry.getKey()).append(':');
SymbolNode entry = symEntry.getValue();
while (entry != null){
sb.append('[').append(entry.scope).append(',').append(entry.dec.toString()).append("] ");
entry = entry.next;
}
sb.append('\n');
}
return sb.toString();
}
}