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