0b2229d89be7c70741aff54cf0c50ef7ce0caaf6
[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.util.*;
5 import edu.berkeley.sbp.Sequence.Position;
6 import java.io.*;
7 import java.util.*;
8
9 // FEATURE: try harder to "fuse" states together along two dimensions:
10 //   - identical (equivalent) states, or states that subsume each other
11 //   - unnecessary intermediate states ("short cut" GLR)
12
13 /** a parser which translates an Input<Token> into a Forest<NodeType> */
14 public abstract class Parser<Token, NodeType> {
15
16     final Table pt;
17
18     /** create a parser to parse the grammar with start symbol <tt>u</tt> */
19     public Parser(Union u)  { this.pt = new Table(u); }
20
21     /** implement this method to create the output forest corresponding to a lone shifted input token */
22     public abstract Forest<NodeType> shiftToken(Token t, Input.Region region);
23
24     public abstract Topology<Token> emptyTopology();
25
26     public String toString() { return pt.toString(); }
27     Grammar cache() { return pt; }
28
29     /** parse <tt>input</tt>, and return the shared packed parse forest (or throw an exception) */
30     public Forest<NodeType> parse(Input<Token> input) throws IOException, ParseFailed {
31         verbose = System.getProperty("sbp.verbose", null) != null;
32         spinpos = 0;
33         GSS gss = new GSS(input, this);
34         try {
35             for(GSS.Phase current = gss.new Phase<Token>(pt.start); ;) {
36                 if (verbose) debug(current.token, gss, input);
37                 if (current.isDone()) return (Forest<NodeType>)current.finalResult;
38                 Input.Region region = current.getLocation().createRegion(current.getNextLocation());
39                 Forest forest = shiftToken((Token)current.token, region);
40                 current = gss.new Phase<Token>(current, forest);
41             }
42         } finally {
43             if (verbose) {
44                 System.err.print("\r"+ANSI.clreol());
45                 debug(null, gss, input);
46             }
47         }
48     }
49
50     // Spinner //////////////////////////////////////////////////////////////////////////////
51
52     private boolean verbose = false;
53     private static final char[] spin = new char[] { '-', '\\', '|', '/' };
54     private int spinpos = 0;
55     private long last = 0;
56     void spin() {
57         if (!verbose) return;
58         long now = System.currentTimeMillis();
59         if (now-last < 70) return;
60         last = now;
61         System.err.print("\r  " + spin[spinpos++ % (spin.length)]+"\r");
62     }
63
64     private int _last = -1;
65     private String buf = "";
66     private void debug(Object t, GSS gss, Input input) {
67         //FIXME
68         int c = t==null ? -1 : ((t+"").charAt(0));
69         int last = _last;
70         _last = c;
71         switch(c) {
72             case edu.berkeley.sbp.chr.CharAtom.left:
73                 buf += "\033[31m{\033[0m";
74                 break;
75             case edu.berkeley.sbp.chr.CharAtom.right:
76                 buf += "\033[31m}\033[0m";
77                 break;
78             case -1: // FIXME 
79             case '\n':
80                 if (verbose) {
81                     if (last==' ') buf += ANSI.blue("\\n");
82                     System.err.println("\r"+ANSI.clreol()+"\r"+buf);
83                     buf = "";
84                 }
85                 break;
86             default:
87                 buf += ANSI.cyan(""+((char)c));
88                 break;
89         }
90         if (t==null) return;
91
92         // FIXME: clean this up
93         String s;
94         s = "  " + spin[spinpos++ % (spin.length)]+" parsing ";
95         s += input.getName();
96         s += " "+input.getLocation();
97         while(s.indexOf(':') != -1 && s.indexOf(':') < 8) s = " " + s;
98         String y = "@"+gss.viewPos+" ";
99         while(y.length() < 9) y = " " + y;
100         s += y;
101         s += "   nodes="+gss.numOldNodes;
102         while(s.length() < 50) s = s + " ";
103         s += " shifted="+gss.numNewNodes;
104         while(s.length() < 60) s = s + " ";
105         s += " reductions="+gss.numReductions;
106         while(s.length() < 78) s = s + " ";
107         System.err.print("\r"+ANSI.invert(s+ANSI.clreol())+"\r");
108     }
109
110     // Table //////////////////////////////////////////////////////////////////////////////
111
112     /** an SLR(1) parse table which may contain conflicts */
113     class Table extends Grammar<Token> {
114
115         /** the start state */
116         final State<Token>   start;
117
118         /** a dummy state from which no reductions can be performed */
119         private final State<Token>   dead_state;
120
121         /** used to generate unique values for State.idx */
122         private int master_state_idx = 0;
123
124         /** all the states for this table */
125         HashSet<State<Token>>                     all_states       = new HashSet<State<Token>>();
126
127         /** all the doomed states in this table */
128         HashMap<HashSet<Position>,State<Token>>   doomed_states    = new HashMap<HashSet<Position>,State<Token>>();
129
130         /** all the non-doomed states in this table */
131         HashMap<HashSet<Position>,State<Token>>   normal_states    = new HashMap<HashSet<Position>,State<Token>>();
132
133         Topology<Token> emptyTopology() { return Parser.this.emptyTopology(); }
134     
135         /** construct a parse table for the given grammar */
136         Table(Union ux) {
137             super(new Union("0", Sequence.create(ux), true));
138
139             // create the "dead state"
140             this.dead_state = new State<Token>(new HashSet<Position>(), true);
141
142             // construct the start state; this will recursively create *all* the states
143             this.start = new State<Token>(reachable(rootUnion), false);
144
145             buildReductions();
146             sortReductions();
147         }
148
149         /** fill in the reductions table */
150         private void buildReductions() {
151             // for each state, fill in the corresponding "row" of the parse table
152             for(State<Token> state : all_states)
153                 for(Position p : state.hs) {
154
155                     // if the element following this position is an atom, copy the corresponding
156                     // set of rows out of the "master" goto table and into this state's shift table
157                     if (p.element() != null && p.element() instanceof Atom)
158                         state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).getTokenTopology()));
159
160                     // RNGLR: we can potentially reduce from any "right-nullable" position -- that is,
161                     // any position for which all Elements after it in the Sequence are capable of
162                     // matching the empty string.
163                     if (!isRightNullable(p)) continue;
164                     Topology<Token> follow = follow(p.owner());
165                     for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next()) {
166                         if (!(p2.element() instanceof Union))
167                             throw new Error("impossible -- only Unions can be nullable");
168                         
169                         // interesting RNGLR-followRestriction interaction: we must intersect
170                         // not just the follow-set of the last non-nullable element, but the
171                         // follow-sets of the nulled elements as well.
172                         for(Sequence s : ((Union)p2.element()))
173                             follow = follow.intersect(follow(s));
174                         Topology<Token> set = epsilonFollowSet((Union)p2.element());
175                         if (set != null) follow = follow.intersect(set);
176                     }
177                     
178                     // indicate that when the next token is in the set "follow", nodes in this
179                     // state should reduce according to Position "p"
180                     state.reductions.put(follow, p);
181                     if (followEof.contains(p.owner())) state.eofReductions.add(p);
182                 }
183
184             // optimize the reductions table
185             if (emptyTopology() instanceof IntegerTopology)
186                 for(State<Token> state : all_states) {
187                     // FIXME: this is pretty ugly
188                     state.oreductions = state.reductions.optimize(((IntegerTopology)emptyTopology()).functor());
189                     state.oshifts     = state.shifts.optimize(((IntegerTopology)emptyTopology()).functor());
190                 }
191         }
192
193         // FIXME: this method needs to be cleaned up and documented
194         private void sortReductions() {
195             // crude algorithm to assing an ordinal ordering to every position
196             // al will be sorted in DECREASING order (al[0] >= al[1])
197             ArrayList<Sequence.Position> al = new ArrayList<Sequence.Position>();
198             for(State s : all_states) {
199                 for(Object po : s) {
200                     Sequence.Position p = (Sequence.Position)po;
201                     if (al.contains(p)) continue;
202                     int i=0;
203                     for(; i<al.size(); i++) {
204                         if (comparePositions(p, al.get(i)) < 0)
205                             break;
206                     }
207                     al.add(i, p);
208                 }
209             }
210             // FIXME: this actually pollutes the "pure" objects (the ones that should not be modified by the Parser)
211             // sort in increasing order...
212             OUTER: while(true) {
213                 for(int i=0; i<al.size(); i++)
214                     for(int j=i+1; j<al.size(); j++)
215                         if (comparePositions(al.get(i), al.get(j)) > 0) {
216                             Sequence.Position p = al.remove(j);
217                             al.add(i, p);
218                             continue OUTER;
219                         }
220                 break;
221             }
222
223             int j = 1;
224             int pk = 0;
225             for(int i=0; i<al.size(); i++) {
226                 boolean inc = false;
227                 for(int k=pk; k<i; k++) {
228                     if (comparePositions(al.get(k), al.get(i)) > 0)
229                         { inc = true; break; }
230                 }
231                 inc = true;
232                 if (inc) {
233                     j++;
234                     pk = i;
235                 }
236                 al.get(i).ord = j;
237             }
238         }
239
240         /**
241          *  A single state in the LR table and the transitions
242          *  possible from it
243          *
244          *  A state corresponds to a set of Sequence.Position's.  Each
245          *  Node in the GSS has a State; the Node represents a set of
246          *  possible parses, one for each Position in the State.
247          *
248          *  Every state is either "doomed" or "normal".  If a Position
249          *  is part of a Sequence which is a conjunct (that is, it was
250          *  passed to Sequence.{and(),andnot()}), then that Position
251          *  will appear only in doomed States.  Furthermore, any set
252          *  of Positions reachable from a doomed State also forms a
253          *  doomed State.  Note that in this latter case, a doomed
254          *  state might have exactly the same set of Positions as a
255          *  non-doomed state.
256          *
257          *  Nodes with non-doomed states represent nodes which
258          *  contribute to actual valid parses.  Nodes with doomed
259          *  States exist for no other purpose than to enable/disable
260          *  some future reduction from a non-doomed Node.  Because of
261          *  this, we "garbage-collect" Nodes with doomed states if
262          *  there are no more non-doomed Nodes which they could
263          *  affect (see Result, Reduction, and Node for details).
264          *
265          *  Without this optimization, many seemingly-innocuous uses
266          *  of positive and negative conjuncts can trigger O(n^2)
267          *  space+time complexity in otherwise simple grammars.  There
268          *  is an example of this in the regression suite.
269          */
270         class State<Token> implements IntegerMappable, Iterable<Position> {
271         
272             public  final     int               idx    = master_state_idx++;
273             private final     HashSet<Position> hs;
274             public HashSet<State<Token>> conjunctStates = new HashSet<State<Token>>();
275
276             HashMap<Sequence,State<Token>>      gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
277             private transient TopologicalBag<Token,State<Token>>  gotoSetTerminals    = new TopologicalBag<Token,State<Token>>();
278
279             private           TopologicalBag<Token,Position>      reductions          = new TopologicalBag<Token,Position>();
280             private           HashSet<Position>                   eofReductions       = new HashSet<Position>();
281             private           TopologicalBag<Token,State<Token>>  shifts              = new TopologicalBag<Token,State<Token>>();
282             private           boolean                             accept              = false;
283
284             private VisitableMap<Token,State<Token>> oshifts     = null;
285             private VisitableMap<Token,Position>     oreductions = null;
286             public  final boolean doomed;
287
288             // Interface Methods //////////////////////////////////////////////////////////////////////////////
289
290             public boolean doomed() { return doomed; }
291             boolean                    isAccepting()           { return accept; }
292             public Iterator<Position>  iterator()              { return hs.iterator(); }
293             boolean                    canShift(Token t)       { return oshifts!=null && oshifts.contains(t); }
294             void                       invokeShifts(Token t, GSS.Phase phase, Result r) { oshifts.invoke(t, phase, r); }
295             boolean                    canReduce(Token t)        {
296                 return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
297             void          invokeEpsilonReductions(Token t, Node node) {
298                 if (t==null) for(Position r : eofReductions) node.invoke(r, null);
299                 else         oreductions.invoke(t, node, null);
300             }
301             void          invokeReductions(Token t, Node node, Result b) {
302                 if (t==null) for(Position r : eofReductions) node.invoke(r, b);
303                 else         oreductions.invoke(t, node, b);
304             }
305
306             // Constructor //////////////////////////////////////////////////////////////////////////////
307
308             /**
309              *  create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
310              *  @param hs           the set of <tt>Position</tt>s comprising this <tt>State</tt>
311              *  @param all the set of all elements (Atom instances need not be included)
312              *  
313              *   In principle these two steps could be merged, but they
314              *   are written separately to highlight these two facts:
315              * <ul>
316              * <li> Non-atom elements either match all-or-nothing, and do not overlap
317              *      with each other (at least not in the sense of which element corresponds
318              *      to the last reduction performed).  Therefore, in order to make sure we
319              *      wind up with the smallest number of states and shifts, we wait until
320              *      we've figured out all the token-to-position multimappings before creating
321              *      any new states
322              *  
323              * <li> In order to be able to run the state-construction algorithm in a single
324              *      shot (rather than repeating until no new items appear in any state set),
325              *      we need to use the "yields" semantics rather than the "produces" semantics
326              *      for non-Atom Elements.
327              *  </ul>
328              */
329             public State(HashSet<Position> hs, boolean doomed) {
330                 this.hs = hs;
331                 this.doomed = doomed;
332
333                 // register ourselves so that no two states are ever
334                 // created with an identical position set (termination depends on this)
335                 ((HashMap)(doomed ? doomed_states : normal_states)).put(hs, this);
336                 ((HashSet)all_states).add(this);
337
338                 for(Position p : hs) {
339                     // Step 1a: take note if we are an accepting state
340                     //          (last position of the root Union's sequence)
341                     if (p.next()==null && !doomed && rootUnion.contains(p.owner()))
342                         accept = true;
343
344                     // Step 1b: If any Position in the set is the first position of its sequence, then this
345                     //          state is responsible for spawning the "doomed" states for each of the
346                     //          Sequence's conjuncts.  This obligation is recorded by adding the to-be-spawned
347                     //          states to conjunctStates.
348                     if (!p.isFirst()) continue;
349                     for(Sequence s : p.owner().needs())
350                         if (!hs.contains(s.firstp()))
351                             conjunctStates.add(mkstate(reachable(s.firstp()), true));
352                     for(Sequence s : p.owner().hates())
353                         if (!hs.contains(s.firstp()))
354                             conjunctStates.add(mkstate(reachable(s.firstp()), true));
355                 }
356
357                 // Step 2a: examine all Position's in this state and compute the mappings from
358                 //          sets of follow tokens (tokens which could follow this position) to sets
359                 //          of _new_ positions (positions after shifting).  These mappings are
360                 //          collectively known as the _closure_
361
362                 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
363                 for(Position position : hs) {
364                     if (position.isLast() || !(position.element() instanceof Atom)) continue;
365                     Atom a = (Atom)position.element();
366                     HashSet<Position> hp = new HashSet<Position>();
367                     reachable(position.next(), hp);
368                     bag0.addAll(a.getTokenTopology(), hp);
369                 }
370
371                 // Step 2b: for each _minimal, contiguous_ set of characters having an identical next-position
372                 //          set, add that character set to the goto table (with the State corresponding to the
373                 //          computed next-position set).
374
375                 for(Topology<Token> r : bag0) {
376                     HashSet<Position> h = new HashSet<Position>();
377                     for(Position p : bag0.getAll(r)) h.add(p);
378                     ((TopologicalBag)gotoSetTerminals).put(r, mkstate(h, doomed));
379                 }
380
381                 // Step 3: for every Sequence, compute the closure over every position in this set which
382                 //         is followed by a symbol which could yield the Sequence.
383                 //
384                 //         "yields" [in one or more step] is used instead of "produces" [in exactly one step]
385                 //         to avoid having to iteratively construct our set of States as shown in most
386                 //         expositions of the algorithm (ie "keep doing XYZ until things stop changing").
387
388                 HashMapBag<Sequence,Position> move = new HashMapBag<Sequence,Position>();
389                 for(Position p : hs)
390                     if (!p.isLast() && p.element() instanceof Union)
391                         for(Sequence s : ((Union)p.element())) {
392                             HashSet<Position> hp = new HashSet<Position>();
393                             reachable(p.next(), hp);
394                             move.addAll(s, hp);
395                         }
396                 OUTER: for(Sequence y : move) {
397                     // if a reduction is "lame", it should wind up in the dead_state after reducing
398                     HashSet<Position> h = move.getAll(y);
399                     State<Token> s = mkstate(h, doomed);
400                     for(Position p : hs)
401                         if (p.element() != null && (p.element() instanceof Union))
402                             for(Sequence seq : ((Union)p.element()))
403                                 if (seq.needs.contains(y) || seq.hates.contains(y)) {
404                                     // FIXME: assumption that no sequence is ever both usefully (non-lamely) matched
405                                     //        and also directly lamely matched
406                                     ((HashMap)gotoSetNonTerminals).put(y, dead_state);
407                                     continue OUTER;
408                                 }
409                     gotoSetNonTerminals.put(y, s);
410                 }
411             }
412
413             private State<Token> mkstate(HashSet<Position> h, boolean b) {
414                 State ret = (b?doomed_states:normal_states).get(h);
415                 if (ret==null) ret = new State<Token>(h,b);
416                 return ret;
417             }
418
419             public int toInt() { return idx; }
420             public String toString() {
421                 StringBuffer ret = new StringBuffer();
422                 for(Position p : hs)
423                     ret.append(p+"\n");
424                 return ret.toString();
425             }
426         }
427
428     }
429
430     // Helpers //////////////////////////////////////////////////////////////////////////////
431     
432     private static HashSet<Position> reachable(Element e) {
433         HashSet<Position> h = new HashSet<Position>();
434         reachable(e, h);
435         return h;
436     }
437     private static void reachable(Element e, HashSet<Position> h) {
438         if (e instanceof Atom) return;
439         for(Sequence s : ((Union)e))
440             reachable(s.firstp(), h);
441     }
442     private static void reachable(Position p, HashSet<Position> h) {
443         if (h.contains(p)) return;
444         h.add(p);
445         if (p.element() != null) reachable(p.element(), h);
446     }
447     private static HashSet<Position> reachable(Position p) {
448         HashSet<Position> ret = new HashSet<Position>();
449         reachable(p, ret);
450         return ret;
451     }
452
453 }