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 public 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, this, null, input.next(1, 0, 0), loc, null);
40 current.newNode(null, Forest.leaf(null, null), pt.start, true);
43 loc = input.getLocation();
44 //current.checkFailure();
46 Forest forest = current.token==null ? null : shiftedToken((T)current.token, loc);
47 GSS.Phase next = gss.new Phase(current, this, current, input.next(count, gss.resets, gss.waits), loc, forest);
48 count = next.hash.size();
49 if (current.isDone()) return (Forest<R>)current.finalResult;
55 // Exceptions //////////////////////////////////////////////////////////////////////////////
57 public static class Failed extends RuntimeException {
58 private final Token.Location location;
59 private final String message;
60 public Failed() { this("", null); }
61 public Failed(String message, Token.Location loc) { this.location = loc; this.message = message; }
62 public Token.Location getLocation() { return location; }
63 public String toString() { return message/* + (location==null ? "" : (" at " + location))*/; }
66 public static class Ambiguous extends RuntimeException {
67 public final Forest ambiguity;
68 public Ambiguous(Forest ambiguity) { this.ambiguity = ambiguity; }
69 public String toString() {
70 StringBuffer sb = new StringBuffer();
71 sb.append("unresolved ambiguity "/*"at " + ambiguity.getLocation() + ":"*/);
72 for(Object result : ambiguity.expand(false))
73 sb.append("\n " + result);
79 // Table //////////////////////////////////////////////////////////////////////////////
81 /** an SLR(1) parse table which may contain conflicts */
82 static class Table extends Walk.Cache {
84 public final Walk.Cache cache = this;
86 public HashMapBag<Position,State> byPosition = new HashMapBag<Position,State>();
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);
100 /** the start state */
101 public final State start;
103 /** used to generate unique values for State.idx */
104 private int master_state_idx = 0;
106 /** construct a parse table for the given grammar */
107 public Table(Topology top) { this("s", top); }
108 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
109 public Table(Union ux, Topology top) {
110 Union start0 = new Union("0");
111 start0.add(new Sequence.Singleton(ux, null, null));
113 for(Sequence s : start0) cache.eof.put(s, true);
114 cache.eof.put(start0, true);
116 // construct the set of states
117 HashMap<HashSet<Position>,State> all_states = new HashMap<HashSet<Position>,State>();
118 HashSet<Element> all_elements = new HashSet<Element>();
119 walk(start0, all_elements);
120 for(Element e : all_elements)
121 cache.ys.put(e, new Walk.YieldSet(e, cache).walk());
122 HashSet<Position> hp = new HashSet<Position>();
123 reachable(start0, hp);
124 this.start = new State(hp, all_states, all_elements);
126 // for each state, fill in the corresponding "row" of the parse table
127 for(State state : all_states.values())
128 for(Position p : state.hs) {
130 // the Grammar's designated "last position" is the only accepting state
131 if (start0.contains(p.owner()) && p.next()==null)
134 if (p.isRightNullable(cache)) {
135 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
136 Reduction red = new Reduction(p);
138 Topology follow = wf.walk(p.owner());
139 if (p.owner() instanceof Sequence.RewritingSequence &&
140 (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
141 System.out.println("follow before: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
143 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next())
144 follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
145 if (p.owner() instanceof Sequence.RewritingSequence &&
146 (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
147 System.out.println("follow after: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
149 state.reductions.put(follow, red);
150 if (wf.includesEof()) state.eofReductions.add(red);
153 // if the element following this position is an atom, copy the corresponding
154 // set of rows out of the "master" goto table and into this state's shift table
155 if (p.element() != null && p.element() instanceof Atom)
156 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
158 for(State state : all_states.values()) {
159 state.oreductions = state.reductions.optimize();
160 state.oshifts = state.shifts.optimize();
164 /** a single state in the LR table and the transitions possible from it */
166 public class State implements Comparable<Table.State>, IntegerMappable, Iterable<Position> {
168 public int toInt() { return idx; }
170 public boolean lame() {
171 for(Position p : this)
172 for(Position p2 = p; p2!=null; p2=p2.next())
173 if (p2.isLast() && !p2.owner().lame)
178 public boolean isResolvable(Token t) {
179 boolean found = false;
180 for(Reduction r : getReductions(t)) {
181 Position p = r.position;
182 if (!p.isRightNullable(cache)) continue;
183 if (p.owner().firstp()==p) continue;
185 // found two items meeting criteria #1
191 if (p.element()==null) continue;
192 Topology first = new Walk.First(top(), cache).walk(p.element());
193 if (first.contains(t))
198 public final int idx = master_state_idx++;
199 private final HashSet<Position> hs;
201 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
202 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
204 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
205 private HashSet<Reduction> eofReductions = new HashSet<Reduction>();
206 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
207 private boolean accept = false;
209 private VisitableMap<Token,State> oshifts = null;
210 private VisitableMap<Token,Reduction> oreductions = null;
212 // Interface Methods //////////////////////////////////////////////////////////////////////////////
214 public boolean isAccepting() { return accept; }
216 public boolean canShift(Token t) { return oshifts.contains(t); }
217 public boolean canReduce(Token t) { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
219 public Iterator<Position> iterator() { return hs.iterator(); }
221 public <B,C> void invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) {
222 oshifts.invoke(t, irbc, b, c);
224 public <B,C> void invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
225 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
226 else oreductions.invoke(t, irbc, b, c);
229 // Constructor //////////////////////////////////////////////////////////////////////////////
232 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
233 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
234 * @param all_states the set of states already constructed (to avoid recreating states)
235 * @param all_elements the set of all elements (Atom instances need not be included)
237 * In principle these two steps could be merged, but they
238 * are written separately to highlight these two facts:
240 * <li> Non-atom elements either match all-or-nothing, and do not overlap
241 * with each other (at least not in the sense of which element corresponds
242 * to the last reduction performed). Therefore, in order to make sure we
243 * wind up with the smallest number of states and shifts, we wait until
244 * we've figured out all the token-to-position multimappings before creating
247 * <li> In order to be able to run the state-construction algorithm in a single
248 * shot (rather than repeating until no new items appear in any state set),
249 * we need to use the "yields" semantics rather than the "produces" semantics
250 * for non-Atom Elements.
253 public State(HashSet<Position> hs,
254 HashMap<HashSet<Position>,State> all_states,
255 HashSet<Element> all_elements) {
258 // register ourselves in the all_states hash so that no
259 // two states are ever created with an identical position set
260 all_states.put(hs, this);
261 for(Position p : hs) byPosition.add(p,this);
263 // Step 1a: examine all Position's in this state and compute the mappings from
264 // sets of follow tokens (tokens which could follow this position) to sets
265 // of _new_ positions (positions after shifting). These mappings are
266 // collectively known as the _closure_
268 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
269 for(Position position : hs) {
270 if (position.isLast() || !(position.element() instanceof Atom)) continue;
271 Atom a = (Atom)position.element();
272 HashSet<Position> hp = new HashSet<Position>();
273 reachable(position.next(), hp);
277 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
278 // set, add that character set to the goto table (with the State corresponding to the
279 // computed next-position set).
281 for(Topology<Token> r : bag0) {
282 HashSet<Position> h = new HashSet<Position>();
283 for(Position p : bag0.getAll(r)) h.add(p);
284 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
287 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
288 // compute the closure over every position in this set which is followed by a symbol
289 // which could yield the Element in question.
291 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
292 // to avoid having to iteratively construct our set of States as shown in most
293 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
295 for(Element e : all_elements) {
296 if (e instanceof Atom) continue;
297 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
298 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
299 if (gotoSetNonTerminals.get(e) != null)
300 throw new Error("this should not happen");
301 gotoSetNonTerminals.put(e, s);
304 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
305 for(Position p : hs) {
306 Element e = p.element();
307 if (e==null) continue;
308 HashSet<Element> ys = cache.ys.get(e);
310 for(Element y : ys) {
311 HashSet<Position> hp = new HashSet<Position>();
312 reachable(p.next(), hp);
317 for(Element y : move) {
318 HashSet<Position> h = move.getAll(y);
319 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
320 gotoSetNonTerminals.put(y, s);
324 public String toString() {
325 //return "state["+idx+"]";
326 StringBuffer ret = new StringBuffer();
327 ret.append("state["+idx+"]: ");
328 for(Position p : this) ret.append("{"+p+"} ");
329 return ret.toString();
332 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
336 * the information needed to perform a reduction; copied here to
337 * avoid keeping references to <tt>Element</tt> objects in a Table
339 public class Reduction {
340 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
341 public final int numPop;
342 /*private*/ final Position position;
343 private final Forest[] holder; // to avoid constant reallocation
344 public int hashCode() { return position.hashCode(); }
345 public boolean equals(Object o) {
346 if (o==null) return false;
347 if (o==this) return true;
348 if (!(o instanceof Reduction)) return false;
349 Reduction r = (Reduction)o;
350 return r.position == position;
352 public Reduction(Position p) {
355 this.holder = new Forest[numPop];
357 public String toString() { return "[reduce " + position + "]"; }
359 private Forest zero = null;
360 public Forest zero() {
361 if (zero != null) return zero;
362 if (numPop > 0) throw new Error();
363 return zero = position.rewrite(null);
366 public void reduce(GSS.Phase.Node parent) {
367 if (numPop==0) finish(parent, zero(), parent.phase());
368 else reduce(parent, numPop-1, parent.phase());
371 public void reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild) {
372 if (numPop<=0) throw new Error("called wrong form of reduce()");
374 Forest old = holder[pos];
375 holder[pos] = parent.pending();
377 System.arraycopy(holder, 0, position.holder, 0, holder.length);
378 finish(onlychild, position.rewrite(parent.phase().getLocation()), parent.phase());
380 reduce(onlychild, pos-1, parent.phase());
385 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
386 private void reduce(GSS.Phase.Node parent, int pos, GSS.Phase target) {
387 Forest old = holder[pos];
388 holder[pos] = parent.pending();
390 System.arraycopy(holder, 0, position.holder, 0, holder.length);
391 for(int i=0; i<position.pos; i++) if (position.holder[i]==null) throw new Error("realbad");
392 Forest rex = position.rewrite(target.getLocation());
393 for(GSS.Phase.Node child : parent.parents()) finish(child, rex, target);
395 for(GSS.Phase.Node child : parent.parents()) reduce(child, pos-1, target);
399 private void finish(GSS.Phase.Node parent, Forest result, GSS.Phase target) {
400 State state = parent.state.gotoSetNonTerminals.get(position.owner());
401 if (result==null) throw new Error();
403 target.newNode(parent, result, state, numPop<=0, this);
408 private static final Forest[] emptyForestArray = new Forest[0];
411 // Helpers //////////////////////////////////////////////////////////////////////////////
413 private static void reachable(Element e, HashSet<Position> h) {
414 if (e instanceof Atom) return;
415 for(Sequence s : ((Union)e))
416 reachable(s.firstp(), h);
418 private static void reachable(Position p, HashSet<Position> h) {
419 if (h.contains(p)) return;
421 if (p.element() != null) reachable(p.element(), h);