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) {
77             Node p = hash.get(code(state, parent==null?null:parent.phase()));
78             if (p != null)  newNode2(p, parent, pending, state, fromEmptyReduction);
79             else            newNode3(parent, pending, state, fromEmptyReduction);
80         }
81         private void newNode2(Node p, Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction) {
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) {
88             do {
89                 if (token != null && state.canShift(token)) break;
90                 if (state.isAccepting()) break;
91                 if (token==null) break;
92                 if (!state.canReduce(token)) return;
93                 //if (count > 1) break;
94                 //if (r.numPop == 0) break;
95                 //r.reduce(pending, parent, null, Phase.this, null);
96                 //return;
97             } while(false);
98
99             Node n = new Node(parent, pending, state);  // ALLOC
100             n.queueEmptyReductions();
101             if (!fromEmptyReduction) n.queueReductions(parent);
102         }
103
104         
105         /** perform all reduction operations */
106         public void reduce() {
107             reducing = true;
108             if (reducing_list==null || reducing_list.length < hash.size())
109                 reducing_list = new Phase.Node[hash.size() * 4];
110             Collection<Node> hv = hash.values();
111             hv.toArray(reducing_list);
112             int num = hv.size();
113             for(int i=0; i<num; i++) {
114                 Node n = reducing_list[i];
115                 n.queueEmptyReductions();
116                 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
117             }
118             for(int i=0; i<num; i++) {
119                 Node n = reducing_list[i];
120                 reducing_list[i] = null;
121                 n.queueReductions();
122             }
123         }
124
125         public void invoke(Parser.Table.State st, Forest result, Node n) {
126             next.newNode(n, result, st, true);
127         }
128         private Phase next = null;
129
130         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
131         public void shift(Phase next, Forest result) {
132             this.next = next;
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                 n.state.invokeShifts(token, this, result, n);
147                 /*
148                 for(Parser.Table.State st : n.state.getShifts(token)) {
149                     if (res == null) res = result;
150                     next.newNode(n, res, st, true, this);
151                     ok = true;
152                 }
153                 */
154             }
155
156             if (!ok && token != null) {
157                 StringBuffer error = new StringBuffer();
158                 error.append("error: unable to shift token \"" + token + "\"\n");
159                 //error.append("  before: " +pendingReductions+ "\n");
160                 //error.append("  before: " +totalReductions+ "\n");
161                 //for(Phase.Node n : hash.values()) {
162                 //n.queueReductions();
163                 //n.queueEmptyReductions();
164                 //}
165                 //error.append("  after: " +pendingReductions+ "\n");
166                 //error.append("  candidate states:\n");
167                 //for(Phase.Node n : hash.values()) {
168                     //for(Sequence.Position p : n.state) error.append("        " + p + "\n");
169                     //error.append("        --\n");
170                 //for(Parser.Table.Reduction r : n.state.getReductions(token)) error.append("        " + r + "\n");
171                     //error.append("        ==\n");
172                 //}
173                 next.error = error.toString();
174             }
175
176             // this massively improves GC performance
177             hash = null;
178         }
179
180        
181         // GSS Nodes //////////////////////////////////////////////////////////////////////////////
182
183         /** a node in the GSS */
184         public final class Node extends FastSet<Node> implements Invokable<Parser.Table.Reduction, Node, Node> {
185
186             private Forest.Ref holder = null;
187             private boolean allqueued = false;
188
189             /** what state this node is in */
190             public final Parser.Table.State state;
191
192             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
193             public Phase phase() { return Phase.this; }
194
195             public  Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
196             public  Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
197             public  FastSet<Node> parents() { return this; }
198
199             public void queueReductions() {
200                 if (allqueued) return;
201                 allqueued = true;
202                 int where = parents().size();
203                 state.invokeReductions(token, this, this, null);
204             }
205
206             public void queueReductions(Node n2) {
207                 if (!allqueued) { queueReductions(); return; }
208                 state.invokeReductions(token, this, this, n2);
209             }
210
211             public final void invoke(Parser.Table.Reduction r, Node n, Node n2) {
212                 if (n==null) {
213                     if (r.numPop==0) r.reduce(this);
214                     return;
215                 }
216                 if (r.numPop==0) return;
217                 if (n2==null) r.reduce(n);
218                 else          r.reduce(n, n2);
219             }
220             public void queueEmptyReductions() {
221                 if (!reducing) return;
222                 state.invokeReductions(token, this, null, null);
223             }
224
225             private Node(Node parent, Forest pending, Parser.Table.State state) {
226                 this.state = state;
227                 Phase start = parent==null ? null : parent.phase();
228                 if (pending != null) this.holder().merge(pending);
229                 if (parent != null) parents().add(parent, true);
230                 if (Phase.this.hash.get(code(state, start)) != null) throw new Error("severe problem!");
231                 Phase.this.hash.put(code(state, start), this);
232                 Phase.this.numNodes++;
233                 if (parent==null) holder().valid = true; // hack to make sure that the "base" node is always considered valid
234             }
235         }
236
237     }
238
239     /** helper method */
240     private static boolean equal(Object a, Object b) {
241         if (a==null && b==null) return true;
242         if (a==null || b==null) return false;
243         return a.equals(b);
244     }
245
246     /** this is something of a hack right now */
247     private static long code(Parser.Table.State state, Phase start) {
248         return (((long)state.idx) << 32) | (start==null ? 0 : (start.pos+1));
249     }
250 }