645fa8ff6f290d7750f382b7b04f0c7141158307
[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         boolean reducing = false;
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 nodes, keyed by the value returned by code() */
47         private HashMap<Long,Phase.Node> hash    = new HashMap<Long,Phase.Node>();  /* ALLOC */
48
49         /** the number of nodes in this phase */
50         private int numNodes = 0;
51
52         boolean closed = false;
53
54         private Token.Location location;
55         public Phase(Phase previous, Token token, Token.Location location) {
56             this.pos = previous==null ? 0 : previous.pos+1;
57             this.token = token;
58             this.location = location;
59         }
60
61         public boolean isDone() { return token == null; }
62
63         private String error = "generic syntax error";
64         public void checkFailure() throws Parser.Failed {
65             if (numNodes <= 0)
66                 throw new Parser.Failed(error, getLocation());
67         }
68
69         public Token.Location getLocation() { return location; }
70
71         /** add a new node (merging with existing nodes if possible)
72          *  @param parent             the parent of the new node
73          *  @param result             the SPPF result corresponding to the new node
74          *  @param state              the state that the new node is in
75          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
76          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
77          */
78         public void newNode(Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
79             Node p = hash.get(code(state, start));
80             if (p != null)  newNode2(p, parent, pending, state, fromEmptyReduction, start);
81             else            newNode3(parent, pending, state, fromEmptyReduction, start);
82         }
83         private void newNode2(Node p, Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
84             p.holder.merge(pending);
85             if (p.parents().contains(parent)) return;
86             p.addParent(parent, fromEmptyReduction);
87         }
88         private void newNode3(Node parent, Forest pending, Parser.Table.State state, boolean fromEmptyReduction, Phase start) {
89             do {
90                 if (token != null && state.canShift(token)) break;
91                 if (state.isAccepting()) break;
92                 if (token==null) break;
93                 int count = 0;
94                 Parser.Table.Reduction r = null;
95                 if (!state.hasReductions(token)) return;
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         /** perform all reduction operations */
109         public void reduce() {
110             reducing = true;
111             if (reducing_list==null || reducing_list.length < hash.size())
112                 reducing_list = new Phase.Node[hash.size() * 4];
113             Collection<Node> hv = hash.values();
114             hv.toArray(reducing_list);
115             int num = hv.size();
116             for(int i=0; i<num; i++) {
117                 Node n = reducing_list[i];
118                 n.queueEmptyReductions();
119                 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
120             }
121             for(int i=0; i<num; i++) {
122                 Node n = reducing_list[i];
123                 reducing_list[i] = null;
124                 n.queueReductions();
125             }
126         }
127
128         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
129         public void shift(Phase next, Forest result) {
130             closed = true;
131             Forest res = null;
132             boolean ok = false;
133             for(Phase.Node n : hash.values()) {
134                 if (n.holder==null) continue;
135                 n.holder.resolve();
136                 if (token == null && n.state.isAccepting()) {
137                     ok = true;
138                     if (finalResult==null) finalResult = new Forest.Ref();
139                     finalResult.merge(n.holder);
140                 }
141                 if (!n.holder.valid()) continue;
142                 if (token == null) continue;
143                 for(Parser.Table.State st : n.state.getShifts(token)) {
144                     if (res == null) res = result;
145                     next.newNode(n, res, st, true, this);
146                     ok = true;
147                 }
148             }
149
150             if (!ok && token != null) {
151                 StringBuffer error = new StringBuffer();
152                 error.append("error: unable to shift token \"" + token + "\"\n");
153                 //error.append("  before: " +pendingReductions+ "\n");
154                 //error.append("  before: " +totalReductions+ "\n");
155                 //for(Phase.Node n : hash.values()) {
156                 //n.queueReductions();
157                 //n.queueEmptyReductions();
158                 //}
159                 //error.append("  after: " +pendingReductions+ "\n");
160                 //error.append("  candidate states:\n");
161                 //for(Phase.Node n : hash.values()) {
162                     //for(Sequence.Position p : n.state) error.append("        " + p + "\n");
163                     //error.append("        --\n");
164                 //for(Parser.Table.Reduction r : n.state.getReductions(token)) error.append("        " + r + "\n");
165                     //error.append("        ==\n");
166                 //}
167                 next.error = error.toString();
168             }
169
170             // this massively improves GC performance
171             hash = null;
172         }
173
174        
175         // GSS Nodes //////////////////////////////////////////////////////////////////////////////
176
177         /** a node in the GSS */
178         public final class Node extends FastSet<Node> {
179
180             public void addParent(Node parent, boolean fromEmptyReduction) {
181                 parents().add(parent, true);
182                 if (this!=parent && !fromEmptyReduction) queueReductions(parent);
183             }
184
185             private Forest.Ref holder = null;
186             private boolean allqueued = false;
187
188             /** what state this node is in */
189             public final Parser.Table.State state;
190
191             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
192             public Phase phase() { return Phase.this; }
193
194             public  Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
195             public  Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
196             public  FastSet<Node> parents() { return this; }
197
198             public void queueReductions() {
199                 if (allqueued) return;
200                 allqueued = true;
201                 int where = parents().size();
202                 for(Parser.Table.Reduction r : state.getReductions(token))
203                     if (r.numPop >= 1)
204                         r.reduce(this);
205             }
206
207             public void queueReductions(Node n2) {
208                 if (!allqueued) { queueReductions(); return; }
209                 for(Parser.Table.Reduction r : state.getReductions(token))
210                     if (r.numPop > 0)
211                         r.reduce(this, n2);
212             }
213
214
215             public void queueEmptyReductions() {
216                 if (reducing)
217                     for(Parser.Table.Reduction r : token==null ? state.getEofReductions() : state.getReductions(token))
218                         if (r.numPop==0)
219                             r.reduce(this);
220             }
221
222             private Node(Node parent, Forest pending, Parser.Table.State state, Phase start) {
223                 this.state = state;
224                 if (pending != null) this.holder().merge(pending);
225                 if (parent != null) parents().add(parent);
226                 if (Phase.this.hash.get(code(state, start)) != null) throw new Error("severe problem!");
227                 Phase.this.hash.put(code(state, start), this);
228                 Phase.this.numNodes++;
229                 if (parent==null) holder().valid = true; // hack to make sure that the "base" node is always considered valid
230             }
231         }
232
233     }
234
235     /** helper method */
236     private static boolean equal(Object a, Object b) {
237         if (a==null && b==null) return true;
238         if (a==null || b==null) return false;
239         return a.equals(b);
240     }
241
242     /** this is something of a hack right now */
243     private static long code(Parser.Table.State state, Phase start) {
244         return (((long)state.idx) << 32) | (start==null ? 0 : start.pos);
245     }
246 }