01: package ro.infoiasi.donald.compiler.cfg;
02:
03: import java.util.*;
04:
05: public class NonTerminals {
06: private Map varByName = new HashMap();
07: private List varByIndex = new ArrayList();
08:
09: public NonTerminal addNew(String name, String type) {
10: NonTerminal var = new NonTerminal(name, count(), type);
11: if (varByName.containsKey(name)) {
12: throw new RuntimeException("Duplicate Non-Terminal ("
13: + name + ")");
14: }
15: varByName.put(name, var);
16: varByIndex.add(var);
17: return var;
18: }
19:
20: public NonTerminal addNew(String name) {
21: return addNew(name, null);
22: }
23:
24: public int count() {
25: return varByIndex.size();
26: }
27:
28: public Iterator iterator() {
29: return Collections.unmodifiableList(varByIndex).iterator();
30: }
31:
32: public NonTerminal find(String name) {
33: return (NonTerminal) varByName.get(name);
34: }
35:
36: public NonTerminal find(int index) {
37: if (index < 0 || index >= count()) {
38: return null;
39: } else {
40: return (NonTerminal) varByIndex.get(index);
41: }
42: }
43:
44: public void clear() {
45: varByName.clear();
46: varByIndex.clear();
47: }
48:
49: /** Used to remove useless nonterminals (package access) */
50: void removeUseless(List s) {
51: Iterator it = s.iterator();
52: while (it.hasNext()) {
53: NonTerminal a = (NonTerminal) it.next();
54: varByName.remove(a.getName());
55: }
56:
57: List tmp = new ArrayList();
58: for (int i = 0; i < varByIndex.size(); i++) {
59: NonTerminal a = (NonTerminal) varByIndex.get(i);
60: if (!s.contains(a)) {
61: a.setIndex(tmp.size());
62: tmp.add(a);
63: }
64: }
65: varByIndex = tmp;
66: }
67:
68: public String toString() {
69: StringBuffer sb = new StringBuffer();
70: Iterator it = iterator();
71: while (it.hasNext()) {
72: sb.append(it.next());
73: if (it.hasNext()) {
74: sb.append(", ");
75: }
76: }
77: return sb.toString();
78: }
79: }
|