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