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 /** perform all reduction operations */
200 public void reduce() throws ParseFailed {
203 if (reducing_list==null || reducing_list.length < hash.size())
204 reducing_list = new Phase.Node[hash.size() * 4];
205 hash.toArray(reducing_list);
206 int num = hash.size();
207 for(int i=0; i<num; i++) {
208 Node n = reducing_list[i];
209 n.performEmptyReductions();
210 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
212 for(int i=0; i<num; i++) {
213 Node n = reducing_list[i];
214 reducing_list[i] = null;
215 n.performReductions();
222 for(int i : expected)
223 for(Sequence s : expected.getAll(i))
224 if (!performed.contains(i, s)) {
225 //System.out.println("resetting due to pos="+i+": " + s + " " + System.identityHashCode(s));
236 private boolean reset = false;
237 class Reset extends RuntimeException { }
239 /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
240 public void shift(Phase next, Forest result) throws ParseFailed {
241 // this massively improves GC performance
242 if (prev!=null && parser.helpgc) {
249 for(Phase.Node n : hash.values()) {
250 if (token == null && n.state.isAccepting()) {
251 if (finalResult==null) finalResult = new Forest.Many();
252 for(Object f : n.results())
253 finalResult.merge((Forest)f);
255 if (token == null) continue;
256 n.state.invokeShifts(token, this, result, n);
259 if (!good && token!=null)
260 ParseFailed.error("unexpected character",
268 if (token==null && finalResult==null)
269 ParseFailed.error("unexpected end of file",
273 getLocation().createRegion(getLocation()),
283 boolean fromEmptyReduction;
285 public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
287 this.parent = parent;
288 this.pending = pending;
290 this.fromEmptyReduction = fromEmptyReduction;
291 this.reduction = reduction;
293 public void perform() {
294 //System.out.println("performing: " + reduction.position);
295 newNode(parent, pending, state, fromEmptyReduction, reduction);
299 // Node /////////////////////////////////////////////////////////////////////////////////
301 /** a node in the GSS */
302 final class Node implements Invokable<Position, Node, Node>, IntegerMappable, GraphViz.ToGraphViz {
303 public FastSet<Node> set = new FastSet<Node>();
306 private boolean allqueued = false;
308 /** what state this node is in */
309 public final Parser.Table<Tok>.State<Tok> state;
311 /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
312 public Phase phase() { return Phase.this; }
314 private HashSet<Forest.Many> resultMap = new HashSet<Forest.Many>();
315 public Iterable<Forest.Many> results() { return resultMap; }
316 public FastSet<Node> parents() { return set; }
317 public boolean merge(Node parent, Forest result) {
318 // FIXME: inefficient!
319 for(Forest.Many f : results()) {
320 if (f.parents.contains(parent) /* UGLY: */ && f.parents.size()==1) {
325 Forest.Many f = new Forest.Many();
326 f.parents.add(parent);
329 set.add(parent, true);
333 public void performReductions() {
334 if (allqueued) return;
336 state.invokeReductions(token, this, this, null);
339 public void performReductions(Node n2) {
340 if (!allqueued) performReductions();
341 else state.invokeReductions(token, this, this, n2);
344 public void performEmptyReductions() { state.invokeReductions(token, this, null, null); }
345 public final void invoke(Position r, Node n, Node n2) {
347 if (n==null || n2==null || r.pos==0) {
349 if (n==null) n = this;
353 Forest[] holder = new Forest[r.pos];
354 if (r.pos==0) n.finish(r, r.zero(n.phase().getLocation().createRegion(n.phase().getLocation())), n.phase());
355 else n.reduce(r, r.pos-1, n.phase(), null);
357 if (r.pos<=0) throw new Error("called wrong form of reduce()");
359 n.reduce(r, pos, n.phase(), n2);
363 public void reduce(Position r, int pos, Phase target, Node only) {
364 Forest[] holder = r.holder;
365 Forest old = holder[pos];
367 HashSet<Forest> rr = new HashSet<Forest>();
368 for(Forest result : results()) rr.add(result);
369 for(Forest result : rr)
370 for(Node child : ((Forest.Many<?>)result).parents) {
371 if (only != null && child!=only) continue;
372 holder[pos] = result;
373 if (pos==0) child.finish(r, r.rewrite(child.phase().getLocation().createRegion(target.getLocation())), target);
374 else child.reduce(r, pos-1, target, null);
380 public void finish(Position r, Forest result, Phase<Tok> target) {
381 Parser.Table<Tok>.State<Tok> state0 = state.gotoSetNonTerminals.get(r.owner());
382 if (result==null) throw new Error();
384 target.newNode(this, result, state0, r.pos<=0, r);
387 private Node(Node parent, Forest pending, State state) {
389 this.merge(parent, pending);
390 Phase start = parent==null ? null : parent.phase();
391 if (parent != null) parents().add(parent, true);
392 if (Phase.this.hash.get(state, start) != null) throw new Error("severe problem!");
393 Phase.this.hash.put(state, start, this);
395 public int toInt() { return idx; }
396 private final int idx = node_idx++;
398 // GraphViz //////////////////////////////////////////////////////////////////////////////
400 public GraphViz.Node toGraphViz(GraphViz gv) {
401 if (gv.hasNode(this)) return gv.createNode(this);
402 GraphViz.Node n = gv.createNode(this);
403 n.label = ""+state.toStringx();
404 n.shape = "rectangle";
406 for(Forest result : results()) n.edge(result, "");
407 for(Node parent : parents()) n.edge(parent, "");
408 ((GraphViz.Group)phase().toGraphViz(gv)).add(n);
411 public boolean isTransparent() { return false; }
412 public boolean isHidden() { return false; }
415 private int node_idx = 0;
417 public int toInt() { return pos+1; }
418 public int size() { return hash==null ? 0 : hash.size(); }
420 // GraphViz //////////////////////////////////////////////////////////////////////////////
422 public GraphViz.Node toGraphViz(GraphViz gv) {
423 if (gv.hasNode(this)) return gv.createNode(this);
424 GraphViz.Group g = gv.createGroup(this);
425 g.label = "Phase " + pos;
430 public boolean isTransparent() { return false; }
431 public boolean isHidden() { return false; }