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 class Parser<T extends Token, R> {
14 private final Table pt;
16 private static void reachable(Element e, HashSet<Position> h) {
17 if (e instanceof Atom) return;
18 for(Sequence s : ((Union)e))
19 reachable(s.firstp(), h);
21 private static void reachable(Position p, HashSet<Position> h) {
22 if (h.contains(p)) return;
24 if (p.element() != null) reachable(p.element(), h);
27 //public Parser( Topology top) { this(new Table( top)); }
28 //public Parser(String s, Topology top) { this(new Table(s, top)); }
31 * create a parser to parse the grammar with start symbol <tt>u</tt>
32 * @param top a "sample" Topology<T> that can be cloned (FIXME, demanding this is lame)
34 public Parser(Union u, Topology<T> top) { this(new Table(u, top)); }
36 Parser(Table pt) { this.pt = pt; }
38 /** parse <tt>input</tt> for a exactly one unique result, throwing <tt>Ambiguous</tt> if not unique or <tt>Failed</tt> if none */
39 public Tree<R> parse1(Token.Stream<T> input) throws IOException, Failed, Ambiguous { return parse(input).expand1(); }
41 /** parse <tt>input</tt>, using the table <tt>pt</tt> to drive the parser */
42 public Forest<R> parse(Token.Stream<T> input) throws IOException, Failed {
44 GSS.Phase current = gss.new Phase(null, input.next());
45 current.newNode(null, null, pt.start, true, null);
47 GSS.Phase next = gss.new Phase(current, input.next());
50 if (current.isDone()) return (Forest<R>)current.finalResult;
51 current.checkFailure();
57 // Exceptions //////////////////////////////////////////////////////////////////////////////
59 public static class Failed extends Exception {
60 private final Token.Location location;
61 private final String message;
62 public Failed() { this("", null); }
63 public Failed(String message, Token.Location loc) { this.location = loc; this.message = message; }
64 public Token.Location getLocation() { return location; }
65 public String toString() { return message + (location==null ? "" : (" at " + location + "\n" + location.getContext())); }
68 public static class Ambiguous extends RuntimeException {
69 public final Forest ambiguity;
70 public Ambiguous(Forest ambiguity) { this.ambiguity = ambiguity; }
71 public String toString() {
72 StringBuffer sb = new StringBuffer();
73 sb.append("unresolved ambiguity "/*"at " + ambiguity.getLocation() + ":"*/);
74 for(Object result : ambiguity.expand(false))
75 sb.append("\n " + result);
81 // Table //////////////////////////////////////////////////////////////////////////////
83 /** an SLR(1) parse table which may contain conflicts */
86 private final Union start0 = new Top();
87 private final Sequence start0seq;
88 static class Top extends Union { public Top() { super("0"); } }
90 public final Walk.Cache cache = new Walk.Cache();
92 public HashSet<Position> closure() {
93 HashSet<Position> hp = new HashSet<Position>();
94 reachable(start0, hp);
97 public Position firstPosition() { return start0seq.firstp(); }
98 public Position lastPosition() { Position ret = start0seq.firstp(); while(!ret.isLast()) ret = ret.next(); return ret; }
100 private void walk(Element e, HashSet<Element> hs) {
102 if (hs.contains(e)) return;
104 if (e instanceof Atom) return;
105 for(Sequence s : (Union)e) {
107 for(Position p = s.firstp(); p != null; p = p.next())
108 walk(p.element(), hs);
111 public HashSet<Element> walk() {
112 HashSet<Element> ret = new HashSet<Element>();
118 public String toString() {
119 StringBuffer sb = new StringBuffer();
120 for(Element e : walk())
121 if (e instanceof Union)
122 ((Union)e).toString(sb);
123 return sb.toString();
127 /** the start state */
128 public final State start;
130 /** used to generate unique values for State.idx */
131 private int master_state_idx = 0;
133 /** construct a parse table for the given grammar */
134 public Table(Topology top) { this("s", top); }
135 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
136 public Table(Union u, Topology top) {
137 start0seq = new Sequence.Singleton(u, null, null);
138 start0.add(start0seq);
140 // construct the set of states
141 HashMap<HashSet<Position>,State> all_states = new HashMap<HashSet<Position>,State>();
142 HashSet<Element> all_elements = walk();
143 for(Element e : all_elements)
144 cache.ys.put(e, new Walk.YieldSet(e, cache).walk());
145 this.start = new State(closure(), all_states, all_elements);
147 // for each state, fill in the corresponding "row" of the parse table
148 for(State state : all_states.values())
149 for(Position p : state.hs) {
151 // the Grammar's designated "last position" is the only accepting state
152 if (p==lastPosition())
155 // FIXME: how does right-nullability interact with follow restrictions?
156 // all right-nullable rules get a reduction [Johnstone 2000]
157 if (p.isRightNullable(cache)) {
158 Walk.Follow wf = new Walk.Follow(top.fresh(), p.owner(), all_elements, cache);
159 Reduction red = new Reduction(p);
160 state.reductions.put(wf.walk(p.owner()), red);
161 if (wf.includesEof()) state.eofReductions.add(red, true);
164 // if the element following this position is an atom, copy the corresponding
165 // set of rows out of the "master" goto table and into this state's shift table
166 if (p.element() != null && p.element() instanceof Atom)
167 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).dup()));
171 /** a single state in the LR table and the transitions possible from it */
172 public class State implements Comparable<Table.State>, Iterable<Position> {
174 public final int idx = master_state_idx++;
175 private final HashSet<Position> hs;
177 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
178 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
180 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
181 private FastSet<Reduction> eofReductions = new FastSet<Reduction>();
182 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
183 private boolean accept = false;
185 // Interface Methods //////////////////////////////////////////////////////////////////////////////
187 public boolean canShift(Token t) { return shifts.contains(t); }
188 public Iterable<State> getShifts(Token t) { return shifts.get(t); }
189 public boolean isAccepting() { return accept; }
190 public Iterable<Reduction> getReductions(Token t) { return reductions.get(t); }
191 public Iterable<Reduction> getEofReductions() { return eofReductions; }
192 public Iterator<Position> iterator() { return hs.iterator(); }
194 // Constructor //////////////////////////////////////////////////////////////////////////////
197 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
198 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
199 * @param all_states the set of states already constructed (to avoid recreating states)
200 * @param all_elements the set of all elements (Atom instances need not be included)
202 * In principle these two steps could be merged, but they
203 * are written separately to highlight these two facts:
205 * <li> Non-atom elements either match all-or-nothing, and do not overlap
206 * with each other (at least not in the sense of which element corresponds
207 * to the last reduction performed). Therefore, in order to make sure we
208 * wind up with the smallest number of states and shifts, we wait until
209 * we've figured out all the token-to-position multimappings before creating
212 * <li> In order to be able to run the state-construction algorithm in a single
213 * shot (rather than repeating until no new items appear in any state set),
214 * we need to use the "yields" semantics rather than the "produces" semantics
215 * for non-Atom Elements.
218 public State(HashSet<Position> hs,
219 HashMap<HashSet<Position>,State> all_states,
220 HashSet<Element> all_elements) {
223 // register ourselves in the all_states hash so that no
224 // two states are ever created with an identical position set
225 all_states.put(hs, this);
227 // Step 1a: examine all Position's in this state and compute the mappings from
228 // sets of follow tokens (tokens which could follow this position) to sets
229 // of _new_ positions (positions after shifting). These mappings are
230 // collectively known as the _closure_
232 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
233 for(Position position : hs) {
234 if (position.isLast() || !(position.element() instanceof Atom)) continue;
235 Atom a = (Atom)position.element();
236 HashSet<Position> hp = new HashSet<Position>();
237 reachable(position.next(), hp);
238 bag0.addAll(a.dup(), /*clo.walk()*/hp);
241 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
242 // set, add that character set to the goto table (with the State corresponding to the
243 // computed next-position set).
245 for(Topology<Token> r : bag0) {
246 HashSet<Position> h = new HashSet<Position>();
247 for(Position p : bag0.getAll(r)) h.add(p);
248 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
251 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
252 // compute the closure over every position in this set which is followed by a symbol
253 // which could yield the Element in question.
255 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
256 // to avoid having to iteratively construct our set of States as shown in most
257 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
259 for(Element e : all_elements) {
260 if (e instanceof Atom) continue;
261 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
262 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
263 if (gotoSetNonTerminals.get(e) != null)
264 throw new Error("this should not happen");
265 gotoSetNonTerminals.put(e, s);
268 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
269 for(Position p : hs) {
270 Element e = p.element();
271 if (e==null) continue;
272 HashSet<Element> ys = cache.ys.get(e);
274 for(Element y : ys) {
275 HashSet<Position> hp = new HashSet<Position>();
276 reachable(p.next(), hp);
281 for(Element y : move) {
282 HashSet<Position> h = move.getAll(y);
283 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
284 gotoSetNonTerminals.put(y, s);
288 public String toString() { return "state["+idx+"]"; }
290 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
294 * the information needed to perform a reduction; copied here to
295 * avoid keeping references to <tt>Element</tt> objects in a Table
297 public class Reduction {
298 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
299 public final int numPop;
300 private final Position position;
301 private final Forest[] holder; // to avoid constant reallocation
302 public int hashCode() { return position.hashCode(); }
303 public boolean equals(Object o) {
304 if (o==null) return false;
305 if (o==this) return true;
306 if (!(o instanceof Reduction)) return false;
307 Reduction r = (Reduction)o;
308 return r.position == position;
310 public Reduction(Position p) {
313 this.holder = new Forest[numPop];
315 public String toString() { return "[reduce " + position + "]"; }
316 public Forest reduce(Forest f, GSS.Phase.Node parent, GSS.Phase.Node onlychild, GSS.Phase target, Forest rex) {
317 holder[numPop-1] = f;
318 return reduce(parent, numPop-2, rex, onlychild, target);
320 public Forest reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild, GSS.Phase target, Forest rex) {
321 return reduce(parent, numPop-1, rex, onlychild, target);
324 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
325 private Forest reduce(GSS.Phase.Node parent, int pos, Forest rex, GSS.Phase.Node onlychild, GSS.Phase target) {
326 if (pos>=0) holder[pos] = parent.pending();
327 if (pos<=0 && rex==null) {
328 System.arraycopy(holder, 0, position.holder, 0, holder.length);
329 rex = position.rewrite(target.getLocation());
332 if (onlychild != null)
333 reduce(onlychild, pos-1, rex, null, target);
335 for(GSS.Phase.Node child : parent.parents())
336 reduce(child, pos-1, rex, null, target);
338 State state = parent.state.gotoSetNonTerminals.get(position.owner());
340 target.newNode(parent, rex, state, numPop<=0, parent.phase);
347 private static final Forest[] emptyForestArray = new Forest[0];