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