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