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 streams of Tokens of type T into a Forest<R> */
9 public abstract class Parser<Tok, Result> {
11 protected final Table<Tok> pt;
13 /** create a parser to parse the grammar with start symbol <tt>u</tt> */
14 protected Parser(Union u, Topology<Tok> top) { this.pt = new Table<Tok>(u, top); }
15 protected Parser(Table<Tok> pt) { this.pt = pt; }
17 /** implement this method to create the output forest corresponding to a lone shifted input token */
18 public abstract Forest<Result> shiftToken(Tok t, Input.Location loc);
20 /** parse <tt>input</tt>, using the table <tt>pt</tt> to drive the parser */
21 public Forest<Result> parse(Input<Tok> input) throws IOException, ParseFailed {
23 Input.Location loc = input.getLocation();
24 GSS.Phase current = gss.new Phase<Tok>(null, this, null, input.next(1, 0, 0), loc, null);
25 current.newNode(null, Forest.leaf(null, null), pt.start, true);
28 loc = input.getLocation();
30 Forest forest = current.token==null ? null : shiftToken((Tok)current.token, loc);
31 GSS.Phase next = gss.new Phase<Tok>(current, this, current, input.next(count, gss.resets, gss.waits), loc, forest);
33 if (current.isDone()) return (Forest<Result>)gss.finalResult;
38 // Table //////////////////////////////////////////////////////////////////////////////
40 /** an SLR(1) parse table which may contain conflicts */
41 public static class Table<Tok> extends Walk.Cache {
43 public final Walk.Cache cache = this;
45 private void walk(Element e, HashSet<Element> hs) {
47 if (hs.contains(e)) return;
49 if (e instanceof Atom) return;
50 for(Sequence s : (Union)e) {
52 for(Position p = s.firstp(); p != null; p = p.next())
53 walk(p.element(), hs);
57 /** the start state */
58 public final State<Tok> start;
60 /** used to generate unique values for State.idx */
61 private int master_state_idx = 0;
62 HashMap<HashSet<Position>,State<Tok>> all_states = new HashMap<HashSet<Position>,State<Tok>>();
64 /** construct a parse table for the given grammar */
65 public Table(Topology top) { this("s", top); }
66 public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
67 public Table(Union ux, Topology top) {
68 Union start0 = new Union("0");
69 start0.add(new Sequence.Singleton(ux));
71 for(Sequence s : start0) cache.eof.put(s, true);
72 cache.eof.put(start0, true);
74 // construct the set of states
75 HashSet<Element> all_elements = new HashSet<Element>();
76 walk(start0, all_elements);
77 for(Element e : all_elements)
78 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
79 HashSet<Position> hp = new HashSet<Position>();
80 reachable(start0, hp);
81 this.start = new State<Tok>(hp, all_states, all_elements);
83 // for each state, fill in the corresponding "row" of the parse table
84 for(State<Tok> state : all_states.values())
85 for(Position p : state.hs) {
87 // the Grammar's designated "last position" is the only accepting state
88 if (start0.contains(p.owner()) && p.next()==null)
91 if (isRightNullable(p)) {
92 Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
93 Topology follow = wf.walk(p.owner());
94 for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next())
95 follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
96 state.reductions.put(follow, p);
97 if (wf.includesEof()) state.eofReductions.add(p);
100 // if the element following this position is an atom, copy the corresponding
101 // set of rows out of the "master" goto table and into this state's shift table
102 if (p.element() != null && p.element() instanceof Atom)
103 state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
105 if (top instanceof IntegerTopology)
106 for(State<Tok> state : all_states.values()) {
107 state.oreductions = state.reductions.optimize(((IntegerTopology)top).functor());
108 state.oshifts = state.shifts.optimize(((IntegerTopology)top).functor());
112 private boolean isRightNullable(Position p) {
113 if (p.isLast()) return true;
114 if (!p.element().possiblyEpsilon(this)) return false;
115 return isRightNullable(p.next());
118 /** a single state in the LR table and the transitions possible from it */
120 public class State<Tok> implements Comparable<State<Tok>>, IntegerMappable, Iterable<Position> {
122 public final int idx = master_state_idx++;
123 private final HashSet<Position> hs;
125 public transient HashMap<Element,State<Tok>> gotoSetNonTerminals = new HashMap<Element,State<Tok>>();
126 private transient TopologicalBag<Tok,State<Tok>> gotoSetTerminals = new TopologicalBag<Tok,State<Tok>>();
128 private TopologicalBag<Tok,Position> reductions = new TopologicalBag<Tok,Position>();
129 private HashSet<Position> eofReductions = new HashSet<Position>();
130 private TopologicalBag<Tok,State<Tok>> shifts = new TopologicalBag<Tok,State<Tok>>();
131 private boolean accept = false;
133 private VisitableMap<Tok,State<Tok>> oshifts = null;
134 private VisitableMap<Tok,Position> oreductions = null;
136 // Interface Methods //////////////////////////////////////////////////////////////////////////////
138 boolean isAccepting() { return accept; }
139 public Iterator<Position> iterator() { return hs.iterator(); }
141 boolean canShift(Tok t) { return oshifts.contains(t); }
142 <B,C> void invokeShifts(Tok t, Invokable<State<Tok>,B,C> irbc, B b, C c) {
143 oshifts.invoke(t, irbc, b, c);
146 boolean canReduce(Tok t) { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
147 <B,C> void invokeReductions(Tok t, Invokable<Position,B,C> irbc, B b, C c) {
148 if (t==null) for(Position r : eofReductions) irbc.invoke(r, b, c);
149 else oreductions.invoke(t, irbc, b, c);
152 // Constructor //////////////////////////////////////////////////////////////////////////////
155 * create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
156 * @param hs the set of <tt>Position</tt>s comprising this <tt>State</tt>
157 * @param all_states the set of states already constructed (to avoid recreating states)
158 * @param all_elements the set of all elements (Atom instances need not be included)
160 * In principle these two steps could be merged, but they
161 * are written separately to highlight these two facts:
163 * <li> Non-atom elements either match all-or-nothing, and do not overlap
164 * with each other (at least not in the sense of which element corresponds
165 * to the last reduction performed). Therefore, in order to make sure we
166 * wind up with the smallest number of states and shifts, we wait until
167 * we've figured out all the token-to-position multimappings before creating
170 * <li> In order to be able to run the state-construction algorithm in a single
171 * shot (rather than repeating until no new items appear in any state set),
172 * we need to use the "yields" semantics rather than the "produces" semantics
173 * for non-Atom Elements.
176 public State(HashSet<Position> hs,
177 HashMap<HashSet<Position>,State<Tok>> all_states,
178 HashSet<Element> all_elements) {
181 // register ourselves in the all_states hash so that no
182 // two states are ever created with an identical position set
183 all_states.put(hs, this);
185 // Step 1a: examine all Position's in this state and compute the mappings from
186 // sets of follow tokens (tokens which could follow this position) to sets
187 // of _new_ positions (positions after shifting). These mappings are
188 // collectively known as the _closure_
190 TopologicalBag<Tok,Position> bag0 = new TopologicalBag<Tok,Position>();
191 for(Position position : hs) {
192 if (position.isLast() || !(position.element() instanceof Atom)) continue;
193 Atom a = (Atom)position.element();
194 HashSet<Position> hp = new HashSet<Position>();
195 reachable(position.next(), hp);
199 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
200 // set, add that character set to the goto table (with the State corresponding to the
201 // computed next-position set).
203 for(Topology<Tok> r : bag0) {
204 HashSet<Position> h = new HashSet<Position>();
205 for(Position p : bag0.getAll(r)) h.add(p);
206 gotoSetTerminals.put(r, all_states.get(h) == null ? new State<Tok>(h, all_states, all_elements) : all_states.get(h));
209 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
210 // compute the closure over every position in this set which is followed by a symbol
211 // which could yield the Element in question.
213 // "yields" [in one or more step] is used instead of "produces" [in exactly one step]
214 // to avoid having to iteratively construct our set of States as shown in most
215 // expositions of the algorithm (ie "keep doing XYZ until things stop changing").
216 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
217 for(Position p : hs) {
218 Element e = p.element();
219 if (e==null) continue;
220 for(Element y : cache.ys.getAll(e)) {
221 HashSet<Position> hp = new HashSet<Position>();
222 reachable(p.next(), hp);
226 for(Element y : move) {
227 HashSet<Position> h = move.getAll(y);
228 State<Tok> s = all_states.get(h) == null ? new State<Tok>(h, all_states, all_elements) : all_states.get(h);
229 gotoSetNonTerminals.put(y, s);
233 public String toString() {
234 StringBuffer ret = new StringBuffer();
235 ret.append("state["+idx+"]: ");
236 for(Position p : this) ret.append("{"+p+"} ");
237 return ret.toString();
240 public int compareTo(State<Tok> s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
241 public int toInt() { return idx; }
245 // Helpers //////////////////////////////////////////////////////////////////////////////
247 private static void reachable(Element e, HashSet<Position> h) {
248 if (e instanceof Atom) return;
249 for(Sequence s : ((Union)e))
250 reachable(s.firstp(), h);
252 private static void reachable(Position p, HashSet<Position> h) {
253 if (h.contains(p)) return;
255 if (p.element() != null) reachable(p.element(), h);