major overhaul to institute optimal GSS sharing
[sbp.git] / src / edu / berkeley / sbp / GSS.java
1 // Copyright 2006-2007 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.Pos;
8 import edu.berkeley.sbp.Sequence.Pos;
9 import java.io.*;
10 import java.util.*;
11 import java.lang.reflect.*;
12
13 /** implements Tomita's Graph Structured Stack */
14 class GSS {
15
16     Input input;
17     private Parser parser;
18     public GSS(Input input, Parser parser) { this.input = input; this.parser = parser;}
19     public Input getInput() { return input; }
20
21     int numNewNodes = 0;
22     int numOldNodes = 0;
23     int viewPos = 0;
24     int numReductions = 0;
25
26     /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
27     class Phase<Tok> implements Invokable<State, Node, Forest>, IntegerMappable, GraphViz.ToGraphViz, Iterable<Node> {
28
29         // FIXME: right now, these are the performance bottleneck
30         private HashMapBag<Integer,Integer>       performed       = new HashMapBag<Integer,Integer>();
31
32         public Forest.Many finalResult;
33         private PriorityQueue<Reduction> reductionQueue = new PriorityQueue<Reduction>();
34
35         Parser parser() { return parser; }
36         public void addReduction(Reduction r) {
37             //System.out.println("+ " + r);
38             parser.spin();
39             reductionQueue.add(r);
40         }
41
42         public void invoke(State st, Node pred, Forest f) {
43             parser.spin();
44             good |= next.newNode(f, null, pred, st, false);
45         }
46
47         /** the token immediately after this phase */
48         final Tok token;
49         final int pos;
50         public IntPairMap<Node> hash = new IntPairMap<Node>();  /* ALLOC */
51         private boolean good = false;
52         private Phase next = null;
53         private Phase prev;
54         private Input.Location location;
55         private Input.Location nextLocation;
56         
57         private Forest forest;
58
59         public Phase(State startState) throws ParseFailed, IOException {
60             this(null, null);
61             newNode(null, null, null, startState, true);
62         }
63         public Phase(Phase prev, Forest forest) throws ParseFailed, IOException {
64             this.location = input.getLocation();
65             this.token = (Tok)input.next();
66             this.nextLocation = input.getLocation();
67             this.prev = prev;
68             this.forest = forest;
69             this.pos = prev==null ? 0 : prev.pos+1;
70             if (prev != null) prev.shift(this, forest);
71             numReductions = 0;
72
73             int minPhasePos = Integer.MAX_VALUE;
74             Reduction best = null;
75             //System.out.println("==============================================================================");
76             while(!reductionQueue.isEmpty()) {
77                 Reduction r = reductionQueue.poll();
78                 //System.out.println("- " + r);
79                 if (r.predPhase() != null)
80                     if (r.predPhase().pos > minPhasePos)
81                         throw new Error();
82                 r.perform();
83                 if (r.predPhase() != null) {
84                     if (r.predPhase().pos < minPhasePos) {
85                         minPhasePos = r.predPhase().pos;
86                         best = r;
87                     } else if (r.predPhase().pos == minPhasePos) {
88                         /*
89                         if (best != null && Parser.mastercache.comparePositions(r.reduction(), best.reduction()) < 0)
90                             throw new Error("\n"+r+"\n"+best+"\n"+
91                                             Parser.mastercache.comparePositions(r.reduction(), best.reduction())+"\n"+r.compareTo(best)+
92                                             "\n"+(r.reduction().ord-best.reduction().ord));
93                         */
94                         best = r;
95                     }
96                 }
97                 numReductions++;
98             }
99             if (token==null) shift(null, null);
100         }
101
102         public boolean isDone() throws ParseFailed {
103             if (token != null) return false;
104             if (token==null && finalResult==null)
105                 ParseFailed.error("unexpected end of file", this, null,
106                                   getLocation().createRegion(getLocation()));
107             return true;
108         }
109
110         public Input.Location getLocation() { return location; }
111         public Input.Location getNextLocation() { return nextLocation; }
112         public boolean        isFrontier() { return hash!=null; }
113
114         /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
115         private void shift(Phase next, Forest f) throws ParseFailed {
116             this.next = next;
117             // this massively improves GC performance
118             if (prev != null) {
119                 IntPairMap<Node> h = prev.hash;
120                 prev.hash = null;
121                 prev.performed = null;
122                 for(Node n : h) n.check();
123             }
124             numOldNodes = hash.size();
125             for(Node n : hash.values()) {
126                 if (token == null && n.state().isAccepting()) {
127                     if (finalResult==null) finalResult = new Forest.Many();
128                     for(Result r : n)
129                         finalResult.merge(r.getForest());
130                 }
131                 if (token == null) continue;
132                 n.state().invokeShifts(token, this, n, f);
133             }
134             numNewNodes = next==null ? 0 : next.hash.size();
135             viewPos = this.pos;
136
137             if (!good && token!=null) {
138                 String toks = token+"";
139                 if (toks.length()==1 && toks.charAt(0) == edu.berkeley.sbp.chr.CharAtom.left) {
140                     ParseFailed.error("unexpected increase in indentation", this,
141                                       token, getRegionFromThisToNext());
142                 } else if (toks.length()==1 && toks.charAt(0) == edu.berkeley.sbp.chr.CharAtom.right) {
143                     ParseFailed.error("unexpected decrease in indentation", this,
144                                       token, getRegionFromThisToNext());
145                 } else {
146                     ParseFailed.error("unexpected character '"+ANSI.cyan(StringUtil.escapify(token+"",
147                                                                                              "\\\'\r\n"))+"'",
148                                       this, token, getRegionFromThisToNext());
149                 }
150             }
151             if (token==null && finalResult==null)
152                 ParseFailed.error("unexpected end of file", this, null,
153                                   getLocation().createRegion(getLocation()));
154             for(Node n : hash) n.check();
155         }
156
157         Input.Region getRegionFromThisToNext() {
158             return getLocation().createRegion(getNextLocation());
159         }
160
161         void newNodeFromReduction(Forest f, Pos reduction, Node pred) {
162             int pos = pred.phase().pos;
163             for(int s : reduction.hates())
164                 if (performed.contains(pos, s))
165                     return;
166             for(int s : reduction.needs())
167                 if (!performed.contains(pos, s))
168                     return;
169             if (reduction.owner_needed_or_hated() && !performed.contains(pos, reduction.provides()))
170                 performed.add(pos, reduction.provides());
171             Parser.Table.State state = (Parser.Table.State)pred.state().gotoSetNonTerminals.get(reduction);
172             if (state!=null)
173                 newNode(f, reduction, pred, state, reduction.numPops()<=0);
174         }
175
176         /** add a new node (merging with existing nodes if possible)
177          *  @param parent             the parent of the new node
178          *  @param result             the SPPF result corresponding to the new node
179          *  @param state              the state that the new node is in
180          *  @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
181          *  @param start              the earliest part of the input contributing to this node (used to make merging decisions)
182          */
183         private boolean newNode(Forest f, Pos reduction, Node pred, State state, boolean fromEmptyReduction) {
184             Node p = pred==null ? null : hash.get(state, pred.phase());
185             if (p != null) {
186                 p.addResult(f, reduction, pred);
187                 return !state.doomed();
188             }
189             do {
190                 if (token != null && state.canShift(token)) break;
191                 if (state.isAccepting()) break;
192                 if (token==null) break;
193                 if (!state.canReduce(token)) return false;
194             } while(false);
195             Node n = new Node(Phase.this, f, reduction, pred, state, fromEmptyReduction);  // ALLOC
196             /** FIXME: this null-result can be used to notice bogus/dead states */
197             for(Object s : state.conjunctStates)
198                 newNode(null, null, n, (State)s, fromEmptyReduction);
199             return !n.state().doomed();
200         }
201
202         public int toInt() { return pos+1; }
203         public int size() { return hash==null ? 0 : hash.size(); }
204         public int pos() { return pos; }
205         public Tok getToken() { return token; }
206         public Iterator<Node> iterator() { return hash.iterator(); }
207         public GSS getGSS() { return GSS.this; }
208
209         // GraphViz //////////////////////////////////////////////////////////////////////////////
210
211         public GraphViz.Node toGraphViz(GraphViz gv) {
212             if (gv.hasNode(this)) return gv.createNode(this);
213             GraphViz.Group g = gv.createGroup(this);
214             g.label = "Phase " + pos;
215             g.color = "gray";
216             g.cluster = true;
217             return g;
218         }
219         public boolean isTransparent() { return false; }
220         public boolean isHidden() { return false; }
221
222         public void dumpGraphViz(String filename) throws IOException {
223             FileOutputStream fos = new FileOutputStream(filename);
224             PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
225             GraphViz gv = new GraphViz();
226             for(Object n : this)
227                 ((Node)n).toGraphViz(gv);
228             gv.dump(p);
229             p.flush();
230             p.close();
231         }
232
233     }
234
235 }