1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.util.*;
5 import edu.berkeley.sbp.Sequence.Position;
9 /** a parser which translates an Input<Token> into a Forest<NodeType> */
10 public abstract class Parser<Token, NodeType> {
14 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
15 public Parser(Union u) { this.pt = new Table(u); }
17 /** implement this method to create the output forest corresponding to a lone shifted input token */
18 public abstract Forest<NodeType> shiftToken(Token t, Input.Region region);
20 public abstract Topology<Token> emptyTopology();
22 public String toString() { return pt.toString(); }
23 Grammar cache() { return pt; }
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 verbose = System.getProperty("sbp.verbose", null) != null;
29 GSS gss = new GSS(input, this);
31 for(GSS.Phase current = gss.new Phase<Token>(pt.start); ;) {
32 if (verbose) debug(current.token, gss, input);
33 if (current.isDone()) return (Forest<NodeType>)current.finalResult;
34 Input.Region region = current.getLocation().createRegion(current.getNextLocation());
35 Forest forest = shiftToken((Token)current.token, region);
36 current = gss.new Phase<Token>(current, forest);
40 System.err.print("\r"+ANSI.clreol());
41 debug(null, gss, input);
46 // Spinner //////////////////////////////////////////////////////////////////////////////
48 private boolean verbose = false;
49 private static final char[] spin = new char[] { '-', '\\', '|', '/' };
50 private int spinpos = 0;
51 private long last = 0;
54 long now = System.currentTimeMillis();
55 if (now-last < 70) return;
57 System.err.print("\r " + spin[spinpos++ % (spin.length)]+"\r");
60 private int _last = -1;
61 private String buf = "";
62 private void debug(Object t, GSS gss, Input input) {
64 int c = t==null ? -1 : ((t+"").charAt(0));
68 case edu.berkeley.sbp.chr.CharAtom.left:
69 buf += "\033[31m{\033[0m";
71 case edu.berkeley.sbp.chr.CharAtom.right:
72 buf += "\033[31m}\033[0m";
77 if (last==' ') buf += ANSI.blue("\\n");
78 System.err.println("\r"+ANSI.clreol()+"\r"+buf);
83 buf += ANSI.cyan(""+((char)c));
88 // FIXME: clean this up
90 s = " " + spin[spinpos++ % (spin.length)]+" parsing ";
92 s += " "+input.getLocation();
93 while(s.indexOf(':') != -1 && s.indexOf(':') < 8) s = " " + s;
94 String y = "@"+gss.viewPos+" ";
95 while(y.length() < 9) y = " " + y;
97 s += " nodes="+gss.numOldNodes;
98 while(s.length() < 50) s = s + " ";
99 s += " shifted="+gss.numNewNodes;
100 while(s.length() < 60) s = s + " ";
101 s += " reductions="+gss.numReductions;
102 while(s.length() < 78) s = s + " ";
103 System.err.print("\r"+ANSI.invert(s+ANSI.clreol())+"\r");
106 // Table //////////////////////////////////////////////////////////////////////////////
108 /** an SLR(1) parse table which may contain conflicts */
109 class Table extends Grammar<Token> {
111 /** the start state */
112 final State<Token> start;
114 /** a dummy state from which no reductions can be performed */
115 private final State<Token> dead_state;
117 /** used to generate unique values for State.idx */
118 private int master_state_idx = 0;
120 /** all the states for this table */
121 HashSet<State<Token>> all_states = new HashSet<State<Token>>();
123 /** all the doomed states in this table */
124 HashMap<HashSet<Position>,State<Token>> doomed_states = new HashMap<HashSet<Position>,State<Token>>();
126 /** all the non-doomed states in this table */
127 HashMap<HashSet<Position>,State<Token>> normal_states = new HashMap<HashSet<Position>,State<Token>>();
129 Topology<Token> emptyTopology() { return Parser.this.emptyTopology(); }
131 /** construct a parse table for the given grammar */
133 super(new Union("0", Sequence.create(ux), true));
135 // create the "dead state"
136 this.dead_state = new State<Token>(new HashSet<Position>(), true);
138 // construct the start state; this will recursively create *all* the states
139 this.start = new State<Token>(reachable(rootUnion), false);
145 /** fill in the reductions table */
146 private void buildReductions() {
147 // for each state, fill in the corresponding "row" of the parse table
148 for(State<Token> state : all_states)
149 for(Position p : state.hs) {
151 // if the element following this position is an atom, copy the corresponding
152 // set of rows out of the "master" goto table and into this state's shift table
153 if (p.element() != null && p.element() instanceof Atom)
154 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).getTokenTopology()));
156 // RNGLR: we can potentially reduce from any "right-nullable" position -- that is,
157 // any position for which all Elements after it in the Sequence are capable of
158 // matching the empty string.
159 if (!isRightNullable(p)) continue;
160 Topology<Token> follow = follow(p.owner());
161 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next()) {
162 if (!(p2.element() instanceof Union))
163 throw new Error("impossible -- only Unions can be nullable");
165 // interesting RNGLR-followRestriction interaction: we must intersect
166 // not just the follow-set of the last non-nullable element, but the
167 // follow-sets of the nulled elements as well.
168 for(Sequence s : ((Union)p2.element()))
169 follow = follow.intersect(follow(s));
170 Topology<Token> set = epsilonFollowSet((Union)p2.element());
171 if (set != null) follow = follow.intersect(set);
174 // indicate that when the next token is in the set "follow", nodes in this
175 // state should reduce according to Position "p"
176 state.reductions.put(follow, p);
177 if (followEof.contains(p.owner())) state.eofReductions.add(p);
180 // optimize the reductions table
181 if (emptyTopology() instanceof IntegerTopology)
182 for(State<Token> state : all_states) {
183 // FIXME: this is pretty ugly
184 state.oreductions = state.reductions.optimize(((IntegerTopology)emptyTopology()).functor());
185 state.oshifts = state.shifts.optimize(((IntegerTopology)emptyTopology()).functor());
189 // FIXME: this method needs to be cleaned up and documented
190 private void sortReductions() {
191 // crude algorithm to assing an ordinal ordering to every position
192 // al will be sorted in DECREASING order (al[0] >= al[1])
193 ArrayList<Sequence.Position> al = new ArrayList<Sequence.Position>();
194 for(State s : all_states) {
196 Sequence.Position p = (Sequence.Position)po;
197 if (al.contains(p)) continue;
199 for(; i<al.size(); i++) {
200 if (comparePositions(p, al.get(i)) < 0)
206 // FIXME: this actually pollutes the "pure" objects (the ones that should not be modified by the Parser)
207 // sort in increasing order...
209 for(int i=0; i<al.size(); i++)
210 for(int j=i+1; j<al.size(); j++)
211 if (comparePositions(al.get(i), al.get(j)) > 0) {
212 Sequence.Position p = al.remove(j);
221 for(int i=0; i<al.size(); i++) {
223 for(int k=pk; k<i; k++) {
224 if (comparePositions(al.get(k), al.get(i)) > 0)
225 { inc = true; break; }
237 * A single state in the LR table and the transitions
240 * A state corresponds to a set of Sequence.Position's. Each
241 * Node in the GSS has a State; the Node represents a set of
242 * possible parses, one for each Position in the State.
244 * Every state is either "doomed" or "normal". If a Position
245 * is part of a Sequence which is a conjunct (that is, it was
246 * passed to Sequence.{and(),andnot()}), then that Position
247 * will appear only in doomed States. Furthermore, any set
248 * of Positions reachable from a doomed State also forms a
249 * doomed State. Note that in this latter case, a doomed
250 * state might have exactly the same set of Positions as a
253 * Nodes with non-doomed states represent nodes which
254 * contribute to actual valid parses. Nodes with doomed
255 * States exist for no other purpose than to enable/disable
256 * some future reduction from a non-doomed Node. Because of
257 * this, we "garbage-collect" Nodes with doomed states if
258 * there are no more non-doomed Nodes which they could
259 * affect (see Result, Reduction, and Node for details).
261 * Without this optimization, many seemingly-innocuous uses
262 * of positive and negative conjuncts can trigger O(n^2)
263 * space+time complexity in otherwise simple grammars. There
264 * is an example of this in the regression suite.
266 class State<Token> implements IntegerMappable, Iterable<Position> {
268 public final int idx = master_state_idx++;
269 private final HashSet<Position> hs;
270 public HashSet<State<Token>> conjunctStates = new HashSet<State<Token>>();
272 HashMap<Sequence,State<Token>> gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
273 private transient TopologicalBag<Token,State<Token>> gotoSetTerminals = new TopologicalBag<Token,State<Token>>();
275 private TopologicalBag<Token,Position> reductions = new TopologicalBag<Token,Position>();
276 private HashSet<Position> eofReductions = new HashSet<Position>();
277 private TopologicalBag<Token,State<Token>> shifts = new TopologicalBag<Token,State<Token>>();
278 private boolean accept = false;
280 private VisitableMap<Token,State<Token>> oshifts = null;
281 private VisitableMap<Token,Position> oreductions = null;
282 public final boolean doomed;
284 // Interface Methods //////////////////////////////////////////////////////////////////////////////
286 public boolean doomed() { return doomed; }
287 boolean isAccepting() { return accept; }
288 public Iterator<Position> iterator() { return hs.iterator(); }
289 boolean canShift(Token t) { return oshifts!=null && oshifts.contains(t); }
290 void invokeShifts(Token t, GSS.Phase phase, Result r) { oshifts.invoke(t, phase, r); }
291 boolean canReduce(Token t) {
292 return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
293 void invokeEpsilonReductions(Token t, Node node) {
294 if (t==null) for(Position r : eofReductions) node.invoke(r, null);
295 else oreductions.invoke(t, node, null);
297 void invokeReductions(Token t, Node node, Result b) {
298 if (t==null) for(Position r : eofReductions) node.invoke(r, b);
299 else oreductions.invoke(t, node, b);
302 // Constructor //////////////////////////////////////////////////////////////////////////////
305 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
306 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
307 * @param all the set of all elements (Atom instances need not be included)
309 * In principle these two steps could be merged, but they
310 * are written separately to highlight these two facts:
312 * <li> Non-atom elements either match all-or-nothing, and do not overlap
313 * with each other (at least not in the sense of which element corresponds
314 * to the last reduction performed). Therefore, in order to make sure we
315 * wind up with the smallest number of states and shifts, we wait until
316 * we've figured out all the token-to-position multimappings before creating
319 * <li> In order to be able to run the state-construction algorithm in a single
320 * shot (rather than repeating until no new items appear in any state set),
321 * we need to use the "yields" semantics rather than the "produces" semantics
322 * for non-Atom Elements.
325 public State(HashSet<Position> hs, boolean doomed) {
327 this.doomed = doomed;
329 // register ourselves so that no two states are ever
330 // created with an identical position set (termination depends on this)
331 ((HashMap)(doomed ? doomed_states : normal_states)).put(hs, this);
332 ((HashSet)all_states).add(this);
334 for(Position p : hs) {
335 // Step 1a: take note if we are an accepting state
336 // (last position of the root Union's sequence)
337 if (p.next()==null && !doomed && rootUnion.contains(p.owner()))
340 // Step 1b: If any Position in the set is the first position of its sequence, then this
341 // state is responsible for spawning the "doomed" states for each of the
342 // Sequence's conjuncts. This obligation is recorded by adding the to-be-spawned
343 // states to conjunctStates.
344 if (!p.isFirst()) continue;
345 for(Sequence s : p.owner().needs())
346 if (!hs.contains(s.firstp()))
347 conjunctStates.add(mkstate(reachable(s.firstp()), true));
348 for(Sequence s : p.owner().hates())
349 if (!hs.contains(s.firstp()))
350 conjunctStates.add(mkstate(reachable(s.firstp()), true));
353 // Step 2a: examine all Position's in this state and compute the mappings from
354 // sets of follow tokens (tokens which could follow this position) to sets
355 // of _new_ positions (positions after shifting). These mappings are
356 // collectively known as the _closure_
358 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
359 for(Position position : hs) {
360 if (position.isLast() || !(position.element() instanceof Atom)) continue;
361 Atom a = (Atom)position.element();
362 HashSet<Position> hp = new HashSet<Position>();
363 reachable(position.next(), hp);
364 bag0.addAll(a.getTokenTopology(), hp);
367 // Step 2b: for each _minimal, contiguous_ set of characters having an identical next-position
368 // set, add that character set to the goto table (with the State corresponding to the
369 // computed next-position set).
371 for(Topology<Token> r : bag0) {
372 HashSet<Position> h = new HashSet<Position>();
373 for(Position p : bag0.getAll(r)) h.add(p);
374 ((TopologicalBag)gotoSetTerminals).put(r, mkstate(h, doomed));
377 // Step 3: for every Sequence, compute the closure over every position in this set which
378 // is followed by a symbol which could yield the Sequence.
380 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
381 // to avoid having to iteratively construct our set of States as shown in most
382 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
384 HashMapBag<Sequence,Position> move = new HashMapBag<Sequence,Position>();
386 if (!p.isLast() && p.element() instanceof Union)
387 for(Sequence s : ((Union)p.element())) {
388 HashSet<Position> hp = new HashSet<Position>();
389 reachable(p.next(), hp);
392 OUTER: for(Sequence y : move) {
393 // if a reduction is "lame", it should wind up in the dead_state after reducing
394 HashSet<Position> h = move.getAll(y);
395 State<Token> s = mkstate(h, doomed);
397 if (p.element() != null && (p.element() instanceof Union))
398 for(Sequence seq : ((Union)p.element()))
399 if (seq.needs.contains(y) || seq.hates.contains(y)) {
400 // FIXME: assumption that no sequence is ever both usefully (non-lamely) matched
401 // and also directly lamely matched
402 ((HashMap)gotoSetNonTerminals).put(y, dead_state);
405 gotoSetNonTerminals.put(y, s);
409 private State<Token> mkstate(HashSet<Position> h, boolean b) {
410 State ret = (b?doomed_states:normal_states).get(h);
411 if (ret==null) ret = new State<Token>(h,b);
415 public int toInt() { return idx; }
416 public String toString() {
417 StringBuffer ret = new StringBuffer();
420 return ret.toString();
426 // Helpers //////////////////////////////////////////////////////////////////////////////
428 private static HashSet<Position> reachable(Element e) {
429 HashSet<Position> h = new HashSet<Position>();
433 private static void reachable(Element e, HashSet<Position> h) {
434 if (e instanceof Atom) return;
435 for(Sequence s : ((Union)e))
436 reachable(s.firstp(), h);
438 private static void reachable(Position p, HashSet<Position> h) {
439 if (h.contains(p)) return;
441 if (p.element() != null) reachable(p.element(), h);
443 private static HashSet<Position> reachable(Position p) {
444 HashSet<Position> ret = new HashSet<Position>();