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> {
13 protected final Table<Token> pt;
15 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
16 public Parser(Union u, Topology<Token> top) { this.pt = new Table<Token>(u, top); }
17 Parser(Table<Token> pt) { this.pt = pt; }
19 /** implement this method to create the output forest corresponding to a lone shifted input token */
20 public abstract Forest<NodeType> shiftToken(Token t, Input.Location newloc);
22 boolean helpgc = true;
24 public String toString() { return pt.toString(); }
26 /** parse <tt>input</tt>, and return the shared packed parse forest (or throw an exception) */
27 public Forest<NodeType> parse(Input<Token> input) throws IOException, ParseFailed {
28 GSS gss = new GSS(input);
29 Input.Location loc = input.getLocation();
30 Token tok = input.next();
31 GSS.Phase current = gss.new Phase<Token>(null, null, tok, loc, input.getLocation(), null);
32 current.newNode(new Result(Forest.create(loc.createRegion(loc), null, null, false), null, null), pt.start, true);
34 for(int idx=0;;idx++) {
35 Input.Location oldloc = loc;
37 Forest forest = current.token==null ? null : shiftToken((Token)current.token, loc);
38 loc = input.getLocation();
39 Token nextToken = input.next();
40 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();
46 ((Node)n).toGraphViz(gv);
52 if (current.isDone()) return (Forest<NodeType>)gss.finalResult;
57 // Table //////////////////////////////////////////////////////////////////////////////
59 /** an SLR(1) parse table which may contain conflicts */
60 static class Table<Token> extends Walk.Cache {
62 public String toString() {
63 StringBuffer sb = new StringBuffer();
64 sb.append("parse table");
65 for(State<Token> state : all_states.values()) {
66 sb.append(" " + state + "\n");
67 for(Topology<Token> t : state.shifts) {
68 sb.append(" shift \""+
69 new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => ");
70 for(State st : state.shifts.getAll(t))
71 sb.append(st.idx+" ");
74 for(Topology<Token> t : state.reductions)
75 sb.append(" reduce \""+
76 new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => " +
77 state.reductions.getAll(t) + "\n");
82 public final Walk.Cache cache = this;
84 private void walk(Element e, HashSet<SequenceOrElement> hs) {
86 if (hs.contains(e)) return;
88 if (e instanceof Atom) return;
89 for(Sequence s : (Union)e)
92 private void walk(Sequence s, HashSet<SequenceOrElement> hs) {
94 for(Position p = s.firstp(); p != null; p = p.next())
95 walk(p.element(), hs);
96 for(Sequence ss : s.needs()) walk(ss, hs);
97 for(Sequence ss : s.hates()) walk(ss, hs);
100 /** the start state */
101 public final State<Token> start;
103 /** the state from which no reductions can be done */
104 private final State<Token> dead_state;
106 /** used to generate unique values for State.idx */
107 private int master_state_idx = 0;
108 HashMap<HashSet<Position>,State<Token>> all_states = new HashMap<HashSet<Position>,State<Token>>();
109 HashSet<SequenceOrElement> all_elements = new HashSet<SequenceOrElement>();
111 /** construct a parse table for the given grammar */
112 public Table(Topology top) { this("s", top); }
113 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
114 public Table(Union ux, Topology top) {
115 Union start0 = new Union("0");
116 start0.add(new Sequence.Singleton(ux));
118 for(Sequence s : start0) cache.eof.put(s, true);
119 cache.eof.put(start0, true);
121 // construct the set of states
122 walk(start0, all_elements);
123 for(SequenceOrElement e : all_elements)
124 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
125 for(SequenceOrElement e : all_elements)
126 cache.ys2.addAll(e, new Walk.YieldSet2(e, cache).walk());
127 HashSet<Position> hp = new HashSet<Position>();
128 reachable(start0, hp);
130 this.dead_state = new State<Token>(new HashSet<Position>());
131 this.start = new State<Token>(hp);
133 // for each state, fill in the corresponding "row" of the parse table
134 for(State<Token> state : all_states.values())
135 for(Position p : state.hs) {
137 // the Grammar's designated "last position" is the only accepting state
138 if (start0.contains(p.owner()) && p.next()==null)
141 if (isRightNullable(p)) {
142 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
143 Topology follow = wf.walk(p.owner());
144 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next()) {
145 Atom set = new Walk.EpsilonFollowSet(new edu.berkeley.sbp.chr.CharAtom(top.empty().complement()),
146 new edu.berkeley.sbp.chr.CharAtom(top.empty()),
147 cache).walk(p2.element());
148 follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
149 if (set != null) follow = follow.intersect(set.getTokenTopology());
151 state.reductions.put(follow, p);
152 if (wf.includesEof()) state.eofReductions.add(p);
155 // if the element following this position is an atom, copy the corresponding
156 // set of rows out of the "master" goto table and into this state's shift table
157 if (p.element() != null && p.element() instanceof Atom)
158 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).getTokenTopology()));
160 if (top instanceof IntegerTopology)
161 for(State<Token> state : all_states.values()) {
162 state.oreductions = state.reductions.optimize(((IntegerTopology)top).functor());
163 state.oshifts = state.shifts.optimize(((IntegerTopology)top).functor());
167 private boolean isRightNullable(Position p) {
168 if (p.isLast()) return true;
169 if (!possiblyEpsilon(p.element())) return false;
170 return isRightNullable(p.next());
173 /** a single state in the LR table and the transitions possible from it */
175 class State<Token> implements IntegerMappable, Iterable<Position> {
177 public final int idx = master_state_idx++;
178 private final HashSet<Position> hs;
179 public HashSet<State<Token>> also = new HashSet<State<Token>>();
181 public transient HashMap<Sequence,State<Token>> gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
182 private transient TopologicalBag<Token,State<Token>> gotoSetTerminals = new TopologicalBag<Token,State<Token>>();
184 private TopologicalBag<Token,Position> reductions = new TopologicalBag<Token,Position>();
185 private HashSet<Position> eofReductions = new HashSet<Position>();
186 private TopologicalBag<Token,State<Token>> shifts = new TopologicalBag<Token,State<Token>>();
187 private boolean accept = false;
189 private VisitableMap<Token,State<Token>> oshifts = null;
190 private VisitableMap<Token,Position> oreductions = null;
192 // Interface Methods //////////////////////////////////////////////////////////////////////////////
194 boolean isAccepting() { return accept; }
195 public Iterator<Position> iterator() { return hs.iterator(); }
197 boolean canShift(Token t) { return oshifts!=null && oshifts.contains(t); }
198 <B,C> void invokeShifts(Token t, Invokable<State<Token>,B,C> irbc, B b, C c) {
199 oshifts.invoke(t, irbc, b, c);
202 boolean canReduce(Token t) { return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
203 <B,C> void invokeReductions(Token t, Invokable<Position,B,C> irbc, B b, C c) {
204 if (t==null) for(Position r : eofReductions) irbc.invoke(r, b, c);
205 else oreductions.invoke(t, irbc, b, c);
208 // Constructor //////////////////////////////////////////////////////////////////////////////
211 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
212 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
213 * @param all_elements the set of all elements (Atom instances need not be included)
215 * In principle these two steps could be merged, but they
216 * are written separately to highlight these two facts:
218 * <li> Non-atom elements either match all-or-nothing, and do not overlap
219 * with each other (at least not in the sense of which element corresponds
220 * to the last reduction performed). Therefore, in order to make sure we
221 * wind up with the smallest number of states and shifts, we wait until
222 * we've figured out all the token-to-position multimappings before creating
225 * <li> In order to be able to run the state-construction algorithm in a single
226 * shot (rather than repeating until no new items appear in any state set),
227 * we need to use the "yields" semantics rather than the "produces" semantics
228 * for non-Atom Elements.
231 public State(HashSet<Position> hs) { this(hs, false); }
232 public boolean special;
233 public State(HashSet<Position> hs, boolean special) {
235 this.special = special;
237 // register ourselves in the all_states hash so that no
238 // two states are ever created with an identical position set
239 ((HashMap)all_states).put(hs, this);
241 for(Position p : hs) {
242 if (!p.isFirst()) continue;
243 for(Sequence s : p.owner().needs()) {
244 if (hs.contains(s.firstp())) continue;
245 HashSet<Position> h2 = new HashSet<Position>();
246 reachable(s.firstp(), h2);
247 also.add((State<Token>)(all_states.get(h2) == null ? (State)new State<Token>(h2,true) : (State)all_states.get(h2)));
249 for(Sequence s : p.owner().hates()) {
250 if (hs.contains(s.firstp())) continue;
251 HashSet<Position> h2 = new HashSet<Position>();
253 also.add((State<Token>)(all_states.get(h2) == null ? (State)new State<Token>(h2,true) : (State)all_states.get(h2)));
257 // Step 1a: examine all Position's in this state and compute the mappings from
258 // sets of follow tokens (tokens which could follow this position) to sets
259 // of _new_ positions (positions after shifting). These mappings are
260 // collectively known as the _closure_
262 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
263 for(Position position : hs) {
264 if (position.isLast() || !(position.element() instanceof Atom)) continue;
265 Atom a = (Atom)position.element();
266 HashSet<Position> hp = new HashSet<Position>();
267 reachable(position.next(), hp);
268 bag0.addAll(a.getTokenTopology(), hp);
271 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
272 // set, add that character set to the goto table (with the State corresponding to the
273 // computed next-position set).
275 for(Topology<Token> r : bag0) {
276 HashSet<Position> h = new HashSet<Position>();
277 for(Position p : bag0.getAll(r)) h.add(p);
278 ((TopologicalBag)gotoSetTerminals).put(r, all_states.get(h) == null
279 ? new State<Token>(h) : all_states.get(h));
282 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
283 // compute the closure over every position in this set which is followed by a symbol
284 // which could yield the Element in question.
286 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
287 // to avoid having to iteratively construct our set of States as shown in most
288 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
290 HashMapBag<SequenceOrElement,Position> move = new HashMapBag<SequenceOrElement,Position>();
291 for(Position p : hs) {
292 Element e = p.element();
293 if (e==null) continue;
294 for(SequenceOrElement y : cache.ys2.getAll(e)) {
295 //System.out.println(e + " yields " + y);
296 HashSet<Position> hp = new HashSet<Position>();
297 reachable(p.next(), hp);
301 OUTER: for(SequenceOrElement y : move) {
302 HashSet<Position> h = move.getAll(y);
303 State<Token> s = all_states.get(h) == null ? (State)new State<Token>(h) : (State)all_states.get(h);
304 // if a reduction is "lame", it should wind up in the dead_state after reducing
305 if (y instanceof Sequence) {
306 for(Position p : hs) {
307 if (p.element() != null && (p.element() instanceof Union)) {
308 Union u = (Union)p.element();
309 for(Sequence seq : u)
310 if (seq.needs.contains((Sequence)y) || seq.hates.contains((Sequence)y)) {
311 // FIXME: what if there are two "routes" to get to the sequence?
312 ((HashMap)gotoSetNonTerminals).put((Sequence)y, dead_state);
317 gotoSetNonTerminals.put((Sequence)y, s);
322 public String toStringx() {
323 StringBuffer st = new StringBuffer();
324 for(Position p : this) {
325 if (st.length() > 0) st.append("\n");
328 return st.toString();
330 public String toString() {
331 StringBuffer ret = new StringBuffer();
332 ret.append("state["+idx+"]: ");
333 for(Position p : this) ret.append("{"+p+"} ");
334 return ret.toString();
337 public Walk.Cache cache() { return cache; }
338 public int toInt() { return idx; }
342 // Helpers //////////////////////////////////////////////////////////////////////////////
344 private static void reachable(Sequence s, HashSet<Position> h) {
345 reachable(s.firstp(), h);
346 //for(Sequence ss : s.needs()) reachable(ss, h);
347 //for(Sequence ss : s.hates()) reachable(ss, h);
349 private static void reachable(Element e, HashSet<Position> h) {
350 if (e instanceof Atom) return;
351 for(Sequence s : ((Union)e))
354 private static void reachable(Position p, HashSet<Position> h) {
355 if (h.contains(p)) return;
357 if (p.element() != null) reachable(p.element(), h);