f239fe5edddf7c30cb61ab22b3bcc5efb3494dfd
[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.values()) {
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         HashMap<HashSet<Position>,State<Token>>   all_states    = new HashMap<HashSet<Position>,State<Token>>();
112         HashSet<SequenceOrElement>                all_elements  = new HashSet<SequenceOrElement>();
113
114         /** construct a parse table for the given grammar */
115         public Table(Topology top) { this("s", top); }
116         public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
117         public Table(Union ux, Topology top) {
118             Union start0 = new Union("0");
119             start0.add(new Sequence.Singleton(ux));
120
121             for(Sequence s : start0) cache.eof.put(s, true);
122             cache.eof.put(start0, true);
123
124             // construct the set of states
125             walk(start0, all_elements);
126             for(SequenceOrElement e : all_elements)
127                 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
128             for(SequenceOrElement e : all_elements)
129                 cache.ys2.addAll(e, new Walk.YieldSet2(e, cache).walk());
130             HashSet<Position> hp = new HashSet<Position>();
131             reachable(start0, hp);
132
133             this.dead_state = new State<Token>(new HashSet<Position>());
134             this.start = new State<Token>(hp);
135
136             // for each state, fill in the corresponding "row" of the parse table
137             for(State<Token> state : all_states.values())
138                 for(Position p : state.hs) {
139
140                     // the Grammar's designated "last position" is the only accepting state
141                     if (start0.contains(p.owner()) && p.next()==null)
142                         state.accept = true;
143
144                     if (isRightNullable(p)) {
145                         Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
146                         Topology follow = wf.walk(p.owner());
147                         for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next()) {
148                             Atom set = new Walk.EpsilonFollowSet(new edu.berkeley.sbp.chr.CharAtom(top.empty().complement()),
149                                                                  new edu.berkeley.sbp.chr.CharAtom(top.empty()),
150                                                                  cache).walk(p2.element());
151                             follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
152                             if (set != null) follow = follow.intersect(set.getTokenTopology());
153                         }
154                         state.reductions.put(follow, p);
155                         if (wf.includesEof()) state.eofReductions.add(p);
156                     }
157
158                     // if the element following this position is an atom, copy the corresponding
159                     // set of rows out of the "master" goto table and into this state's shift table
160                     if (p.element() != null && p.element() instanceof Atom)
161                         state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).getTokenTopology()));
162                 }
163             if (top instanceof IntegerTopology)
164                 for(State<Token> state : all_states.values()) {
165                     state.oreductions = state.reductions.optimize(((IntegerTopology)top).functor());
166                     state.oshifts = state.shifts.optimize(((IntegerTopology)top).functor());
167                 }
168         }
169
170         private boolean isRightNullable(Position p) {
171             if (p.isLast()) return true;
172             if (!possiblyEpsilon(p.element())) return false;
173             return isRightNullable(p.next());
174         }
175
176         /** a single state in the LR table and the transitions possible from it */
177
178         class State<Token> implements IntegerMappable, Iterable<Position> {
179         
180             public  final     int               idx    = master_state_idx++;
181             private final     HashSet<Position> hs;
182             public HashSet<State<Token>> also = new HashSet<State<Token>>();
183
184             public transient HashMap<Sequence,State<Token>>         gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
185             private transient TopologicalBag<Token,State<Token>>     gotoSetTerminals    = new TopologicalBag<Token,State<Token>>();
186
187             private           TopologicalBag<Token,Position> reductions          = new TopologicalBag<Token,Position>();
188             private           HashSet<Position>              eofReductions       = new HashSet<Position>();
189             private           TopologicalBag<Token,State<Token>>     shifts              = new TopologicalBag<Token,State<Token>>();
190             private           boolean                         accept              = false;
191
192             private VisitableMap<Token,State<Token>> oshifts = null;
193             private VisitableMap<Token,Position> oreductions = null;
194
195             // Interface Methods //////////////////////////////////////////////////////////////////////////////
196
197             boolean             isAccepting()           { return accept; }
198             public Iterator<Position>  iterator()       { return hs.iterator(); }
199
200             boolean             canShift(Token t)         { return oshifts!=null && oshifts.contains(t); }
201             <B,C> void          invokeShifts(Token t, Invokable<State<Token>,B,C> irbc, B b, C c) {
202                 oshifts.invoke(t, irbc, b, c);
203             }
204
205             boolean             canReduce(Token t)        { return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
206             <B,C> void          invokeReductions(Token t, Invokable<Position,B,C> irbc, B b, C c) {
207                 if (t==null) for(Position r : eofReductions) irbc.invoke(r, b, c);
208                 else         oreductions.invoke(t, irbc, b, c);
209             }
210
211             // Constructor //////////////////////////////////////////////////////////////////////////////
212
213             /**
214              *  create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
215              *  @param hs           the set of <tt>Position</tt>s comprising this <tt>State</tt>
216              *  @param all_elements the set of all elements (Atom instances need not be included)
217              *  
218              *   In principle these two steps could be merged, but they
219              *   are written separately to highlight these two facts:
220              * <ul>
221              * <li> Non-atom elements either match all-or-nothing, and do not overlap
222              *      with each other (at least not in the sense of which element corresponds
223              *      to the last reduction performed).  Therefore, in order to make sure we
224              *      wind up with the smallest number of states and shifts, we wait until
225              *      we've figured out all the token-to-position multimappings before creating
226              *      any new states
227              *  
228              * <li> In order to be able to run the state-construction algorithm in a single
229              *      shot (rather than repeating until no new items appear in any state set),
230              *      we need to use the "yields" semantics rather than the "produces" semantics
231              *      for non-Atom Elements.
232              *  </ul>
233              */
234             public State(HashSet<Position> hs) { this(hs, false); }
235             public boolean special;
236             public State(HashSet<Position> hs, boolean special) {
237                 this.hs = hs;
238                 this.special = special;
239
240                 // register ourselves in the all_states hash so that no
241                 // two states are ever created with an identical position set
242                 ((HashMap)all_states).put(hs, this);
243
244                 for(Position p : hs) {
245                     if (!p.isFirst()) continue;
246                     for(Sequence s : p.owner().needs()) {
247                         if (hs.contains(s.firstp())) continue;
248                         HashSet<Position> h2 = new HashSet<Position>();
249                         reachable(s.firstp(), h2);
250                         also.add((State<Token>)(all_states.get(h2) == null ? (State)new State<Token>(h2,true) : (State)all_states.get(h2)));
251                     }
252                     for(Sequence s : p.owner().hates()) {
253                         if (hs.contains(s.firstp())) continue;
254                         HashSet<Position> h2 = new HashSet<Position>();
255                         reachable(s, h2);
256                         also.add((State<Token>)(all_states.get(h2) == null ? (State)new State<Token>(h2,true) : (State)all_states.get(h2)));
257                     }
258                 }
259
260                 // Step 1a: examine all Position's in this state and compute the mappings from
261                 //          sets of follow tokens (tokens which could follow this position) to sets
262                 //          of _new_ positions (positions after shifting).  These mappings are
263                 //          collectively known as the _closure_
264
265                 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
266                 for(Position position : hs) {
267                     if (position.isLast() || !(position.element() instanceof Atom)) continue;
268                     Atom a = (Atom)position.element();
269                     HashSet<Position> hp = new HashSet<Position>();
270                     reachable(position.next(), hp);
271                     bag0.addAll(a.getTokenTopology(), hp);
272                 }
273
274                 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
275                 //          set, add that character set to the goto table (with the State corresponding to the
276                 //          computed next-position set).
277
278                 for(Topology<Token> r : bag0) {
279                     HashSet<Position> h = new HashSet<Position>();
280                     for(Position p : bag0.getAll(r)) h.add(p);
281                     ((TopologicalBag)gotoSetTerminals).put(r, all_states.get(h) == null
282                                                            ? new State<Token>(h) : all_states.get(h));
283                 }
284
285                 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
286                 //         compute the closure over every position in this set which is followed by a symbol
287                 //         which could yield the Element in question.
288                 //
289                 //         "yields" [in one or more step] is used instead of "produces" [in exactly one step]
290                 //         to avoid having to iteratively construct our set of States as shown in most
291                 //         expositions of the algorithm (ie "keep doing XYZ until things stop changing").
292
293                 HashMapBag<SequenceOrElement,Position> move = new HashMapBag<SequenceOrElement,Position>();
294                 for(Position p : hs) {
295                     Element e = p.element();
296                     if (e==null) continue;
297                     for(SequenceOrElement y : cache.ys2.getAll(e)) {
298                         //System.out.println(e + " yields " + y);
299                         HashSet<Position> hp = new HashSet<Position>();
300                         reachable(p.next(), hp);
301                         move.addAll(y, hp);
302                     }
303                 }
304                 OUTER: for(SequenceOrElement y : move) {
305                     HashSet<Position> h = move.getAll(y);
306                     State<Token> s = all_states.get(h) == null ? (State)new State<Token>(h) : (State)all_states.get(h);
307                     // if a reduction is "lame", it should wind up in the dead_state after reducing
308                     if (y instanceof Sequence) {
309                         for(Position p : hs) {
310                             if (p.element() != null && (p.element() instanceof Union)) {
311                                 Union u = (Union)p.element();
312                                 for(Sequence seq : u)
313                                     if (seq.needs.contains((Sequence)y) || seq.hates.contains((Sequence)y)) {
314                                         // FIXME: what if there are two "routes" to get to the sequence?
315                                         ((HashMap)gotoSetNonTerminals).put((Sequence)y, dead_state);
316                                         continue OUTER;
317                                     }
318                             }
319                         }
320                         gotoSetNonTerminals.put((Sequence)y, s);
321                     }
322                 }
323             }
324
325             public String toStringx() {
326                 StringBuffer st = new StringBuffer();
327                 for(Position p : this) {
328                     if (st.length() > 0) st.append("\n");
329                     st.append(p);
330                 }
331                 return st.toString();
332             }
333             public String toString() {
334                 StringBuffer ret = new StringBuffer();
335                 ret.append("state["+idx+"]: ");
336                 for(Position p : this) ret.append("{"+p+"}  ");
337                 return ret.toString();
338             }
339
340             public Walk.Cache cache() { return cache; }
341             public int toInt() { return idx; }
342         }
343     }
344
345     // Helpers //////////////////////////////////////////////////////////////////////////////
346     
347     private static void reachable(Sequence s, HashSet<Position> h) {
348         reachable(s.firstp(), h);
349         //for(Sequence ss : s.needs()) reachable(ss, h);
350         //for(Sequence ss : s.hates()) reachable(ss, h);
351     }
352     private static void reachable(Element e, HashSet<Position> h) {
353         if (e instanceof Atom) return;
354         for(Sequence s : ((Union)e))
355             reachable(s, h);
356     }
357     private static void reachable(Position p, HashSet<Position> h) {
358         if (h.contains(p)) return;
359         h.add(p);
360         if (p.element() != null) reachable(p.element(), h);
361     }
362
363 }