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