1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.Sequence.Position;
8 /** a parser which translates streams of Tokens of type T into a Forest<R> */
9 public abstract class Parser<T extends Token, R> {
11 private final Table pt;
13 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
14 protected Parser(Union u) { this.pt = new Table(u, top()); }
15 //protected Parser(Table pt) { this.pt = pt; }
17 /** implement this method to create the output forest corresponding to a lone shifted input token */
18 public abstract Forest<R> shiftedToken(T t, Token.Location loc);
20 /** this method must return an empty topology of the input token type */
21 public abstract Topology<T> top();
23 /** parse <tt>input</tt> for a exactly one unique result, throwing <tt>Ambiguous</tt> if not unique or <tt>ParseFailed</tt> if none */
24 public Tree<R> parse1(Token.Stream<T> input) throws IOException, ParseFailed, Ambiguous {
25 Forest<R> ret = parse(input);
26 try { return ret.expand1(); }
28 System.out.println("while expanding:");
29 System.out.println(ret);
34 /** parse <tt>input</tt>, using the table <tt>pt</tt> to drive the parser */
35 public Forest<R> parse(Token.Stream<T> input) throws IOException, ParseFailed {
37 Token.Location loc = input.getLocation();
38 GSS.Phase current = gss.new Phase(null, this, null, input.next(1, 0, 0), loc, null);
39 current.newNode(null, Forest.leaf(null, null), pt.start, true);
42 loc = input.getLocation();
44 Forest forest = current.token==null ? null : shiftedToken((T)current.token, loc);
45 GSS.Phase next = gss.new Phase(current, this, current, input.next(count, gss.resets, gss.waits), loc, forest);
46 count = next.hash.size();
47 if (current.isDone()) return (Forest<R>)current.finalResult;
53 // Exceptions //////////////////////////////////////////////////////////////////////////////
56 // Table //////////////////////////////////////////////////////////////////////////////
58 /** an SLR(1) parse table which may contain conflicts */
59 static class Table extends Walk.Cache {
61 public final Walk.Cache cache = this;
63 public HashMapBag<Position,State> byPosition = new HashMapBag<Position,State>();
65 private void walk(Element e, HashSet<Element> hs) {
67 if (hs.contains(e)) return;
69 if (e instanceof Atom) return;
70 for(Sequence s : (Union)e) {
72 for(Position p = s.firstp(); p != null; p = p.next())
73 walk(p.element(), hs);
77 /** the start state */
78 public final State start;
80 /** used to generate unique values for State.idx */
81 private int master_state_idx = 0;
83 /** construct a parse table for the given grammar */
84 public Table(Topology top) { this("s", top); }
85 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
86 public Table(Union ux, Topology top) {
87 Union start0 = new Union("0");
88 start0.add(new Sequence.Singleton(ux, null, null));
90 for(Sequence s : start0) cache.eof.put(s, true);
91 cache.eof.put(start0, true);
93 // construct the set of states
94 HashMap<HashSet<Position>,State> all_states = new HashMap<HashSet<Position>,State>();
95 HashSet<Element> all_elements = new HashSet<Element>();
96 walk(start0, all_elements);
97 for(Element e : all_elements)
98 cache.ys.put(e, new Walk.YieldSet(e, cache).walk());
99 HashSet<Position> hp = new HashSet<Position>();
100 reachable(start0, hp);
101 this.start = new State(hp, all_states, all_elements);
103 // for each state, fill in the corresponding "row" of the parse table
104 for(State state : all_states.values())
105 for(Position p : state.hs) {
107 // the Grammar's designated "last position" is the only accepting state
108 if (start0.contains(p.owner()) && p.next()==null)
111 if (p.isRightNullable(cache)) {
112 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
113 Reduction red = new Reduction(p);
115 Topology follow = wf.walk(p.owner());
116 if (p.owner() instanceof Sequence.RewritingSequence &&
117 (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
118 System.out.println("follow before: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
120 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next())
121 follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
122 if (p.owner() instanceof Sequence.RewritingSequence &&
123 (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
124 System.out.println("follow after: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
126 state.reductions.put(follow, red);
127 if (wf.includesEof()) state.eofReductions.add(red);
130 // if the element following this position is an atom, copy the corresponding
131 // set of rows out of the "master" goto table and into this state's shift table
132 if (p.element() != null && p.element() instanceof Atom)
133 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
135 for(State state : all_states.values()) {
136 state.oreductions = state.reductions.optimize();
137 state.oshifts = state.shifts.optimize();
141 /** a single state in the LR table and the transitions possible from it */
143 public class State implements Comparable<Table.State>, IntegerMappable, Iterable<Position> {
145 public int toInt() { return idx; }
147 public boolean lame() {
148 for(Position p : this)
149 for(Position p2 = p; p2!=null; p2=p2.next())
150 if (p2.isLast() && !p2.owner().lame)
155 public boolean isResolvable(Token t) {
156 boolean found = false;
157 for(Reduction r : getReductions(t)) {
158 Position p = r.position;
159 if (!p.isRightNullable(cache)) continue;
160 if (p.owner().firstp()==p) continue;
162 // found two items meeting criteria #1
168 if (p.element()==null) continue;
169 Topology first = new Walk.First(top(), cache).walk(p.element());
170 if (first.contains(t))
175 public final int idx = master_state_idx++;
176 private final HashSet<Position> hs;
178 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
179 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
181 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
182 private HashSet<Reduction> eofReductions = new HashSet<Reduction>();
183 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
184 private boolean accept = false;
186 private VisitableMap<Token,State> oshifts = null;
187 private VisitableMap<Token,Reduction> oreductions = null;
189 // Interface Methods //////////////////////////////////////////////////////////////////////////////
191 public boolean isAccepting() { return accept; }
193 public boolean canShift(Token t) { return oshifts.contains(t); }
194 public boolean canReduce(Token t) { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
196 public Iterator<Position> iterator() { return hs.iterator(); }
198 public <B,C> void invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) {
199 oshifts.invoke(t, irbc, b, c);
201 public <B,C> void invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
202 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
203 else oreductions.invoke(t, irbc, b, c);
206 // Constructor //////////////////////////////////////////////////////////////////////////////
209 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
210 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
211 * @param all_states the set of states already constructed (to avoid recreating states)
212 * @param all_elements the set of all elements (Atom instances need not be included)
214 * In principle these two steps could be merged, but they
215 * are written separately to highlight these two facts:
217 * <li> Non-atom elements either match all-or-nothing, and do not overlap
218 * with each other (at least not in the sense of which element corresponds
219 * to the last reduction performed). Therefore, in order to make sure we
220 * wind up with the smallest number of states and shifts, we wait until
221 * we've figured out all the token-to-position multimappings before creating
224 * <li> In order to be able to run the state-construction algorithm in a single
225 * shot (rather than repeating until no new items appear in any state set),
226 * we need to use the "yields" semantics rather than the "produces" semantics
227 * for non-Atom Elements.
230 public State(HashSet<Position> hs,
231 HashMap<HashSet<Position>,State> all_states,
232 HashSet<Element> all_elements) {
235 // register ourselves in the all_states hash so that no
236 // two states are ever created with an identical position set
237 all_states.put(hs, this);
238 for(Position p : hs) byPosition.add(p,this);
240 // Step 1a: examine all Position's in this state and compute the mappings from
241 // sets of follow tokens (tokens which could follow this position) to sets
242 // of _new_ positions (positions after shifting). These mappings are
243 // collectively known as the _closure_
245 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
246 for(Position position : hs) {
247 if (position.isLast() || !(position.element() instanceof Atom)) continue;
248 Atom a = (Atom)position.element();
249 HashSet<Position> hp = new HashSet<Position>();
250 reachable(position.next(), hp);
254 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
255 // set, add that character set to the goto table (with the State corresponding to the
256 // computed next-position set).
258 for(Topology<Token> r : bag0) {
259 HashSet<Position> h = new HashSet<Position>();
260 for(Position p : bag0.getAll(r)) h.add(p);
261 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
264 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
265 // compute the closure over every position in this set which is followed by a symbol
266 // which could yield the Element in question.
268 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
269 // to avoid having to iteratively construct our set of States as shown in most
270 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
272 for(Element e : all_elements) {
273 if (e instanceof Atom) continue;
274 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
275 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
276 if (gotoSetNonTerminals.get(e) != null)
277 throw new Error("this should not happen");
278 gotoSetNonTerminals.put(e, s);
281 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
282 for(Position p : hs) {
283 Element e = p.element();
284 if (e==null) continue;
285 HashSet<Element> ys = cache.ys.get(e);
287 for(Element y : ys) {
288 HashSet<Position> hp = new HashSet<Position>();
289 reachable(p.next(), hp);
294 for(Element y : move) {
295 HashSet<Position> h = move.getAll(y);
296 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
297 gotoSetNonTerminals.put(y, s);
301 public String toString() {
302 //return "state["+idx+"]";
303 StringBuffer ret = new StringBuffer();
304 ret.append("state["+idx+"]: ");
305 for(Position p : this) ret.append("{"+p+"} ");
306 return ret.toString();
309 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
313 * the information needed to perform a reduction; copied here to
314 * avoid keeping references to <tt>Element</tt> objects in a Table
316 public class Reduction {
317 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
318 public final int numPop;
319 /*private*/ final Position position;
320 private final Forest[] holder; // to avoid constant reallocation
321 public int hashCode() { return position.hashCode(); }
322 public boolean equals(Object o) {
323 if (o==null) return false;
324 if (o==this) return true;
325 if (!(o instanceof Reduction)) return false;
326 Reduction r = (Reduction)o;
327 return r.position == position;
329 public Reduction(Position p) {
332 this.holder = new Forest[numPop];
334 public String toString() { return "[reduce " + position + "]"; }
336 private Forest zero = null;
337 public Forest zero() {
338 if (zero != null) return zero;
339 if (numPop > 0) throw new Error();
340 return zero = position.rewrite(null);
343 public void reduce(GSS.Phase.Node parent) {
344 if (numPop==0) finish(parent, zero(), parent.phase());
345 else reduce(parent, numPop-1, parent.phase());
348 public void reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild) {
349 if (numPop<=0) throw new Error("called wrong form of reduce()");
351 Forest old = holder[pos];
352 holder[pos] = parent.pending();
354 System.arraycopy(holder, 0, position.holder, 0, holder.length);
355 finish(onlychild, position.rewrite(parent.phase().getLocation()), parent.phase());
357 reduce(onlychild, pos-1, parent.phase());
362 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
363 private void reduce(GSS.Phase.Node parent, int pos, GSS.Phase target) {
364 Forest old = holder[pos];
365 holder[pos] = parent.pending();
367 System.arraycopy(holder, 0, position.holder, 0, holder.length);
368 for(int i=0; i<position.pos; i++) if (position.holder[i]==null) throw new Error("realbad");
369 Forest rex = position.rewrite(target.getLocation());
370 for(GSS.Phase.Node child : parent.parents()) finish(child, rex, target);
372 for(GSS.Phase.Node child : parent.parents()) reduce(child, pos-1, target);
376 private void finish(GSS.Phase.Node parent, Forest result, GSS.Phase target) {
377 State state = parent.state.gotoSetNonTerminals.get(position.owner());
378 if (result==null) throw new Error();
380 target.newNode(parent, result, state, numPop<=0, this);
385 private static final Forest[] emptyForestArray = new Forest[0];
388 // Helpers //////////////////////////////////////////////////////////////////////////////
390 private static void reachable(Element e, HashSet<Position> h) {
391 if (e instanceof Atom) return;
392 for(Sequence s : ((Union)e))
393 reachable(s.firstp(), h);
395 private static void reachable(Position p, HashSet<Position> h) {
396 if (h.contains(p)) return;
398 if (p.element() != null) reachable(p.element(), h);