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