6db929bb8893f33fde1ff7f70c87b18665b729b4
[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 /** implements Tomita's Graph Structured Stack */
26 class GSS {
27
28     public GSS() { }
29
30     private Phase.Node[] reducing_list = null;
31
32     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
33     public class Phase {
34
35         /** the token immediately after this phase */
36         public  final Token token;
37
38         /** currently this is necessary only for the code() hack -- it doesn't actually correspond to the input */
39         private final int pos;
40
41         /** FIXME */
42         public  Forest.Ref finalResult = null;
43
44         /** all nodes, keyed by the value returned by code() */
45         private HashMap<Long,Phase.Node> hash    = new HashMap<Long,Phase.Node>();  /* ALLOC */
46
47         /** the number of nodes in this phase */
48         private int numNodes = 0;
49
50         boolean closed = false;
51
52         private Token.Location location;
53         public Phase(Phase previous, Token token, Token.Location location) {
54             this.pos = previous==null ? 0 : previous.pos+1;
55             this.token = token;
56             this.location = location;
57         }
58
59         public boolean isDone() { return token == null; }
60
61         private String error = "generic syntax error";
62         public void checkFailure() throws Parser.Failed {
63             if (numNodes <= 0)
64                 throw new Parser.Failed(error, getLocation());
65         }
66
67         public Token.Location getLocation() { return location; }
68
69         /** add a new node (merging with existing nodes if possible)
70          *  @param parent             the parent of the new node
71          *  @param result             the SPPF result corresponding to the new node
72          *  @param state              the state that the new node is in
73          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
74          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
75          */
76         public void newNode(Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
77             Node p = hash.get(code(state, start));
78             if (p != null)  newNode2(p, parent, pending, state, fromEmptyReduction, start);
79             else            newNode3(parent, pending, state, fromEmptyReduction, start);
80         }
81         private void newNode2(Node p, Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
82             p.holder.merge(pending);
83             if (p.parents().contains(parent)) return;
84             p.parents().add(parent, true);
85             if (p!=parent && !fromEmptyReduction) p.queueReductions(parent);
86         }
87         private void newNode3(Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
88             do {
89                 if (token != null && state.canShift(token)) break;
90                 if (state.isAccepting()) break;
91                 if (token==null) break;
92                 int count = 0;
93                 Parser.Table.Reduction r = null;
94                 for(Parser.Table.Reduction red : token==null ? state.getEofReductions() : state.getReductions(token)) { r = red; count++; }
95                 if (count==0) return;     // BEWARE! this optimization is suspected to cause really nasty heisenbugs
96                 //if (count > 1) break;
97                 //if (r.numPop == 0) break;
98                 //r.reduce(pending, parent, null, Phase.this, null);
99                 //return;
100             } while(false);
101
102             Node n = new Node(parent, pending, state, start);  // ALLOC
103             n.queueEmptyReductions();
104             if (!fromEmptyReduction) n.queueReductions(parent);
105         }
106
107         
108         boolean reducing = false;
109         /** perform all reduction operations */
110         public void reduce() {
111             reducing = true;
112             if (reducing_list==null || reducing_list.length < hash.size())
113                 reducing_list = new Phase.Node[hash.size() * 4];
114             Collection<Node> hv = hash.values();
115             hv.toArray(reducing_list);
116             int num = hv.size();
117             for(int i=0; i<num; i++) {
118                 Node n = reducing_list[i];
119                 reducing_list[i] = null;
120                 n.queueEmptyReductions();
121                 n.queueReductions();
122             }
123         }
124
125         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
126         public void shift(Phase next, Forest result) {
127             closed = true;
128             Forest res = null;
129             boolean ok = false;
130             for(Phase.Node n : hash.values()) {
131                 if (n.holder==null) continue;
132                 n.holder.resolve();
133                 if (token == null && n.state.isAccepting()) {
134                     ok = true;
135                     if (finalResult==null) finalResult = new Forest.Ref();
136                     finalResult.merge(n.holder);
137                 }
138                 if (!n.holder.valid()) continue;
139                 if (token == null) continue;
140                 for(Parser.Table.State st : n.state.getShifts(token)) {
141                     if (res == null) res = result;
142                     next.newNode(n, res, st, true, this);
143                     ok = true;
144                 }
145             }
146
147             if (!ok && token != null) {
148                 StringBuffer error = new StringBuffer();
149                 error.append("error: unable to shift token \"" + token + "\"\n");
150                 //error.append("  before: " +pendingReductions+ "\n");
151                 //error.append("  before: " +totalReductions+ "\n");
152                 //for(Phase.Node n : hash.values()) {
153                 //n.queueReductions();
154                 //n.queueEmptyReductions();
155                 //}
156                 //error.append("  after: " +pendingReductions+ "\n");
157                 error.append("  candidate states:\n");
158                 for(Phase.Node n : hash.values()) {
159                     //for(Sequence.Position p : n.state) error.append("        " + p + "\n");
160                     //error.append("        --\n");
161                     for(Parser.Table.Reduction r : n.state.getReductions(token)) error.append("        " + r + "\n");
162                     //error.append("        ==\n");
163                 }
164                 next.error = error.toString();
165             }
166
167             // this massively improves GC performance
168             hash = null;
169         }
170
171        
172         // GSS Nodes //////////////////////////////////////////////////////////////////////////////
173
174         /** a node in the GSS */
175         public final class Node extends FastSet<Node> {
176
177             private Forest.Ref holder = null;
178             private boolean allqueued = false;
179
180             private HashMap<Parser.Table.Reduction,Forest> cache = null;
181
182             /** the set of nodes to which there is an edge starting at this node */
183             //public final FastSet<Node> parents = new FastSet<Node>();  /* ALLOC */
184
185             /** what state this node is in */
186             public final Parser.Table.State state;
187
188             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
189             public final Phase phase = Phase.this;
190
191             public  HashMap<Parser.Table.Reduction,Forest> cache() {
192                 return cache==null ? (cache = new HashMap<Parser.Table.Reduction,Forest>()) : cache; }
193             public  Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
194             public  Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
195             public  FastSet<Node> parents() { return this; }
196
197             /** FIXME */
198             public void queueReductions() {
199                 if (allqueued) return;
200                 allqueued = true;
201                 int where = parents().size();
202                 for(int i=0; i<where; i++) queueReductions(get(i));
203             }
204
205             /** FIXME */
206             public void queueReductions(Node n2) {
207                 if (!allqueued) { queueReductions(); return; }
208                 Node n = this;
209                 for(Parser.Table.Reduction r : token==null ? n.state.getEofReductions() : n.state.getReductions(token)) {
210                     
211                     // UGLY HACK
212                     // The problem here is that a "reduction of length 1"
213                     // performed twice with different values of n2 needs
214                     // to only create a *single* new result, but must add
215                     // multiple parents to the node holding that result.
216                     // The current reducer doesn't differentiate between
217                     // the next node of an n-pop reduction and the
218                     // ultimate parent of the last pop, so we need to
219                     // cache instances here as a way of avoiding
220                     // recreating them.
221                     
222                     // currently we have this weird problem where we
223                     // have to do an individual reduct for each child
224                     // when the reduction length is one (ie the
225                     // children wind up being children of the newly
226                     // created node rather than part of the popped
227                     // sequence
228                     if (r.numPop <= 0) continue;
229                     if (r.numPop == 1) {
230                         Forest ret = n.cache().get(r);
231                         if (ret != null) r.reduce(n, n2, n.phase, ret);
232                         else n.cache().put(r, r.reduce(n, n2, n.phase, null));
233                     } else {
234                         r.reduce(n, n2, Phase.this, null);
235                     }
236                 }
237             }
238
239
240             /** FIXME */
241             public void queueEmptyReductions() {
242                 if (reducing)
243                     for(Parser.Table.Reduction r : token==null ? state.getEofReductions() : state.getReductions(token))
244                         if (r.numPop==0)
245                             r.reduce(this, null, this.phase, r.zero());
246             }
247
248             private Node(Node parent, Forest pending, Parser.Table.State state, Phase start) {
249                 this.state = state;
250                 if (pending != null) this.holder().merge(pending);
251                 if (parent != null) parents().add(parent, true);
252                 if (Phase.this.hash.get(code(state, start)) != null) throw new Error("severe problem!");
253                 Phase.this.hash.put(code(state, start), this);
254                 Phase.this.numNodes++;
255                 if (parent==null) holder().valid = true; // hack to make sure that the "base" node is always considered valid
256             }
257         }
258
259     }
260
261     /** helper method */
262     private static boolean equal(Object a, Object b) {
263         if (a==null && b==null) return true;
264         if (a==null || b==null) return false;
265         return a.equals(b);
266     }
267
268     /** this is something of a hack right now */
269     private static long code(Parser.Table.State state, Phase start) {
270         return (((long)state.idx) << 32) | (start==null ? 0 : start.pos);
271     }
272     public boolean yak = false;
273 }