cleanup Walk a bit
[sbp.git] / src / edu / berkeley / sbp / Parser.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.Sequence.Position;
5 import java.io.*;
6 import java.util.*;
7
8 /** a parser which translates streams of Tokens of type T into a Forest<R> */
9 public abstract class Parser<T extends Token, R> {
10
11     private final Table pt;
12
13     /** create a parser to parse the grammar with start symbol <tt>u</tt> */
14     protected Parser(Union u)  { this.pt = new Table(u, top()); }
15     protected Parser(Table pt) { this.pt = pt; }
16
17     /** implement this method to create the output forest corresponding to a lone shifted input token */
18     public abstract Forest<R> shiftedToken(T t, Token.Location loc);
19
20     /** this method must return an empty topology of the input token type */
21     public abstract Topology<T> top();
22
23     /** parse <tt>input</tt>, using the table <tt>pt</tt> to drive the parser */
24     public Forest<R> parse(Token.Stream<T> input) throws IOException, ParseFailed {
25         GSS gss = new GSS();
26         Token.Location loc = input.getLocation();
27         GSS.Phase current = gss.new Phase(null, this, null, input.next(1, 0, 0), loc, null);
28         current.newNode(null, Forest.leaf(null, null), pt.start, true);
29         int count = 1;
30         for(;;) {
31             loc = input.getLocation();
32             current.reduce();
33             Forest forest = current.token==null ? null : shiftedToken((T)current.token, loc);
34             GSS.Phase next = gss.new Phase(current, this, current, input.next(count, gss.resets, gss.waits), loc, forest);
35             count = next.hash.size();
36             if (current.isDone()) return (Forest<R>)current.finalResult;
37             current = next;
38         }
39     }
40
41     // Table //////////////////////////////////////////////////////////////////////////////
42
43     /** an SLR(1) parse table which may contain conflicts */
44     static class Table extends Walk.Cache {
45
46         public final Walk.Cache cache = this;
47
48         private void walk(Element e, HashSet<Element> hs) {
49             if (e==null) return;
50             if (hs.contains(e)) return;
51             hs.add(e);
52             if (e instanceof Atom) return;
53             for(Sequence s : (Union)e) {
54                 hs.add(s);
55                 for(Position p = s.firstp(); p != null; p = p.next())
56                     walk(p.element(), hs);
57             }
58         }
59
60         /** the start state */
61         public final State   start;
62
63         /** used to generate unique values for State.idx */
64         private int master_state_idx = 0;
65
66         /** construct a parse table for the given grammar */
67         public Table(Topology top) { this("s", top); }
68         public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
69         public Table(Union ux, Topology top) {
70             Union start0 = new Union("0");
71             start0.add(new Sequence.Singleton(ux, null, null));
72
73             for(Sequence s : start0) cache.eof.put(s, true);
74             cache.eof.put(start0, true);
75
76             // construct the set of states
77             HashMap<HashSet<Position>,State>   all_states    = new HashMap<HashSet<Position>,State>();
78             HashSet<Element>                   all_elements  = new HashSet<Element>();
79             walk(start0, all_elements);
80             for(Element e : all_elements)
81                 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
82             HashSet<Position> hp = new HashSet<Position>();
83             reachable(start0, hp);
84             this.start = new State(hp, all_states, all_elements);
85
86             // for each state, fill in the corresponding "row" of the parse table
87             for(State state : all_states.values())
88                 for(Position p : state.hs) {
89
90                     // the Grammar's designated "last position" is the only accepting state
91                     if (start0.contains(p.owner()) && p.next()==null)
92                         state.accept = true;
93
94                     if (p.isRightNullable(cache)) {
95                         Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
96                         Reduction red = new Reduction(p);
97
98                         Topology follow = wf.walk(p.owner());
99                         if (p.owner() instanceof Sequence.RewritingSequence &&
100                             (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
101                             System.out.println("follow before: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
102                         }
103                         for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next())
104                             follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
105                         if (p.owner() instanceof Sequence.RewritingSequence &&
106                             (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
107                             System.out.println("follow after: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
108                         }
109                         state.reductions.put(follow, red);
110                         if (wf.includesEof()) state.eofReductions.add(red);
111                     }
112
113                     // if the element following this position is an atom, copy the corresponding
114                     // set of rows out of the "master" goto table and into this state's shift table
115                     if (p.element() != null && p.element() instanceof Atom)
116                         state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
117                 }
118             for(State state : all_states.values()) {
119                 state.oreductions = state.reductions.optimize();
120                 state.oshifts = state.shifts.optimize();
121             }
122         }
123
124         /** a single state in the LR table and the transitions possible from it */
125
126         public class State implements Comparable<Table.State>, IntegerMappable, Iterable<Position> {
127         
128             public int toInt() { return idx; }
129
130             public boolean lame() {
131                 for(Position p : this)
132                     for(Position p2 = p; p2!=null; p2=p2.next())
133                         if (p2.isLast() && !p2.owner().lame)
134                             return false;
135                 return true;
136             }
137             /*
138             public boolean isResolvable(Token t) {
139                 boolean found = false;
140                 for(Reduction r : getReductions(t)) {
141                     Position p = r.position;
142                     if (!p.isRightNullable(cache)) continue;
143                     if (p.owner().firstp()==p) continue;
144                     if (found) {
145                         // found two items meeting criteria #1
146                         return false;
147                     } else {
148                         found = true;
149                         continue;
150                     }
151                     if (p.element()==null) continue;
152                     Topology first = new Walk.First(top(), cache).walk(p.element());
153                     if (first.contains(t))
154                 }
155             }
156             */
157
158             public  final     int               idx    = master_state_idx++;
159             private final     HashSet<Position> hs;
160
161             private transient HashMap<Element,State>          gotoSetNonTerminals = new HashMap<Element,State>();
162             private transient TopologicalBag<Token,State>     gotoSetTerminals    = new TopologicalBag<Token,State>();
163
164             private           TopologicalBag<Token,Reduction> reductions          = new TopologicalBag<Token,Reduction>();
165             private           HashSet<Reduction>              eofReductions       = new HashSet<Reduction>();
166             private           TopologicalBag<Token,State>     shifts              = new TopologicalBag<Token,State>();
167             private           boolean                         accept              = false;
168
169             private VisitableMap<Token,State> oshifts = null;
170             private VisitableMap<Token,Reduction> oreductions = null;
171
172             // Interface Methods //////////////////////////////////////////////////////////////////////////////
173
174             public boolean             isAccepting()               { return accept; }
175
176             public boolean             canShift(Token t)           { return oshifts.contains(t); }
177             public boolean             canReduce(Token t)          { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
178
179             public Iterator<Position>  iterator()                  { return hs.iterator(); }
180
181             public <B,C> void          invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) {
182                 oshifts.invoke(t, irbc, b, c);
183             }
184             public <B,C> void          invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
185                 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
186                 else         oreductions.invoke(t, irbc, b, c);
187             }
188
189             // Constructor //////////////////////////////////////////////////////////////////////////////
190
191             /**
192              *  create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
193              *  @param hs           the set of <tt>Position</tt>s comprising this <tt>State</tt>
194              *  @param all_states   the set of states already constructed (to avoid recreating states)
195              *  @param all_elements the set of all elements (Atom instances need not be included)
196              *  
197              *   In principle these two steps could be merged, but they
198              *   are written separately to highlight these two facts:
199              * <ul>
200              * <li> Non-atom elements either match all-or-nothing, and do not overlap
201              *      with each other (at least not in the sense of which element corresponds
202              *      to the last reduction performed).  Therefore, in order to make sure we
203              *      wind up with the smallest number of states and shifts, we wait until
204              *      we've figured out all the token-to-position multimappings before creating
205              *      any new states
206              *  
207              * <li> In order to be able to run the state-construction algorithm in a single
208              *      shot (rather than repeating until no new items appear in any state set),
209              *      we need to use the "yields" semantics rather than the "produces" semantics
210              *      for non-Atom Elements.
211              *  </ul>
212              */
213             public State(HashSet<Position> hs,
214                          HashMap<HashSet<Position>,State> all_states,
215                          HashSet<Element> all_elements) {
216                 this.hs = hs;
217
218                 // register ourselves in the all_states hash so that no
219                 // two states are ever created with an identical position set
220                 all_states.put(hs, this);
221
222                 // Step 1a: examine all Position's in this state and compute the mappings from
223                 //          sets of follow tokens (tokens which could follow this position) to sets
224                 //          of _new_ positions (positions after shifting).  These mappings are
225                 //          collectively known as the _closure_
226
227                 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
228                 for(Position position : hs) {
229                     if (position.isLast() || !(position.element() instanceof Atom)) continue;
230                     Atom a = (Atom)position.element();
231                     HashSet<Position> hp = new HashSet<Position>();
232                     reachable(position.next(), hp);
233                     bag0.addAll(a, hp);
234                 }
235
236                 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
237                 //          set, add that character set to the goto table (with the State corresponding to the
238                 //          computed next-position set).
239
240                 for(Topology<Token> r : bag0) {
241                     HashSet<Position> h = new HashSet<Position>();
242                     for(Position p : bag0.getAll(r)) h.add(p);
243                     gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
244                 }
245
246                 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
247                 //         compute the closure over every position in this set which is followed by a symbol
248                 //         which could yield the Element in question.
249                 //
250                 //         "yields" [in one or more step] is used instead of "produces" [in exactly one step]
251                 //         to avoid having to iteratively construct our set of States as shown in most
252                 //         expositions of the algorithm (ie "keep doing XYZ until things stop changing").
253                 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
254                 for(Position p : hs) {
255                     Element e = p.element();
256                     if (e==null) continue;
257                     for(Element y : cache.ys.getAll(e)) {
258                         HashSet<Position> hp = new HashSet<Position>();
259                         reachable(p.next(), hp);
260                         move.addAll(y, hp);
261                     }
262                 }
263                 for(Element y : move) {
264                     HashSet<Position> h = move.getAll(y);
265                     State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
266                     gotoSetNonTerminals.put(y, s);
267                 }
268             }
269
270             public String toString() {
271                 //return "state["+idx+"]";
272                 StringBuffer ret = new StringBuffer();
273                 ret.append("state["+idx+"]: ");
274                 for(Position p : this) ret.append("{"+p+"}  ");
275                 return ret.toString();
276             }
277
278             public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
279         }
280
281         /**
282          *  the information needed to perform a reduction; copied here to
283          *  avoid keeping references to <tt>Element</tt> objects in a Table
284          */
285         public class Reduction {
286             // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
287             public final int numPop;
288             /*private*/ final Position position;
289             private final Forest[] holder;    // to avoid constant reallocation
290             public int hashCode() { return position.hashCode(); }
291             public boolean equals(Object o) {
292                 if (o==null) return false;
293                 if (o==this) return true;
294                 if (!(o instanceof Reduction)) return false;
295                 Reduction r = (Reduction)o;
296                 return r.position == position;
297             }
298             public Reduction(Position p) {
299                 this.position = p;
300                 this.numPop = p.pos;
301                 this.holder = new Forest[numPop];
302             }
303             public String toString() { return "[reduce " + position + "]"; }
304
305             private Forest zero = null;
306             public Forest zero() {
307                 if (zero != null) return zero;
308                 if (numPop > 0) throw new Error();
309                 return zero = position.rewrite(null);
310             }
311
312             public void reduce(GSS.Phase.Node parent) {
313                 if (numPop==0) finish(parent, zero(), parent.phase());
314                 else           reduce(parent, numPop-1, parent.phase());
315             }
316
317             public void reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild) {
318                 if (numPop<=0) throw new Error("called wrong form of reduce()");
319                 int pos = numPop-1;
320                 Forest old = holder[pos];
321                 holder[pos] = parent.pending();
322                 if (pos==0) {
323                     System.arraycopy(holder, 0, position.holder, 0, holder.length);
324                     finish(onlychild, position.rewrite(parent.phase().getLocation()), parent.phase());
325                 } else {
326                     reduce(onlychild, pos-1, parent.phase());
327                 }
328                 holder[pos] = old;
329             }
330
331             // FIXME: this could be more elegant and/or cleaner and/or somewhere else
332             private void reduce(GSS.Phase.Node parent, int pos, GSS.Phase target) {
333                 Forest old = holder[pos];
334                 holder[pos] = parent.pending();
335                 if (pos==0) {
336                     System.arraycopy(holder, 0, position.holder, 0, holder.length);
337                     for(int i=0; i<position.pos; i++) if (position.holder[i]==null) throw new Error("realbad");
338                     Forest rex = position.rewrite(target.getLocation());
339                     for(GSS.Phase.Node child : parent.parents()) finish(child, rex, target);
340                 } else {
341                     for(GSS.Phase.Node child : parent.parents()) reduce(child, pos-1, target);
342                 }
343                 holder[pos] = old;
344             }
345             private void finish(GSS.Phase.Node parent, Forest result, GSS.Phase target) {
346                 State state = parent.state.gotoSetNonTerminals.get(position.owner());
347                 if (result==null) throw new Error();
348                 if (state!=null)
349                     target.newNode(parent, result, state, numPop<=0, this);
350             }
351         }
352     }
353
354     private static final Forest[] emptyForestArray = new Forest[0];
355
356
357     // Helpers //////////////////////////////////////////////////////////////////////////////
358
359     private static void reachable(Element e, HashSet<Position> h) {
360         if (e instanceof Atom) return;
361         for(Sequence s : ((Union)e))
362             reachable(s.firstp(), h);
363     }
364     private static void reachable(Position p, HashSet<Position> h) {
365         if (h.contains(p)) return;
366         h.add(p);
367         if (p.element() != null) reachable(p.element(), h);
368     }
369
370 }