-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSymbolTable.java
106 lines (88 loc) · 1.71 KB
/
SymbolTable.java
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
package cop5556sp17;
import java.util.*;
import cop5556sp17.AST.Dec;
public class SymbolTable
{
int current_scope, next_scope;
Stack <Integer>scope_stack = new Stack<Integer>();
HashMap <String, ArrayList<Pair>> hm = new HashMap <String, ArrayList<Pair>>();
/**
* to be called when block entered
*/
public void enterScope()
{
current_scope = next_scope++;
scope_stack.push(current_scope);
}
/**
* leaves scope
*/
public void leaveScope()
{
scope_stack.pop();
current_scope = scope_stack.peek();
}
public boolean insert(String ident, Dec dec)
{
ArrayList<Pair> ps = new ArrayList<Pair>();
Pair p = new Pair(current_scope, dec);
if(hm.containsKey(ident))
{
ps = hm.get(ident);
for(Pair it: ps)
{
if(it.getScope()==current_scope)
return false;
}
}
ps.add(p);
hm.put(ident, ps);
return true;
}
public Dec lookup(String ident)
{
if(!hm.containsKey(ident))
return null;
Dec dec=null;
ArrayList<Pair> ps = hm.get(ident);
for(int i=ps.size()-1;i>=0;i--)
{
int temp_scope = ps.get(i).getScope();
if(scope_stack.contains(temp_scope))
{
dec = ps.get(i).getDec();
break;
}
}
return dec;
}
public SymbolTable()
{
this.current_scope = 0;
this.next_scope = 1;
scope_stack.push(0);
}
@Override
public String toString()
{
return this.toString();
}
public class Pair
{
int scope;
Dec dec;
public Pair(int s, Dec d)
{
this.scope = s;
this.dec = d;
}
public int getScope()
{
return scope;
}
public Dec getDec()
{
return dec;
}
}
}