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()));
165 if (top instanceof IntegerTopology)
166 for(State<Token> state : all_states) {
167 state.oreductions = state.reductions.optimize(((IntegerTopology)top).functor());
168 state.oshifts = state.shifts.optimize(((IntegerTopology)top).functor());
172 private boolean isRightNullable(Position p) {
173 if (p.isLast()) return true;
174 if (!possiblyEpsilon(p.element())) return false;
175 return isRightNullable(p.next());
178 /** a single state in the LR table and the transitions possible from it */
180 class State<Token> implements IntegerMappable, Iterable<Position> {
182 public final int idx = master_state_idx++;
183 private final HashSet<Position> hs;
184 public HashSet<State<Token>> also = new HashSet<State<Token>>();
186 public transient HashMap<Sequence,State<Token>> gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
187 private transient TopologicalBag<Token,State<Token>> gotoSetTerminals = new TopologicalBag<Token,State<Token>>();
189 private TopologicalBag<Token,Position> reductions = new TopologicalBag<Token,Position>();
190 private HashSet<Position> eofReductions = new HashSet<Position>();
191 private TopologicalBag<Token,State<Token>> shifts = new TopologicalBag<Token,State<Token>>();
192 private boolean accept = false;
194 private VisitableMap<Token,State<Token>> oshifts = null;
195 private VisitableMap<Token,Position> oreductions = null;
197 // Interface Methods //////////////////////////////////////////////////////////////////////////////
199 boolean isAccepting() { return accept; }
200 public Iterator<Position> iterator() { return hs.iterator(); }
202 boolean canShift(Token t) { return oshifts!=null && oshifts.contains(t); }
203 <B,C> void invokeShifts(Token t, Invokable<State<Token>,B,C> irbc, B b, C c) {
204 oshifts.invoke(t, irbc, b, c);
207 boolean canReduce(Token t) { return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
208 <B,C> void invokeReductions(Token t, Invokable<Position,B,C> irbc, B b, C c) {
209 if (t==null) for(Position r : eofReductions) irbc.invoke(r, b, c);
210 else oreductions.invoke(t, irbc, b, c);
213 // Constructor //////////////////////////////////////////////////////////////////////////////
216 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
217 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
218 * @param all_elements the set of all elements (Atom instances need not be included)
220 * In principle these two steps could be merged, but they
221 * are written separately to highlight these two facts:
223 * <li> Non-atom elements either match all-or-nothing, and do not overlap
224 * with each other (at least not in the sense of which element corresponds
225 * to the last reduction performed). Therefore, in order to make sure we
226 * wind up with the smallest number of states and shifts, we wait until
227 * we've figured out all the token-to-position multimappings before creating
230 * <li> In order to be able to run the state-construction algorithm in a single
231 * shot (rather than repeating until no new items appear in any state set),
232 * we need to use the "yields" semantics rather than the "produces" semantics
233 * for non-Atom Elements.
236 public State(HashSet<Position> hs) { this(hs, false); }
237 public boolean doomed;
238 public State(HashSet<Position> hs, boolean doomed) {
240 this.doomed = doomed;
242 // register ourselves in the all_states hash so that no
243 // two states are ever created with an identical position set
244 ((HashMap)(doomed ? doomed_states : normal_states)).put(hs, this);
245 ((HashSet)all_states).add(this);
247 for(Position p : hs) {
248 if (!p.isFirst()) continue;
249 for(Sequence s : p.owner().needs()) {
250 if (hs.contains(s.firstp())) continue;
251 HashSet<Position> h2 = new HashSet<Position>();
252 reachable(s.firstp(), h2);
253 also.add(mkstate(h2, true));
255 for(Sequence s : p.owner().hates()) {
256 if (hs.contains(s.firstp())) continue;
257 HashSet<Position> h2 = new HashSet<Position>();
259 also.add(mkstate(h2, true));
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);
274 bag0.addAll(a.getTokenTopology(), 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 ((TopologicalBag)gotoSetTerminals).put(r, mkstate(h, doomed));
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 HashMapBag<SequenceOrElement,Position> move = new HashMapBag<SequenceOrElement,Position>();
296 for(Position p : hs) {
297 Element e = p.element();
298 if (e==null) continue;
299 for(SequenceOrElement y : cache.ys2.getAll(e)) {
300 //System.out.println(e + " yields " + y);
301 HashSet<Position> hp = new HashSet<Position>();
302 reachable(p.next(), hp);
306 OUTER: for(SequenceOrElement y : move) {
307 HashSet<Position> h = move.getAll(y);
308 State<Token> s = mkstate(h, doomed);
309 // if a reduction is "lame", it should wind up in the dead_state after reducing
310 if (y instanceof Sequence) {
311 for(Position p : hs) {
312 if (p.element() != null && (p.element() instanceof Union)) {
313 Union u = (Union)p.element();
314 for(Sequence seq : u)
315 if (seq.needs.contains((Sequence)y) || seq.hates.contains((Sequence)y)) {
316 // FIXME: what if there are two "routes" to get to the sequence?
317 ((HashMap)gotoSetNonTerminals).put((Sequence)y, dead_state);
322 gotoSetNonTerminals.put((Sequence)y, s);
327 private State<Token> mkstate(HashSet<Position> h, boolean b) {
328 if (b) return doomed_states.get(h) == null ? (State)new State<Token>(h,b) : (State)doomed_states.get(h);
329 else return normal_states.get(h) == null ? (State)new State<Token>(h,b) : (State)normal_states.get(h);
332 public String toStringx() {
333 StringBuffer st = new StringBuffer();
334 for(Position p : this) {
335 if (st.length() > 0) st.append("\n");
338 return st.toString();
340 public String toString() {
341 StringBuffer ret = new StringBuffer();
342 ret.append("state["+idx+"]: ");
343 for(Position p : this) ret.append("{"+p+"} ");
344 return ret.toString();
347 public Walk.Cache cache() { return cache; }
348 public int toInt() { return idx; }
352 // Helpers //////////////////////////////////////////////////////////////////////////////
354 private static void reachable(Sequence s, HashSet<Position> h) {
355 reachable(s.firstp(), h);
356 //for(Sequence ss : s.needs()) reachable(ss, h);
357 //for(Sequence ss : s.hates()) reachable(ss, h);
359 private static void reachable(Element e, HashSet<Position> h) {
360 if (e instanceof Atom) return;
361 for(Sequence s : ((Union)e))
364 private static void reachable(Position p, HashSet<Position> h) {
365 if (h.contains(p)) return;
367 if (p.element() != null) reachable(p.element(), h);