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