1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.*;
5 import edu.berkeley.sbp.Sequence.Position;
6 import edu.berkeley.sbp.*;
9 import java.lang.reflect.*;
11 /** a parser which translates streams of Tokens of type T into a Forest<R> */
12 public abstract class Parser<T extends Token, R> {
14 private final Table pt;
16 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
17 protected Parser(Union u) { this.pt = new Table(u, top()); }
18 protected Parser(Table pt) { this.pt = pt; }
20 public abstract Forest<R> shiftedToken(T t, Token.Location loc);
21 public abstract Topology<T> top();
24 /** parse <tt>input</tt> for a exactly one unique result, throwing <tt>Ambiguous</tt> if not unique or <tt>Failed</tt> if none */
25 public Tree<R> parse1(Token.Stream<T> input) throws IOException, Failed, Ambiguous {
26 Forest<R> ret = parse(input);
27 try { return ret.expand1(); }
29 System.out.println("while expanding:");
30 System.out.println(ret);
35 /** parse <tt>input</tt>, using the table <tt>pt</tt> to drive the parser */
36 public Forest<R> parse(Token.Stream<T> input) throws IOException, Failed {
38 Token.Location loc = input.getLocation();
39 GSS.Phase current = gss.new Phase(null, input.next(), loc);
40 current.newNode(null, null, pt.start, true, null);
42 loc = input.getLocation();
43 GSS.Phase next = gss.new Phase(current, input.next(), loc);
45 Forest forest = current.token==null ? null : shiftedToken((T)current.token, loc);
46 current.shift(next, forest);
47 if (current.isDone()) return (Forest<R>)current.finalResult;
48 current.checkFailure();
54 // Exceptions //////////////////////////////////////////////////////////////////////////////
56 public static class Failed extends Exception {
57 private final Token.Location location;
58 private final String message;
59 public Failed() { this("", null); }
60 public Failed(String message, Token.Location loc) { this.location = loc; this.message = message; }
61 public Token.Location getLocation() { return location; }
62 public String toString() { return message + (location==null ? "" : (" at " + location)); }
65 public static class Ambiguous extends RuntimeException {
66 public final Forest ambiguity;
67 public Ambiguous(Forest ambiguity) { this.ambiguity = ambiguity; }
68 public String toString() {
69 StringBuffer sb = new StringBuffer();
70 sb.append("unresolved ambiguity "/*"at " + ambiguity.getLocation() + ":"*/);
71 for(Object result : ambiguity.expand(false))
72 sb.append("\n " + result);
78 // Table //////////////////////////////////////////////////////////////////////////////
80 /** an SLR(1) parse table which may contain conflicts */
81 static class Table extends Walk.Cache {
83 public final Walk.Cache cache = this;
85 private void walk(Element e, HashSet<Element> hs) {
87 if (hs.contains(e)) return;
89 if (e instanceof Atom) return;
90 for(Sequence s : (Union)e) {
92 for(Position p = s.firstp(); p != null; p = p.next())
93 walk(p.element(), hs);
97 /** the start state */
98 public final State start;
100 /** used to generate unique values for State.idx */
101 private int master_state_idx = 0;
103 /** construct a parse table for the given grammar */
104 public Table(Topology top) { this("s", top); }
105 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
106 public Table(Union ux, Topology top) {
107 Union start0 = new Union("0");
108 start0.add(new Sequence.Singleton(ux, null, null));
110 for(Sequence s : start0) cache.eof.put(s, true);
111 cache.eof.put(start0, true);
113 // construct the set of states
114 HashMap<HashSet<Position>,State> all_states = new HashMap<HashSet<Position>,State>();
115 HashSet<Element> all_elements = new HashSet<Element>();
116 walk(start0, all_elements);
117 for(Element e : all_elements)
118 cache.ys.put(e, new Walk.YieldSet(e, cache).walk());
119 HashSet<Position> hp = new HashSet<Position>();
120 reachable(start0, hp);
121 this.start = new State(hp, all_states, all_elements);
123 // for each state, fill in the corresponding "row" of the parse table
124 for(State state : all_states.values())
125 for(Position p : state.hs) {
127 // the Grammar's designated "last position" is the only accepting state
128 if (start0.contains(p.owner()) && p.next()==null)
131 // FIXME: how does right-nullability interact with follow restrictions?
132 // all right-nullable rules get a reduction [Johnstone 2000]
133 if (p.isRightNullable(cache)) {
134 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
135 Reduction red = new Reduction(p);
136 state.reductions.put(wf.walk(p.owner()), red);
137 if (wf.includesEof()) state.eofReductions.add(red);
140 // if the element following this position is an atom, copy the corresponding
141 // set of rows out of the "master" goto table and into this state's shift table
142 if (p.element() != null && p.element() instanceof Atom)
143 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
147 /** a single state in the LR table and the transitions possible from it */
148 public class State implements Comparable<Table.State>, Iterable<Position> {
151 public boolean isResolvable(Token t) {
152 boolean found = false;
153 for(Reduction r : getReductions(t)) {
154 Position p = r.position;
155 if (!p.isRightNullable(cache)) continue;
156 if (p.owner().firstp()==p) continue;
158 // found two items meeting criteria #1
164 if (p.element()==null) continue;
165 Topology first = new Walk.First(top(), cache).walk(p.element());
166 if (first.contains(t))
171 public final int idx = master_state_idx++;
172 private final HashSet<Position> hs;
174 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
175 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
177 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
178 private HashSet<Reduction> eofReductions = new HashSet<Reduction>();
179 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
180 private boolean accept = false;
182 // Interface Methods //////////////////////////////////////////////////////////////////////////////
184 public boolean isAccepting() { return accept; }
186 public boolean canShift(Token t) { return shifts.contains(t); }
187 public Iterable<State> getShifts(Token t) { return shifts.get(t); }
189 public Iterable<Reduction> getReductions(Token t) { return t==null ? eofReductions : reductions.get(t); }
190 public boolean hasReductions(Token t) { return t==null ? eofReductions.size()>0 : reductions.has(t); }
192 public Iterator<Position> iterator() { return hs.iterator(); }
194 public <B,C> void invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) { shifts.invoke(t, irbc, b, c); }
195 public <B,C> void invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
196 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
197 else reductions.invoke(t, irbc, b, c);
200 // Constructor //////////////////////////////////////////////////////////////////////////////
203 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
204 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
205 * @param all_states the set of states already constructed (to avoid recreating states)
206 * @param all_elements the set of all elements (Atom instances need not be included)
208 * In principle these two steps could be merged, but they
209 * are written separately to highlight these two facts:
211 * <li> Non-atom elements either match all-or-nothing, and do not overlap
212 * with each other (at least not in the sense of which element corresponds
213 * to the last reduction performed). Therefore, in order to make sure we
214 * wind up with the smallest number of states and shifts, we wait until
215 * we've figured out all the token-to-position multimappings before creating
218 * <li> In order to be able to run the state-construction algorithm in a single
219 * shot (rather than repeating until no new items appear in any state set),
220 * we need to use the "yields" semantics rather than the "produces" semantics
221 * for non-Atom Elements.
224 public State(HashSet<Position> hs,
225 HashMap<HashSet<Position>,State> all_states,
226 HashSet<Element> all_elements) {
229 // register ourselves in the all_states hash so that no
230 // two states are ever created with an identical position set
231 all_states.put(hs, this);
233 // Step 1a: examine all Position's in this state and compute the mappings from
234 // sets of follow tokens (tokens which could follow this position) to sets
235 // of _new_ positions (positions after shifting). These mappings are
236 // collectively known as the _closure_
238 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
239 for(Position position : hs) {
240 if (position.isLast() || !(position.element() instanceof Atom)) continue;
241 Atom a = (Atom)position.element();
242 HashSet<Position> hp = new HashSet<Position>();
243 reachable(position.next(), hp);
247 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
248 // set, add that character set to the goto table (with the State corresponding to the
249 // computed next-position set).
251 for(Topology<Token> r : bag0) {
252 HashSet<Position> h = new HashSet<Position>();
253 for(Position p : bag0.getAll(r)) h.add(p);
254 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
257 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
258 // compute the closure over every position in this set which is followed by a symbol
259 // which could yield the Element in question.
261 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
262 // to avoid having to iteratively construct our set of States as shown in most
263 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
265 for(Element e : all_elements) {
266 if (e instanceof Atom) continue;
267 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
268 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
269 if (gotoSetNonTerminals.get(e) != null)
270 throw new Error("this should not happen");
271 gotoSetNonTerminals.put(e, s);
274 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
275 for(Position p : hs) {
276 Element e = p.element();
277 if (e==null) continue;
278 HashSet<Element> ys = cache.ys.get(e);
280 for(Element y : ys) {
281 HashSet<Position> hp = new HashSet<Position>();
282 reachable(p.next(), hp);
287 for(Element y : move) {
288 HashSet<Position> h = move.getAll(y);
289 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
290 gotoSetNonTerminals.put(y, s);
294 public String toString() { return "state["+idx+"]"; }
296 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
300 * the information needed to perform a reduction; copied here to
301 * avoid keeping references to <tt>Element</tt> objects in a Table
303 public class Reduction {
304 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
305 public final int numPop;
306 /*private*/ final Position position;
307 private final Forest[] holder; // to avoid constant reallocation
308 public int hashCode() { return position.hashCode(); }
309 public boolean equals(Object o) {
310 if (o==null) return false;
311 if (o==this) return true;
312 if (!(o instanceof Reduction)) return false;
313 Reduction r = (Reduction)o;
314 return r.position == position;
316 public Reduction(Position p) {
319 this.holder = new Forest[numPop];
321 public String toString() { return "[reduce " + position + "]"; }
323 private Forest zero = null;
324 public Forest zero() {
325 if (zero != null) return zero;
326 if (numPop > 0) throw new Error();
327 return zero = position.rewrite(null);
330 public void reduce(GSS.Phase.Node parent) {
331 if (numPop==0) finish(parent, zero(), parent.phase());
332 else reduce(parent, numPop-1, parent.phase());
335 public void reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild) {
336 if (numPop<=0) throw new Error("called wrong form of reduce()");
338 holder[pos] = parent.pending();
340 System.arraycopy(holder, 0, position.holder, 0, holder.length);
341 finish(onlychild, position.rewrite(parent.phase().getLocation()), parent.phase());
343 reduce(onlychild, pos-1, parent.phase());
347 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
348 private void reduce(GSS.Phase.Node parent, int pos, GSS.Phase target) {
349 holder[pos] = parent.pending();
351 System.arraycopy(holder, 0, position.holder, 0, holder.length);
352 Forest rex = position.rewrite(target.getLocation());
353 for(GSS.Phase.Node child : parent.parents()) finish(child, rex, target);
355 for(GSS.Phase.Node child : parent.parents()) reduce(child, pos-1, target);
358 private void finish(GSS.Phase.Node parent, Forest result, GSS.Phase target) {
359 State state = parent.state.gotoSetNonTerminals.get(position.owner());
361 target.newNode(parent, result, state, numPop<=0, parent.phase());
366 private static final Forest[] emptyForestArray = new Forest[0];
369 // Helpers //////////////////////////////////////////////////////////////////////////////
371 private static void reachable(Element e, HashSet<Position> h) {
372 if (e instanceof Atom) return;
373 for(Sequence s : ((Union)e))
374 reachable(s.firstp(), h);
376 private static void reachable(Position p, HashSet<Position> h) {
377 if (h.contains(p)) return;
379 if (p.element() != null) reachable(p.element(), h);