1 // Copyright 2006-2007 all rights reserved; see LICENSE file for BSD-style license
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;
11 import java.lang.reflect.*;
13 /** implements Tomita's Graph Structured Stack */
17 private Parser parser;
18 public GSS(Input input, Parser parser) { this.input = input; this.parser = parser;}
19 public Input getInput() { return input; }
24 int numReductions = 0;
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> {
29 // FIXME: right now, these are the performance bottleneck
30 private HashMapBag<Integer,Integer> performed = new HashMapBag<Integer,Integer>();
32 public Forest.Many finalResult;
33 private PriorityQueue<Reduction> reductionQueue = new PriorityQueue<Reduction>();
35 Parser parser() { return parser; }
36 public void addReduction(Reduction r) {
37 //System.out.println("+ " + r);
39 reductionQueue.add(r);
42 public void invoke(State st, Node pred, Forest f) {
44 good |= next.newNode(f, null, pred, st, false);
47 /** the token immediately after this phase */
50 public IntPairMap<Node> hash = new IntPairMap<Node>(); /* ALLOC */
51 private boolean good = false;
52 private Phase next = null;
54 private Input.Location location;
55 private Input.Location nextLocation;
57 private Forest forest;
59 public Phase(State startState) throws ParseFailed, IOException {
61 newNode(null, null, null, startState, true);
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();
69 this.pos = prev==null ? 0 : prev.pos+1;
70 if (prev != null) prev.shift(this, forest);
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)
83 if (r.predPhase() != null) {
84 if (r.predPhase().pos < minPhasePos) {
85 minPhasePos = r.predPhase().pos;
87 } else if (r.predPhase().pos == minPhasePos) {
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));
99 if (token==null) shift(null, null);
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()));
110 public Input.Location getLocation() { return location; }
111 public Input.Location getNextLocation() { return nextLocation; }
112 public boolean isFrontier() { return hash!=null; }
114 /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
115 private void shift(Phase next, Forest f) throws ParseFailed {
117 // this massively improves GC performance
119 IntPairMap<Node> h = prev.hash;
121 prev.performed = null;
122 for(Node n : h) n.check();
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();
129 finalResult.merge(r.getForest());
131 if (token == null) continue;
132 n.state().invokeShifts(token, this, n, f);
134 numNewNodes = next==null ? 0 : next.hash.size();
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());
146 ParseFailed.error("unexpected character '"+ANSI.cyan(StringUtil.escapify(token+"",
148 this, token, getRegionFromThisToNext());
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();
157 Input.Region getRegionFromThisToNext() {
158 return getLocation().createRegion(getNextLocation());
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))
166 for(int s : reduction.needs())
167 if (!performed.contains(pos, s))
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);
173 newNode(f, reduction, pred, state, reduction.numPops()<=0);
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)
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());
186 p.addResult(f, reduction, pred);
187 return !state.doomed();
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;
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();
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; }
209 // GraphViz //////////////////////////////////////////////////////////////////////////////
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;
219 public boolean isTransparent() { return false; }
220 public boolean isHidden() { return false; }
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();
227 ((Node)n).toGraphViz(gv);