1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.*;
5 import edu.berkeley.sbp.util.*;
6 import edu.berkeley.sbp.Sequence.Position;
10 /** a parser which translates an Input<Token> into a Forest<NodeType> */
11 public abstract class Parser<Token, NodeType> {
12 protected final Table<Token> pt;
14 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
15 public Parser(Union u, Topology<Token> top) { this.pt = new Table<Token>(u, top); }
16 Parser(Table<Token> pt) { this.pt = pt; }
18 /** implement this method to create the output forest corresponding to a lone shifted input token */
19 public abstract Forest<NodeType> shiftToken(Token t, Input.Location newloc);
21 boolean helpgc = true;
23 public String toString() { return pt.toString(); }
25 /** parse <tt>input</tt>, and return the shared packed parse forest (or throw an exception) */
26 public Forest<NodeType> parse(Input<Token> input) throws IOException, ParseFailed {
27 GSS gss = new GSS(input);
28 Input.Location loc = input.getLocation();
29 Token tok = input.next();
30 GSS.Phase current = gss.new Phase<Token>(null, null, tok, loc, input.getLocation(), null);
31 current.newNode(new Result(Forest.create(loc.createRegion(loc), null, null, false), null, null), pt.start, true);
33 for(int idx=0;;idx++) {
34 Input.Location oldloc = loc;
36 Forest forest = current.token==null ? null : shiftToken((Token)current.token, loc);
37 loc = input.getLocation();
38 Token nextToken = input.next();
39 GSS.Phase next = gss.new Phase<Token>(current, current, nextToken, loc, input.getLocation(), forest);
42 FileOutputStream fos = new FileOutputStream("out-"+idx+".dot");
43 PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
44 GraphViz gv = new GraphViz();
45 for(Object n : current)
46 ((Node)n).toGraphViz(gv);
53 if (current.isDone()) return (Forest<NodeType>)gss.finalResult;
58 // Table //////////////////////////////////////////////////////////////////////////////
60 /** an SLR(1) parse table which may contain conflicts */
61 static class Table<Token> extends Walk.Cache {
63 public String toString() {
64 StringBuffer sb = new StringBuffer();
65 sb.append("parse table");
66 for(State<Token> state : all_states) {
67 sb.append(" " + state + "\n");
68 for(Topology<Token> t : state.shifts) {
69 sb.append(" shift \""+
70 new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => ");
71 for(State st : state.shifts.getAll(t))
72 sb.append(st.idx+" ");
75 for(Topology<Token> t : state.reductions)
76 sb.append(" reduce \""+
77 new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => " +
78 state.reductions.getAll(t) + "\n");
79 for(Sequence s : state.gotoSetNonTerminals.keySet())
80 sb.append(" goto "+state.gotoSetNonTerminals.get(s)+" from " + s + "\n");
85 public final Walk.Cache cache = this;
87 private void walk(Element e, HashSet<SequenceOrElement> hs) {
89 if (hs.contains(e)) return;
91 if (e instanceof Atom) return;
92 for(Sequence s : (Union)e)
95 private void walk(Sequence s, HashSet<SequenceOrElement> hs) {
97 for(Position p = s.firstp(); p != null; p = p.next())
98 walk(p.element(), hs);
99 for(Sequence ss : s.needs()) walk(ss, hs);
100 for(Sequence ss : s.hates()) walk(ss, hs);
103 /** the start state */
104 public final State<Token> start;
106 /** the state from which no reductions can be done */
107 private final State<Token> dead_state;
109 /** used to generate unique values for State.idx */
110 private int master_state_idx = 0;
111 HashSet<State<Token>> all_states = new HashSet<State<Token>>();
112 HashMap<HashSet<Position>,State<Token>> doomed_states = new HashMap<HashSet<Position>,State<Token>>();
113 HashMap<HashSet<Position>,State<Token>> normal_states = new HashMap<HashSet<Position>,State<Token>>();
114 HashSet<SequenceOrElement> all_elements = new HashSet<SequenceOrElement>();
116 /** construct a parse table for the given grammar */
117 public Table(Topology top) { this("s", top); }
118 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
119 public Table(Union ux, Topology top) {
120 Union start0 = new Union("0");
121 start0.add(new Sequence.Singleton(ux));
123 for(Sequence s : start0) cache.eof.put(s, true);
124 cache.eof.put(start0, true);
126 // construct the set of states
127 walk(start0, all_elements);
128 for(SequenceOrElement e : all_elements)
129 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
130 for(SequenceOrElement e : all_elements)
131 cache.ys2.addAll(e, new Walk.YieldSet2(e, cache).walk());
132 HashSet<Position> hp = new HashSet<Position>();
133 reachable(start0, hp);
135 this.dead_state = new State<Token>(new HashSet<Position>(), true);
136 this.start = new State<Token>(hp);
138 // for each state, fill in the corresponding "row" of the parse table
139 for(State<Token> state : all_states)
140 for(Position p : state.hs) {
142 // the Grammar's designated "last position" is the only accepting state
143 if (start0.contains(p.owner()) && p.next()==null && !state.doomed)
146 if (isRightNullable(p)) {
147 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
148 Topology follow = wf.walk(p.owner());
149 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next()) {
150 Atom set = new Walk.EpsilonFollowSet(new edu.berkeley.sbp.chr.CharAtom(top.empty().complement()),
151 new edu.berkeley.sbp.chr.CharAtom(top.empty()),
152 cache).walk(p2.element());
153 follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
154 if (set != null) follow = follow.intersect(set.getTokenTopology());
156 state.reductions.put(follow, p);
157 if (wf.includesEof()) state.eofReductions.add(p);
160 // if the element following this position is an atom, copy the corresponding
161 // set of rows out of the "master" goto table and into this state's shift table
162 if (p.element() != null && p.element() instanceof Atom)
163 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).getTokenTopology()));
166 if (top instanceof IntegerTopology)
167 for(State<Token> state : all_states) {
168 state.oreductions = state.reductions.optimize(((IntegerTopology)top).functor());
169 state.oshifts = state.shifts.optimize(((IntegerTopology)top).functor());
172 // crude algorithm to assing an ordinal ordering to every position
173 ArrayList<Sequence.Position> al = new ArrayList<Sequence.Position>();
174 for(State s : all_states) {
176 Sequence.Position p = (Sequence.Position)po;
177 if (al.contains(p)) continue;
179 for(; i<al.size(); i++) {
180 if (p.compareTo(al.get(i), cache) > 0)
186 for(int i=0; i<al.size(); i++)
190 private boolean isRightNullable(Position p) {
191 if (p.isLast()) return true;
192 if (!possiblyEpsilon(p.element())) return false;
193 return isRightNullable(p.next());
196 /** a single state in the LR table and the transitions possible from it */
198 class State<Token> implements IntegerMappable, Iterable<Position> {
200 public final int idx = master_state_idx++;
201 private final HashSet<Position> hs;
202 public HashSet<State<Token>> also = new HashSet<State<Token>>();
204 public transient HashMap<Sequence,State<Token>> gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
205 private transient TopologicalBag<Token,State<Token>> gotoSetTerminals = new TopologicalBag<Token,State<Token>>();
207 private TopologicalBag<Token,Position> reductions = new TopologicalBag<Token,Position>();
208 private HashSet<Position> eofReductions = new HashSet<Position>();
209 private TopologicalBag<Token,State<Token>> shifts = new TopologicalBag<Token,State<Token>>();
210 private boolean accept = false;
212 private VisitableMap<Token,State<Token>> oshifts = null;
213 private VisitableMap<Token,Position> oreductions = null;
215 // Interface Methods //////////////////////////////////////////////////////////////////////////////
217 boolean isAccepting() { return accept; }
218 public Iterator<Position> iterator() { return hs.iterator(); }
220 boolean canShift(Token t) { return oshifts!=null && oshifts.contains(t); }
221 <B,C> void invokeShifts(Token t, Invokable<State<Token>,B,C> irbc, B b, C c) {
222 oshifts.invoke(t, irbc, b, c);
225 boolean canReduce(Token t) { return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
226 <B,C> void invokeReductions(Token t, Invokable<Position,B,C> irbc, B b, C c) {
227 if (t==null) for(Position r : eofReductions) irbc.invoke(r, b, c);
228 else oreductions.invoke(t, irbc, b, c);
231 // Constructor //////////////////////////////////////////////////////////////////////////////
234 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
235 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
236 * @param all_elements the set of all elements (Atom instances need not be included)
238 * In principle these two steps could be merged, but they
239 * are written separately to highlight these two facts:
241 * <li> Non-atom elements either match all-or-nothing, and do not overlap
242 * with each other (at least not in the sense of which element corresponds
243 * to the last reduction performed). Therefore, in order to make sure we
244 * wind up with the smallest number of states and shifts, we wait until
245 * we've figured out all the token-to-position multimappings before creating
248 * <li> In order to be able to run the state-construction algorithm in a single
249 * shot (rather than repeating until no new items appear in any state set),
250 * we need to use the "yields" semantics rather than the "produces" semantics
251 * for non-Atom Elements.
254 public State(HashSet<Position> hs) { this(hs, false); }
255 public boolean doomed;
256 public State(HashSet<Position> hs, boolean doomed) {
258 this.doomed = doomed;
260 // register ourselves in the all_states hash so that no
261 // two states are ever created with an identical position set
262 ((HashMap)(doomed ? doomed_states : normal_states)).put(hs, this);
263 ((HashSet)all_states).add(this);
265 for(Position p : hs) {
266 if (!p.isFirst()) continue;
267 for(Sequence s : p.owner().needs()) {
268 if (hs.contains(s.firstp())) continue;
269 HashSet<Position> h2 = new HashSet<Position>();
270 reachable(s.firstp(), h2);
271 also.add(mkstate(h2, true));
273 for(Sequence s : p.owner().hates()) {
274 if (hs.contains(s.firstp())) continue;
275 HashSet<Position> h2 = new HashSet<Position>();
277 also.add(mkstate(h2, true));
281 // Step 1a: examine all Position's in this state and compute the mappings from
282 // sets of follow tokens (tokens which could follow this position) to sets
283 // of _new_ positions (positions after shifting). These mappings are
284 // collectively known as the _closure_
286 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
287 for(Position position : hs) {
288 if (position.isLast() || !(position.element() instanceof Atom)) continue;
289 Atom a = (Atom)position.element();
290 HashSet<Position> hp = new HashSet<Position>();
291 reachable(position.next(), hp);
292 bag0.addAll(a.getTokenTopology(), hp);
295 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
296 // set, add that character set to the goto table (with the State corresponding to the
297 // computed next-position set).
299 for(Topology<Token> r : bag0) {
300 HashSet<Position> h = new HashSet<Position>();
301 for(Position p : bag0.getAll(r)) h.add(p);
302 ((TopologicalBag)gotoSetTerminals).put(r, mkstate(h, doomed));
305 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
306 // compute the closure over every position in this set which is followed by a symbol
307 // which could yield the Element in question.
309 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
310 // to avoid having to iteratively construct our set of States as shown in most
311 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
313 HashMapBag<SequenceOrElement,Position> move = new HashMapBag<SequenceOrElement,Position>();
314 for(Position p : hs) {
315 Element e = p.element();
316 if (e==null) continue;
317 for(SequenceOrElement y : cache.ys2.getAll(e)) {
318 //System.out.println(e + " yields " + y);
319 HashSet<Position> hp = new HashSet<Position>();
320 reachable(p.next(), hp);
324 OUTER: for(SequenceOrElement y : move) {
325 HashSet<Position> h = move.getAll(y);
326 State<Token> s = mkstate(h, doomed);
327 // if a reduction is "lame", it should wind up in the dead_state after reducing
328 if (y instanceof Sequence) {
329 for(Position p : hs) {
330 if (p.element() != null && (p.element() instanceof Union)) {
331 Union u = (Union)p.element();
332 for(Sequence seq : u)
333 if (seq.needs.contains((Sequence)y) || seq.hates.contains((Sequence)y)) {
334 // FIXME: what if there are two "routes" to get to the sequence?
335 ((HashMap)gotoSetNonTerminals).put((Sequence)y, dead_state);
340 gotoSetNonTerminals.put((Sequence)y, s);
345 private State<Token> mkstate(HashSet<Position> h, boolean b) {
346 if (b) return doomed_states.get(h) == null ? (State)new State<Token>(h,b) : (State)doomed_states.get(h);
347 else return normal_states.get(h) == null ? (State)new State<Token>(h,b) : (State)normal_states.get(h);
350 public String toStringx() {
351 StringBuffer st = new StringBuffer();
352 for(Position p : this) {
353 if (st.length() > 0) st.append("\n");
356 return st.toString();
358 public String toString() {
359 StringBuffer ret = new StringBuffer();
360 ret.append("state["+idx+"]: ");
361 for(Position p : this) ret.append("{"+p+"} ");
362 return ret.toString();
365 public Walk.Cache cache() { return cache; }
366 public int toInt() { return idx; }
370 // Helpers //////////////////////////////////////////////////////////////////////////////
372 private static void reachable(Sequence s, HashSet<Position> h) {
373 reachable(s.firstp(), h);
374 //for(Sequence ss : s.needs()) reachable(ss, h);
375 //for(Sequence ss : s.hates()) reachable(ss, h);
377 private static void reachable(Element e, HashSet<Position> h) {
378 if (e instanceof Atom) return;
379 for(Sequence s : ((Union)e))
382 private static void reachable(Position p, HashSet<Position> h) {
383 if (h.contains(p)) return;
385 if (p.element() != null) reachable(p.element(), h);