integermappable
[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), 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>, IntegerMappable {
166         
167             public int toInt() { return idx; }
168
169             /*
170             public boolean isResolvable(Token t) {
171                 boolean found = false;
172                 for(Reduction r : getReductions(t)) {
173                     Position p = r.position;
174                     if (!p.isRightNullable(cache)) continue;
175                     if (p.owner().firstp()==p) continue;
176                     if (found) {
177                         // found two items meeting criteria #1
178                         return false;
179                     } else {
180                         found = true;
181                         continue;
182                     }
183                     if (p.element()==null) continue;
184                     Topology first = new Walk.First(top(), cache).walk(p.element());
185                     if (first.contains(t))
186                 }
187             }
188             */
189
190             public  final     int               idx    = master_state_idx++;
191             private final     HashSet<Position> hs;
192
193             private transient HashMap<Element,State>          gotoSetNonTerminals = new HashMap<Element,State>();
194             private transient TopologicalBag<Token,State>     gotoSetTerminals    = new TopologicalBag<Token,State>();
195
196             private           TopologicalBag<Token,Reduction> reductions          = new TopologicalBag<Token,Reduction>();
197             private           HashSet<Reduction>              eofReductions       = new HashSet<Reduction>();
198             private           TopologicalBag<Token,State>     shifts              = new TopologicalBag<Token,State>();
199             private           boolean                         accept              = false;
200
201             private VisitableMap<Token,State> oshifts = null;
202             private VisitableMap<Token,Reduction> oreductions = null;
203
204             // Interface Methods //////////////////////////////////////////////////////////////////////////////
205
206             public boolean             isAccepting()               { return accept; }
207
208             public boolean             canShift(Token t)           { return oshifts.contains(t); }
209             public boolean             canReduce(Token t)          { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
210
211             public Iterator<Position>  iterator()                  { return hs.iterator(); }
212
213             public <B,C> void          invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) {
214                 oshifts.invoke(t, irbc, b, c);
215             }
216             public <B,C> void          invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
217                 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
218                 else         oreductions.invoke(t, irbc, b, c);
219             }
220
221             // Constructor //////////////////////////////////////////////////////////////////////////////
222
223             /**
224              *  create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
225              *  @param hs           the set of <tt>Position</tt>s comprising this <tt>State</tt>
226              *  @param all_states   the set of states already constructed (to avoid recreating states)
227              *  @param all_elements the set of all elements (Atom instances need not be included)
228              *  
229              *   In principle these two steps could be merged, but they
230              *   are written separately to highlight these two facts:
231              * <ul>
232              * <li> Non-atom elements either match all-or-nothing, and do not overlap
233              *      with each other (at least not in the sense of which element corresponds
234              *      to the last reduction performed).  Therefore, in order to make sure we
235              *      wind up with the smallest number of states and shifts, we wait until
236              *      we've figured out all the token-to-position multimappings before creating
237              *      any new states
238              *  
239              * <li> In order to be able to run the state-construction algorithm in a single
240              *      shot (rather than repeating until no new items appear in any state set),
241              *      we need to use the "yields" semantics rather than the "produces" semantics
242              *      for non-Atom Elements.
243              *  </ul>
244              */
245             public State(HashSet<Position> hs,
246                          HashMap<HashSet<Position>,State> all_states,
247                          HashSet<Element> all_elements) {
248                 this.hs = hs;
249
250                 // register ourselves in the all_states hash so that no
251                 // two states are ever created with an identical position set
252                 all_states.put(hs, this);
253                 for(Position p : hs) byPosition.add(p,this);
254
255                 // Step 1a: examine all Position's in this state and compute the mappings from
256                 //          sets of follow tokens (tokens which could follow this position) to sets
257                 //          of _new_ positions (positions after shifting).  These mappings are
258                 //          collectively known as the _closure_
259
260                 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
261                 for(Position position : hs) {
262                     if (position.isLast() || !(position.element() instanceof Atom)) continue;
263                     Atom a = (Atom)position.element();
264                     HashSet<Position> hp = new HashSet<Position>();
265                     reachable(position.next(), hp);
266                     bag0.addAll(a, hp);
267                 }
268
269                 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
270                 //          set, add that character set to the goto table (with the State corresponding to the
271                 //          computed next-position set).
272
273                 for(Topology<Token> r : bag0) {
274                     HashSet<Position> h = new HashSet<Position>();
275                     for(Position p : bag0.getAll(r)) h.add(p);
276                     gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
277                 }
278
279                 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
280                 //         compute the closure over every position in this set which is followed by a symbol
281                 //         which could yield the Element in question.
282                 //
283                 //         "yields" [in one or more step] is used instead of "produces" [in exactly one step]
284                 //         to avoid having to iteratively construct our set of States as shown in most
285                 //         expositions of the algorithm (ie "keep doing XYZ until things stop changing").
286                 /*
287                 for(Element e : all_elements) {
288                     if (e instanceof Atom) continue;
289                     HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
290                     State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
291                     if (gotoSetNonTerminals.get(e) != null)
292                         throw new Error("this should not happen");
293                     gotoSetNonTerminals.put(e, s);
294                 }
295                 */
296                 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
297                 for(Position p : hs) {
298                     Element e = p.element();
299                     if (e==null) continue;
300                     HashSet<Element> ys = cache.ys.get(e);
301                     if (ys != null) {
302                         for(Element y : ys) {
303                             HashSet<Position> hp = new HashSet<Position>();
304                             reachable(p.next(), hp);
305                             move.addAll(y, hp);
306                         }
307                     }
308                 }
309                 for(Element y : move) {
310                     HashSet<Position> h = move.getAll(y);
311                     State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
312                     gotoSetNonTerminals.put(y, s);
313                 }
314             }
315
316             public String toString() { return "state["+idx+"]"; }
317
318             public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
319         }
320
321         /**
322          *  the information needed to perform a reduction; copied here to
323          *  avoid keeping references to <tt>Element</tt> objects in a Table
324          */
325         public class Reduction {
326             // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
327             public final int numPop;
328             /*private*/ final Position position;
329             private final Forest[] holder;    // to avoid constant reallocation
330             public int hashCode() { return position.hashCode(); }
331             public boolean equals(Object o) {
332                 if (o==null) return false;
333                 if (o==this) return true;
334                 if (!(o instanceof Reduction)) return false;
335                 Reduction r = (Reduction)o;
336                 return r.position == position;
337             }
338             public Reduction(Position p) {
339                 this.position = p;
340                 this.numPop = p.pos;
341                 this.holder = new Forest[numPop];
342             }
343             public String toString() { return "[reduce " + position + "]"; }
344
345             private Forest zero = null;
346             public Forest zero() {
347                 if (zero != null) return zero;
348                 if (numPop > 0) throw new Error();
349                 return zero = position.rewrite(null);
350             }
351
352             public void reduce(GSS.Phase.Node parent) {
353                 if (numPop==0) finish(parent, zero(), parent.phase());
354                 else           reduce(parent, numPop-1, parent.phase());
355             }
356
357             public void reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild) {
358                 if (numPop<=0) throw new Error("called wrong form of reduce()");
359                 int pos = numPop-1;
360                 Forest old = holder[pos];
361                 holder[pos] = parent.pending();
362                 if (pos==0) {
363                     System.arraycopy(holder, 0, position.holder, 0, holder.length);
364                     finish(onlychild, position.rewrite(parent.phase().getLocation()), parent.phase());
365                 } else {
366                     reduce(onlychild, pos-1, parent.phase());
367                 }
368                 holder[pos] = old;
369             }
370
371             // FIXME: this could be more elegant and/or cleaner and/or somewhere else
372             private void reduce(GSS.Phase.Node parent, int pos, GSS.Phase target) {
373                 Forest old = holder[pos];
374                 holder[pos] = parent.pending();
375                 if (pos==0) {
376                     System.arraycopy(holder, 0, position.holder, 0, holder.length);
377                     for(int i=0; i<position.pos; i++) if (position.holder[i]==null) throw new Error("realbad");
378                     Forest rex = position.rewrite(target.getLocation());
379                     for(GSS.Phase.Node child : parent.parents()) finish(child, rex, target);
380                 } else {
381                     for(GSS.Phase.Node child : parent.parents()) reduce(child, pos-1, target);
382                 }
383                 holder[pos] = old;
384             }
385             private void finish(GSS.Phase.Node parent, Forest result, GSS.Phase target) {
386                 State state = parent.state.gotoSetNonTerminals.get(position.owner());
387                 if (result==null) throw new Error();
388                 if (state!=null)
389                     target.newNode(parent, result, state, numPop<=0, this);
390             }
391         }
392     }
393
394     private static final Forest[] emptyForestArray = new Forest[0];
395
396
397     // Helpers //////////////////////////////////////////////////////////////////////////////
398
399     private static void reachable(Element e, HashSet<Position> h) {
400         if (e instanceof Atom) return;
401         for(Sequence s : ((Union)e))
402             reachable(s.firstp(), h);
403     }
404     private static void reachable(Position p, HashSet<Position> h) {
405         if (h.contains(p)) return;
406         h.add(p);
407         if (p.element() != null) reachable(p.element(), h);
408     }
409
410 }