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.Parser.Table.*;
7 import edu.berkeley.sbp.Sequence.Position;
10 import java.lang.reflect.*;
12 /** implements Tomita's Graph Structured Stack */
16 static int shifts = 0;
17 static int reductions = 0;
23 public GSS(Input input) { this.input = input; }
25 private Phase.Node[] reducing_list = null;
27 // FIXME: right now, these are the performance bottleneck
28 HashMapBag<Sequence,Phase.Waiting> waiting = new HashMapBag<Sequence,Phase.Waiting>();
29 HashMapBag<Integer,Sequence> performed = new HashMapBag<Integer,Sequence>();
30 HashMapBag<Integer,Sequence> lastperformed = new HashMapBag<Integer,Sequence>();
31 HashMapBag<Integer,Sequence> expected = new HashMapBag<Integer,Sequence>();
34 Forest.Many finalResult;
36 /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
37 class Phase<Tok> implements Invokable<State, Forest, Phase<Tok>.Node>, IntegerMappable, GraphViz.ToGraphViz, Iterable<Phase.Node> {
39 public Iterator<Phase.Node> iterator() { return hash.iterator(); }
40 public void invoke(State st, Forest result, Node n) {
42 good |= next.newNode(n, result, st, false);
45 /** the token immediately after this phase */
48 private final int pos;
51 private IntPairMap<Phase.Node> hash; /* ALLOC */
52 private boolean closed;
54 private Phase next = null;
56 private Input.Location location;
57 private Input.Location nextLocation;
58 private Input.Location prevLocation;
60 public final Parser parser;
62 private Forest forest;
64 public Phase(Phase prev, Parser parser, Phase previous, Tok token, Input.Location location,
65 Input.Location nextLocation, Forest forest) throws ParseFailed {
66 this.prevLocation = prev==null ? location : prev.getLocation();
70 this.pos = previous==null ? 0 : previous.pos+1;
72 this.location = location;
73 this.nextLocation = nextLocation;
78 public void reset() throws ParseFailed {
81 lastperformed.clear();
82 lastperformed.addAll(performed);
84 hash = new IntPairMap<Phase.Node>();
90 if (prev != null) prev.shift(this, forest);
94 public boolean isDone() throws ParseFailed {
95 if (token != null) return false;
96 if (token==null && finalResult==null)
97 ParseFailed.error("unexpected end of file",
101 getLocation().createRegion(getLocation()),
107 public Input.Location getPrevLocation() { return prevLocation; }
108 public Input.Location getLocation() { return location; }
109 public Input.Region getRegion() { return getPrevLocation().createRegion(getLocation()); }
110 public Input.Location getNextLocation() { return nextLocation; }
112 /** add a new node (merging with existing nodes if possible)
113 * @param parent the parent of the new node
114 * @param result the SPPF result corresponding to the new node
115 * @param state the state that the new node is in
116 * @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
117 * @param start the earliest part of the input contributing to this node (used to make merging decisions)
119 public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
120 Node p = hash.get(state, parent==null?null:parent.phase());
121 if (p != null) return newNode2(p, parent, pending, state, fromEmptyReduction);
122 else return newNode3(parent, pending, state, fromEmptyReduction);
124 public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
125 int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
126 Sequence owner = reduction==null ? null : reduction.owner();
127 if (reduction!=null) {
128 if (owner.hates!=null) {
129 for (Sequence s : performed.getAll(pos))
130 if (owner.hates.contains(s))
132 for (Sequence s : lastperformed.getAll(pos))
133 if (owner.hates.contains(s)) {
134 //System.out.println("now expecting ["+pos+"] => " + s);
135 expected.add(pos, s);
139 if (owner.needs != null)
140 for(Sequence s : owner.needs)
141 if (!performed.contains(pos, s)) {
142 waiting.add(s, new Waiting(parent, pending, state, fromEmptyReduction, reduction));
145 if (!performed.contains(pos, owner)) {
146 performed.add(pos, owner);
147 if (owner.hated != null)
148 for(Sequence seq : owner.hated)
149 if (performed.contains(pos, seq)) {
150 performed.remove(pos, seq);
155 newNode(parent, pending, state, fromEmptyReduction);
156 if (reduction != null) {
160 for(Waiting w : waiting.getAll(owner)) {
161 if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
162 waiting.remove(owner, w);
172 private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
173 if (p.merge(parent, pending)) return true;
174 p.parents().add(parent, true);
175 if (p!=parent && !fromEmptyReduction && reducing) p.performReductions(parent);
179 private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
181 if (token != null && state.canShift(token)) break;
182 if (state.isAccepting()) break;
183 if (token==null) break;
184 if (!state.canReduce(token)) return false;
185 //if (count > 1) break;
186 //if (r.numPop == 0) break;
187 //r.reduce(pending, parent, null, Phase.this, null);
191 Node n = new Node(parent, pending, state); // ALLOC
193 n.performEmptyReductions();
194 if (!fromEmptyReduction) n.performReductions(parent);
199 LinkedList<Node> reductionQueue = new LinkedList<Node>();
201 /** perform all reduction operations */
202 public void reduce() throws ParseFailed {
205 if (reducing_list==null || reducing_list.length < hash.size())
206 reducing_list = new Phase.Node[hash.size() * 4];
207 hash.toArray(reducing_list);
208 int num = hash.size();
209 for(int i=0; i<num; i++) {
210 Node n = reducing_list[i];
211 n.performEmptyReductions();
212 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
214 for(int i=0; i<num; i++) {
215 reductionQueue.add(reducing_list[i]);
216 reducing_list[i] = null;
218 while(!reductionQueue.isEmpty()) {
219 reductionQueue.remove().performReductions();
226 for(int i : expected)
227 for(Sequence s : expected.getAll(i))
228 if (!performed.contains(i, s)) {
229 //System.out.println("resetting due to pos="+i+": " + s + " " + System.identityHashCode(s));
240 private boolean reset = false;
241 class Reset extends RuntimeException { }
243 /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
244 public void shift(Phase next, Forest result) throws ParseFailed {
245 // this massively improves GC performance
246 if (prev!=null && parser.helpgc) {
253 for(Phase.Node n : hash.values()) {
254 if (token == null && n.state.isAccepting()) {
255 if (finalResult==null) finalResult = new Forest.Many();
256 for(Object f : n.results())
257 finalResult.merge((Forest)f);
259 if (token == null) continue;
260 n.state.invokeShifts(token, this, result, n);
263 if (!good && token!=null)
264 ParseFailed.error("unexpected character",
272 if (token==null && finalResult==null)
273 ParseFailed.error("unexpected end of file",
277 getLocation().createRegion(getLocation()),
287 boolean fromEmptyReduction;
289 public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
291 this.parent = parent;
292 this.pending = pending;
294 this.fromEmptyReduction = fromEmptyReduction;
295 this.reduction = reduction;
297 public void perform() {
298 //System.out.println("performing: " + reduction.position);
299 newNode(parent, pending, state, fromEmptyReduction, reduction);
303 // Node /////////////////////////////////////////////////////////////////////////////////
305 /** a node in the GSS */
306 final class Node implements Invokable<Position, Node, Node>, IntegerMappable, GraphViz.ToGraphViz {
307 public FastSet<Node> set = new FastSet<Node>();
308 private boolean allqueued = false;
310 /** what state this node is in */
311 public final Parser.Table<Tok>.State<Tok> state;
313 /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
314 public Phase phase() { return Phase.this; }
316 private HashSet<Forest.Many> resultMap = new HashSet<Forest.Many>();
317 public Iterable<Forest.Many> results() { return resultMap; }
318 public FastSet<Node> parents() { return set; }
319 public boolean merge(Node parent, Forest result) {
320 // FIXME: inefficient!
321 for(Forest.Many f : results()) {
322 if (f.parents.contains(parent) /* UGLY: */ && f.parents.size()==1) {
327 Forest.Many f = new Forest.Many();
328 f.parents.add(parent);
331 set.add(parent, true);
335 public void performReductions() {
336 if (allqueued) return;
338 state.invokeReductions(token, this, this, null);
341 public void performReductions(Node n2) {
342 if (!allqueued) reductionQueue.add(this);//performReductions();
343 else state.invokeReductions(token, this, this, n2);
346 public void performEmptyReductions() { state.invokeReductions(token, this, null, null); }
347 public final void invoke(Position r, Node n, Node n2) {
349 if (n==null || n2==null || r.pos==0) {
351 if (n==null) n = this;
355 Forest[] holder = new Forest[r.pos];
356 if (r.pos==0) n.finish(r, r.zero(n.phase().getLocation().createRegion(n.phase().getLocation())), n.phase());
357 else n.reduce(r, r.pos-1, n.phase(), null);
359 if (r.pos<=0) throw new Error("called wrong form of reduce()");
361 n.reduce(r, pos, n.phase(), n2);
365 public void reduce(Position r, int pos, Phase target, Node only) {
366 Forest[] holder = r.holder;
367 Forest old = holder[pos];
369 HashSet<Forest> rr = new HashSet<Forest>();
370 for(Forest result : results()) rr.add(result);
371 for(Forest result : rr)
372 for(Node child : ((Forest.Many<?>)result).parents) {
373 if (only != null && child!=only) continue;
374 holder[pos] = result;
375 if (pos==0) child.finish(r, r.rewrite(child.phase().getLocation().createRegion(target.getLocation())), target);
376 else child.reduce(r, pos-1, target, null);
382 public void finish(Position r, Forest result, Phase<Tok> target) {
383 Parser.Table<Tok>.State<Tok> state0 = state.gotoSetNonTerminals.get(r.owner());
384 if (result==null) throw new Error();
386 target.newNode(this, result, state0, r.pos<=0, r);
389 private Node(Node parent, Forest pending, State state) {
391 this.merge(parent, pending);
392 Phase start = parent==null ? null : parent.phase();
393 if (parent != null) parents().add(parent, true);
394 if (Phase.this.hash.get(state, start) != null) throw new Error("severe problem!");
395 Phase.this.hash.put(state, start, this);
397 public int toInt() { return idx; }
398 private final int idx = node_idx++;
400 // GraphViz //////////////////////////////////////////////////////////////////////////////
402 public GraphViz.Node toGraphViz(GraphViz gv) {
403 if (gv.hasNode(this)) return gv.createNode(this);
404 GraphViz.Node n = gv.createNode(this);
405 n.label = ""+state.toStringx();
406 n.shape = "rectangle";
408 for(Forest result : results()) n.edge(result, "");
409 for(Node parent : parents()) n.edge(parent, "");
410 ((GraphViz.Group)phase().toGraphViz(gv)).add(n);
413 public boolean isTransparent() { return false; }
414 public boolean isHidden() { return false; }
417 private int node_idx = 0;
419 public int toInt() { return pos+1; }
420 public int size() { return hash==null ? 0 : hash.size(); }
422 // GraphViz //////////////////////////////////////////////////////////////////////////////
424 public GraphViz.Node toGraphViz(GraphViz gv) {
425 if (gv.hasNode(this)) return gv.createNode(this);
426 GraphViz.Group g = gv.createGroup(this);
427 g.label = "Phase " + pos;
432 public boolean isTransparent() { return false; }
433 public boolean isHidden() { return false; }