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 // 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)
13 /** a parser which translates an Input<Token> into a Forest<NodeType> */
14 public abstract class Parser<Token, NodeType> {
18 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
19 public Parser(Union u) { this.pt = new Table(u); }
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);
24 public abstract Topology<Token> emptyTopology();
26 public String toString() { return pt.toString(); }
27 Grammar cache() { return pt; }
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;
33 GSS gss = new GSS(input, this);
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);
44 System.err.print("\r"+ANSI.clreol());
45 debug(null, gss, input);
50 // Spinner //////////////////////////////////////////////////////////////////////////////
52 private boolean verbose = false;
53 private static final char[] spin = new char[] { '-', '\\', '|', '/' };
54 private int spinpos = 0;
55 private long last = 0;
58 long now = System.currentTimeMillis();
59 if (now-last < 70) return;
61 System.err.print("\r " + spin[spinpos++ % (spin.length)]+"\r");
64 private int _last = -1;
65 private String buf = "";
66 private void debug(Object t, GSS gss, Input input) {
68 int c = t==null ? -1 : ((t+"").charAt(0));
72 case edu.berkeley.sbp.chr.CharAtom.left:
73 buf += "\033[31m{\033[0m";
75 case edu.berkeley.sbp.chr.CharAtom.right:
76 buf += "\033[31m}\033[0m";
81 if (last==' ') buf += ANSI.blue("\\n");
82 System.err.println("\r"+ANSI.clreol()+"\r"+buf);
87 buf += ANSI.cyan(""+((char)c));
92 // FIXME: clean this up
94 s = " " + spin[spinpos++ % (spin.length)]+" parsing ";
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;
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");
110 // Table //////////////////////////////////////////////////////////////////////////////
112 /** an SLR(1) parse table which may contain conflicts */
113 class Table extends Grammar<Token> {
115 /** the start state */
116 final State<Token> start;
118 /** a dummy state from which no reductions can be performed */
119 private final State<Token> dead_state;
121 /** used to generate unique values for State.idx */
122 private int master_state_idx = 0;
124 /** all the states for this table */
125 HashSet<State<Token>> all_states = new HashSet<State<Token>>();
127 /** all the doomed states in this table */
128 HashMap<HashSet<Position>,State<Token>> doomed_states = new HashMap<HashSet<Position>,State<Token>>();
130 /** all the non-doomed states in this table */
131 HashMap<HashSet<Position>,State<Token>> normal_states = new HashMap<HashSet<Position>,State<Token>>();
133 Topology<Token> emptyTopology() { return Parser.this.emptyTopology(); }
135 /** construct a parse table for the given grammar */
137 super(new Union("0", Sequence.create(ux), true));
139 // create the "dead state"
140 this.dead_state = new State<Token>(new HashSet<Position>(), true);
142 // construct the start state; this will recursively create *all* the states
143 this.start = new State<Token>(reachable(rootUnion), false);
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) {
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()));
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");
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);
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);
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());
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) {
200 Sequence.Position p = (Sequence.Position)po;
201 if (al.contains(p)) continue;
203 for(; i<al.size(); i++) {
204 if (comparePositions(p, al.get(i)) < 0)
210 // FIXME: this actually pollutes the "pure" objects (the ones that should not be modified by the Parser)
211 // sort in increasing order...
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);
225 for(int i=0; i<al.size(); i++) {
227 for(int k=pk; k<i; k++) {
228 if (comparePositions(al.get(k), al.get(i)) > 0)
229 { inc = true; break; }
241 * A single state in the LR table and the transitions
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.
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
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).
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.
270 class State<Token> implements IntegerMappable, Iterable<Position> {
272 public final int idx = master_state_idx++;
273 private final HashSet<Position> hs;
274 public HashSet<State<Token>> conjunctStates = new HashSet<State<Token>>();
276 HashMap<Sequence,State<Token>> gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
277 private transient TopologicalBag<Token,State<Token>> gotoSetTerminals = new TopologicalBag<Token,State<Token>>();
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;
284 private VisitableMap<Token,State<Token>> oshifts = null;
285 private VisitableMap<Token,Position> oreductions = null;
286 public final boolean doomed;
288 // Interface Methods //////////////////////////////////////////////////////////////////////////////
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);
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);
306 // Constructor //////////////////////////////////////////////////////////////////////////////
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)
313 * In principle these two steps could be merged, but they
314 * are written separately to highlight these two facts:
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
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.
329 public State(HashSet<Position> hs, boolean doomed) {
331 this.doomed = doomed;
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);
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()))
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));
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_
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);
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).
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));
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.
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").
388 HashMapBag<Sequence,Position> move = new HashMapBag<Sequence,Position>();
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);
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);
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);
409 gotoSetNonTerminals.put(y, s);
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);
419 public int toInt() { return idx; }
420 public String toString() {
421 StringBuffer ret = new StringBuffer();
424 return ret.toString();
430 // Helpers //////////////////////////////////////////////////////////////////////////////
432 private static HashSet<Position> reachable(Element e) {
433 HashSet<Position> h = new HashSet<Position>();
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);
442 private static void reachable(Position p, HashSet<Position> h) {
443 if (h.contains(p)) return;
445 if (p.element() != null) reachable(p.element(), h);
447 private static HashSet<Position> reachable(Position p) {
448 HashSet<Position> ret = new HashSet<Position>();