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