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 private final Union start0 = new Union("0");
78 private final Sequence start0seq;
80 public final Walk.Cache cache = new Walk.Cache();
82 public HashSet<Position> closure() {
83 HashSet<Position> hp = new HashSet<Position>();
84 reachable(start0, hp);
88 private void walk(Element e, HashSet<Element> hs) {
90 if (hs.contains(e)) return;
92 if (e instanceof Atom) return;
93 for(Sequence s : (Union)e) {
95 for(Position p = s.firstp(); p != null; p = p.next())
96 walk(p.element(), hs);
99 public HashSet<Element> walk() {
100 HashSet<Element> ret = new HashSet<Element>();
106 public String toString() {
107 StringBuffer sb = new StringBuffer();
108 for(Element e : walk())
109 if (e instanceof Union)
110 ((Union)e).toString(sb);
111 return sb.toString();
115 /** the start state */
116 public final State start;
118 /** used to generate unique values for State.idx */
119 private int master_state_idx = 0;
121 /** construct a parse table for the given grammar */
122 public Table(Topology top) { this("s", top); }
123 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
124 public Table(Union u, Topology top) {
125 cache.eof.put(start0, true);
126 start0seq = new Sequence.Singleton(u, null, null);
127 cache.eof.put(start0seq, true);
128 start0.add(start0seq);
130 // construct the set of states
131 HashMap<HashSet<Position>,State> all_states = new HashMap<HashSet<Position>,State>();
132 HashSet<Element> all_elements = walk();
133 all_elements.add(start0);
134 all_elements.add(start0seq);
135 for(Element e : all_elements)
136 cache.ys.put(e, new Walk.YieldSet(e, cache).walk());
137 this.start = new State(closure(), all_states, all_elements);
139 // for each state, fill in the corresponding "row" of the parse table
140 for(State state : all_states.values())
141 for(Position p : state.hs) {
143 // the Grammar's designated "last position" is the only accepting state
144 if (p==start0seq.firstp().next())
147 // FIXME: how does right-nullability interact with follow restrictions?
148 // all right-nullable rules get a reduction [Johnstone 2000]
149 if (p.isRightNullable(cache)) {
150 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
151 Reduction red = new Reduction(p);
152 state.reductions.put(wf.walk(p.owner()), red);
153 if (wf.includesEof()) state.eofReductions.add(red, true);
156 // if the element following this position is an atom, copy the corresponding
157 // set of rows out of the "master" goto table and into this state's shift table
158 if (p.element() != null && p.element() instanceof Atom)
159 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
163 /** a single state in the LR table and the transitions possible from it */
164 public class State implements Comparable<Table.State>, Iterable<Position> {
166 public final int idx = master_state_idx++;
167 private final HashSet<Position> hs;
169 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
170 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
172 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
173 private FastSet<Reduction> eofReductions = new FastSet<Reduction>();
174 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
175 private boolean accept = false;
177 // Interface Methods //////////////////////////////////////////////////////////////////////////////
179 public boolean canShift(Token t) { return shifts.contains(t); }
180 public Iterable<State> getShifts(Token t) { return shifts.get(t); }
181 public boolean isAccepting() { return accept; }
182 public Iterable<Reduction> getReductions(Token t) { return reductions.get(t); }
183 public Iterable<Reduction> getEofReductions() { return eofReductions; }
184 public Iterator<Position> iterator() { return hs.iterator(); }
186 // Constructor //////////////////////////////////////////////////////////////////////////////
189 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
190 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
191 * @param all_states the set of states already constructed (to avoid recreating states)
192 * @param all_elements the set of all elements (Atom instances need not be included)
194 * In principle these two steps could be merged, but they
195 * are written separately to highlight these two facts:
197 * <li> Non-atom elements either match all-or-nothing, and do not overlap
198 * with each other (at least not in the sense of which element corresponds
199 * to the last reduction performed). Therefore, in order to make sure we
200 * wind up with the smallest number of states and shifts, we wait until
201 * we've figured out all the token-to-position multimappings before creating
204 * <li> In order to be able to run the state-construction algorithm in a single
205 * shot (rather than repeating until no new items appear in any state set),
206 * we need to use the "yields" semantics rather than the "produces" semantics
207 * for non-Atom Elements.
210 public State(HashSet<Position> hs,
211 HashMap<HashSet<Position>,State> all_states,
212 HashSet<Element> all_elements) {
215 // register ourselves in the all_states hash so that no
216 // two states are ever created with an identical position set
217 all_states.put(hs, this);
219 // Step 1a: examine all Position's in this state and compute the mappings from
220 // sets of follow tokens (tokens which could follow this position) to sets
221 // of _new_ positions (positions after shifting). These mappings are
222 // collectively known as the _closure_
224 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
225 for(Position position : hs) {
226 if (position.isLast() || !(position.element() instanceof Atom)) continue;
227 Atom a = (Atom)position.element();
228 HashSet<Position> hp = new HashSet<Position>();
229 reachable(position.next(), hp);
233 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
234 // set, add that character set to the goto table (with the State corresponding to the
235 // computed next-position set).
237 for(Topology<Token> r : bag0) {
238 HashSet<Position> h = new HashSet<Position>();
239 for(Position p : bag0.getAll(r)) h.add(p);
240 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
243 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
244 // compute the closure over every position in this set which is followed by a symbol
245 // which could yield the Element in question.
247 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
248 // to avoid having to iteratively construct our set of States as shown in most
249 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
251 for(Element e : all_elements) {
252 if (e instanceof Atom) continue;
253 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
254 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
255 if (gotoSetNonTerminals.get(e) != null)
256 throw new Error("this should not happen");
257 gotoSetNonTerminals.put(e, s);
260 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
261 for(Position p : hs) {
262 Element e = p.element();
263 if (e==null) continue;
264 HashSet<Element> ys = cache.ys.get(e);
266 for(Element y : ys) {
267 HashSet<Position> hp = new HashSet<Position>();
268 reachable(p.next(), hp);
273 for(Element y : move) {
274 HashSet<Position> h = move.getAll(y);
275 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
276 gotoSetNonTerminals.put(y, s);
280 public String toString() { return "state["+idx+"]"; }
282 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
286 * the information needed to perform a reduction; copied here to
287 * avoid keeping references to <tt>Element</tt> objects in a Table
289 public class Reduction {
290 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
291 public final int numPop;
292 private final Position position;
293 private final Forest[] holder; // to avoid constant reallocation
294 public int hashCode() { return position.hashCode(); }
295 public boolean equals(Object o) {
296 if (o==null) return false;
297 if (o==this) return true;
298 if (!(o instanceof Reduction)) return false;
299 Reduction r = (Reduction)o;
300 return r.position == position;
302 public Reduction(Position p) {
305 this.holder = new Forest[numPop];
307 public String toString() { return "[reduce " + position + "]"; }
308 public Forest reduce(Forest f, GSS.Phase.Node parent, GSS.Phase.Node onlychild, GSS.Phase target, Forest rex) {
309 holder[numPop-1] = f;
310 return reduce(parent, numPop-2, rex, onlychild, target);
312 public Forest reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild, GSS.Phase target, Forest rex) {
313 return reduce(parent, numPop-1, rex, onlychild, target);
316 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
317 private Forest reduce(GSS.Phase.Node parent, int pos, Forest rex, GSS.Phase.Node onlychild, GSS.Phase target) {
318 if (pos>=0) holder[pos] = parent.pending();
319 if (pos<=0 && rex==null) {
320 System.arraycopy(holder, 0, position.holder, 0, holder.length);
321 rex = position.rewrite(target.getLocation());
324 if (onlychild != null)
325 reduce(onlychild, pos-1, rex, null, target);
327 for(GSS.Phase.Node child : parent.parents())
328 reduce(child, pos-1, rex, null, target);
330 State state = parent.state.gotoSetNonTerminals.get(position.owner());
332 target.newNode(parent, rex, state, numPop<=0, parent.phase);
339 private static final Forest[] emptyForestArray = new Forest[0];
342 // Helpers //////////////////////////////////////////////////////////////////////////////
344 private static void reachable(Element e, HashSet<Position> h) {
345 if (e instanceof Atom) return;
346 for(Sequence s : ((Union)e))
347 reachable(s.firstp(), h);
349 private static void reachable(Position p, HashSet<Position> h) {
350 if (h.contains(p)) return;
352 if (p.element() != null) reachable(p.element(), h);