checkpoint
[sbp.git] / src / edu / berkeley / sbp / GSS.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import java.io.*;
5 import java.util.*;
6 import java.lang.reflect.*;
7
8 //////////////////////////////////////////////////////////////////////////////
9 // TODO:
10 //
11 //  - fix public/package/private status
12 //
13
14 //////////////////////////////////////////////////////////////////////////////
15 // Optimizations to add
16 //
17 // ** NOTE: not all of these are appropriate for this class -- it is
18 //          simply a list of optimizations not implemented.  This
19 //          class is meant to remain simple and easy to understand;
20 //          optimizations which obscure that do not belong here (they
21 //          should go into the compiled version instead)
22
23 /** implements Tomita's Graph Structured Stack */
24 class GSS {
25
26     public GSS() { }
27
28     private Phase.Node[] reducing_list = null;
29
30     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
31     public class Phase implements Invokable<Parser.Table.State, Forest, GSS.Phase.Node> {
32
33         /** the token immediately after this phase */
34         public  final Token token;
35
36         boolean reducing = false;
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.addParent(parent, fromEmptyReduction);
85         }
86         private void newNode3(Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
87             do {
88                 if (token != null && state.canShift(token)) break;
89                 if (state.isAccepting()) break;
90                 if (token==null) break;
91                 int count = 0;
92                 Parser.Table.Reduction r = null;
93                 if (!state.hasReductions(token)) return;
94                 //if (count > 1) break;
95                 //if (r.numPop == 0) break;
96                 //r.reduce(pending, parent, null, Phase.this, null);
97                 //return;
98             } while(false);
99
100             Node n = new Node(parent, pending, state, start);  // ALLOC
101             n.queueEmptyReductions();
102             if (!fromEmptyReduction) n.queueReductions(parent);
103         }
104
105         
106         /** perform all reduction operations */
107         public void reduce() {
108             reducing = true;
109             if (reducing_list==null || reducing_list.length < hash.size())
110                 reducing_list = new Phase.Node[hash.size() * 4];
111             Collection<Node> hv = hash.values();
112             hv.toArray(reducing_list);
113             int num = hv.size();
114             for(int i=0; i<num; i++) {
115                 Node n = reducing_list[i];
116                 n.queueEmptyReductions();
117                 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
118             }
119             for(int i=0; i<num; i++) {
120                 Node n = reducing_list[i];
121                 reducing_list[i] = null;
122                 n.queueReductions();
123             }
124         }
125
126         public void invoke(Parser.Table.State st, Forest result, Node n) {
127             next.newNode(n, result, st, true, this);
128         }
129         private Phase next = null;
130
131         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
132         public void shift(Phase next, Forest result) {
133             this.next = next;
134             closed = true;
135             Forest res = null;
136             boolean ok = false;
137             for(Phase.Node n : hash.values()) {
138                 if (n.holder==null) continue;
139                 n.holder.resolve();
140                 if (token == null && n.state.isAccepting()) {
141                     ok = true;
142                     if (finalResult==null) finalResult = new Forest.Ref();
143                     finalResult.merge(n.holder);
144                 }
145                 if (!n.holder.valid()) continue;
146                 if (token == null) continue;
147                 n.state.invokeShifts(token, this, result, n);
148                 /*
149                 for(Parser.Table.State st : n.state.getShifts(token)) {
150                     if (res == null) res = result;
151                     next.newNode(n, res, st, true, this);
152                     ok = true;
153                 }
154                 */
155             }
156
157             if (!ok && token != null) {
158                 StringBuffer error = new StringBuffer();
159                 error.append("error: unable to shift token \"" + token + "\"\n");
160                 //error.append("  before: " +pendingReductions+ "\n");
161                 //error.append("  before: " +totalReductions+ "\n");
162                 //for(Phase.Node n : hash.values()) {
163                 //n.queueReductions();
164                 //n.queueEmptyReductions();
165                 //}
166                 //error.append("  after: " +pendingReductions+ "\n");
167                 //error.append("  candidate states:\n");
168                 //for(Phase.Node n : hash.values()) {
169                     //for(Sequence.Position p : n.state) error.append("        " + p + "\n");
170                     //error.append("        --\n");
171                 //for(Parser.Table.Reduction r : n.state.getReductions(token)) error.append("        " + r + "\n");
172                     //error.append("        ==\n");
173                 //}
174                 next.error = error.toString();
175             }
176
177             // this massively improves GC performance
178             hash = null;
179         }
180
181        
182         // GSS Nodes //////////////////////////////////////////////////////////////////////////////
183
184         /** a node in the GSS */
185         public final class Node extends FastSet<Node> implements Invokable<Parser.Table.Reduction, Node, Node> {
186
187             public void addParent(Node parent, boolean fromEmptyReduction) {
188                 if (parents().contains(parent)) return;
189                 parents().add(parent);
190                 if (this!=parent && !fromEmptyReduction) queueReductions(parent);
191             }
192
193             private Forest.Ref holder = null;
194             private boolean allqueued = false;
195
196             /** what state this node is in */
197             public final Parser.Table.State state;
198
199             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
200             public Phase phase() { return Phase.this; }
201
202             public  Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
203             public  Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
204             public  FastSet<Node> parents() { return this; }
205
206             public void queueReductions() {
207                 if (allqueued) return;
208                 allqueued = true;
209                 int where = parents().size();
210                 /*
211                 for(Parser.Table.Reduction r : state.getReductions(token))
212                     if (r.numPop > 0)
213                         r.reduce(this);
214                 */
215                 state.invokeReductions(token, this, this, null);
216             }
217
218             public void queueReductions(Node n2) {
219                 if (!allqueued) { queueReductions(); return; }
220                 /*
221                 for(Parser.Table.Reduction r : state.getReductions(token))
222                     if (r.numPop > 0)
223                         r.reduce(this, n2);
224                 */
225                 state.invokeReductions(token, this, this, n2);
226             }
227
228             public final void invoke(Parser.Table.Reduction r, Node n, Node n2) {
229                 if (n==null) {
230                     if (r.numPop==0) r.reduce(this);
231                     return;
232                 }
233                 if (r.numPop==0) return;
234                 if (n2==null) {
235                     r.reduce(n);
236                 } else {
237                     r.reduce(n, n2);
238                 }
239             }
240             public void queueEmptyReductions() {
241                 if (!reducing) return;
242                 /*
243                   for(Parser.Table.Reduction r : state.getReductions(token))
244                         if (r.numPop==0)
245                             r.reduce(this);
246                 */
247                 state.invokeReductions(token, this, null, null);
248             }
249
250             private Node(Node parent, Forest pending, Parser.Table.State state, Phase start) {
251                 this.state = state;
252                 if (pending != null) this.holder().merge(pending);
253                 if (parent != null) parents().add(parent);
254                 if (Phase.this.hash.get(code(state, start)) != null) throw new Error("severe problem!");
255                 Phase.this.hash.put(code(state, start), this);
256                 Phase.this.numNodes++;
257                 if (parent==null) holder().valid = true; // hack to make sure that the "base" node is always considered valid
258             }
259         }
260
261     }
262
263     /** helper method */
264     private static boolean equal(Object a, Object b) {
265         if (a==null && b==null) return true;
266         if (a==null || b==null) return false;
267         return a.equals(b);
268     }
269
270     /** this is something of a hack right now */
271     private static long code(Parser.Table.State state, Phase start) {
272         return (((long)state.idx) << 32) | (start==null ? 0 : start.pos);
273     }
274 }