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