df94e8301093752745e1314b8dcee5d69b5a364a
[sbp.git] / src / edu / berkeley / sbp / Parser.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.*;
5 import edu.berkeley.sbp.util.*;
6 import edu.berkeley.sbp.Sequence.Position;
7 import java.io.*;
8 import java.util.*;
9
10 /** a parser which translates an Input<Token> into a Forest<NodeType> */
11 public abstract class Parser<Token, NodeType> {
12     protected final Table<Token> pt;
13
14     /** create a parser to parse the grammar with start symbol <tt>u</tt> */
15     public Parser(Union u, Topology<Token> top)  { this.pt = new Table<Token>(u, top); }
16     Parser(Table<Token> pt)               { this.pt = pt; }
17
18     /** implement this method to create the output forest corresponding to a lone shifted input token */
19     public abstract Forest<NodeType> shiftToken(Token t, Input.Location newloc);
20
21     boolean helpgc = true;
22
23     public String toString() { return pt.toString(); }
24
25     /** parse <tt>input</tt>, and return the shared packed parse forest (or throw an exception) */
26     public Forest<NodeType> parse(Input<Token> input) throws IOException, ParseFailed {
27         GSS gss = new GSS(input);
28         Input.Location loc = input.getLocation();
29         Token tok = input.next();
30         GSS.Phase current = gss.new Phase<Token>(null, null, tok, loc, input.getLocation(), null);
31         current.newNode(new Result(Forest.create(loc.createRegion(loc), null, null, false), null, null), pt.start, true);
32         int count = 1;
33         for(int idx=0;;idx++) {
34             Input.Location oldloc = loc;
35             current.reduce();
36             Forest forest = current.token==null ? null : shiftToken((Token)current.token, loc);
37             loc = input.getLocation();
38             Token nextToken = input.next();
39             GSS.Phase next = gss.new Phase<Token>(current, current, nextToken, loc, input.getLocation(), forest);
40
41             /*
42             FileOutputStream fos = new FileOutputStream("out-"+idx+".dot");
43             PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
44             GraphViz gv = new GraphViz();
45             for(Object n : current)
46                 ((Node)n).toGraphViz(gv);
47             gv.dump(p);
48             p.flush();
49             p.close();
50             */
51
52             count = next.size();
53             if (current.isDone()) return (Forest<NodeType>)gss.finalResult;
54             current = next;
55         }
56     }
57
58     // Table //////////////////////////////////////////////////////////////////////////////
59
60     /** an SLR(1) parse table which may contain conflicts */
61     static class Table<Token> extends Walk.Cache {
62
63         public String toString() {
64             StringBuffer sb = new StringBuffer();
65             sb.append("parse table");
66             for(State<Token> state : all_states) {
67                 sb.append("  " + state + "\n");
68                 for(Topology<Token> t : state.shifts) {
69                     sb.append("      shift  \""+
70                               new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => ");
71                     for(State st : state.shifts.getAll(t))
72                         sb.append(st.idx+"  ");
73                     sb.append("\n");
74                 }
75                 for(Topology<Token> t : state.reductions)
76                     sb.append("      reduce \""+
77                               new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => " +
78                               state.reductions.getAll(t) + "\n");
79                 for(Sequence s : state.gotoSetNonTerminals.keySet())
80                     sb.append("      goto   "+state.gotoSetNonTerminals.get(s)+" from " + s + "\n");
81             }
82             return sb.toString();
83         }
84
85         public final Walk.Cache cache = this;
86
87         private void walk(Element e, HashSet<SequenceOrElement> 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                 walk(s, hs);
94         }
95         private void walk(Sequence s, HashSet<SequenceOrElement> hs) {
96             hs.add(s);
97             for(Position p = s.firstp(); p != null; p = p.next())
98                 walk(p.element(), hs);
99             for(Sequence ss : s.needs()) walk(ss, hs);
100             for(Sequence ss : s.hates()) walk(ss, hs);
101         }
102
103         /** the start state */
104         public  final State<Token>   start;
105
106         /** the state from which no reductions can be done */
107         private final State<Token>   dead_state;
108
109         /** used to generate unique values for State.idx */
110         private int master_state_idx = 0;
111         HashSet<State<Token>>   all_states    = new HashSet<State<Token>>();
112         HashMap<HashSet<Position>,State<Token>>   doomed_states    = new HashMap<HashSet<Position>,State<Token>>();
113         HashMap<HashSet<Position>,State<Token>>   normal_states    = new HashMap<HashSet<Position>,State<Token>>();
114         HashSet<SequenceOrElement>                all_elements  = new HashSet<SequenceOrElement>();
115
116         /** construct a parse table for the given grammar */
117         public Table(Topology top) { this("s", top); }
118         public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
119         public Table(Union ux, Topology top) {
120             Union start0 = new Union("0");
121             start0.add(new Sequence.Singleton(ux));
122
123             for(Sequence s : start0) cache.eof.put(s, true);
124             cache.eof.put(start0, true);
125
126             // construct the set of states
127             walk(start0, all_elements);
128             for(SequenceOrElement e : all_elements)
129                 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
130             for(SequenceOrElement e : all_elements)
131                 cache.ys2.addAll(e, new Walk.YieldSet2(e, cache).walk());
132             HashSet<Position> hp = new HashSet<Position>();
133             reachable(start0, hp);
134
135             this.dead_state = new State<Token>(new HashSet<Position>(), true);
136             this.start = new State<Token>(hp);
137
138             // for each state, fill in the corresponding "row" of the parse table
139             for(State<Token> state : all_states)
140                 for(Position p : state.hs) {
141
142                     // the Grammar's designated "last position" is the only accepting state
143                     if (start0.contains(p.owner()) && p.next()==null && !state.doomed)
144                         state.accept = true;
145
146                     if (isRightNullable(p)) {
147                         Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
148                         Topology follow = wf.walk(p.owner());
149                         for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next()) {
150                             Atom set = new Walk.EpsilonFollowSet(new edu.berkeley.sbp.chr.CharAtom(top.empty().complement()),
151                                                                  new edu.berkeley.sbp.chr.CharAtom(top.empty()),
152                                                                  cache).walk(p2.element());
153                             follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
154                             if (set != null) follow = follow.intersect(set.getTokenTopology());
155                         }
156                         state.reductions.put(follow, p);
157                         if (wf.includesEof()) state.eofReductions.add(p);
158                     }
159
160                     // if the element following this position is an atom, copy the corresponding
161                     // set of rows out of the "master" goto table and into this state's shift table
162                     if (p.element() != null && p.element() instanceof Atom)
163                         state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).getTokenTopology()));
164                 }
165             if (top instanceof IntegerTopology)
166                 for(State<Token> state : all_states) {
167                     state.oreductions = state.reductions.optimize(((IntegerTopology)top).functor());
168                     state.oshifts = state.shifts.optimize(((IntegerTopology)top).functor());
169                 }
170         }
171
172         private boolean isRightNullable(Position p) {
173             if (p.isLast()) return true;
174             if (!possiblyEpsilon(p.element())) return false;
175             return isRightNullable(p.next());
176         }
177
178         /** a single state in the LR table and the transitions possible from it */
179
180         class State<Token> implements IntegerMappable, Iterable<Position> {
181         
182             public  final     int               idx    = master_state_idx++;
183             private final     HashSet<Position> hs;
184             public HashSet<State<Token>> also = new HashSet<State<Token>>();
185
186             public transient HashMap<Sequence,State<Token>>         gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
187             private transient TopologicalBag<Token,State<Token>>     gotoSetTerminals    = new TopologicalBag<Token,State<Token>>();
188
189             private           TopologicalBag<Token,Position> reductions          = new TopologicalBag<Token,Position>();
190             private           HashSet<Position>              eofReductions       = new HashSet<Position>();
191             private           TopologicalBag<Token,State<Token>>     shifts              = new TopologicalBag<Token,State<Token>>();
192             private           boolean                         accept              = false;
193
194             private VisitableMap<Token,State<Token>> oshifts = null;
195             private VisitableMap<Token,Position> oreductions = null;
196
197             // Interface Methods //////////////////////////////////////////////////////////////////////////////
198
199             boolean             isAccepting()           { return accept; }
200             public Iterator<Position>  iterator()       { return hs.iterator(); }
201
202             boolean             canShift(Token t)         { return oshifts!=null && oshifts.contains(t); }
203             <B,C> void          invokeShifts(Token t, Invokable<State<Token>,B,C> irbc, B b, C c) {
204                 oshifts.invoke(t, irbc, b, c);
205             }
206
207             boolean             canReduce(Token t)        { return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
208             <B,C> void          invokeReductions(Token t, Invokable<Position,B,C> irbc, B b, C c) {
209                 if (t==null) for(Position r : eofReductions) irbc.invoke(r, b, c);
210                 else         oreductions.invoke(t, irbc, b, c);
211             }
212
213             // Constructor //////////////////////////////////////////////////////////////////////////////
214
215             /**
216              *  create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
217              *  @param hs           the set of <tt>Position</tt>s comprising this <tt>State</tt>
218              *  @param all_elements the set of all elements (Atom instances need not be included)
219              *  
220              *   In principle these two steps could be merged, but they
221              *   are written separately to highlight these two facts:
222              * <ul>
223              * <li> Non-atom elements either match all-or-nothing, and do not overlap
224              *      with each other (at least not in the sense of which element corresponds
225              *      to the last reduction performed).  Therefore, in order to make sure we
226              *      wind up with the smallest number of states and shifts, we wait until
227              *      we've figured out all the token-to-position multimappings before creating
228              *      any new states
229              *  
230              * <li> In order to be able to run the state-construction algorithm in a single
231              *      shot (rather than repeating until no new items appear in any state set),
232              *      we need to use the "yields" semantics rather than the "produces" semantics
233              *      for non-Atom Elements.
234              *  </ul>
235              */
236             public State(HashSet<Position> hs) { this(hs, false); }
237             public boolean doomed;
238             public State(HashSet<Position> hs, boolean doomed) {
239                 this.hs = hs;
240                 this.doomed = doomed;
241
242                 // register ourselves in the all_states hash so that no
243                 // two states are ever created with an identical position set
244                 ((HashMap)(doomed ? doomed_states : normal_states)).put(hs, this);
245                 ((HashSet)all_states).add(this);
246                 
247                 for(Position p : hs) {
248                     if (!p.isFirst()) continue;
249                     for(Sequence s : p.owner().needs()) {
250                         if (hs.contains(s.firstp())) continue;
251                         HashSet<Position> h2 = new HashSet<Position>();
252                         reachable(s.firstp(), h2);
253                         also.add(mkstate(h2, true));
254                     }
255                     for(Sequence s : p.owner().hates()) {
256                         if (hs.contains(s.firstp())) continue;
257                         HashSet<Position> h2 = new HashSet<Position>();
258                         reachable(s, h2);
259                         also.add(mkstate(h2, true));
260                     }
261                 }
262
263                 // Step 1a: examine all Position's in this state and compute the mappings from
264                 //          sets of follow tokens (tokens which could follow this position) to sets
265                 //          of _new_ positions (positions after shifting).  These mappings are
266                 //          collectively known as the _closure_
267
268                 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
269                 for(Position position : hs) {
270                     if (position.isLast() || !(position.element() instanceof Atom)) continue;
271                     Atom a = (Atom)position.element();
272                     HashSet<Position> hp = new HashSet<Position>();
273                     reachable(position.next(), hp);
274                     bag0.addAll(a.getTokenTopology(), hp);
275                 }
276
277                 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
278                 //          set, add that character set to the goto table (with the State corresponding to the
279                 //          computed next-position set).
280
281                 for(Topology<Token> r : bag0) {
282                     HashSet<Position> h = new HashSet<Position>();
283                     for(Position p : bag0.getAll(r)) h.add(p);
284                     ((TopologicalBag)gotoSetTerminals).put(r, mkstate(h, doomed));
285                 }
286
287                 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
288                 //         compute the closure over every position in this set which is followed by a symbol
289                 //         which could yield the Element in question.
290                 //
291                 //         "yields" [in one or more step] is used instead of "produces" [in exactly one step]
292                 //         to avoid having to iteratively construct our set of States as shown in most
293                 //         expositions of the algorithm (ie "keep doing XYZ until things stop changing").
294
295                 HashMapBag<SequenceOrElement,Position> move = new HashMapBag<SequenceOrElement,Position>();
296                 for(Position p : hs) {
297                     Element e = p.element();
298                     if (e==null) continue;
299                     for(SequenceOrElement y : cache.ys2.getAll(e)) {
300                         //System.out.println(e + " yields " + y);
301                         HashSet<Position> hp = new HashSet<Position>();
302                         reachable(p.next(), hp);
303                         move.addAll(y, hp);
304                     }
305                 }
306                 OUTER: for(SequenceOrElement y : move) {
307                     HashSet<Position> h = move.getAll(y);
308                     State<Token> s = mkstate(h, doomed);
309                     // if a reduction is "lame", it should wind up in the dead_state after reducing
310                     if (y instanceof Sequence) {
311                         for(Position p : hs) {
312                             if (p.element() != null && (p.element() instanceof Union)) {
313                                 Union u = (Union)p.element();
314                                 for(Sequence seq : u)
315                                     if (seq.needs.contains((Sequence)y) || seq.hates.contains((Sequence)y)) {
316                                         // FIXME: what if there are two "routes" to get to the sequence?
317                                         ((HashMap)gotoSetNonTerminals).put((Sequence)y, dead_state);
318                                         continue OUTER;
319                                     }
320                             }
321                         }
322                         gotoSetNonTerminals.put((Sequence)y, s);
323                     }
324                 }
325             }
326
327             private State<Token> mkstate(HashSet<Position> h, boolean b) {
328                 if (b) return doomed_states.get(h) == null ? (State)new State<Token>(h,b) : (State)doomed_states.get(h);
329                 else   return normal_states.get(h) == null ? (State)new State<Token>(h,b) : (State)normal_states.get(h);
330             }
331
332             public String toStringx() {
333                 StringBuffer st = new StringBuffer();
334                 for(Position p : this) {
335                     if (st.length() > 0) st.append("\n");
336                     st.append(p);
337                 }
338                 return st.toString();
339             }
340             public String toString() {
341                 StringBuffer ret = new StringBuffer();
342                 ret.append("state["+idx+"]: ");
343                 for(Position p : this) ret.append("{"+p+"}  ");
344                 return ret.toString();
345             }
346
347             public Walk.Cache cache() { return cache; }
348             public int toInt() { return idx; }
349         }
350     }
351
352     // Helpers //////////////////////////////////////////////////////////////////////////////
353     
354     private static void reachable(Sequence s, HashSet<Position> h) {
355         reachable(s.firstp(), h);
356         //for(Sequence ss : s.needs()) reachable(ss, h);
357         //for(Sequence ss : s.hates()) reachable(ss, h);
358     }
359     private static void reachable(Element e, HashSet<Position> h) {
360         if (e instanceof Atom) return;
361         for(Sequence s : ((Union)e))
362             reachable(s, h);
363     }
364     private static void reachable(Position p, HashSet<Position> h) {
365         if (h.contains(p)) return;
366         h.add(p);
367         if (p.element() != null) reachable(p.element(), h);
368     }
369
370 }