001: // find better name for isNew -> ???
002:
003: package ro.infoiasi.donald.compiler.parser;
004:
005: import ro.infoiasi.donald.compiler.cfg.*;
006:
007: public class LR0Item implements Cloneable {
008: private Production p;
009: private WordIterator it;
010:
011: public LR0Item(Production p, int position) {
012: this .p = p;
013: Word w = p.getRHS();
014: if (position >= 0 && position <= w.size()) {
015: it = w.iterator();
016: while (position > 0) {
017: it.next();
018: position--;
019: }
020: } else {
021: throw new IndexOutOfBoundsException();
022: }
023: }
024:
025: public LR0Item(Production p) {
026: this (p, 0);
027: }
028:
029: public boolean equals(Object o) {
030: return (o instanceof LR0Item && p.equals(((LR0Item) o).p) && getPosition() == ((LR0Item) o)
031: .getPosition());
032: }
033:
034: public int hashCode() {
035: return 17 + p.hashCode() * 37 + getPosition();
036: }
037:
038: public Object clone() {
039: try {
040: LR0Item item = (LR0Item) super .clone();
041: item.it = (WordIterator) it.clone();
042: return item;
043: } catch (CloneNotSupportedException e) {
044: throw new RuntimeException(e);
045: }
046: }
047:
048: public LR0Item nextItem() {
049: LR0Item item = (LR0Item) clone();
050: item.it.next();
051: return item;
052: }
053:
054: public boolean isComplete() {
055: return !it.hasNext();
056: }
057:
058: public boolean isNew() {
059: return !it.hasPrev();
060: }
061:
062: public Symbol getNextSymbol() {
063: return it.getNext();
064: }
065:
066: public Production getProduction() {
067: return p;
068: }
069:
070: public int getPosition() {
071: return it.nextIndex();
072: }
073:
074: public String toString() {
075: return p.getLHS() + " ::= " + it.prefix() + " * " + it.suffix();
076: }
077:
078: Word suffix() {
079: return it.suffix();
080: }
081:
082: public static void main(String args[]) {
083: Terminals t = new Terminals();
084: Terminal a = t.addNew("a");
085: Terminal b = t.addNew("b");
086: Terminal c = t.addNew("c");
087: NonTerminals v = new NonTerminals();
088: NonTerminal S = v.addNew("S");
089: NonTerminal A = v.addNew("A");
090: NonTerminal B = v.addNew("B");
091: Word w = new Word();
092: w.addLast(a);
093: w.addLast(A);
094: w.addLast(b);
095: w.addLast(B);
096: w.addLast(c);
097: Productions p = new Productions();
098: Production prod = p.addNew(S, w);
099: LR0Item items[] = new LR0Item[w.size() + 1];
100: items[0] = new LR0Item(prod);
101: System.out.println("items[0]: " + items[0]);
102: for (int i = 1; i <= w.size(); i++) {
103: items[i] = items[i - 1].nextItem();
104: System.out.println("items[" + i + "]: " + items[i]);
105: }
106: // in the end
107: for (int i = 0; i <= w.size(); i++) {
108: System.out.println("items[" + i + "]: " + items[i]);
109: }
110: }
111: }
|