slow down spinner
[sbp.git] / src / edu / berkeley / sbp / GSS.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
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;
8 import java.io.*;
9 import java.util.*;
10 import java.lang.reflect.*;
11
12 /** implements Tomita's Graph Structured Stack */
13 class GSS {
14
15     Input input;
16     private Parser parser;
17     public GSS(Input input, Parser parser) { this.input = input; this.parser = parser;}
18     public Input getInput() { return input; }
19
20     int numNewNodes = 0;
21     int numOldNodes = 0;
22     int viewPos = 0;
23     int numReductions = 0;
24
25     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
26     class Phase<Tok> implements Invokable<State, Result>, IntegerMappable, GraphViz.ToGraphViz, Iterable<Node> {
27
28         // FIXME: right now, these are the performance bottleneck
29         private HashMapBag<Integer,Sequence>       performed       = new HashMapBag<Integer,Sequence>();
30
31         public Forest.Many finalResult;
32         private PriorityQueue<Reduction> reductionQueue = new PriorityQueue<Reduction>();
33
34         public void addReduction(Reduction r) {
35             //System.out.println("+ " + r);
36             parser.spin();
37             reductionQueue.add(r);
38         }
39         public void invoke(State st, Result result) {
40             parser.spin();
41             good |= next.newNode(result, st, false);
42         }
43
44         /** the token immediately after this phase */
45         final Tok token;
46         final int pos;
47
48         public IntPairMap<Node> hash = new IntPairMap<Node>();  /* ALLOC */
49         private boolean good = false;
50         private Phase next = null;
51         private Phase prev;
52         private Input.Location location;
53         private Input.Location nextLocation;
54         private Input.Location prevLocation;
55         
56         private Forest forest;
57
58         public Phase(State startState) throws ParseFailed, IOException {
59             this(null, null);
60             Result primordealResult = new Result(null, null, null);
61             newNode(primordealResult, startState, true);
62         }
63         public Phase(Phase prev, Forest forest) throws ParseFailed, IOException {
64             this.location = input.getLocation();
65             this.token = (Tok)input.next();
66             this.prevLocation = prev==null ? location : prev.getLocation();
67             this.prev = prev;
68             this.forest = forest;
69             this.pos = prev==null ? 0 : prev.pos+1;
70             this.nextLocation = input.getLocation();
71             if (prev != null) prev.shift(this, forest);
72             numReductions = 0;
73
74             int minPhasePos = Integer.MAX_VALUE;
75             int maxOrd = -1;
76             Reduction best = null;
77             //System.out.println("==============================================================================");
78             while(!reductionQueue.isEmpty()) {
79                 Reduction r = reductionQueue.poll();
80                 //System.out.println("- " + r);
81                 if (r.parentPhase() != null)
82                     if (r.parentPhase().pos > minPhasePos)
83                         throw new Error();
84                 r.perform();
85                 if (r.parentPhase() != null) {
86                     if (r.parentPhase().pos < minPhasePos) {
87                         minPhasePos = r.parentPhase().pos;
88                         maxOrd = r.reduction().ord;
89                         best = r;
90                     } else if (r.parentPhase().pos == minPhasePos) {
91                         /*
92                         if (best != null && Parser.mastercache.comparePositions(r.reduction(), best.reduction()) < 0)
93                             throw new Error("\n"+r+"\n"+best+"\n"+
94                                             Parser.mastercache.comparePositions(r.reduction(), best.reduction())+"\n"+r.compareTo(best)+
95                                             "\n"+(r.reduction().ord-best.reduction().ord));
96                         */
97                         maxOrd = r.reduction().ord;
98                         best = r;
99                     }
100                 }
101                 numReductions++;
102             }
103             if (token==null) shift(null, null);
104         }
105
106         public boolean isDone() throws ParseFailed {
107             if (token != null) return false;
108             if (token==null && finalResult==null)
109                 ParseFailed.error("unexpected end of file", this);
110             return true;
111         }
112
113         public Input.Location getPrevLocation() { return prevLocation; }
114         public Input.Location getLocation() { return location; }
115         public Input.Region   getRegion() { return getPrevLocation().createRegion(getLocation()); }
116         public Input.Location getNextLocation() { return nextLocation; }
117         public boolean        isFrontier() { return hash!=null; }
118
119         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
120         private void shift(Phase next, Forest result) throws ParseFailed {
121             this.next = next;
122             // this massively improves GC performance
123             if (prev != null) {
124                 IntPairMap<Node> h = prev.hash;
125                 prev.hash = null;
126                 prev.performed = null;
127                 for(Node n : h)
128                     n.check();
129             }
130             numOldNodes = hash.size();
131             for(Node n : hash.values()) {
132                 if (token == null && n.state().isAccepting()) {
133                     if (finalResult==null) finalResult = new Forest.Many();
134                     for(Result r : n)
135                         finalResult.merge(r.getForest());
136                 }
137                 if (token == null) continue;
138                 n.state().invokeShifts(token, this, new Result(result, n, null));
139             }
140             numNewNodes = next==null ? 0 : next.hash.size();
141             viewPos = this.pos;
142             if (!good && token!=null) ParseFailed.error("unexpected character", this);
143             if (token==null && finalResult==null) ParseFailed.error("unexpected end of file", this);
144             for(Node n : hash) n.check();
145         }
146
147         void newNodeFromReduction(Result result, State state, Position reduction) {
148             int pos = result.phase().pos;
149             Sequence owner = reduction.owner();
150             for(Sequence s : owner.hates())
151                 if (performed.contains(pos, s))
152                     return;
153             for(Sequence s : owner.needs())
154                 if (!performed.contains(pos, s))
155                     return;
156             if (owner.needed_or_hated && !performed.contains(pos, owner))
157                 performed.add(pos, owner);
158             if (state!=null)
159                 newNode(result, state, reduction.pos<=0);
160         }
161
162         /** add a new node (merging with existing nodes if possible)
163          *  @param parent             the parent of the new node
164          *  @param result             the SPPF result corresponding to the new node
165          *  @param state              the state that the new node is in
166          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
167          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
168          */
169         private boolean newNode(Result result, State state, boolean fromEmptyReduction) {
170             Node p = hash.get(state, result.phase());
171             if (p != null) { p.addResult(result); return true; }
172             do {
173                 if (token != null && state.canShift(token)) break;
174                 if (state.isAccepting()) break;
175                 if (token==null) break;
176                 if (!state.canReduce(token)) return false;
177             } while(false);
178             Node n = new Node(Phase.this, result, state, fromEmptyReduction);  // ALLOC
179             for(Object s : state.also)
180                 newNode(new Result(null, n, null), (State)s, fromEmptyReduction);
181             return true;
182         }
183
184         public int toInt() { return pos+1; }
185         public int size() { return hash==null ? 0 : hash.size(); }
186         public int pos() { return pos; }
187         public Tok getToken() { return token; }
188         public Iterator<Node> iterator() { return hash.iterator(); }
189         public GSS getGSS() { return GSS.this; }
190
191         // GraphViz //////////////////////////////////////////////////////////////////////////////
192
193         public GraphViz.Node toGraphViz(GraphViz gv) {
194             if (gv.hasNode(this)) return gv.createNode(this);
195             GraphViz.Group g = gv.createGroup(this);
196             g.label = "Phase " + pos;
197             g.color = "gray";
198             g.cluster = true;
199             return g;
200         }
201         public boolean isTransparent() { return false; }
202         public boolean isHidden() { return false; }
203
204         public void dumpGraphViz(String filename) throws IOException {
205             FileOutputStream fos = new FileOutputStream(filename);
206             PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
207             GraphViz gv = new GraphViz();
208             for(Object n : this)
209                 ((Node)n).toGraphViz(gv);
210             gv.dump(p);
211             p.flush();
212             p.close();
213         }
214
215     }
216
217 }