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