1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.Sequence.Position;
5 import edu.berkeley.sbp.Parser.Table.State;
6 import edu.berkeley.sbp.Parser.Table.Reduction;
9 import java.lang.reflect.*;
11 /** implements Tomita's Graph Structured Stack */
16 private Phase.Node[] reducing_list = null;
17 public int resets = 0;
20 HashMapBag<Integer,Sequence> inhibited = new HashMapBag<Integer,Sequence>();
21 HashMapBag<Sequence,Phase.Waiting> waiting = new HashMapBag<Sequence,Phase.Waiting>();
22 HashMapBag<Integer,Sequence> performed = new HashMapBag<Integer,Sequence>();
24 /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
25 public class Phase implements Invokable<State, Forest, GSS.Phase.Node>, IntegerMappable {
26 public int toInt() { return pos+1; }
28 /** the token immediately after this phase */
29 public final Token token;
33 /** currently this is necessary only for the code() hack -- it doesn't actually correspond to the input */
34 private final int pos;
37 public Forest.Ref finalResult;
39 /** all nodes, keyed by the value returned by code() */
40 /*private*/ IntPairMap<Phase.Node> hash; /* ALLOC */
42 /** the number of nodes in this phase */
48 private Phase next = null;
50 private Token.Location location;
51 public final Parser parser;
53 private Forest forest;
55 public Phase(Phase prev, Parser parser, Phase previous, Token token, Token.Location location, Forest forest) {
59 this.pos = previous==null ? 0 : previous.pos+1;
61 this.location = location;
69 hash = new IntPairMap<Phase.Node>();
75 if (prev != null) prev.shift(this, forest);
78 public void complain(Node n, HashMap<String,HashSet<String>> errors, boolean force) {
79 if (n.touched) return;
81 for(Position p : n.state) {
82 if (((p.isFirst() || p.isLast()) && !force) || p.owner().name==null) {
83 for(Node n2 : n.parents())
84 complain(n2, errors, force | p.isFirst());
86 String seqname = p.owner().name;
87 HashSet<String> hs = errors.get(seqname);
88 if (hs==null) errors.put(seqname, hs = new HashSet<String>());
89 hs.add(p.element()+"");
94 public String black(Object o) { return "\033[30m"+o+"\033[0m"; }
95 public String red(Object o) { return "\033[31m"+o+"\033[0m"; }
96 public String green(Object o) { return "\033[32m"+o+"\033[0m"; }
97 public String yellow(Object o) { return "\033[33m"+o+"\033[0m"; }
98 public String blue(Object o) { return "\033[34m"+o+"\033[0m"; }
99 public String purple(Object o) { return "\033[35m"+o+"\033[0m"; }
100 public String cyan(Object o) { return "\033[36m"+o+"\033[0m"; }
101 public String el(Object e) {
102 String s = e.toString();
103 if (s.length()==0 || s.charAt(0)!='\"' || s.charAt(s.length()-1)!='\"') return yellow(s);
105 s = s.substring(0, s.length()-1);
106 StringBuffer ret = new StringBuffer();
107 for(int i=0; i<s.length(); i++) {
108 if (s.charAt(i)=='\\' && i<s.length()-1) ret.append(s.charAt(++i));
111 return purple(ret.toString());
113 public String error(String message) {
114 String lookAhead = token==null ? "<EOF>" : token.toString();
115 StringBuffer ret = new StringBuffer();
118 HashMap<String,HashSet<String>> errors = new HashMap<String,HashSet<String>>();
119 for(Node n : hash.values()) {
120 //System.out.println(n.state);
121 complain(n, errors, false);
123 for(String s : errors.keySet()) {
124 ret.append(" while parsing " + yellow(s));
125 HashSet<String> hs = errors.get(s);
126 if (hs.size()==1) ret.append(" expected " + yellow(el(hs.iterator().next())) + "\n");
128 ret.append(" expected ");
129 boolean first = true;
130 for(String s2 : hs) {
131 if (!first) ret.append(" or ");
133 ret.append(yellow(el(s2)));
138 return ret.toString();
141 public boolean isDone() throws ParseFailed {
142 if (token != null) return false;
143 if (token==null && finalResult==null)
144 throw new ParseFailed(error(red("unexpected end of file\n")),
149 public Token.Location getLocation() { return location; }
151 /** add a new node (merging with existing nodes if possible)
152 * @param parent the parent of the new node
153 * @param result the SPPF result corresponding to the new node
154 * @param state the state that the new node is in
155 * @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
156 * @param start the earliest part of the input contributing to this node (used to make merging decisions)
158 public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
159 Node p = hash.get(state, parent==null?null:parent.phase());
160 if (p != null) return newNode2(p, parent, pending, state, fromEmptyReduction);
161 else return newNode3(parent, pending, state, fromEmptyReduction);
163 public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
164 int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
165 Sequence owner = reduction==null ? null : reduction.position.owner();
166 if (reduction!=null) {
167 if (inhibited.contains(pos, owner)) return;
168 if (owner.needs != null)
169 for(Sequence s : owner.needs)
170 if (!performed.contains(pos, s)) {
171 waiting.add(s, new Waiting(parent, pending, state, fromEmptyReduction, reduction));
174 if ((owner.needed != null && owner.needed.size()>0) ||
175 (owner.hated != null && owner.hated.size()>0) ||
176 (owner.hates != null && owner.hates.size()>0))
177 performed.add(pos, owner);
180 newNode(parent, pending, state, fromEmptyReduction);
181 if (reduction!=null) inhibit(reduction, parent==null?0:parent.phase().pos);
182 if (reduction != null) {
186 for(Waiting w : waiting.getAll(owner)) {
187 if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
188 waiting.remove(owner, w);
197 private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
198 p.holder.merge(pending);
199 if (p.parents().contains(parent)) return true;
200 p.parents().add(parent, true);
201 if (p!=parent && !fromEmptyReduction) p.queueReductions(parent);
204 private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
206 if (token != null && state.canShift(token)) break;
207 if (state.isAccepting()) break;
208 if (token==null) break;
209 if (!state.canReduce(token)) return false;
210 //if (count > 1) break;
211 //if (r.numPop == 0) break;
212 //r.reduce(pending, parent, null, Phase.this, null);
216 Node n = new Node(parent, pending, state, fromEmptyReduction); // ALLOC
217 n.queueEmptyReductions();
218 if (!fromEmptyReduction) n.queueReductions(parent);
222 public void uninhibit(int p, Sequence s) {
224 for(Sequence s2 : s.hated)
225 inhibited.remove(p, s2);
228 public void inhibit(Reduction r, int p) {
229 if (r.position.owner().hated == null) return;
230 // remember that dead states are still allowed to shift -- just not allowed to reduce
231 boolean reset = false;
232 for(Sequence seq : r.position.owner().hated) {
233 if (performed.contains(p,seq)) {
235 //System.out.println("\nresetting due to " + r.position.owner() + " killing " + seq);
237 inhibited.add(p, seq);
238 //inhibited = new HashMapBag<Integer,Sequence>();
243 inhibited.add(p, seq);
247 /** perform all reduction operations */
248 public void reduce() {
251 if (reducing_list==null || reducing_list.length < hash.size())
252 reducing_list = new Phase.Node[hash.size() * 4];
253 hash.toArray(reducing_list);
254 int num = hash.size();
255 for(int i=0; i<num; i++) {
256 Node n = reducing_list[i];
257 n.queueEmptyReductions();
258 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
260 for(int i=0; i<num; i++) {
261 Node n = reducing_list[i];
262 reducing_list[i] = null;
271 class Reset extends RuntimeException { }
273 public void invoke(State st, Forest result, Node n) {
274 good |= next.newNode(n, result, st, false);
277 /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
278 public void shift(Phase next, Forest result) throws ParseFailed {
279 if (prev!=null) prev.hash = null;
284 for(Phase.Node n : hash.values()) {
285 if (token == null && n.state.isAccepting()) {
286 if (finalResult==null) finalResult = new Forest.Ref();
287 finalResult.merge(n.holder);
289 if (token == null) continue;
290 n.state.invokeShifts(token, this, result, n);
293 if (!good && token!=null)
294 throw new ParseFailed(error(red("unexpected character")+" "+purple(token)+" encountered at "+green(getLocation())+"\n"),
296 if (token==null && finalResult==null)
297 throw new ParseFailed(error(red("unexpected end of file\n")),
300 // this massively improves GC performance
305 public class Waiting {
309 boolean fromEmptyReduction;
311 public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
313 this.parent = parent;
314 this.pending = pending;
316 this.fromEmptyReduction = fromEmptyReduction;
317 this.reduction = reduction;
319 public void perform() {
320 //System.out.println("performing: " + reduction.position);
321 newNode(parent, pending, state, fromEmptyReduction, reduction);
325 // GSS Nodes //////////////////////////////////////////////////////////////////////////////
327 /** a node in the GSS */
328 public final class Node extends FastSet<Node> implements Invokable<Reduction, Node, Node> {
330 public boolean touched = false;
331 private Forest.Ref holder = null;
332 private boolean allqueued = false;
334 /** what state this node is in */
335 public final State state;
337 /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
338 public Phase phase() { return Phase.this; }
340 public Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
341 public Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
342 public FastSet<Node> parents() { return this; }
344 public void queueReductions() {
345 if (!reducing) return;
346 if (allqueued) return;
348 int where = parents().size();
349 state.invokeReductions(token, this, this, null);
352 public void queueReductions(Node n2) {
353 if (!allqueued) { queueReductions(); return; }
354 state.invokeReductions(token, this, this, n2);
357 public final void invoke(Reduction r, Node n, Node n2) {
359 if (r.position.pos==0) r.reduce(this);
362 if (r.position.pos==0) return;
363 if (n2==null) r.reduce(n);
364 else r.reduce(n, n2);
366 public void queueEmptyReductions() {
367 if (!reducing) return;
368 state.invokeReductions(token, this, null, null);
372 public boolean dead = false;
373 public boolean redo = false;
374 private Node(Node parent, Forest pending, State state, boolean fe) {
377 this.holder().merge(pending);
378 Phase start = parent==null ? null : parent.phase();
379 if (parent != null) parents().add(parent, true);
380 if (Phase.this.hash.get(state, start) != null) throw new Error("severe problem!");
381 Phase.this.hash.put(state, start, this);
382 Phase.this.numNodes++;
389 private static boolean equal(Object a, Object b) {
390 if (a==null && b==null) return true;
391 if (a==null || b==null) return false;