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