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