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