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