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;
17 private Phase.Node[] reducing_list = null;
18 public int resets = 0;
21 HashMapBag<Sequence,Phase.Waiting> waiting = new HashMapBag<Sequence,Phase.Waiting>();
22 HashMapBag<Integer,Sequence> performed = new HashMapBag<Integer,Sequence>();
23 HashMapBag<Integer,Sequence> lastperformed = new HashMapBag<Integer,Sequence>();
24 HashMapBag<Integer,Sequence> expected = 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, GraphViz.ToGraphViz, Iterable<Phase.Node> {
32 public Iterator<Phase.Node> iterator() { return hash.iterator(); }
33 public void invoke(State st, Forest result, Node n) {
34 good |= next.newNode(n, result, st, false);
37 /** the token immediately after this phase */
40 private final int pos;
43 private IntPairMap<Phase.Node> hash; /* 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 {
67 lastperformed.clear();
68 lastperformed.addAll(performed);
70 hash = new IntPairMap<Phase.Node>();
76 if (prev != null) prev.shift(this, forest);
80 public boolean isDone() throws ParseFailed {
81 if (token != null) return false;
82 if (token==null && finalResult==null)
83 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()), getLocation());
87 public Input.Location getLocation() { return location; }
89 /** add a new node (merging with existing nodes if possible)
90 * @param parent the parent of the new node
91 * @param result the SPPF result corresponding to the new node
92 * @param state the state that the new node is in
93 * @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
94 * @param start the earliest part of the input contributing to this node (used to make merging decisions)
96 public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
97 Node p = hash.get(state, parent==null?null:parent.phase());
98 if (p != null) return newNode2(p, parent, pending, state, fromEmptyReduction);
99 else return newNode3(parent, pending, state, fromEmptyReduction);
101 public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
102 int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
103 Sequence owner = reduction==null ? null : reduction.owner();
104 if (reduction!=null) {
105 if (owner.hates!=null) {
106 for (Sequence s : performed.getAll(pos))
107 if (owner.hates.contains(s))
109 for (Sequence s : lastperformed.getAll(pos))
110 if (owner.hates.contains(s)) {
111 //System.out.println("now expecting ["+pos+"] => " + s);
112 expected.add(pos, s);
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));
122 if (!performed.contains(pos, owner)) {
123 performed.add(pos, owner);
124 if (owner.hated != null)
125 for(Sequence seq : owner.hated)
126 if (performed.contains(pos, seq)) {
127 performed.remove(pos, seq);
133 newNode(parent, pending, state, fromEmptyReduction);
134 if (reduction != null) {
138 for(Waiting w : waiting.getAll(owner)) {
139 if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
140 waiting.remove(owner, w);
149 private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
150 //if (p.parents().contains(parent)) return true;
151 p.merge(parent, pending);
152 p.parents().add(parent, true);
153 if (p!=parent && !fromEmptyReduction && reducing) p.performReductions(parent);
156 private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
158 if (token != null && state.canShift(token)) break;
159 if (state.isAccepting()) break;
160 if (token==null) break;
161 if (!state.canReduce(token)) return false;
162 //if (count > 1) break;
163 //if (r.numPop == 0) break;
164 //r.reduce(pending, parent, null, Phase.this, null);
168 Node n = new Node(parent, pending, state); // ALLOC
170 n.performEmptyReductions();
171 if (!fromEmptyReduction) n.performReductions(parent);
176 /** perform all reduction operations */
177 public void reduce() throws ParseFailed {
180 if (reducing_list==null || reducing_list.length < hash.size())
181 reducing_list = new Phase.Node[hash.size() * 4];
182 hash.toArray(reducing_list);
183 int num = hash.size();
184 for(int i=0; i<num; i++) {
185 Node n = reducing_list[i];
186 n.performEmptyReductions();
187 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
189 for(int i=0; i<num; i++) {
190 Node n = reducing_list[i];
191 reducing_list[i] = null;
192 n.performReductions();
199 for(int i : expected)
200 for(Sequence s : expected.getAll(i))
201 if (!performed.contains(i, s)) {
202 //System.out.println("resetting due to pos="+i+": " + s + " " + System.identityHashCode(s));
213 private boolean reset = false;
214 class Reset extends RuntimeException { }
216 /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
217 public void shift(Phase next, Forest result) throws ParseFailed {
218 // this massively improves GC performance
219 if (prev!=null && parser.helpgc) {
226 for(Phase.Node n : hash.values()) {
227 if (token == null && n.state.isAccepting()) {
228 if (finalResult==null) finalResult = new Forest.Ref();
229 for(Object f : n.results())
230 finalResult.merge((Forest)f);
232 if (token == null) continue;
233 n.state.invokeShifts(token, this, result, n);
236 if (!good && token!=null)
237 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected character ")+" \'"+
238 ANSI.purple(StringUtil.escapify(token+"", "\\\'\r\n"))+
239 "\' encountered at "+
240 ANSI.green(getLocation())+"\n", token, hash.values()),
242 if (token==null && finalResult==null)
243 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()),
252 boolean fromEmptyReduction;
254 public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
256 this.parent = parent;
257 this.pending = pending;
259 this.fromEmptyReduction = fromEmptyReduction;
260 this.reduction = reduction;
262 public void perform() {
263 //System.out.println("performing: " + reduction.position);
264 newNode(parent, pending, state, fromEmptyReduction, reduction);
268 // Node /////////////////////////////////////////////////////////////////////////////////
270 /** a node in the GSS */
271 final class Node implements Invokable<Position, Node, Node>, IntegerMappable, GraphViz.ToGraphViz {
272 public FastSet<Node> set = new FastSet<Node>();
274 public GraphViz.Node toGraphViz(GraphViz gv) {
275 if (gv.hasNode(this)) return gv.createNode(this);
276 GraphViz.Node n = gv.createNode(this);
277 n.label = ""+state.toStringx();
278 n.shape = "rectangle";
280 //GraphViz.Node f = pending().toGraphViz(gv);
282 for(Forest result : results()) n.edge(result, "");
283 for(Node parent : parents()) n.edge(parent, "");
284 ((GraphViz.Group)phase().toGraphViz(gv)).add(n);
287 public boolean isTransparent() { return false; }
288 public boolean isHidden() { return false; }
291 //private Forest.Ref holder = new Forest.Ref();
292 private boolean allqueued = false;
294 /** what state this node is in */
295 public final Parser.Table<Tok>.State<Tok> state;
297 /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
298 public Phase phase() { return Phase.this; }
299 //private HashMap<Node,Forest> resultMap = new HashMap<Node,Forest>();
301 private HashSet<Forest.Ref> resultMap = new HashSet<Forest.Ref>();
302 public void merge(Node parent, Forest result) {
303 for(Forest.Ref f : results()) {
304 if (f.parents.contains(parent) && f.parents.size()==1) {
309 Forest.Ref f = new Forest.Ref();
310 f.parents.add(parent);
313 set.add(parent, true);
315 Forest.Ref f = (Forest.Ref)resultMap.get(parent);
316 if (f==null) { f = new Forest.Ref(); resultMap.put(parent, f); }
318 set.add(parent, true);
321 public Iterable<Forest.Ref> results() { return resultMap; }
322 //private Forest pending(Node n) {
323 //return !Phase.this.closed ? holder : holder.resolve();
325 for(Forest f : resultMap)
326 if (resultMap.contains(f, n))
331 return resultMap.get(n);
334 public FastSet<Node> parents() { return set; }
336 public void performReductions() {
337 if (allqueued) return;
339 state.invokeReductions(token, this, this, null);
342 public void performReductions(Node n2) {
343 if (!allqueued) performReductions();
344 else state.invokeReductions(token, this, this, n2);
347 public void performEmptyReductions() { state.invokeReductions(token, this, null, null); }
348 public final void invoke(Position r, Node n, Node n2) {
349 //if (r.owner().lame) return;
350 if (n==null || n2==null || r.pos==0) {
352 if (n==null) n = this;
356 Forest[] holder = new Forest[r.pos];
357 if (r.pos==0) n.finish(r, r.zero(), n.phase(), holder);
358 else n.reduce(r, r.pos-1, n.phase(), holder, null);
360 Forest[] holder = new Forest[r.pos];
361 if (r.pos<=0) throw new Error("called wrong form of reduce()");
363 n.reduce(r, pos, n.phase(), holder, n2);
367 public void reduce(Position r, int pos, Phase target, Forest[] holder, Node only) {
368 Forest old = holder[pos];
370 // FIXME: I'm unsure about this -- basically we want to deal with the case where
371 // there are two nodes, each of whose Ref points to the same Forest instance.
372 // Some node in the next phase has both of these as parents. This might happen
373 // since the same reduction can appear in more than one state.
375 for(Forest result : results())
376 for(Node child : ((Forest.Ref<?>)result).parents) {
377 if (only != null && child!=only) continue;
378 holder[pos] = result;
380 System.arraycopy(holder, 0, r.holder, 0, holder.length);
381 for(int i=0; i<r.pos; i++) if (r.holder[i]==null) throw new Error("realbad");
382 child.finish(r, r.rewrite(phase().getLocation()), target, holder);
384 child.reduce(r, pos-1, target, holder, null);
391 public void finish(Position r, Forest result, Phase<Tok> target, Forest[] holder) {
392 Parser.Table<Tok>.State<Tok> state0 = state.gotoSetNonTerminals.get(r.owner());
393 if (result==null) throw new Error();
395 target.newNode(this, result, state0, r.pos<=0, r);
398 private Node(Node parent, Forest pending, State state) {
400 this.merge(parent, pending);
401 Phase start = parent==null ? null : parent.phase();
402 if (parent != null) parents().add(parent, true);
403 if (Phase.this.hash.get(state, start) != null) throw new Error("severe problem!");
404 Phase.this.hash.put(state, start, this);
406 public int toInt() { return idx; }
407 private final int idx = node_idx++;
409 private int node_idx = 0;
411 public int toInt() { return pos+1; }
412 public int size() { return hash==null ? 0 : hash.size(); }
414 // GraphViz //////////////////////////////////////////////////////////////////////////////
416 public GraphViz.Node toGraphViz(GraphViz gv) {
417 if (gv.hasNode(this)) return gv.createNode(this);
418 GraphViz.Group g = gv.createGroup(this);
419 g.label = "Phase " + pos;
424 public boolean isTransparent() { return false; }
425 public boolean isHidden() { return false; }