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