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