refactored error reporting
[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 edu.berkeley.sbp.Sequence.Position;
5 import edu.berkeley.sbp.Parser.Table.State;
6 import edu.berkeley.sbp.Parser.Table.Reduction;
7 import java.io.*;
8 import java.util.*;
9 import java.lang.reflect.*;
10
11 /** implements Tomita's Graph Structured Stack */
12 class GSS {
13
14     public GSS() { }
15
16     private Phase.Node[] reducing_list = null;
17     public int resets = 0;
18     public int waits = 0;
19
20     HashMapBag<Integer,Sequence>       inhibited = new HashMapBag<Integer,Sequence>();
21     HashMapBag<Sequence,Phase.Waiting> waiting   = new HashMapBag<Sequence,Phase.Waiting>();
22     HashMapBag<Integer,Sequence>       performed = new HashMapBag<Integer,Sequence>();
23     
24     /** FIXME */
25     public  Forest.Ref finalResult;
26
27     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
28     public class Phase implements Invokable<State, Forest, GSS.Phase.Node>, IntegerMappable {
29
30         /** the token immediately after this phase */
31         final Token token;
32
33         private final int pos;
34
35         boolean reducing;
36         private IntPairMap<Phase.Node> hash;  /* ALLOC */
37         private boolean closed;
38         private boolean good;
39         private Phase next = null;
40         private Phase prev;
41         private Token.Location location;
42         public final Parser parser;
43
44         private Forest forest;
45
46         public Phase(Phase prev, Parser parser, Phase previous, Token token, Token.Location location, Forest forest) {
47             this.prev = prev;
48             this.forest = forest;
49             this.parser = parser;
50             this.pos = previous==null ? 0 : previous.pos+1;
51             this.token = token;
52             this.location = location;
53             inhibited.clear();
54             reset();
55         }
56
57         public void reset() {
58             waiting.clear();
59             performed.clear();
60             hash = new IntPairMap<Phase.Node>();
61             good = false;
62             closed = false;
63             reducing = false;
64             finalResult = null;
65             if (prev != null) prev.shift(this, forest);
66         }
67
68       
69         public boolean isDone() throws ParseFailed {
70             if (token != null) return false;
71             if (token==null && finalResult==null)
72                 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()), getLocation());
73             return true;
74         }
75
76         public Token.Location getLocation() { return location; }
77
78         /** add a new node (merging with existing nodes if possible)
79          *  @param parent             the parent of the new node
80          *  @param result             the SPPF result corresponding to the new node
81          *  @param state              the state that the new node is in
82          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
83          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
84          */
85         public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
86             Node p = hash.get(state, parent==null?null:parent.phase());
87             if (p != null)  return newNode2(p, parent, pending, state, fromEmptyReduction);
88             else            return newNode3(parent, pending, state, fromEmptyReduction);
89         }
90         public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
91             int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
92             Sequence owner = reduction==null ? null : reduction.position.owner();
93             if (reduction!=null) {
94                 if (inhibited.contains(pos, owner)) return;
95                 if (owner.needs != null)
96                     for(Sequence s : owner.needs)
97                         if (!performed.contains(pos, s)) {
98                             waiting.add(s, new Waiting(parent, pending, state, fromEmptyReduction, reduction));
99                             return;
100                         }
101                 if ((owner.needed != null && owner.needed.size()>0) ||
102                     (owner.hated != null && owner.hated.size()>0) ||
103                     (owner.hates != null && owner.hates.size()>0))
104                     performed.add(pos, owner);
105             }
106             if (!owner.lame)
107                 newNode(parent, pending, state, fromEmptyReduction);
108             if (reduction!=null) inhibit(reduction, parent==null?0:parent.phase().pos);
109             if (reduction != null) {
110                 boolean redo = true;
111                 while(redo) {
112                     redo = false;
113                     for(Waiting w : waiting.getAll(owner)) {
114                         if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
115                             waiting.remove(owner, w);
116                             w.perform();
117                             redo = true;
118                             break;
119                         }
120                     }
121                 }
122             }
123         }
124         private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
125             p.holder.merge(pending);
126             if (p.parents().contains(parent)) return true;
127             p.parents().add(parent, true);
128             if (p!=parent && !fromEmptyReduction) p.queueReductions(parent);
129             return true;
130         }
131         private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
132             do {
133                 if (token != null && state.canShift(token)) break;
134                 if (state.isAccepting()) break;
135                 if (token==null) break;
136                 if (!state.canReduce(token)) return false;
137                 //if (count > 1) break;
138                 //if (r.numPop == 0) break;
139                 //r.reduce(pending, parent, null, Phase.this, null);
140                 //return;
141             } while(false);
142
143             Node n = new Node(parent, pending, state, fromEmptyReduction);  // ALLOC
144             n.queueEmptyReductions();
145             if (!fromEmptyReduction) n.queueReductions(parent);
146             return true;
147         }
148
149         public void uninhibit(int p, Sequence s) {
150             if (s.hated!=null)
151                 for(Sequence s2 : s.hated)
152                     inhibited.remove(p, s2);
153         }
154
155         public void inhibit(Reduction r, int p) {
156             if (r.position.owner().hated == null) return;
157             // remember that dead states are still allowed to shift -- just not allowed to reduce
158             boolean reset = false;
159             for(Sequence seq : r.position.owner().hated) {
160                 if (performed.contains(p,seq)) {
161                     uninhibit(p, seq);
162                     //System.out.println("\nresetting due to " + r.position.owner() + " killing " + seq);
163                     //inhibited.clear();
164                     inhibited.add(p, seq);
165                     //inhibited = new HashMapBag<Integer,Sequence>();
166                     reset = true;
167                     resets++;
168                     throw new Reset();
169                 }
170                 inhibited.add(p, seq);
171             }
172         }
173         
174         /** perform all reduction operations */
175         public void reduce() {
176             try {
177                 reducing = true;
178                 if (reducing_list==null || reducing_list.length < hash.size())
179                     reducing_list = new Phase.Node[hash.size() * 4];
180                 hash.toArray(reducing_list);
181                 int num = hash.size();
182                 for(int i=0; i<num; i++) {
183                     Node n = reducing_list[i];
184                     n.queueEmptyReductions();
185                     // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
186                 }
187                 for(int i=0; i<num; i++) {
188                     Node n = reducing_list[i];
189                     reducing_list[i] = null;
190                     n.queueReductions();
191                 }
192             } catch (Reset r) {
193                 reset();
194                 reduce();
195             }
196         }
197
198         class Reset extends RuntimeException { }
199
200         public void invoke(State st, Forest result, Node n) {
201             good |= next.newNode(n, result, st, false);
202         }
203
204         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
205         public void shift(Phase next, Forest result) throws ParseFailed {
206             // this massively improves GC performance
207             if (prev!=null) prev.hash = null;
208             this.next = next;
209             closed = true;
210             Forest res = null;
211             boolean ok = false;
212             for(Phase.Node n : hash.values()) {
213                 if (token == null && n.state.isAccepting()) {
214                     if (finalResult==null) finalResult = new Forest.Ref();
215                     finalResult.merge(n.holder);
216                 }
217                 if (token == null) continue;
218                 n.state.invokeShifts(token, this, result, n);
219             }
220
221             if (!good && token!=null)
222                 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected character")+" "+ANSI.purple(token)+" encountered at "+ANSI.green(getLocation())+"\n", token, hash.values()),
223                                         getLocation());
224             if (token==null && finalResult==null)
225                 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()),
226                                         getLocation());
227         }
228
229
230         public class Waiting {
231             Node parent;
232             Forest pending;
233             State state;
234             boolean fromEmptyReduction;
235             Reduction reduction;
236             public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
237                 waits++;
238                 this.parent = parent;
239                 this.pending = pending;
240                 this.state = state;
241                 this.fromEmptyReduction = fromEmptyReduction;
242                 this.reduction = reduction;
243             }
244             public void perform() {
245                 //System.out.println("performing: " + reduction.position);
246                 newNode(parent, pending, state, fromEmptyReduction, reduction);
247             }
248         }
249        
250         // GSS Nodes //////////////////////////////////////////////////////////////////////////////
251
252         /** a node in the GSS */
253         public final class Node extends FastSet<Node> implements Invokable<Reduction, Node, Node> {
254
255             public boolean touched = false;
256             private Forest.Ref holder = null;
257             private boolean allqueued = false;
258
259             /** what state this node is in */
260             public final State state;
261
262             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
263             public Phase phase() { return Phase.this; }
264
265             public  Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
266             public  Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
267             public  FastSet<Node> parents() { return this; }
268
269             public void queueReductions() {
270                 if (!reducing) return;
271                 if (allqueued) return;
272                 allqueued = true;
273                 int where = parents().size();
274                 state.invokeReductions(token, this, this, null);
275             }
276
277             public void queueReductions(Node n2) {
278                 if (!allqueued) { queueReductions(); return; }
279                 state.invokeReductions(token, this, this, n2);
280             }
281
282             public final void invoke(Reduction r, Node n, Node n2) {
283                 if (n==null) {
284                     if (r.position.pos==0) r.reduce(this);
285                     return;
286                 }
287                 if (r.position.pos==0) return;
288                 if (n2==null) r.reduce(n);
289                 else          r.reduce(n, n2);
290             }
291             public void queueEmptyReductions() {
292                 if (!reducing) return;
293                 state.invokeReductions(token, this, null, null);
294             }
295
296             private boolean fe;
297             public boolean dead = false;
298             public boolean redo = false;
299             private Node(Node parent, Forest pending, State state, boolean fe) {
300                 this.fe = fe;
301                 this.state = state;
302                 this.holder().merge(pending);
303                 Phase start = parent==null ? null : parent.phase();
304                 if (parent != null) parents().add(parent, true);
305                 if (Phase.this.hash.get(state, start) != null) throw new Error("severe problem!");
306                 Phase.this.hash.put(state, start, this);
307             }
308         }
309
310         public int toInt() { return pos+1; }
311         public int size() { return hash==null ? 0 : hash.size(); }
312     }
313
314 }