1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.Sequence.Position;
8 /** a parser which translates an Input<Token> into a Forest<NodeType> */
9 public abstract class Parser<Token, NodeType> {
11 protected final Table<Token> pt;
13 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
14 protected Parser(Union u, Topology<Token> top) { this.pt = new Table<Token>(u, top); }
15 protected Parser(Table<Token> pt) { this.pt = pt; }
17 /** implement this method to create the output forest corresponding to a lone shifted input token */
18 protected abstract Forest<NodeType> shiftToken(Token t, Input.Location newloc);
20 boolean helpgc = true;
22 public String toString() { return pt.toString(); }
24 /** parse <tt>input</tt>, and return the shared packed parse forest (or throw an exception) */
25 public Forest<NodeType> parse(Input<Token> input) throws IOException, ParseFailed {
27 Input.Location loc = input.getLocation();
28 Token tok = input.next();
29 GSS.Phase current = gss.new Phase<Token>(null, this, null, tok, loc, input.getLocation(), null);
30 current.newNode(null, Forest.create(null, null, null, false), pt.start, true);
32 for(int idx=0;;idx++) {
33 Input.Location oldloc = loc;
35 Forest forest = current.token==null ? null : shiftToken((Token)current.token, loc);
36 loc = input.getLocation();
37 Token nextToken = input.next();
38 GSS.Phase next = gss.new Phase<Token>(current, this, current, nextToken, loc, input.getLocation(), forest);
40 FileOutputStream fos = new FileOutputStream("out-"+idx+".dot");
41 PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
42 GraphViz gv = new GraphViz();
44 ((GSS.Phase.Node)n).toGraphViz(gv);
50 if (current.isDone()) return (Forest<NodeType>)gss.finalResult;
55 // Table //////////////////////////////////////////////////////////////////////////////
57 /** an SLR(1) parse table which may contain conflicts */
58 static class Table<Token> extends Walk.Cache {
60 public String toString() {
61 StringBuffer sb = new StringBuffer();
62 sb.append("parse table");
63 for(State<Token> state : all_states.values()) {
64 sb.append(" " + state + "\n");
65 for(Topology<Token> t : state.shifts) {
66 sb.append(" shift \""+
67 new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => ");
68 for(State st : state.shifts.getAll(t))
69 sb.append(st.idx+" ");
72 for(Topology<Token> t : state.reductions)
73 sb.append(" reduce \""+
74 new edu.berkeley.sbp.chr.CharTopology((IntegerTopology<Character>)t)+"\" => " +
75 state.reductions.getAll(t) + "\n");
80 public final Walk.Cache cache = this;
82 private void walk(Element e, HashSet<SequenceOrElement> hs) {
84 if (hs.contains(e)) return;
86 if (e instanceof Atom) return;
87 for(Sequence s : (Union)e)
90 private void walk(Sequence s, HashSet<SequenceOrElement> hs) {
92 for(Position p = s.firstp(); p != null; p = p.next())
93 walk(p.element(), hs);
94 for(Sequence ss : s.needs()) walk(ss, hs);
95 for(Sequence ss : s.hates()) walk(ss, hs);
98 /** the start state */
99 public final State<Token> start;
101 /** the state from which no reductions can be done */
102 private final State<Token> dead_state;
104 /** used to generate unique values for State.idx */
105 private int master_state_idx = 0;
106 HashMap<HashSet<Position>,State<Token>> all_states = new HashMap<HashSet<Position>,State<Token>>();
108 /** construct a parse table for the given grammar */
109 public Table(Topology top) { this("s", top); }
110 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
111 public Table(Union ux, Topology top) {
112 Union start0 = new Union("0");
113 start0.add(new Sequence.Singleton(ux));
115 for(Sequence s : start0) cache.eof.put(s, true);
116 cache.eof.put(start0, true);
118 // construct the set of states
119 HashSet<SequenceOrElement> all_elements = new HashSet<SequenceOrElement>();
120 walk(start0, all_elements);
121 for(SequenceOrElement e : all_elements)
122 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
123 HashSet<Position> hp = new HashSet<Position>();
124 reachable(start0, hp);
126 this.dead_state = new State<Token>(new HashSet<Position>(), all_states, all_elements);
127 this.start = new State<Token>(hp, all_states, all_elements);
129 // for each state, fill in the corresponding "row" of the parse table
130 for(State<Token> state : all_states.values())
131 for(Position p : state.hs) {
133 // the Grammar's designated "last position" is the only accepting state
134 if (start0.contains(p.owner()) && p.next()==null)
137 if (isRightNullable(p)) {
138 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
139 Topology follow = wf.walk(p.owner());
140 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next())
141 follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
142 state.reductions.put(follow, p);
143 if (wf.includesEof()) state.eofReductions.add(p);
146 // if the element following this position is an atom, copy the corresponding
147 // set of rows out of the "master" goto table and into this state's shift table
148 if (p.element() != null && p.element() instanceof Atom)
149 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element()).getTokenTopology()));
151 if (top instanceof IntegerTopology)
152 for(State<Token> state : all_states.values()) {
153 state.oreductions = state.reductions.optimize(((IntegerTopology)top).functor());
154 state.oshifts = state.shifts.optimize(((IntegerTopology)top).functor());
158 private boolean isRightNullable(Position p) {
159 if (p.isLast()) return true;
160 if (!possiblyEpsilon(p.element())) return false;
161 return isRightNullable(p.next());
164 /** a single state in the LR table and the transitions possible from it */
166 class State<Token> implements Comparable<State<Token>>, IntegerMappable, Iterable<Position> {
168 public final int idx = master_state_idx++;
169 private final HashSet<Position> hs;
171 public transient HashMap<Sequence,State<Token>> gotoSetNonTerminals = new HashMap<Sequence,State<Token>>();
172 private transient TopologicalBag<Token,State<Token>> gotoSetTerminals = new TopologicalBag<Token,State<Token>>();
174 private TopologicalBag<Token,Position> reductions = new TopologicalBag<Token,Position>();
175 private HashSet<Position> eofReductions = new HashSet<Position>();
176 private TopologicalBag<Token,State<Token>> shifts = new TopologicalBag<Token,State<Token>>();
177 private boolean accept = false;
179 private VisitableMap<Token,State<Token>> oshifts = null;
180 private VisitableMap<Token,Position> oreductions = null;
182 // Interface Methods //////////////////////////////////////////////////////////////////////////////
184 boolean isAccepting() { return accept; }
185 public Iterator<Position> iterator() { return hs.iterator(); }
187 boolean canShift(Token t) { return oshifts!=null && oshifts.contains(t); }
188 <B,C> void invokeShifts(Token t, Invokable<State<Token>,B,C> irbc, B b, C c) {
189 oshifts.invoke(t, irbc, b, c);
192 boolean canReduce(Token t) { return oreductions != null && (t==null ? eofReductions.size()>0 : oreductions.contains(t)); }
193 <B,C> void invokeReductions(Token t, Invokable<Position,B,C> irbc, B b, C c) {
194 if (t==null) for(Position r : eofReductions) irbc.invoke(r, b, c);
195 else oreductions.invoke(t, irbc, b, c);
198 // Constructor //////////////////////////////////////////////////////////////////////////////
201 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
202 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
203 * @param all_states the set of states already constructed (to avoid recreating states)
204 * @param all_elements the set of all elements (Atom instances need not be included)
206 * In principle these two steps could be merged, but they
207 * are written separately to highlight these two facts:
209 * <li> Non-atom elements either match all-or-nothing, and do not overlap
210 * with each other (at least not in the sense of which element corresponds
211 * to the last reduction performed). Therefore, in order to make sure we
212 * wind up with the smallest number of states and shifts, we wait until
213 * we've figured out all the token-to-position multimappings before creating
216 * <li> In order to be able to run the state-construction algorithm in a single
217 * shot (rather than repeating until no new items appear in any state set),
218 * we need to use the "yields" semantics rather than the "produces" semantics
219 * for non-Atom Elements.
222 public State(HashSet<Position> hs,
223 HashMap<HashSet<Position>,State<Token>> all_states,
224 HashSet<SequenceOrElement> all_elements) {
227 // register ourselves in the all_states hash so that no
228 // two states are ever created with an identical position set
229 all_states.put(hs, this);
231 // Step 1a: examine all Position's in this state and compute the mappings from
232 // sets of follow tokens (tokens which could follow this position) to sets
233 // of _new_ positions (positions after shifting). These mappings are
234 // collectively known as the _closure_
236 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
237 for(Position position : hs) {
238 if (position.isLast() || !(position.element() instanceof Atom)) continue;
239 Atom a = (Atom)position.element();
240 HashSet<Position> hp = new HashSet<Position>();
241 reachable(position.next(), hp);
242 bag0.addAll(a.getTokenTopology(), hp);
245 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
246 // set, add that character set to the goto table (with the State corresponding to the
247 // computed next-position set).
249 for(Topology<Token> r : bag0) {
250 HashSet<Position> h = new HashSet<Position>();
251 for(Position p : bag0.getAll(r)) h.add(p);
252 gotoSetTerminals.put(r, all_states.get(h) == null ? new State<Token>(h, all_states, all_elements) : all_states.get(h));
255 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
256 // compute the closure over every position in this set which is followed by a symbol
257 // which could yield the Element in question.
259 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
260 // to avoid having to iteratively construct our set of States as shown in most
261 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
263 HashMapBag<SequenceOrElement,Position> move = new HashMapBag<SequenceOrElement,Position>();
264 for(Position p : hs) {
265 Element e = p.element();
266 if (e==null) continue;
267 for(SequenceOrElement y : cache.ys.getAll(e)) {
268 HashSet<Position> hp = new HashSet<Position>();
269 reachable(p.next(), hp);
273 OUTER: for(SequenceOrElement y : move) {
274 HashSet<Position> h = move.getAll(y);
275 State<Token> s = all_states.get(h) == null ? new State<Token>(h, all_states, all_elements) : all_states.get(h);
276 // if a reduction is "lame", it should wind up in the dead_state after reducing
277 if (y instanceof Sequence) {
278 for(Position p : hs) {
279 if (p.element() != null && (p.element() instanceof Union)) {
280 Union u = (Union)p.element();
281 for(Sequence seq : u)
282 if (seq.needs.contains((Sequence)y) || seq.hates.contains((Sequence)y)) {
283 // FIXME: what if there are two "routes" to get to the sequence?
284 ((HashMap)gotoSetNonTerminals).put((Sequence)y, dead_state);
289 gotoSetNonTerminals.put((Sequence)y, s);
294 public String toStringx() {
295 StringBuffer st = new StringBuffer();
296 for(Position p : this) {
297 if (st.length() > 0) st.append("\n");
300 return st.toString();
302 public String toString() {
303 StringBuffer ret = new StringBuffer();
304 ret.append("state["+idx+"]: ");
305 for(Position p : this) ret.append("{"+p+"} ");
306 return ret.toString();
309 public int compareTo(State<Token> s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
310 public int toInt() { return idx; }
314 // Helpers //////////////////////////////////////////////////////////////////////////////
316 private static void reachable(Sequence s, HashSet<Position> h) {
317 reachable(s.firstp(), h);
318 for(Sequence ss : s.needs()) reachable(ss, h);
319 for(Sequence ss : s.hates()) reachable(ss, h);
321 private static void reachable(Element e, HashSet<Position> h) {
322 if (e instanceof Atom) return;
323 for(Sequence s : ((Union)e))
326 private static void reachable(Position p, HashSet<Position> h) {
327 if (h.contains(p)) return;
329 if (p.element() != null) reachable(p.element(), h);