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