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