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, 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 */
165 public class State implements Comparable<Table.State>, Iterable<Position> {
168 public boolean isResolvable(Token t) {
169 boolean found = false;
170 for(Reduction r : getReductions(t)) {
171 Position p = r.position;
172 if (!p.isRightNullable(cache)) continue;
173 if (p.owner().firstp()==p) continue;
175 // found two items meeting criteria #1
181 if (p.element()==null) continue;
182 Topology first = new Walk.First(top(), cache).walk(p.element());
183 if (first.contains(t))
188 public final int idx = master_state_idx++;
189 private final HashSet<Position> hs;
191 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
192 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
194 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
195 private HashSet<Reduction> eofReductions = new HashSet<Reduction>();
196 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
197 private boolean accept = false;
199 private VisitableMap<Token,State> oshifts = null;
200 private VisitableMap<Token,Reduction> oreductions = null;
202 // Interface Methods //////////////////////////////////////////////////////////////////////////////
204 public boolean isAccepting() { return accept; }
206 public boolean canShift(Token t) { return oshifts.contains(t); }
207 public boolean canReduce(Token t) { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
209 public Iterator<Position> iterator() { return hs.iterator(); }
211 public <B,C> void invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) {
212 oshifts.invoke(t, irbc, b, c);
214 public <B,C> void invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
215 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
216 else oreductions.invoke(t, irbc, b, c);
219 // Constructor //////////////////////////////////////////////////////////////////////////////
222 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
223 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
224 * @param all_states the set of states already constructed (to avoid recreating states)
225 * @param all_elements the set of all elements (Atom instances need not be included)
227 * In principle these two steps could be merged, but they
228 * are written separately to highlight these two facts:
230 * <li> Non-atom elements either match all-or-nothing, and do not overlap
231 * with each other (at least not in the sense of which element corresponds
232 * to the last reduction performed). Therefore, in order to make sure we
233 * wind up with the smallest number of states and shifts, we wait until
234 * we've figured out all the token-to-position multimappings before creating
237 * <li> In order to be able to run the state-construction algorithm in a single
238 * shot (rather than repeating until no new items appear in any state set),
239 * we need to use the "yields" semantics rather than the "produces" semantics
240 * for non-Atom Elements.
243 public State(HashSet<Position> hs,
244 HashMap<HashSet<Position>,State> all_states,
245 HashSet<Element> all_elements) {
248 // register ourselves in the all_states hash so that no
249 // two states are ever created with an identical position set
250 all_states.put(hs, this);
251 for(Position p : hs) byPosition.add(p,this);
253 // Step 1a: examine all Position's in this state and compute the mappings from
254 // sets of follow tokens (tokens which could follow this position) to sets
255 // of _new_ positions (positions after shifting). These mappings are
256 // collectively known as the _closure_
258 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
259 for(Position position : hs) {
260 if (position.isLast() || !(position.element() instanceof Atom)) continue;
261 Atom a = (Atom)position.element();
262 HashSet<Position> hp = new HashSet<Position>();
263 reachable(position.next(), hp);
267 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
268 // set, add that character set to the goto table (with the State corresponding to the
269 // computed next-position set).
271 for(Topology<Token> r : bag0) {
272 HashSet<Position> h = new HashSet<Position>();
273 for(Position p : bag0.getAll(r)) h.add(p);
274 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
277 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
278 // compute the closure over every position in this set which is followed by a symbol
279 // which could yield the Element in question.
281 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
282 // to avoid having to iteratively construct our set of States as shown in most
283 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
285 for(Element e : all_elements) {
286 if (e instanceof Atom) continue;
287 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
288 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
289 if (gotoSetNonTerminals.get(e) != null)
290 throw new Error("this should not happen");
291 gotoSetNonTerminals.put(e, s);
294 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
295 for(Position p : hs) {
296 Element e = p.element();
297 if (e==null) continue;
298 HashSet<Element> ys = cache.ys.get(e);
300 for(Element y : ys) {
301 HashSet<Position> hp = new HashSet<Position>();
302 reachable(p.next(), hp);
307 for(Element y : move) {
308 HashSet<Position> h = move.getAll(y);
309 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
310 gotoSetNonTerminals.put(y, s);
314 public String toString() { return "state["+idx+"]"; }
316 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
320 * the information needed to perform a reduction; copied here to
321 * avoid keeping references to <tt>Element</tt> objects in a Table
323 public class Reduction {
324 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
325 public final int numPop;
326 /*private*/ final Position position;
327 private final Forest[] holder; // to avoid constant reallocation
328 public int hashCode() { return position.hashCode(); }
329 public boolean equals(Object o) {
330 if (o==null) return false;
331 if (o==this) return true;
332 if (!(o instanceof Reduction)) return false;
333 Reduction r = (Reduction)o;
334 return r.position == position;
336 public Reduction(Position p) {
339 this.holder = new Forest[numPop];
341 public String toString() { return "[reduce " + position + "]"; }
343 private Forest zero = null;
344 public Forest zero() {
345 if (zero != null) return zero;
346 if (numPop > 0) throw new Error();
347 return zero = position.rewrite(null);
350 public void reduce(GSS.Phase.Node parent) {
351 if (numPop==0) finish(parent, zero(), parent.phase());
352 else reduce(parent, numPop-1, parent.phase());
355 public void reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild) {
356 if (numPop<=0) throw new Error("called wrong form of reduce()");
358 Forest old = holder[pos];
359 holder[pos] = parent.pending();
361 System.arraycopy(holder, 0, position.holder, 0, holder.length);
362 finish(onlychild, position.rewrite(parent.phase().getLocation()), parent.phase());
364 reduce(onlychild, pos-1, parent.phase());
369 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
370 private void reduce(GSS.Phase.Node parent, int pos, GSS.Phase target) {
371 Forest old = holder[pos];
372 holder[pos] = parent.pending();
374 System.arraycopy(holder, 0, position.holder, 0, holder.length);
375 for(int i=0; i<position.pos; i++) if (position.holder[i]==null) throw new Error("realbad");
376 Forest rex = position.rewrite(target.getLocation());
377 for(GSS.Phase.Node child : parent.parents()) finish(child, rex, target);
379 for(GSS.Phase.Node child : parent.parents()) reduce(child, pos-1, target);
383 private void finish(GSS.Phase.Node parent, Forest result, GSS.Phase target) {
384 State state = parent.state.gotoSetNonTerminals.get(position.owner());
385 if (result==null) throw new Error();
387 target.newNode(parent, result, state, numPop<=0, this);
392 private static final Forest[] emptyForestArray = new Forest[0];
395 // Helpers //////////////////////////////////////////////////////////////////////////////
397 private static void reachable(Element e, HashSet<Position> h) {
398 if (e instanceof Atom) return;
399 for(Sequence s : ((Union)e))
400 reachable(s.firstp(), h);
402 private static void reachable(Position p, HashSet<Position> h) {
403 if (h.contains(p)) return;
405 if (p.element() != null) reachable(p.element(), h);