1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.Parser.Table.*;
5 import edu.berkeley.sbp.Sequence.Position;
8 import java.lang.reflect.*;
10 /** implements Tomita's Graph Structured Stack */
13 public static int count = 0;
16 private Phase.Node[] reducing_list = null;
17 public int resets = 0;
20 HashMapBag<Integer,Sequence> inhibited = new HashMapBag<Integer,Sequence>();
21 HashMapBag<Integer,Sequence> expectedInhibit = new HashMapBag<Integer,Sequence>();
22 HashMapBag<Sequence,Phase.Waiting> waiting = new HashMapBag<Sequence,Phase.Waiting>();
23 HashMapBag<Integer,Sequence> performed = new HashMapBag<Integer,Sequence>();
24 HashMapBag<Integer,Sequence> lastperformed = new HashMapBag<Integer,Sequence>();
27 public Forest.Ref finalResult;
29 /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
30 class Phase<Tok> implements Invokable<State, Forest, Phase<Tok>.Node>, IntegerMappable {
32 public void invoke(State st, Forest result, Node n) {
33 good |= next.newNode(n, result, st, false);
36 /** the token immediately after this phase */
39 private final int pos;
42 private IntPairMap<Phase.Node> hash; /* ALLOC */
43 private IntPairMap<Forest> singularReductions; /* ALLOC */
44 private boolean closed;
46 private Phase next = null;
48 private Input.Location location;
49 public final Parser parser;
51 private Forest forest;
53 public Phase(Phase prev, Parser parser, Phase previous, Tok token, Input.Location location, Forest forest) throws ParseFailed {
57 this.pos = previous==null ? 0 : previous.pos+1;
59 this.location = location;
64 public void reset() throws ParseFailed {
66 lastperformed.clear();
67 lastperformed.addAll(performed);
69 hash = new IntPairMap<Phase.Node>();
70 singularReductions = new IntPairMap<Forest>();
71 expectedInhibit.clear();
72 expectedInhibit.addAll(inhibited);
78 if (prev != null) prev.shift(this, forest);
82 public boolean isDone() throws ParseFailed {
83 if (token != null) return false;
84 if (token==null && finalResult==null)
85 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()), getLocation());
89 public Input.Location getLocation() { return location; }
91 /** add a new node (merging with existing nodes if possible)
92 * @param parent the parent of the new node
93 * @param result the SPPF result corresponding to the new node
94 * @param state the state that the new node is in
95 * @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
96 * @param start the earliest part of the input contributing to this node (used to make merging decisions)
98 public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
99 Node p = hash.get(state, parent==null?null:parent.phase());
100 if (p != null) return newNode2(p, parent, pending, state, fromEmptyReduction);
101 else return newNode3(parent, pending, state, fromEmptyReduction);
103 public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
104 int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
105 Sequence owner = reduction==null ? null : reduction.owner();
106 if (reduction!=null) {
107 if (owner.hates!=null) {
108 for (Sequence s : lastperformed.getAll(pos))
109 if (owner.hates.contains(s))
111 for (Sequence s : performed.getAll(pos))
112 if (owner.hates.contains(s))
115 if (inhibited.contains(pos, owner)) return;
116 if (owner.needs != null)
117 for(Sequence s : owner.needs)
118 if (!performed.contains(pos, s)) {
119 waiting.add(s, new Waiting(parent, pending, state, fromEmptyReduction, reduction));
123 if ((owner.needed != null && owner.needed.size()>0) ||
124 (owner.hated != null && owner.hated.size()>0) ||
125 (owner.hates != null && owner.hates.size()>0))
126 performed.add(pos, owner);
129 if (reduction!=null) uninhibit(reduction, parent==null?0:parent.phase().pos);
131 newNode(parent, pending, state, fromEmptyReduction);
132 if (reduction != null) {
136 for(Waiting w : waiting.getAll(owner)) {
137 if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
138 waiting.remove(owner, w);
147 private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
148 p.holder.merge(pending);
149 if (p.parents().contains(parent)) return true;
150 p.parents().add(parent, true);
151 if (p!=parent && !fromEmptyReduction && reducing) p.performReductions(parent);
154 private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
156 if (token != null && state.canShift(token)) break;
157 if (state.isAccepting()) break;
158 if (token==null) break;
159 if (!state.canReduce(token)) return false;
160 //if (count > 1) break;
161 //if (r.numPop == 0) break;
162 //r.reduce(pending, parent, null, Phase.this, null);
166 Node n = new Node(parent, pending, state); // ALLOC
168 n.performEmptyReductions();
169 if (!fromEmptyReduction) n.performReductions(parent);
174 public void inhibit(int p, Sequence s) {
175 //if (inhibited.contains(p, s)) return;
176 if (performed.contains(p, s)) throw new Reset();
179 for(Sequence s2 : s.hated)
183 for(Sequence s2 : s.needed)
184 if (performed.contains(p, s2))
186 if (performed.contains(p, s)) throw new Reset();
189 public void uninhibit(Position r, int p) { uninhibit(p, r.owner()); }
190 public void uninhibit(int p, Sequence s) {
191 if (performed.contains(p, s)) return;
194 for(Sequence seq : s.hated)
198 /** perform all reduction operations */
199 public void reduce() throws ParseFailed {
202 if (reducing_list==null || reducing_list.length < hash.size())
203 reducing_list = new Phase.Node[hash.size() * 4];
204 hash.toArray(reducing_list);
205 int num = hash.size();
206 for(int i=0; i<num; i++) {
207 Node n = reducing_list[i];
208 n.performEmptyReductions();
209 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
211 for(int i=0; i<num; i++) {
212 Node n = reducing_list[i];
213 reducing_list[i] = null;
214 n.performReductions();
217 if (expectedInhibit.size() > 0) {
218 System.out.println("\n!!!!");
219 for(int i : expectedInhibit)
220 for(Sequence es : expectedInhibit.getAll(i))
221 System.out.println(" " + i + ": " + es);
222 System.out.println("");
223 inhibited.removeAll(expectedInhibit);
239 private boolean reset = false;
240 class Reset extends RuntimeException { }
242 /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
243 public void shift(Phase next, Forest result) throws ParseFailed {
244 // this massively improves GC performance
247 prev.singularReductions = null;
253 for(Phase.Node n : hash.values()) {
254 if (token == null && n.state.isAccepting()) {
255 if (finalResult==null) finalResult = new Forest.Ref();
256 finalResult.merge(n.holder);
258 if (token == null) continue;
259 n.state.invokeShifts(token, this, result, n);
262 if (!good && token!=null)
263 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected character ")+" \'"+
264 ANSI.purple(StringUtil.escapify(token+"", "\\\'\r\n"))+
265 "\' encountered at "+
266 ANSI.green(getLocation())+"\n", token, hash.values()),
268 if (token==null && finalResult==null)
269 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()),
278 boolean fromEmptyReduction;
280 public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
282 this.parent = parent;
283 this.pending = pending;
285 this.fromEmptyReduction = fromEmptyReduction;
286 this.reduction = reduction;
288 public void perform() {
289 //System.out.println("performing: " + reduction.position);
290 newNode(parent, pending, state, fromEmptyReduction, reduction);
294 // Node /////////////////////////////////////////////////////////////////////////////////
296 /** a node in the GSS */
297 final class Node extends FastSet<Node> implements Invokable<Position, Node, Node>, IntegerMappable {
299 private Forest.Ref holder = null;
300 private boolean allqueued = false;
302 /** what state this node is in */
303 public final Parser.Table<Tok>.State<Tok> state;
305 /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
306 public Phase phase() { return Phase.this; }
307 public Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
308 public Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
309 public FastSet<Node> parents() { return this; }
311 public void performReductions() {
312 if (allqueued) return;
314 state.invokeReductions(token, this, this, null);
317 public void performReductions(Node n2) {
318 if (!allqueued) performReductions();
319 else state.invokeReductions(token, this, this, n2);
322 public void performEmptyReductions() { state.invokeReductions(token, this, null, null); }
323 public final void invoke(Position r, Node n, Node n2) {
324 if (n==null || n2==null || r.pos==0) {
326 if (n==null) n = this;
330 Forest[] holder = new Forest[r.pos];
331 if (r.pos==0) n.finish(r, r.zero(), n.phase(), holder);
332 else n.reduce(r, r.pos-1, n.phase(), holder);
334 Forest[] holder = new Forest[r.pos];
335 if (r.pos<=0) throw new Error("called wrong form of reduce()");
337 n.reduce(r, pos, n.phase(), holder, n2);
341 public void reduce(Position r, int pos, Phase target, Forest[] holder) { reduce(r, pos, target, holder, null); }
342 public void reduce(Position r, int pos, Phase target, Forest[] holder, Node only) {
343 Forest old = holder[pos];
344 holder[pos] = this.pending();
346 System.arraycopy(holder, 0, r.holder, 0, holder.length);
347 for(int i=0; i<r.pos; i++) if (r.holder[i]==null) throw new Error("realbad");
350 // FIXME: I'm unsure about this -- basically we want to deal with the case where
351 // there are two nodes, each of whose Ref points to the same Forest instance.
352 // Some node in the next phase has both of these as parents. This might happen
353 // since the same reduction can appear in more than one state.
354 if (r.pos==1) rex = singularReductions.get(this.pending(), r);
356 rex = r.rewrite(phase().getLocation());
357 if (r.pos==1) singularReductions.put(this.pending(), r, rex);
359 if (only != null) only.finish(r, rex, target, holder);
360 else for(Node child : this.parents()) child.finish(r, rex, target, holder);
362 if (only != null) only.reduce(r, pos-1, target, holder);
363 else for(Node child : this.parents()) child.reduce(r, pos-1, target, holder);
368 public void finish(Position r, Forest result, Phase<Tok> target, Forest[] holder) {
369 Parser.Table<Tok>.State<Tok> state0 = state.gotoSetNonTerminals.get(r.owner());
370 if (result==null) throw new Error();
372 target.newNode(this, result, state0, r.pos<=0, r);
375 private Node(Node parent, Forest pending, State state) {
377 this.holder().merge(pending);
378 Phase start = parent==null ? null : parent.phase();
379 if (parent != null) parents().add(parent, true);
380 if (Phase.this.hash.get(state, start) != null) throw new Error("severe problem!");
381 Phase.this.hash.put(state, start, this);
383 public int toInt() { return idx; }
384 private final int idx = node_idx++;
386 private int node_idx = 0;
388 public int toInt() { return pos+1; }
389 public int size() { return hash==null ? 0 : hash.size(); }