-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSymbolTable.java
More file actions
90 lines (83 loc) · 1.71 KB
/
Copy pathSymbolTable.java
File metadata and controls
90 lines (83 loc) · 1.71 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
package cop5556sp18;
import cop5556sp18.AST.Declaration;
import java.util.Stack;
import java.util.ArrayList;
import java.util.HashMap;
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>>();
public void enterScope()
{
current_scope = next_scope++;
scope_stack.push(current_scope);
}
public void leaveScope()
{
scope_stack.pop();
current_scope = scope_stack.peek();
}
public boolean insert(String ident, Declaration 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 Declaration lookup(String ident)
{
if(!hm.containsKey(ident))
return null;
Declaration 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;
Declaration dec;
public Pair(int s, Declaration d)
{
this.scope = s;
this.dec = d;
}
public int getScope()
{
return scope;
}
public Declaration getDec()
{
return dec;
}
}
}