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