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