checkpoint
[sbp.git] / src / edu / berkeley / sbp / GSS.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.*;
5 import edu.berkeley.sbp.util.*;
6 import java.io.*;
7 import java.util.*;
8 import java.lang.reflect.*;
9
10 //////////////////////////////////////////////////////////////////////////////
11 // TODO:
12 //
13 //  - fix public/package/private status
14 //
15
16 //////////////////////////////////////////////////////////////////////////////
17 // Optimizations to add
18 //
19 // ** NOTE: not all of these are appropriate for this class -- it is
20 //          simply a list of optimizations not implemented.  This
21 //          class is meant to remain simple and easy to understand;
22 //          optimizations which obscure that do not belong here (they
23 //          should go into the compiled version instead)
24 //
25 // - most of our time is now spent creating and storing Reduct instances
26 // - we should be able to perform Reduct's immediately after creating them...
27 //
28
29 /** implements Tomita's Graph Structured Stack */
30 class GSS {
31
32     public GSS() { }
33
34     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
35     public class Phase {
36
37         /** the token immediately after this phase */
38         public  final Token token;
39
40         /** currently this is necessary only for the code() hack -- it doesn't actually correspond to the input */
41         private final int pos;
42
43         /** FIXME */
44         public  Forest.Ref finalResult = null;
45
46         /** all reductions (pending and completed) */
47         private HashSet<Phase.Reduct> reductions = new HashSet<Phase.Reduct>();     /* ALLOC */
48         
49         /** all nodes, keyed by the value returned by code() */
50         private HashMap<Long,Phase.Node> hash    = new HashMap<Long,Phase.Node>();  /* ALLOC */
51
52         /** the number of pending reductions */
53         private int pendingReductions = 0;
54         private int totalReductions = 0;
55         //private HashSet<Reduct> pendingReduct = new HashSet<Reduct>();
56         private LinkedList<Reduct> pendingReduct = new LinkedList<Reduct>();
57
58         /** the number of nodes in this phase */
59         private int numNodes = 0;
60
61         boolean closed = false;
62
63         private Token.Location location;
64         public Phase(Phase previous, Token token, Token.Location location) {
65             this.pos = previous==null ? 0 : previous.pos+1;
66             this.token = token;
67             this.location = location;
68         }
69
70         public boolean isDone() { return token == null; }
71
72         private String error = "generic syntax error";
73         public void checkFailure() throws Parser.Failed {
74             if (numNodes <= 0)
75                 throw new Parser.Failed(error, getLocation());
76         }
77
78         public Token.Location getLocation() { return location; }
79
80         /** add a new node (merging with existing nodes if possible)
81          *  @param parent             the parent of the new node
82          *  @param result             the SPPF result corresponding to the new node
83          *  @param state              the state that the new node is in
84          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
85          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
86          */
87         public void newNode(Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
88             Node p = hash.get(code(state, start));
89             if (p != null)  newNode2(p, parent, pending, state, fromEmptyReduction, start);
90             else            newNode3(parent, pending, state, fromEmptyReduction, start);
91         }
92         private void newNode2(Node p, Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
93             p.holder.merge(pending);
94             if (p.parents.contains(parent)) return;
95             p.parents.add(parent, true);
96             if (p!=parent && !fromEmptyReduction) p.queueReductions(parent);
97         }
98         private void newNode3(Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
99             do {
100                 if (token != null && state.canShift(token)) break;
101                 if (state.isAccepting()) break;
102                 if (token==null) break;
103                 int count = 0;
104                 Parser.Table.Reduction r = null;
105                 for(Parser.Table.Reduction red : token==null ? state.getEofReductions() : state.getReductions(token)) { r = red; count++; }
106                 //if (count==0) return;     // BEWARE! this optimization is suspected to cause really nasty heisenbugs
107                 //if (count > 1) break;
108                 //if (r.numPop == 0) break;
109                 //r.reduce(pending, parent, null, Phase.this, null);
110                 //return;
111             } while(false);
112
113             Node n = new Node(parent, pending, state, start);  // ALLOC
114             n.queueEmptyReductions();
115             if (!fromEmptyReduction) n.queueReductions();
116         }
117
118         
119         boolean reducing = false;
120         /** perform all reduction operations */
121         public void reduce() {
122             reducing = true;
123             HashSet<Phase.Node> s = new HashSet<Phase.Node>();
124             s.addAll(hash.values());
125             //while(pendingReduct.size()>0)
126             //pendingReduct.removeFirst().go();
127             for(Phase.Node n : s) n.queueEmptyReductions();
128             for(Phase.Node n : s) n.queueReductions();
129         }
130
131         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
132         public void shift(Phase next, Forest result) {
133             closed = true;
134             Forest res = null;
135             boolean ok = false;
136             for(Phase.Node n : hash.values()) {
137                 if (n.holder==null) continue;
138                 n.holder.resolve();
139                 if (token == null && n.state.isAccepting()) {
140                     ok = true;
141                     if (finalResult==null) finalResult = new Forest.Ref();
142                     finalResult.merge(n.holder);
143                 }
144                 if (!n.holder.valid()) continue;
145                 if (token == null) continue;
146                 for(Parser.Table.State st : n.state.getShifts(token)) {
147                     if (res == null) res = result;
148                     next.newNode(n, res, st, true, this);
149                     ok = true;
150                 }
151             }
152
153             if (!ok && token != null) {
154                 StringBuffer error = new StringBuffer();
155                 error.append("error: unable to shift token \"" + token + "\"\n");
156                 error.append("  before: " +pendingReductions+ "\n");
157                 error.append("  before: " +totalReductions+ "\n");
158                 //for(Phase.Node n : hash.values()) {
159                 //n.queueReductions();
160                 //n.queueEmptyReductions();
161                 //}
162                 error.append("  after: " +pendingReductions+ "\n");
163                 error.append("  candidate states:\n");
164                 for(Phase.Node n : hash.values()) {
165                     //for(Sequence.Position p : n.state) error.append("        " + p + "\n");
166                     //error.append("        --\n");
167                     for(Parser.Table.Reduction r : n.state.getReductions(token)) error.append("        " + r + "\n");
168                     //error.append("        ==\n");
169                 }
170                 next.error = error.toString();
171             }
172
173             // this massively improves GC performance
174             reductions = null;
175             hash = null;
176         }
177
178        
179         // GSS Nodes //////////////////////////////////////////////////////////////////////////////
180
181         //private HashMap<Parser.Table.Reduction,Forest> pcache = new HashMap<Parser.Table.Reduction,Forest>();
182         /** a node in the GSS */
183         public final class Node {
184
185             private Forest.Ref holder = null;
186
187             private HashMap<Parser.Table.Reduction,Forest> cache = null;
188
189             /** the set of nodes to which there is an edge starting at this node */
190             public final FastSet<Node> parents = new FastSet<Node>();  /* ALLOC */
191
192             /** what state this node is in */
193             public final Parser.Table.State state;
194             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
195             public final Phase phase = Phase.this;
196
197             public  HashMap<Parser.Table.Reduction,Forest> cache() {
198                 return cache==null ? (cache = new HashMap<Parser.Table.Reduction,Forest>()) : cache; }
199             public  Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
200             public  Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
201             public  FastSet<Node> parents() { return parents; }
202
203             /** FIXME */
204             public void queueReductions() {
205                 for(Node n2 : parents)
206                     queueReductions(n2);
207             }
208
209             private HashSet<Node> queued = new HashSet<Node>();
210             /** FIXME */
211             public void queueReductions(Node n2) {
212                 if (queued.contains(n2)) return;
213                 queued.add(n2);
214                 Node n = this;
215                 for(Parser.Table.Reduction r : token==null ? n.state.getEofReductions() : n.state.getReductions(token)) {
216                     
217                     // UGLY HACK
218                     // The problem here is that a "reduction of length 1"
219                     // performed twice with different values of n2 needs
220                     // to only create a *single* new result, but must add
221                     // multiple parents to the node holding that result.
222                     // The current reducer doesn't differentiate between
223                     // the next node of an n-pop reduction and the
224                     // ultimate parent of the last pop, so we need to
225                     // cache instances here as a way of avoiding
226                     // recreating them.
227                     
228                     // currently we have this weird problem where we
229                     // have to do an individual reduct for each child
230                     // when the reduction length is one (ie the
231                     // children wind up being children of the newly
232                     // created node rather than part of the popped
233                     // sequence
234                     if (r.numPop <= 0) continue;
235                     if (r.numPop == 1) {
236                         Forest ret = n.cache().get(r);
237                         if (ret != null) r.reduce(n, n2, n.phase, ret);
238                         else n.cache().put(r, r.reduce(n, n2, n.phase, null));
239                     } else {
240                         r.reduce(n, n2, Phase.this, null);
241                     }
242                 }
243             }
244
245
246             /** FIXME */
247             public void queueEmptyReductions() {
248                 if (reducing)
249                     for(Parser.Table.Reduction r : token==null ? state.getEofReductions() : state.getReductions(token))
250                         if (r.numPop==0)
251                             r.reduce(this, null, this.phase, r.zero());
252             }
253
254             private Node(Node parent, Forest pending, Parser.Table.State state, Phase start) {
255                 this.state = state;
256                 if (pending != null) this.holder().merge(pending);
257                 if (parent != null) parents.add(parent, true);
258                 if (Phase.this.hash.get(code(state, start)) != null) throw new Error("severe problem!");
259                 Phase.this.hash.put(code(state, start), this);
260                 Phase.this.numNodes++;
261                 if (parent==null) holder().valid = true; // hack to make sure that the "base" node is always considered valid
262             }
263         }
264
265         // Forest / Completed Reductions //////////////////////////////////////////////////////////////////////////////
266
267         /** a pending or completed reduction */
268         class Reduct {
269             
270             /** the node from which the reduction should begin */
271             public Node n = null;
272
273             /** the node on the other end of the edge to be reduced along (either: null, the second node of the reduction,
274              *  or the parent of the result of a length-one reduction)
275              */
276             public Node n2 = null;
277
278             /** true iff the reduction has already been performed */
279             private boolean done = false;
280
281             /** the reduction to be applied */
282             public Parser.Table.Reduction r;
283
284             public Tree<String> result = null;
285
286             public Reduct(Node n, Node n2, Parser.Table.Reduction r) {
287                 this.n = n;
288                 this.n2 = n2;
289                 this.r = r;
290                 //if (reductions.contains(this)) { done = true; return; }
291                 //reductions.add(this);
292                 //pendingReduct.addFirst(this);
293                 //pendingReductions++;
294                 go();
295             }
296
297             /** perform the reduction */
298             public void go() {
299                 if (done) return;
300                 done = true;
301                 //pendingReduct.remove(this);
302                 //pendingReductions--;
303
304                 if (r==null) {
305                     for(Parser.Table.Reduction r : token==null ? n.state.getEofReductions() : n.state.getReductions(token)) {
306                         
307                         // UGLY HACK
308                         // The problem here is that a "reduction of length 1"
309                         // performed twice with different values of n2 needs
310                         // to only create a *single* new result, but must add
311                         // multiple parents to the node holding that result.
312                         // The current reducer doesn't differentiate between
313                         // the next node of an n-pop reduction and the
314                         // ultimate parent of the last pop, so we need to
315                         // cache instances here as a way of avoiding
316                         // recreating them.
317
318                         // currently we have this weird problem where we
319                         // have to do an individual reduct for each child
320                         // when the reduction length is one (ie the
321                         // children wind up being children of the newly
322                         // created node rather than part of the popped
323                         // sequence
324                         if (r.numPop <= 0) continue;
325                         if (r.numPop == 1) {
326                             Forest ret = n.cache().get(r);
327                             if (ret != null) r.reduce(n, n2, n.phase, ret);
328                             else n.cache().put(r, r.reduce(n, n2, n.phase, null));
329                         } else {
330                             r.reduce(n, n2, Phase.this, null);
331                         }
332                     }
333                 } else if (r.numPop != 1) {
334                     r.reduce(n, n2, Phase.this, null);
335                 }
336             }
337
338             // FIXME: this is a PITA
339             public int hashCode() { return n.hashCode() ^ (r==null ? 0 : r.hashCode()) ^ (n2==null ? 0 : n2.hashCode()); }
340             public boolean equals(Object o) {
341                 if (o==null) return false;
342                 if (o==this) return true;
343                 if (!(o instanceof Reduct)) return false;
344                 Reduct other = (Reduct)o;
345                 return equal(r, other.r) && equal(n, other.n) && equal(n2, other.n2);
346             }
347         }
348
349     }
350
351     /** helper method */
352     private static boolean equal(Object a, Object b) {
353         if (a==null && b==null) return true;
354         if (a==null || b==null) return false;
355         return a.equals(b);
356     }
357
358     /** this is something of a hack right now */
359     private static long code(Parser.Table.State state, Phase start) {
360         return (((long)state.idx) << 32) | (start==null ? 0 : start.pos);
361     }
362     public boolean yak = false;
363 }