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