misc updates
[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<Integer,Sequence> assumed = new HashMapBag<Integer,Sequence>();
22     HashMapBag<Sequence,Phase.Waiting> waiting   = new HashMapBag<Sequence,Phase.Waiting>();
23     HashMapBag<Integer,Sequence> performed = new HashMapBag<Integer,Sequence>();
24     HashSet<Phase.Waiting> tail = new     HashSet<Phase.Waiting>();
25     
26     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
27     public class Phase implements Invokable<State, Forest, GSS.Phase.Node> {
28
29         /** the token immediately after this phase */
30         public  final Token token;
31
32         boolean reducing;
33
34         /** currently this is necessary only for the code() hack -- it doesn't actually correspond to the input */
35         private final int pos;
36
37         /** FIXME */
38         public  Forest.Ref finalResult;
39
40         /** all nodes, keyed by the value returned by code() */
41         /*private*/ HashMap<Long,Phase.Node> hash;  /* ALLOC */
42
43         /** the number of nodes in this phase */
44         private int numNodes;
45
46         boolean closed;
47
48         private boolean good;
49         private Phase next = null;
50
51         private Token.Location location;
52         public final Parser parser;
53
54         private Forest forest;
55         Phase prev;
56         public Phase(Phase prev, Parser parser, Phase previous, Token token, Token.Location location, Forest forest) {
57             this.prev = prev;
58             this.forest = forest;
59             this.parser = parser;
60             this.pos = previous==null ? 0 : previous.pos+1;
61             this.token = token;
62             this.location = location;
63             inhibited.clear();
64             assumed.clear();
65             reset();
66         }
67
68         public void reset() {
69             tail.clear();
70             waiting.clear();
71             performed.clear();
72             hash = new HashMap<Long,Phase.Node>();
73             good = false;
74             closed = false;
75             numNodes = 0;
76             reducing = false;
77             finalResult = null;
78             if (prev != null) prev.shift(this, forest);
79         }
80
81         public void complain(Node n, HashMap<String,HashSet<String>> errors, boolean force) {
82             if (n.touched) return;
83             n.touched = true;
84             for(Position p : n.state) {
85                 //if (!p.isLast()) { 
86                 if (((p.isFirst() || p.isLast()) && !force) || p.owner().name==null) {
87                     for(Node n2 : n.parents())
88                         complain(n2, errors, force | p.isFirst());
89                 } else {
90                     String seqname = p.owner().name;
91                     HashSet<String> hs = errors.get(seqname);
92                     if (hs==null) errors.put(seqname, hs = new HashSet<String>());
93                     hs.add(p.element()+"");
94                     //String s = "  while parsing " + seqname + ": expected a " + p.element();
95                         //"\n";
96                     /*
97                     s +=       "      parsed: ";
98                     for(Position p2 = p.owner().firstp(); p2 != null && p2 != p && !p2.isLast(); p2 = p2.next()) s += (p2.element() + " ");
99                     s += "\n";
100                     s +=       "    expected: ";
101                     for(Position p2 = p; p2 != null && !p2.isLast(); p2 = p2.next()) s += (p2.element() + " ");
102                     */
103                     //s += "\n";
104                     //errors.add(s);
105                 }
106             }
107         }
108
109         public String black(Object o) { return "\033[30m"+o+"\033[0m"; }
110         public String red(Object o) { return "\033[31m"+o+"\033[0m"; }
111         public String green(Object o) { return "\033[32m"+o+"\033[0m"; }
112         public String yellow(Object o) { return "\033[33m"+o+"\033[0m"; }
113         public String blue(Object o) { return "\033[34m"+o+"\033[0m"; }
114         public String purple(Object o) { return "\033[35m"+o+"\033[0m"; }
115         public String cyan(Object o) { return "\033[36m"+o+"\033[0m"; }
116         public String el(Object e) {
117             String s = e.toString();
118             if (s.length()==0 || s.charAt(0)!='\"' || s.charAt(s.length()-1)!='\"') return yellow(s);
119             s = s.substring(1);
120             s = s.substring(0, s.length()-1);
121             StringBuffer ret = new StringBuffer();
122             for(int i=0; i<s.length(); i++) {
123                 if (s.charAt(i)=='\\' && i<s.length()-1) ret.append(s.charAt(++i));
124                 else ret.append(s);
125             }
126             return purple(ret.toString());
127         }
128         public String error(String message) {
129             String lookAhead = token==null ? "<EOF>" : token.toString();
130             StringBuffer ret = new StringBuffer();
131             ret.append("\n  ");
132             ret.append(message);
133             HashMap<String,HashSet<String>> errors = new HashMap<String,HashSet<String>>();
134             for(Node n : hash.values()) complain(n, errors, false);
135             for(String s : errors.keySet()) {
136                 ret.append("    while parsing " + yellow(s));
137                 HashSet<String> hs = errors.get(s);
138                 if (hs.size()==1) ret.append(" expected " + yellow(el(hs.iterator().next())) + "\n");
139                 else {
140                     ret.append(" expected ");
141                     boolean first = true;
142                     for(String s2 : hs) {
143                         if (!first) ret.append(" or ");
144                         first = false;
145                         ret.append(yellow(el(s2)));
146                     }
147                     ret.append("\n");
148                 }
149             }
150             return ret.toString();
151         }
152         
153         public boolean isDone() throws Parser.Failed {
154             if (token != null) return false;
155             if (token==null && finalResult==null)
156                 throw new Parser.Failed(error(red("unexpected end of file\n")),
157                                         getLocation());
158             return true;
159         }
160
161         public Token.Location getLocation() { return location; }
162
163         /** add a new node (merging with existing nodes if possible)
164          *  @param parent             the parent of the new node
165          *  @param result             the SPPF result corresponding to the new node
166          *  @param state              the state that the new node is in
167          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
168          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
169          */
170         public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
171             Node p = hash.get(code(state, parent==null?null:parent.phase()));
172             if (p != null)  return newNode2(p, parent, pending, state, fromEmptyReduction);
173             else            return newNode3(parent, pending, state, fromEmptyReduction);
174         }
175         public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
176             int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
177             Sequence owner = reduction==null ? null : reduction.position.owner();
178             if (reduction!=null) {
179                 if (inhibited.contains(pos, owner)) return;
180                 /*
181                 if (assumed.contains(pos, owner)) {
182                     tail.add(new Waiting(parent, pending, state, fromEmptyReduction, reduction));
183                     return;
184                 }
185                 */
186                 if (owner.needs != null)
187                     for(Sequence s : owner.needs)
188                         if (!performed.contains(pos, s)) {
189                             waiting.add(s, new Waiting(parent, pending, state, fromEmptyReduction, reduction));
190                             return;
191                         }
192                 if ((owner.needed != null && owner.needed.size()>0) ||
193                     (owner.hated != null && owner.hated.size()>0) ||
194                     (owner.hates != null && owner.hates.size()>0))
195                     performed.add(pos, owner);
196             }
197             if (!owner.lame)
198                 newNode(parent, pending, state, fromEmptyReduction);
199             if (reduction!=null) inhibit(reduction, parent==null?0:parent.phase().pos);
200             if (reduction != null) {
201                 boolean redo = true;
202                 while(redo) {
203                     redo = false;
204                     for(Waiting w : waiting.getAll(owner)) {
205                         if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
206                             waiting.remove(owner, w);
207                             w.perform();
208                             redo = true;
209                             break;
210                         }
211                     }
212                 }
213             }
214         }
215         private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
216             p.holder.merge(pending);
217             if (p.parents().contains(parent)) return true;
218             p.parents().add(parent, true);
219             if (p!=parent && !fromEmptyReduction) p.queueReductions(parent);
220             return true;
221         }
222         private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
223             do {
224                 if (token != null && state.canShift(token)) break;
225                 if (state.isAccepting()) break;
226                 if (token==null) break;
227                 //if (!state.canReduce(token)) return false;
228                 //if (count > 1) break;
229                 //if (r.numPop == 0) break;
230                 //r.reduce(pending, parent, null, Phase.this, null);
231                 //return;
232             } while(false);
233
234             Node n = new Node(parent, pending, state, fromEmptyReduction);  // ALLOC
235             n.queueEmptyReductions();
236             if (!fromEmptyReduction) n.queueReductions(parent);
237             return true;
238         }
239
240         public void uninhibit(int p, Sequence s) {
241             if (s.hated!=null)
242                 for(Sequence s2 : s.hated)
243                     inhibited.remove(p, s2);
244         }
245
246         public void inhibit(Reduction r, int p) {
247             if (r.position.owner().hated == null) return;
248             // remember that dead states are still allowed to shift -- just not allowed to reduce
249             boolean reset = false;
250             for(Sequence seq : r.position.owner().hated) {
251                 if (performed.contains(p,seq)) {
252                     uninhibit(p, seq);
253                     //System.out.println("\nresetting due to " + r.position.owner() + " killing " + seq);
254                     //inhibited.clear();
255                     inhibited.add(p, seq);
256                     //assumed = inhibited;
257                     //inhibited = new HashMapBag<Integer,Sequence>();
258                     reset = true;
259                     resets++;
260                     throw new Reset();
261                 }
262                 inhibited.add(p, seq);
263             }
264         }
265         
266         /** perform all reduction operations */
267         public void reduce() {
268             try {
269                 reducing = true;
270                 if (reducing_list==null || reducing_list.length < hash.size())
271                     reducing_list = new Phase.Node[hash.size() * 4];
272                 Collection<Node> hv = hash.values();
273                 hv.toArray(reducing_list);
274                 int num = hv.size();
275                 for(int i=0; i<num; i++) {
276                     Node n = reducing_list[i];
277                     n.queueEmptyReductions();
278                     // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
279                 }
280                 for(int i=0; i<num; i++) {
281                     Node n = reducing_list[i];
282                     reducing_list[i] = null;
283                     n.queueReductions();
284                 }
285                 //for(Waiting w : tail)
286                 //w.perform();
287             } catch (Reset r) {
288                 reset();
289                 reduce();
290             }
291         }
292
293         class Reset extends RuntimeException { }
294
295         public void invoke(State st, Forest result, Node n) {
296             good |= next.newNode(n, result, st, false);
297         }
298
299         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
300         public void shift(Phase next, Forest result) throws Parser.Failed {
301             if (prev!=null) prev.hash = null;
302             this.next = next;
303             closed = true;
304             Forest res = null;
305             boolean ok = false;
306             for(Phase.Node n : hash.values()) {
307                 //if (n.holder().empty() && pos>0) continue;
308                 if (token == null && n.state.isAccepting()) {
309                     if (finalResult==null) finalResult = new Forest.Ref();
310                     finalResult.merge(n.holder);
311                 }
312                 if (token == null) continue;
313                 n.state.invokeShifts(token, this, result, n);
314             }
315
316             if (!good && token!=null)
317                 throw new Parser.Failed(error(red("unexpected character")+" "+purple(token)+" encountered at "+green(getLocation())+"\n"),
318                                         getLocation());
319             if (token==null && finalResult==null)
320                 throw new Parser.Failed(error(red("unexpected end of file\n")),
321                                         getLocation());
322
323             // this massively improves GC performance
324             //hash = null;
325         }
326
327
328         public class Waiting {
329             Node parent;
330             Forest pending;
331             State state;
332             boolean fromEmptyReduction;
333             Reduction reduction;
334             public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
335                 waits++;
336                 this.parent = parent;
337                 this.pending = pending;
338                 this.state = state;
339                 this.fromEmptyReduction = fromEmptyReduction;
340                 this.reduction = reduction;
341             }
342             public void perform() {
343                 //System.out.println("performing: " + reduction.position);
344                 newNode(parent, pending, state, fromEmptyReduction, reduction);
345             }
346         }
347        
348         // GSS Nodes //////////////////////////////////////////////////////////////////////////////
349
350         /** a node in the GSS */
351         public final class Node extends FastSet<Node> implements Invokable<Reduction, Node, Node> {
352
353             public boolean touched = false;
354             private Forest.Ref holder = null;
355             private boolean allqueued = false;
356
357             /** what state this node is in */
358             public final State state;
359
360             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
361             public Phase phase() { return Phase.this; }
362
363             public  Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
364             public  Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
365             public  FastSet<Node> parents() { return this; }
366
367             public void queueReductions() {
368                 if (!reducing) return;
369                 if (allqueued) return;
370                 allqueued = true;
371                 int where = parents().size();
372                 state.invokeReductions(token, this, this, null);
373             }
374
375             public void queueReductions(Node n2) {
376                 if (!allqueued) { queueReductions(); return; }
377                 state.invokeReductions(token, this, this, n2);
378             }
379
380             public final void invoke(Reduction r, Node n, Node n2) {
381                 if (n==null) {
382                     if (r.numPop==0) r.reduce(this);
383                     return;
384                 }
385                 if (r.numPop==0) return;
386                 if (n2==null) r.reduce(n);
387                 else          r.reduce(n, n2);
388             }
389             public void queueEmptyReductions() {
390                 if (!reducing) return;
391                 state.invokeReductions(token, this, null, null);
392             }
393
394             private boolean fe;
395             public boolean dead = false;
396             public boolean redo = false;
397             private Node(Node parent, Forest pending, State state, boolean fe) {
398                 this.fe = fe;
399                 this.state = state;
400                 this.holder().merge(pending);
401                 //if (holder().empty()) throw new Error(holder()+"");
402                 Phase start = parent==null ? null : parent.phase();
403                 if (parent != null) parents().add(parent, true);
404                 if (Phase.this.hash.get(code(state, start)) != null) throw new Error("severe problem!");
405                 Phase.this.hash.put(code(state, start), this);
406                 Phase.this.numNodes++;
407             }
408         }
409
410     }
411
412     /** helper method */
413     private static boolean equal(Object a, Object b) {
414         if (a==null && b==null) return true;
415         if (a==null || b==null) return false;
416         return a.equals(b);
417     }
418
419     /** this is something of a hack right now */
420     private static long code(State state, Phase start) {
421         return (((long)state.idx) << 32) | (start==null ? 0 : (start.pos+1));
422     }
423 }