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