1 3 package ro.infoiasi.donald.compiler.parser; 4 5 import ro.infoiasi.donald.compiler.cfg.*; 6 7 public class LR0Item 8 implements Cloneable { 9 private Production p; 10 private WordIterator it; 11 12 public LR0Item(Production p, int position) { 13 this.p = p; 14 Word w = p.getRHS(); 15 if (position >=0 && position<=w.size()) { 16 it = w.iterator(); 17 while (position>0) { 18 it.next(); 19 position--; 20 } 21 } else { 22 throw new IndexOutOfBoundsException (); 23 } 24 } 25 26 public LR0Item(Production p) { 27 this(p, 0); 28 } 29 30 public boolean equals(Object o) { 31 return (o instanceof LR0Item && 32 p.equals(((LR0Item)o).p) && 33 getPosition() == ((LR0Item)o).getPosition()); 34 } 35 36 public int hashCode() { 37 return 17+p.hashCode()*37+getPosition(); 38 } 39 40 public Object clone() { 41 try { 42 LR0Item item = (LR0Item)super.clone(); 43 item.it = (WordIterator)it.clone(); 44 return item; 45 } catch (CloneNotSupportedException e) { 46 throw new RuntimeException (e); 47 } 48 } 49 50 public LR0Item nextItem() { 51 LR0Item item = (LR0Item)clone(); 52 item.it.next(); 53 return item; 54 } 55 56 public boolean isComplete() { 57 return !it.hasNext(); 58 } 59 60 public boolean isNew() { 61 return !it.hasPrev(); 62 } 63 64 public Symbol getNextSymbol() { 65 return it.getNext(); 66 } 67 68 public Production getProduction() { 69 return p; 70 } 71 72 public int getPosition() { 73 return it.nextIndex(); 74 } 75 76 public String toString() { 77 return p.getLHS()+" ::= "+it.prefix()+" * "+it.suffix(); 78 } 79 80 Word suffix() { 81 return it.suffix(); 82 } 83 84 public static void main(String args[]) { 85 Terminals t = new Terminals(); 86 Terminal a = t.addNew("a"); 87 Terminal b = t.addNew("b"); 88 Terminal c = t.addNew("c"); 89 NonTerminals v = new NonTerminals(); 90 NonTerminal S = v.addNew("S"); 91 NonTerminal A = v.addNew("A"); 92 NonTerminal B = v.addNew("B"); 93 Word w = new Word(); 94 w.addLast(a); w.addLast(A); w.addLast(b); w.addLast(B); w.addLast(c); 95 Productions p = new Productions(); 96 Production prod = p.addNew(S, w); 97 LR0Item items[] = new LR0Item[w.size()+1]; 98 items[0] = new LR0Item(prod); 99 System.out.println("items[0]: "+items[0]); 100 for (int i = 1; i<=w.size(); i++) { 101 items[i] = items[i-1].nextItem(); 102 System.out.println("items["+i+"]: "+items[i]); 103 } 104 for (int i = 0; i<=w.size(); i++) { 106 System.out.println("items["+i+"]: "+items[i]); 107 } 108 } 109 } 110 | Popular Tags |