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();
45 Forest forest = current.token==null ? null : shiftedToken((T)current.token, loc);
46 GSS.Phase next = gss.new Phase(current, this, current, input.next(count, gss.resets, gss.waits), loc, forest);
47 count = next.hash.size();
48 if (current.isDone()) return (Forest<R>)current.finalResult;
54 // Exceptions //////////////////////////////////////////////////////////////////////////////
56 public static class Failed extends RuntimeException {
57 private final Token.Location location;
58 private final String message;
59 public Failed() { this("", null); }
60 public Failed(String message, Token.Location loc) { this.location = loc; this.message = message; }
61 public Token.Location getLocation() { return location; }
62 public String toString() { return message/* + (location==null ? "" : (" at " + location))*/; }
65 public static class Ambiguous extends RuntimeException {
66 public final Forest ambiguity;
67 public Ambiguous(Forest ambiguity) { this.ambiguity = ambiguity; }
68 public String toString() {
69 StringBuffer sb = new StringBuffer();
70 sb.append("unresolved ambiguity "/*"at " + ambiguity.getLocation() + ":"*/);
71 for(Object result : ambiguity.expand(false))
72 sb.append("\n " + result);
78 // Table //////////////////////////////////////////////////////////////////////////////
80 /** an SLR(1) parse table which may contain conflicts */
81 static class Table extends Walk.Cache {
83 public final Walk.Cache cache = this;
85 public HashMapBag<Position,State> byPosition = new HashMapBag<Position,State>();
87 private void walk(Element e, HashSet<Element> hs) {
89 if (hs.contains(e)) return;
91 if (e instanceof Atom) return;
92 for(Sequence s : (Union)e) {
94 for(Position p = s.firstp(); p != null; p = p.next())
95 walk(p.element(), hs);
99 /** the start state */
100 public final State start;
102 /** used to generate unique values for State.idx */
103 private int master_state_idx = 0;
105 /** construct a parse table for the given grammar */
106 public Table(Topology top) { this("s", top); }
107 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
108 public Table(Union ux, Topology top) {
109 Union start0 = new Union("0");
110 start0.add(new Sequence.Singleton(ux, null, null));
112 for(Sequence s : start0) cache.eof.put(s, true);
113 cache.eof.put(start0, true);
115 // construct the set of states
116 HashMap<HashSet<Position>,State> all_states = new HashMap<HashSet<Position>,State>();
117 HashSet<Element> all_elements = new HashSet<Element>();
118 walk(start0, all_elements);
119 for(Element e : all_elements)
120 cache.ys.put(e, new Walk.YieldSet(e, cache).walk());
121 HashSet<Position> hp = new HashSet<Position>();
122 reachable(start0, hp);
123 this.start = new State(hp, all_states, all_elements);
125 // for each state, fill in the corresponding "row" of the parse table
126 for(State state : all_states.values())
127 for(Position p : state.hs) {
129 // the Grammar's designated "last position" is the only accepting state
130 if (start0.contains(p.owner()) && p.next()==null)
133 if (p.isRightNullable(cache)) {
134 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
135 Reduction red = new Reduction(p);
137 Topology follow = wf.walk(p.owner());
138 if (p.owner() instanceof Sequence.RewritingSequence &&
139 (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
140 System.out.println("follow before: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
142 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next())
143 follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
144 if (p.owner() instanceof Sequence.RewritingSequence &&
145 (((Sequence.RewritingSequence)p.owner()).tag+"").equals("emailaddr")) {
146 System.out.println("follow after: " + new edu.berkeley.sbp.misc.CharToken.CharRange(follow));
148 state.reductions.put(follow, red);
149 if (wf.includesEof()) state.eofReductions.add(red);
152 // if the element following this position is an atom, copy the corresponding
153 // set of rows out of the "master" goto table and into this state's shift table
154 if (p.element() != null && p.element() instanceof Atom)
155 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
157 for(State state : all_states.values()) {
158 state.oreductions = state.reductions.optimize();
159 state.oshifts = state.shifts.optimize();
163 /** a single state in the LR table and the transitions possible from it */
165 public class State implements Comparable<Table.State>, IntegerMappable, Iterable<Position> {
167 public int toInt() { return idx; }
169 public boolean lame() {
170 for(Position p : this)
171 for(Position p2 = p; p2!=null; p2=p2.next())
172 if (p2.isLast() && !p2.owner().lame)
177 public boolean isResolvable(Token t) {
178 boolean found = false;
179 for(Reduction r : getReductions(t)) {
180 Position p = r.position;
181 if (!p.isRightNullable(cache)) continue;
182 if (p.owner().firstp()==p) continue;
184 // found two items meeting criteria #1
190 if (p.element()==null) continue;
191 Topology first = new Walk.First(top(), cache).walk(p.element());
192 if (first.contains(t))
197 public final int idx = master_state_idx++;
198 private final HashSet<Position> hs;
200 private transient HashMap<Element,State> gotoSetNonTerminals = new HashMap<Element,State>();
201 private transient TopologicalBag<Token,State> gotoSetTerminals = new TopologicalBag<Token,State>();
203 private TopologicalBag<Token,Reduction> reductions = new TopologicalBag<Token,Reduction>();
204 private HashSet<Reduction> eofReductions = new HashSet<Reduction>();
205 private TopologicalBag<Token,State> shifts = new TopologicalBag<Token,State>();
206 private boolean accept = false;
208 private VisitableMap<Token,State> oshifts = null;
209 private VisitableMap<Token,Reduction> oreductions = null;
211 // Interface Methods //////////////////////////////////////////////////////////////////////////////
213 public boolean isAccepting() { return accept; }
215 public boolean canShift(Token t) { return oshifts.contains(t); }
216 public boolean canReduce(Token t) { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
218 public Iterator<Position> iterator() { return hs.iterator(); }
220 public <B,C> void invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) {
221 oshifts.invoke(t, irbc, b, c);
223 public <B,C> void invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
224 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
225 else oreductions.invoke(t, irbc, b, c);
228 // Constructor //////////////////////////////////////////////////////////////////////////////
231 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
232 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
233 * @param all_states the set of states already constructed (to avoid recreating states)
234 * @param all_elements the set of all elements (Atom instances need not be included)
236 * In principle these two steps could be merged, but they
237 * are written separately to highlight these two facts:
239 * <li> Non-atom elements either match all-or-nothing, and do not overlap
240 * with each other (at least not in the sense of which element corresponds
241 * to the last reduction performed). Therefore, in order to make sure we
242 * wind up with the smallest number of states and shifts, we wait until
243 * we've figured out all the token-to-position multimappings before creating
246 * <li> In order to be able to run the state-construction algorithm in a single
247 * shot (rather than repeating until no new items appear in any state set),
248 * we need to use the "yields" semantics rather than the "produces" semantics
249 * for non-Atom Elements.
252 public State(HashSet<Position> hs,
253 HashMap<HashSet<Position>,State> all_states,
254 HashSet<Element> all_elements) {
257 // register ourselves in the all_states hash so that no
258 // two states are ever created with an identical position set
259 all_states.put(hs, this);
260 for(Position p : hs) byPosition.add(p,this);
262 // Step 1a: examine all Position's in this state and compute the mappings from
263 // sets of follow tokens (tokens which could follow this position) to sets
264 // of _new_ positions (positions after shifting). These mappings are
265 // collectively known as the _closure_
267 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
268 for(Position position : hs) {
269 if (position.isLast() || !(position.element() instanceof Atom)) continue;
270 Atom a = (Atom)position.element();
271 HashSet<Position> hp = new HashSet<Position>();
272 reachable(position.next(), hp);
276 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
277 // set, add that character set to the goto table (with the State corresponding to the
278 // computed next-position set).
280 for(Topology<Token> r : bag0) {
281 HashSet<Position> h = new HashSet<Position>();
282 for(Position p : bag0.getAll(r)) h.add(p);
283 gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
286 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
287 // compute the closure over every position in this set which is followed by a symbol
288 // which could yield the Element in question.
290 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
291 // to avoid having to iteratively construct our set of States as shown in most
292 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
294 for(Element e : all_elements) {
295 if (e instanceof Atom) continue;
296 HashSet<Position> h = new Walk.Closure(null, g.cache).closure(e, hs);
297 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
298 if (gotoSetNonTerminals.get(e) != null)
299 throw new Error("this should not happen");
300 gotoSetNonTerminals.put(e, s);
303 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
304 for(Position p : hs) {
305 Element e = p.element();
306 if (e==null) continue;
307 HashSet<Element> ys = cache.ys.get(e);
309 for(Element y : ys) {
310 HashSet<Position> hp = new HashSet<Position>();
311 reachable(p.next(), hp);
316 for(Element y : move) {
317 HashSet<Position> h = move.getAll(y);
318 State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
319 gotoSetNonTerminals.put(y, s);
323 public String toString() {
324 //return "state["+idx+"]";
325 StringBuffer ret = new StringBuffer();
326 ret.append("state["+idx+"]: ");
327 for(Position p : this) ret.append("{"+p+"} ");
328 return ret.toString();
331 public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
335 * the information needed to perform a reduction; copied here to
336 * avoid keeping references to <tt>Element</tt> objects in a Table
338 public class Reduction {
339 // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
340 public final int numPop;
341 /*private*/ final Position position;
342 private final Forest[] holder; // to avoid constant reallocation
343 public int hashCode() { return position.hashCode(); }
344 public boolean equals(Object o) {
345 if (o==null) return false;
346 if (o==this) return true;
347 if (!(o instanceof Reduction)) return false;
348 Reduction r = (Reduction)o;
349 return r.position == position;
351 public Reduction(Position p) {
354 this.holder = new Forest[numPop];
356 public String toString() { return "[reduce " + position + "]"; }
358 private Forest zero = null;
359 public Forest zero() {
360 if (zero != null) return zero;
361 if (numPop > 0) throw new Error();
362 return zero = position.rewrite(null);
365 public void reduce(GSS.Phase.Node parent) {
366 if (numPop==0) finish(parent, zero(), parent.phase());
367 else reduce(parent, numPop-1, parent.phase());
370 public void reduce(GSS.Phase.Node parent, GSS.Phase.Node onlychild) {
371 if (numPop<=0) throw new Error("called wrong form of reduce()");
373 Forest old = holder[pos];
374 holder[pos] = parent.pending();
376 System.arraycopy(holder, 0, position.holder, 0, holder.length);
377 finish(onlychild, position.rewrite(parent.phase().getLocation()), parent.phase());
379 reduce(onlychild, pos-1, parent.phase());
384 // FIXME: this could be more elegant and/or cleaner and/or somewhere else
385 private void reduce(GSS.Phase.Node parent, int pos, GSS.Phase target) {
386 Forest old = holder[pos];
387 holder[pos] = parent.pending();
389 System.arraycopy(holder, 0, position.holder, 0, holder.length);
390 for(int i=0; i<position.pos; i++) if (position.holder[i]==null) throw new Error("realbad");
391 Forest rex = position.rewrite(target.getLocation());
392 for(GSS.Phase.Node child : parent.parents()) finish(child, rex, target);
394 for(GSS.Phase.Node child : parent.parents()) reduce(child, pos-1, target);
398 private void finish(GSS.Phase.Node parent, Forest result, GSS.Phase target) {
399 State state = parent.state.gotoSetNonTerminals.get(position.owner());
400 if (result==null) throw new Error();
402 target.newNode(parent, result, state, numPop<=0, this);
407 private static final Forest[] emptyForestArray = new Forest[0];
410 // Helpers //////////////////////////////////////////////////////////////////////////////
412 private static void reachable(Element e, HashSet<Position> h) {
413 if (e instanceof Atom) return;
414 for(Sequence s : ((Union)e))
415 reachable(s.firstp(), h);
417 private static void reachable(Position p, HashSet<Position> h) {
418 if (h.contains(p)) return;
420 if (p.element() != null) reachable(p.element(), h);