001: package ro.infoiasi.donald.compiler.parser;
002:
003: import ro.infoiasi.donald.compiler.cfg.*;
004: import ro.infoiasi.donald.compiler.simple.*;
005: import java.util.*;
006:
007: // a relation on the symbols of a CFG grammar
008: public class SymbolRelation {
009: public interface SymbolPair {
010: Symbol getFirst();
011:
012: Symbol getSecond();
013: }
014:
015: private CFG g;
016: private Relation r;
017:
018: private class SymbolPairP implements SymbolPair {
019: private Symbol first;
020: private Symbol second;
021:
022: public SymbolPairP(Symbol first, Symbol second) {
023: this .first = first;
024: this .second = second;
025: }
026:
027: public SymbolPairP(Relation.IntPair ip) {
028: this .first = g.symbol(ip.getFirst());
029: this .second = g.symbol(ip.getSecond());
030:
031: }
032:
033: public Symbol getFirst() {
034: return first;
035: }
036:
037: public Symbol getSecond() {
038: return second;
039: }
040:
041: public String toString() {
042: return "(" + first + "," + second + ")";
043: }
044: }
045:
046: SymbolRelation(CFG g) {
047: this .g = g;
048: r = new Relation(g.getNonTerminals().count()
049: + g.getTerminals().count());
050: }
051:
052: private SymbolRelation(CFG g, Relation r) {
053: this .g = g;
054: this .r = r;
055: }
056:
057: public boolean contains(Symbol x, Symbol y) {
058: return r.contains(g.getSID(x), g.getSID(y));
059: }
060:
061: public boolean add(Symbol x, Symbol y) {
062: return r.add(g.getSID(x), g.getSID(y));
063: }
064:
065: public SymbolRelation inverse() {
066: return new SymbolRelation(g, r.inverse());
067: }
068:
069: public SymbolRelation plus() {
070: return new SymbolRelation(g, r.transitiveClosure());
071: }
072:
073: public SymbolRelation star() {
074: return new SymbolRelation(g, r.reflexiveTransitiveClosure());
075: }
076:
077: public SymbolRelation product(SymbolRelation sr) {
078: return new SymbolRelation(g, Relation.product(r, sr.r));
079: }
080:
081: private class IteratorP implements Iterator {
082: private Iterator it = r.iterator();
083:
084: public boolean hasNext() {
085: return it.hasNext();
086: }
087:
088: public Object next() {
089: return new SymbolPairP((Relation.IntPair) it.next());
090: }
091:
092: public void remove() {
093: it.remove();
094: }
095: }
096:
097: public Iterator iteratorSP() {
098: return new IteratorP();
099: }
100:
101: public Iterator iteratorIP() {
102: return r.iterator();
103: }
104:
105: public String toString() {
106: StringBuffer sb = new StringBuffer();
107: sb.append("{");
108: Iterator it = iteratorSP();
109: while (it.hasNext()) {
110: SymbolPair sp = (SymbolPair) it.next();
111: sb.append(sp.toString());
112: }
113: sb.append("}");
114: return sb.toString();
115: }
116: }
|