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