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;
17 * create a parser to parse the grammar with start symbol <tt>u</tt>
19 protected Parser(Union u) { this.pt = new Table(u, top()); }
20 protected Parser(Table pt) { this.pt = pt; }
22 public abstract Forest<R> shiftedToken(T t, Token.Location loc);
23 public abstract Topology<T> top();
26 /** parse <tt>input</tt> for a exactly one unique result, throwing <tt>Ambiguous</tt> if not unique or <tt>Failed</tt> if none */
27 public Tree<R> parse1(Token.Stream<T> input) throws IOException, Failed, Ambiguous { return parse(input).expand1(); }
29 /** parse <tt>input</tt>, using the table <tt>pt</tt> to drive the parser */
30 public Forest<R> parse(Token.Stream<T> input) throws IOException, Failed {
32 Token.Location loc = input.getLocation();
33 GSS.Phase current = gss.new Phase(null, input.next(), loc);
34 current.newNode(null, null, pt.start, true, null);
36 loc = input.getLocation();
37 GSS.Phase next = gss.new Phase(current, input.next(), loc);
39 Forest forest = current.token==null ? null : shiftedToken((T)current.token, loc);
40 current.shift(next, forest);
41 if (current.isDone()) return (Forest<R>)current.finalResult;
42 current.checkFailure();
48 // Exceptions //////////////////////////////////////////////////////////////////////////////
50 public static class Failed extends Exception {
51 private final Token.Location location;
52 private final String message;
53 public Failed() { this("", null); }
54 public Failed(String message, Token.Location loc) { this.location = loc; this.message = message; }
55 public Token.Location getLocation() { return location; }
56 public String toString() { return message + (location==null ? "" : (" at " + location)); }
59 public static class Ambiguous extends RuntimeException {
60 public final Forest ambiguity;
61 public Ambiguous(Forest ambiguity) { this.ambiguity = ambiguity; }
62 public String toString() {
63 StringBuffer sb = new StringBuffer();
64 sb.append("unresolved ambiguity "/*"at " + ambiguity.getLocation() + ":"*/);
65 for(Object result : ambiguity.expand(false))
66 sb.append("\n " + result);
72 // Table //////////////////////////////////////////////////////////////////////////////
74 /** an SLR(1) parse table which may contain conflicts */
77 public final Walk.Cache cache = new Walk.Cache();
79 private void walk(Element e, HashSet<Element> hs) {
81 if (hs.contains(e)) return;
83 if (e instanceof Atom) return;
84 for(Sequence s : (Union)e) {
86 for(Position p = s.firstp(); p != null; p = p.next())
87 walk(p.element(), hs);
92 public String toString() {
93 StringBuffer sb = new StringBuffer();
94 for(Element e : walk())
95 if (e instanceof Union)
96 ((Union)e).toString(sb);
101 /** the start state */
102 public final State start;
104 /** used to generate unique values for State.idx */
105 private int master_state_idx = 0;
107 /** construct a parse table for the given grammar */
108 public Table(Topology top) { this("s", top); }
109 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
110 public Table(Union ux, Topology top) {
111 Union start0 = new Union("0");
112 start0.add(new Sequence.Singleton(ux, null, null));
114 for(Sequence s : start0) cache.eof.put(s, true);
115 cache.eof.put(start0, true);
117 // construct the set of states
118 HashMap<HashSet<Position>,State> all_states = new HashMap<HashSet<Position>,State>();
119 HashSet<Element> all_elements = new HashSet<Element>();
120 walk(start0, all_elements);
121 for(Element e : all_elements)
122 cache.ys.put(e, new Walk.YieldSet(e, cache).walk());
123 HashSet<Position> hp = new HashSet<Position>();
124 reachable(start0, hp);
125 this.start = new State(hp, all_states, all_elements);
127 // for each state, fill in the corresponding "row" of the parse table
128 for(State state : all_states.values())
129 for(Position p : state.hs) {
131 // the Grammar's designated "last position" is the only accepting state
132 if (start0.contains(p.owner()) && p.next()==null)
135 // FIXME: how does right-nullability interact with follow restrictions?
136 // all right-nullable rules get a reduction [Johnstone 2000]
137 if (p.isRightNullable(cache)) {
138 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
139 Reduction red = new Reduction(p);
140 state.reductions.put(wf.walk(p.owner()), red);
141 if (wf.includesEof()) state.eofReductions.add(red, true);
144 // if the element following this position is an atom, copy the corresponding
145 // set of rows out of the "master" goto table and into this state's shift table
146 if (p.element() != null && p.element() instanceof Atom)
147 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
151 /** a single state in the LR table and the transitions possible from it */
152 public class State implements Comparable<Table.State>, Iterable<Position> {
154 public final int idx = master_state_idx++;
155 private final HashSet<Position> hs;
157 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
158 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
160 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
161 private FastSet<Reduction> eofReductions = new FastSet<Reduction>();
162 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
163 private boolean accept = false;
165 // Interface Methods //////////////////////////////////////////////////////////////////////////////
167 public boolean canShift(Token t) { return shifts.contains(t); }
168 public Iterable<State> getShifts(Token t) { return shifts.get(t); }
169 public boolean isAccepting() { return accept; }
170 public Iterable<Reduction> getReductions(Token t) { return reductions.get(t); }
171 public Iterable<Reduction> getEofReductions() { return eofReductions; }
172 public Iterator<Position> iterator() { return hs.iterator(); }
174 // Constructor //////////////////////////////////////////////////////////////////////////////
177 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
178 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
179 * @param all_states the set of states already constructed (to avoid recreating states)
180 * @param all_elements the set of all elements (Atom instances need not be included)
182 * In principle these two steps could be merged, but they
183 * are written separately to highlight these two facts:
185 * <li> Non-atom elements either match all-or-nothing, and do not overlap
186 * with each other (at least not in the sense of which element corresponds
187 * to the last reduction performed). Therefore, in order to make sure we
188 * wind up with the smallest number of states and shifts, we wait until
189 * we've figured out all the token-to-position multimappings before creating
192 * <li> In order to be able to run the state-construction algorithm in a single
193 * shot (rather than repeating until no new items appear in any state set),
194 * we need to use the "yields" semantics rather than the "produces" semantics
195 * for non-Atom Elements.
198 public State(HashSet<Position> hs,
199 HashMap<HashSet<Position>,State> all_states,
200 HashSet<Element> all_elements) {
203 // register ourselves in the all_states hash so that no
204 // two states are ever created with an identical position set
205 all_states.put(hs, this);
207 // Step 1a: examine all Position's in this state and compute the mappings from
208 // sets of follow tokens (tokens which could follow this position) to sets
209 // of _new_ positions (positions after shifting). These mappings are
210 // collectively known as the _closure_
212 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
213 for(Position position : hs) {
214 if (position.isLast() || !(position.element() instanceof Atom)) continue;
215 Atom a = (Atom)position.element();
216 HashSet<Position> hp = new HashSet<Position>();
217 reachable(position.next(), hp);
221 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
222 // set, add that character set to the goto table (with the State corresponding to the
223 // computed next-position set).
225 for(Topology<Token> r : bag0) {
226 HashSet<Position> h = new HashSet<Position>();
227 for(Position p : bag0.getAll(r)) h.add(p);
228 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
231 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
232 // compute the closure over every position in this set which is followed by a symbol
233 // which could yield the Element in question.
235 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
236 // to avoid having to iteratively construct our set of States as shown in most
237 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
239 for(Element e : all_elements) {
240 if (e instanceof Atom) continue;
241 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
242 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
243 if (gotoSetNonTerminals.get(e) != null)
244 throw new Error("this should not happen");
245 gotoSetNonTerminals.put(e, s);
248 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
249 for(Position p : hs) {
250 Element e = p.element();
251 if (e==null) continue;
252 HashSet<Element> ys = cache.ys.get(e);
254 for(Element y : ys) {
255 HashSet<Position> hp = new HashSet<Position>();
256 reachable(p.next(), hp);
261 for(Element y : move) {
262 HashSet<Position> h = move.getAll(y);
263 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
264 gotoSetNonTerminals.put(y, s);
268 public String toString() { return "state["+idx+"]"; }
270 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
274 * the information needed to perform a reduction; copied here to
275 * avoid keeping references to <tt>Element</tt> objects in a Table
277 public class Reduction {
278 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
279 public final int numPop;
280 private final Position position;
281 private final Forest[] holder; // to avoid constant reallocation
282 public int hashCode() { return position.hashCode(); }
283 public boolean equals(Object o) {
284 if (o==null) return false;
285 if (o==this) return true;
286 if (!(o instanceof Reduction)) return false;
287 Reduction r = (Reduction)o;
288 return r.position == position;
290 public Reduction(Position p) {
293 this.holder = new Forest[numPop];
295 public String toString() { return "[reduce " + position + "]"; }
296 public Forest reduce(Forest f, GSS.Phase.Node parent, GSS.Phase.Node onlychild, GSS.Phase target, Forest rex) {
297 holder[numPop-1] = f;
298 return reduce(parent, numPop-2, rex, onlychild, target);
300 public Forest reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild, GSS.Phase target, Forest rex) {
301 return reduce(parent, numPop-1, rex, onlychild, target);
304 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
305 private Forest reduce(GSS.Phase.Node parent, int pos, Forest rex, GSS.Phase.Node onlychild, GSS.Phase target) {
306 if (pos>=0) holder[pos] = parent.pending();
307 if (pos<=0 && rex==null) {
308 System.arraycopy(holder, 0, position.holder, 0, holder.length);
309 rex = position.rewrite(target.getLocation());
312 if (onlychild != null)
313 reduce(onlychild, pos-1, rex, null, target);
315 for(GSS.Phase.Node child : parent.parents())
316 reduce(child, pos-1, rex, null, target);
318 State state = parent.state.gotoSetNonTerminals.get(position.owner());
320 target.newNode(parent, rex, state, numPop<=0, parent.phase);
327 private static final Forest[] emptyForestArray = new Forest[0];
330 // Helpers //////////////////////////////////////////////////////////////////////////////
332 private static void reachable(Element e, HashSet<Position> h) {
333 if (e instanceof Atom) return;
334 for(Sequence s : ((Union)e))
335 reachable(s.firstp(), h);
337 private static void reachable(Position p, HashSet<Position> h) {
338 if (h.contains(p)) return;
340 if (p.element() != null) reachable(p.element(), h);