checkpoint
[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.Parser.Table.*;
5 import edu.berkeley.sbp.Sequence.Position;
6 import java.io.*;
7 import java.util.*;
8 import java.lang.reflect.*;
9
10 /** implements Tomita's Graph Structured Stack */
11 class GSS {
12
13     static int count = 0;
14     static int shifts = 0;
15     static int reductions = 0;
16     int resets = 0;
17     int waits = 0;
18     
19     public GSS() { }
20
21     private Phase.Node[] reducing_list = null;
22
23     // FIXME: right now, these are the performance bottleneck
24     HashMapBag<Sequence,Phase.Waiting> waiting         = new HashMapBag<Sequence,Phase.Waiting>();
25     HashMapBag<Integer,Sequence>       performed       = new HashMapBag<Integer,Sequence>();
26     HashMapBag<Integer,Sequence>       lastperformed   = new HashMapBag<Integer,Sequence>();
27     HashMapBag<Integer,Sequence>       expected        = new HashMapBag<Integer,Sequence>();
28     
29     /** FIXME */
30     Forest.Many finalResult;
31
32     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
33     class Phase<Tok> implements Invokable<State, Forest, Phase<Tok>.Node>, IntegerMappable, GraphViz.ToGraphViz, Iterable<Phase.Node> {
34
35         public Iterator<Phase.Node> iterator() { return hash.iterator(); }
36         public void invoke(State st, Forest result, Node n) {
37             shifts++;
38             good |= next.newNode(n, result, st, false);
39         }
40
41         /** the token immediately after this phase */
42         final Tok token;
43
44         private final int pos;
45
46         boolean reducing;
47         private IntPairMap<Phase.Node> hash;  /* ALLOC */
48         private boolean closed;
49         private boolean good;
50         private Phase next = null;
51         private Phase prev;
52         private Input.Location location;
53         public final Parser parser;
54
55         private Forest forest;
56
57         public Phase(Phase prev, Parser parser, Phase previous, Tok token, Input.Location location, Forest forest) throws ParseFailed {
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             performed.clear();
65             reset();
66         }
67
68         public void reset() throws ParseFailed {
69             waiting.clear();
70             expected.clear();
71             lastperformed.clear();
72             lastperformed.addAll(performed);
73             performed.clear();
74             hash = new IntPairMap<Phase.Node>();
75             reset = false;
76             good = false;
77             closed = false;
78             reducing = false;
79             finalResult = null;
80             if (prev != null) prev.shift(this, forest);
81         }
82
83       
84         public boolean isDone() throws ParseFailed {
85             if (token != null) return false;
86             if (token==null && finalResult==null)
87                 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()), getLocation());
88             return true;
89         }
90
91         public Input.Location getLocation() { return location; }
92
93         /** add a new node (merging with existing nodes if possible)
94          *  @param parent             the parent of the new node
95          *  @param result             the SPPF result corresponding to the new node
96          *  @param state              the state that the new node is in
97          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
98          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
99          */
100         public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
101             Node p = hash.get(state, parent==null?null:parent.phase());
102             if (p != null)  return newNode2(p, parent, pending, state, fromEmptyReduction);
103             else            return newNode3(parent, pending, state, fromEmptyReduction);
104         }
105         public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
106             int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
107             Sequence owner = reduction==null ? null : reduction.owner();
108             if (reduction!=null) {
109                 if (owner.hates!=null) {
110                     for (Sequence s : performed.getAll(pos))
111                         if (owner.hates.contains(s))
112                             return;
113                     for (Sequence s : lastperformed.getAll(pos))
114                         if (owner.hates.contains(s)) {
115                             //System.out.println("now expecting ["+pos+"] => " + s);
116                             expected.add(pos, s);
117                             return;
118                         }
119                 }
120                 if (owner.needs != null)
121                     for(Sequence s : owner.needs)
122                         if (!performed.contains(pos, s)) {
123                             waiting.add(s, new Waiting(parent, pending, state, fromEmptyReduction, reduction));
124                             return;
125                         }
126                 if (!performed.contains(pos, owner)) {
127                     performed.add(pos, owner);
128                     if (owner.hated != null)
129                         for(Sequence seq : owner.hated)
130                             if (performed.contains(pos, seq)) {
131                                 performed.remove(pos, seq);
132                                 reset = true;
133                             }
134                 }
135             }
136             newNode(parent, pending, state, fromEmptyReduction);
137             if (reduction != null) {
138                 boolean redo = true;
139                 while(redo) {
140                     redo = false;
141                     for(Waiting w : waiting.getAll(owner)) {
142                         if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
143                             waiting.remove(owner, w);
144                             w.perform();
145                             redo = true;
146                             break;
147                         }
148                     }
149                 }
150             }
151         }
152
153         private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
154             if (p.merge(parent, pending)) return true;
155             p.parents().add(parent, true);
156             if (p!=parent && !fromEmptyReduction && reducing) p.performReductions(parent);
157             return true;
158         }
159
160         private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
161             do {
162                 if (token != null && state.canShift(token)) break;
163                 if (state.isAccepting()) break;
164                 if (token==null) break;
165                 if (!state.canReduce(token)) return false;
166                 //if (count > 1) break;
167                 //if (r.numPop == 0) break;
168                 //r.reduce(pending, parent, null, Phase.this, null);
169                 //return;
170             } while(false);
171
172             Node n = new Node(parent, pending, state);  // ALLOC
173             if (reducing) {
174                 n.performEmptyReductions();
175                 if (!fromEmptyReduction) n.performReductions(parent);
176             }
177             return true;
178         }
179
180         /** perform all reduction operations */
181         public void reduce() throws ParseFailed {
182             try {
183                 reducing = true;
184                 if (reducing_list==null || reducing_list.length < hash.size())
185                     reducing_list = new Phase.Node[hash.size() * 4];
186                 hash.toArray(reducing_list);
187                 int num = hash.size();
188                 for(int i=0; i<num; i++) {
189                     Node n = reducing_list[i];
190                     n.performEmptyReductions();
191                     // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
192                 }
193                 for(int i=0; i<num; i++) {
194                     Node n = reducing_list[i];
195                     reducing_list[i] = null;
196                     n.performReductions();
197                 }
198                 if (reset) {
199                     reset = false;
200                     resets++;
201                     throw new Reset();
202                 }                
203                 for(int i : expected)
204                     for(Sequence s : expected.getAll(i))
205                         if (!performed.contains(i, s)) {
206                             //System.out.println("resetting due to pos="+i+": " + s + " " + System.identityHashCode(s));
207                             resets++;
208                             throw new Reset();
209                         }
210             } catch (Reset r) {
211                 reset();
212                 reduce();
213             }
214             count = 0;
215         }
216
217         private boolean reset = false;
218         class Reset extends RuntimeException { }
219
220         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
221         public void shift(Phase next, Forest result) throws ParseFailed {
222             // this massively improves GC performance
223             if (prev!=null && parser.helpgc) {
224                 prev.hash = null;
225             }
226             this.next = next;
227             closed = true;
228             Forest res = null;
229             boolean ok = false;
230             for(Phase.Node n : hash.values()) {
231                 if (token == null && n.state.isAccepting()) {
232                     if (finalResult==null) finalResult = new Forest.Many();
233                     for(Object f : n.results())
234                         finalResult.merge((Forest)f);
235                 }
236                 if (token == null) continue;
237                 n.state.invokeShifts(token, this, result, n);
238             }
239
240             if (!good && token!=null)
241                 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected character ")+" \'"+
242                                                         ANSI.purple(StringUtil.escapify(token+"", "\\\'\r\n"))+
243                                                         "\' encountered at "+
244                                                         ANSI.green(getLocation())+"\n", token, hash.values()),
245                                         getLocation());
246             if (token==null && finalResult==null)
247                 throw new ParseFailed(ParseFailed.error(ANSI.red("unexpected end of file\n"), token, hash.values()),
248                                         getLocation());
249         }
250
251
252         class Waiting {
253             Node parent;
254             Forest pending;
255             State state;
256             boolean fromEmptyReduction;
257             Position reduction;
258             public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Position reduction) {
259                 waits++;
260                 this.parent = parent;
261                 this.pending = pending;
262                 this.state = state;
263                 this.fromEmptyReduction = fromEmptyReduction;
264                 this.reduction = reduction;
265             }
266             public void perform() {
267                 //System.out.println("performing: " + reduction.position);
268                 newNode(parent, pending, state, fromEmptyReduction, reduction);
269             }
270         }
271        
272         // Node /////////////////////////////////////////////////////////////////////////////////
273
274         /** a node in the GSS */
275         final class Node implements Invokable<Position, Node, Node>, IntegerMappable, GraphViz.ToGraphViz {
276             public FastSet<Node> set = new FastSet<Node>();
277
278            
279             private boolean allqueued = false;
280
281             /** what state this node is in */
282             public final Parser.Table<Tok>.State<Tok> state;
283
284             /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
285             public  Phase phase() { return Phase.this; }
286
287             private HashSet<Forest.Many> resultMap = new HashSet<Forest.Many>();
288             public Iterable<Forest.Many> results() { return resultMap; }
289             public FastSet<Node> parents() { return set; }
290             public boolean merge(Node parent, Forest result) {
291                 // FIXME: inefficient!
292                 for(Forest.Many f : results()) {
293                     if (f.parents.contains(parent) /* UGLY: */ && f.parents.size()==1) {
294                         f.merge(result);
295                         return true;
296                     }
297                 }
298                 Forest.Many f = new Forest.Many();
299                 f.parents.add(parent);
300                 f.merge(result);
301                 resultMap.add(f);
302                 set.add(parent, true);
303                 return false;
304             }
305
306             public void performReductions() {
307                 if (allqueued) return;
308                 allqueued = true;
309                 state.invokeReductions(token, this, this, null);
310             }
311
312             public void performReductions(Node n2) {
313                 if (!allqueued) performReductions();
314                 else            state.invokeReductions(token, this, this, n2);
315             }
316
317             public void performEmptyReductions() { state.invokeReductions(token, this, null, null); }
318             public final void invoke(Position r, Node n, Node n2) {
319                 reductions++;
320                 if (n==null || n2==null || r.pos==0) {
321                     if (r.pos==0) {
322                         if (n==null) n = this;
323                         else return;
324                     }
325                     if (n==null) return;
326                     Forest[] holder = new Forest[r.pos];
327                     if (r.pos==0) n.finish(r, r.zero(), n.phase());
328                     else          n.reduce(r, r.pos-1,  n.phase(), null);
329                 } else {
330                     if (r.pos<=0) throw new Error("called wrong form of reduce()");
331                     int pos = r.pos-1;
332                     n.reduce(r, pos, n.phase(), n2);
333                 }
334             }
335
336             public void reduce(Position r, int pos, Phase target, Node only) {
337                 Forest[] holder = r.holder;
338                 Forest old = holder[pos];
339
340                 HashSet<Forest> rr = new HashSet<Forest>();
341                 for(Forest result : results()) rr.add(result);
342                 for(Forest result : rr)
343                     for(Node child : ((Forest.Many<?>)result).parents) {
344                         if (only != null && child!=only) continue;
345                         holder[pos] = result;
346                         if (pos==0) child.finish(r, r.rewrite(child.phase().getLocation().createRegion(phase().getLocation())), target);
347                         else        child.reduce(r, pos-1, target, null);
348                     }
349
350                 holder[pos] = old;
351             }
352
353             public void finish(Position r, Forest result, Phase<Tok> target) {
354                 Parser.Table<Tok>.State<Tok> state0 = state.gotoSetNonTerminals.get(r.owner());
355                 if (result==null) throw new Error();
356                 if (state0!=null)
357                     target.newNode(this, result, state0, r.pos<=0, r);
358             }
359
360             private Node(Node parent, Forest pending, State state) {
361                 this.state = state;
362                 this.merge(parent, pending);
363                 Phase start = parent==null ? null : parent.phase();
364                 if (parent != null) parents().add(parent, true);
365                 if (Phase.this.hash.get(state, start) != null) throw new Error("severe problem!");
366                 Phase.this.hash.put(state, start, this);
367             }
368             public int toInt() { return idx; }
369             private final int idx = node_idx++;
370
371             // GraphViz //////////////////////////////////////////////////////////////////////////////
372
373             public GraphViz.Node toGraphViz(GraphViz gv) {
374                 if (gv.hasNode(this)) return gv.createNode(this);
375                 GraphViz.Node n = gv.createNode(this);
376                 n.label = ""+state.toStringx();
377                 n.shape = "rectangle";
378                 n.fill = "green";
379                 for(Forest result : results()) n.edge(result, "");
380                 for(Node parent : parents()) n.edge(parent, "");
381                 ((GraphViz.Group)phase().toGraphViz(gv)).add(n);
382                 return n;
383             }
384             public boolean isTransparent() { return false; }
385             public boolean isHidden() { return false; }
386
387         }
388         private int node_idx = 0;
389
390         public int toInt() { return pos+1; }
391         public int size() { return hash==null ? 0 : hash.size(); }
392
393         // GraphViz //////////////////////////////////////////////////////////////////////////////
394
395         public GraphViz.Node toGraphViz(GraphViz gv) {
396             if (gv.hasNode(this)) return gv.createNode(this);
397             GraphViz.Group g = gv.createGroup(this);
398             g.label = "Phase " + pos;
399             g.color = "gray";
400             g.cluster = true;
401             return g;
402         }
403         public boolean isTransparent() { return false; }
404         public boolean isHidden() { return false; }
405
406     }
407 }