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<Integer,Sequence> assumed = 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 HashSet<Phase.Waiting> tail = new HashSet<Phase.Waiting>();
26 /** corresponds to a positions <i>between tokens</i> the input stream; same as Tomita's U_i's */
27 public class Phase implements Invokable<State, Forest, GSS.Phase.Node>, IntegerMappable {
28 public int toInt() { return pos+1; }
30 /** the token immediately after this phase */
31 public final Token token;
35 /** currently this is necessary only for the code() hack -- it doesn't actually correspond to the input */
36 private final int pos;
39 public Forest.Ref finalResult;
41 /** all nodes, keyed by the value returned by code() */
42 /*private*/ HashMap<Long,Phase.Node> hash; /* ALLOC */
44 /** the number of nodes in this phase */
50 private Phase next = null;
52 private Token.Location location;
53 public final Parser parser;
55 private Forest forest;
57 public Phase(Phase prev, Parser parser, Phase previous, Token token, Token.Location location, Forest forest) {
61 this.pos = previous==null ? 0 : previous.pos+1;
63 this.location = location;
73 hash = new HashMap<Long,Phase.Node>();
79 if (prev != null) prev.shift(this, forest);
82 public void complain(Node n, HashMap<String,HashSet<String>> errors, boolean force) {
83 if (n.touched) return;
85 for(Position p : n.state) {
87 if (((p.isFirst() || p.isLast()) && !force) || p.owner().name==null) {
88 for(Node n2 : n.parents())
89 complain(n2, errors, force | p.isFirst());
91 String seqname = p.owner().name;
92 HashSet<String> hs = errors.get(seqname);
93 if (hs==null) errors.put(seqname, hs = new HashSet<String>());
94 hs.add(p.element()+"");
95 //String s = " while parsing " + seqname + ": expected a " + p.element();
99 for(Position p2 = p.owner().firstp(); p2 != null && p2 != p && !p2.isLast(); p2 = p2.next()) s += (p2.element() + " ");
102 for(Position p2 = p; p2 != null && !p2.isLast(); p2 = p2.next()) s += (p2.element() + " ");
110 public String black(Object o) { return "\033[30m"+o+"\033[0m"; }
111 public String red(Object o) { return "\033[31m"+o+"\033[0m"; }
112 public String green(Object o) { return "\033[32m"+o+"\033[0m"; }
113 public String yellow(Object o) { return "\033[33m"+o+"\033[0m"; }
114 public String blue(Object o) { return "\033[34m"+o+"\033[0m"; }
115 public String purple(Object o) { return "\033[35m"+o+"\033[0m"; }
116 public String cyan(Object o) { return "\033[36m"+o+"\033[0m"; }
117 public String el(Object e) {
118 String s = e.toString();
119 if (s.length()==0 || s.charAt(0)!='\"' || s.charAt(s.length()-1)!='\"') return yellow(s);
121 s = s.substring(0, s.length()-1);
122 StringBuffer ret = new StringBuffer();
123 for(int i=0; i<s.length(); i++) {
124 if (s.charAt(i)=='\\' && i<s.length()-1) ret.append(s.charAt(++i));
127 return purple(ret.toString());
129 public String error(String message) {
130 String lookAhead = token==null ? "<EOF>" : token.toString();
131 StringBuffer ret = new StringBuffer();
134 HashMap<String,HashSet<String>> errors = new HashMap<String,HashSet<String>>();
135 for(Node n : hash.values()) complain(n, errors, false);
136 for(String s : errors.keySet()) {
137 ret.append(" while parsing " + yellow(s));
138 HashSet<String> hs = errors.get(s);
139 if (hs.size()==1) ret.append(" expected " + yellow(el(hs.iterator().next())) + "\n");
141 ret.append(" expected ");
142 boolean first = true;
143 for(String s2 : hs) {
144 if (!first) ret.append(" or ");
146 ret.append(yellow(el(s2)));
151 return ret.toString();
154 public boolean isDone() throws Parser.Failed {
155 if (token != null) return false;
156 if (token==null && finalResult==null)
157 throw new Parser.Failed(error(red("unexpected end of file\n")),
162 public Token.Location getLocation() { return location; }
164 /** add a new node (merging with existing nodes if possible)
165 * @param parent the parent of the new node
166 * @param result the SPPF result corresponding to the new node
167 * @param state the state that the new node is in
168 * @param fromEmptyReduction true iff this node is being created as a result of a reduction of length zero (see GRMLR paper)
169 * @param start the earliest part of the input contributing to this node (used to make merging decisions)
171 public boolean newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
172 Node p = hash.get(code(state, parent==null?null:parent.phase()));
173 if (p != null) return newNode2(p, parent, pending, state, fromEmptyReduction);
174 else return newNode3(parent, pending, state, fromEmptyReduction);
176 public void newNode(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
177 int pos = parent==null?0:parent.phase()==null?0:parent.phase().pos;
178 Sequence owner = reduction==null ? null : reduction.position.owner();
179 if (reduction!=null) {
180 if (inhibited.contains(pos, owner)) return;
182 if (assumed.contains(pos, owner)) {
183 tail.add(new Waiting(parent, pending, state, fromEmptyReduction, reduction));
187 if (owner.needs != null)
188 for(Sequence s : owner.needs)
189 if (!performed.contains(pos, s)) {
190 waiting.add(s, new Waiting(parent, pending, state, fromEmptyReduction, reduction));
193 if ((owner.needed != null && owner.needed.size()>0) ||
194 (owner.hated != null && owner.hated.size()>0) ||
195 (owner.hates != null && owner.hates.size()>0))
196 performed.add(pos, owner);
199 newNode(parent, pending, state, fromEmptyReduction);
200 if (reduction!=null) inhibit(reduction, parent==null?0:parent.phase().pos);
201 if (reduction != null) {
205 for(Waiting w : waiting.getAll(owner)) {
206 if (w.parent==parent || (parent!=null&&w.parent!=null&&w.parent.phase()==parent.phase())) {
207 waiting.remove(owner, w);
216 private boolean newNode2(Node p, Node parent, Forest pending, State state, boolean fromEmptyReduction) {
217 p.holder.merge(pending);
218 if (p.parents().contains(parent)) return true;
219 p.parents().add(parent, true);
220 if (p!=parent && !fromEmptyReduction) p.queueReductions(parent);
223 private boolean newNode3(Node parent, Forest pending, State state, boolean fromEmptyReduction) {
225 if (token != null && state.canShift(token)) break;
226 if (state.isAccepting()) break;
227 if (token==null) break;
228 //if (!state.canReduce(token)) return false;
229 //if (count > 1) break;
230 //if (r.numPop == 0) break;
231 //r.reduce(pending, parent, null, Phase.this, null);
235 Node n = new Node(parent, pending, state, fromEmptyReduction); // ALLOC
236 n.queueEmptyReductions();
237 if (!fromEmptyReduction) n.queueReductions(parent);
241 public void uninhibit(int p, Sequence s) {
243 for(Sequence s2 : s.hated)
244 inhibited.remove(p, s2);
247 public void inhibit(Reduction r, int p) {
248 if (r.position.owner().hated == null) return;
249 // remember that dead states are still allowed to shift -- just not allowed to reduce
250 boolean reset = false;
251 for(Sequence seq : r.position.owner().hated) {
252 if (performed.contains(p,seq)) {
254 //System.out.println("\nresetting due to " + r.position.owner() + " killing " + seq);
256 inhibited.add(p, seq);
257 //assumed = inhibited;
258 //inhibited = new HashMapBag<Integer,Sequence>();
263 inhibited.add(p, seq);
267 /** perform all reduction operations */
268 public void reduce() {
271 if (reducing_list==null || reducing_list.length < hash.size())
272 reducing_list = new Phase.Node[hash.size() * 4];
273 Collection<Node> hv = hash.values();
274 hv.toArray(reducing_list);
276 for(int i=0; i<num; i++) {
277 Node n = reducing_list[i];
278 n.queueEmptyReductions();
279 // INVARIANT: we never "see" a node until its parent-set is complete, modulo merges
281 for(int i=0; i<num; i++) {
282 Node n = reducing_list[i];
283 reducing_list[i] = null;
286 //for(Waiting w : tail)
294 class Reset extends RuntimeException { }
296 public void invoke(State st, Forest result, Node n) {
297 good |= next.newNode(n, result, st, false);
300 /** perform all shift operations, adding promoted nodes to <tt>next</tt> */
301 public void shift(Phase next, Forest result) throws Parser.Failed {
302 if (prev!=null) prev.hash = null;
307 for(Phase.Node n : hash.values()) {
308 if (token == null && n.state.isAccepting()) {
309 if (finalResult==null) finalResult = new Forest.Ref();
310 finalResult.merge(n.holder);
312 if (token == null) continue;
313 n.state.invokeShifts(token, this, result, n);
316 if (!good && token!=null)
317 throw new Parser.Failed(error(red("unexpected character")+" "+purple(token)+" encountered at "+green(getLocation())+"\n"),
319 if (token==null && finalResult==null)
320 throw new Parser.Failed(error(red("unexpected end of file\n")),
323 // this massively improves GC performance
328 public class Waiting {
332 boolean fromEmptyReduction;
334 public Waiting(Node parent, Forest pending, State state, boolean fromEmptyReduction, Reduction reduction) {
336 this.parent = parent;
337 this.pending = pending;
339 this.fromEmptyReduction = fromEmptyReduction;
340 this.reduction = reduction;
342 public void perform() {
343 //System.out.println("performing: " + reduction.position);
344 newNode(parent, pending, state, fromEmptyReduction, reduction);
348 // GSS Nodes //////////////////////////////////////////////////////////////////////////////
350 /** a node in the GSS */
351 public final class Node extends FastSet<Node> implements Invokable<Reduction, Node, Node> {
353 public boolean touched = false;
354 private Forest.Ref holder = null;
355 private boolean allqueued = false;
357 /** what state this node is in */
358 public final State state;
360 /** which Phase this Node belongs to (node that Node is also a non-static inner class of Phase) */
361 public Phase phase() { return Phase.this; }
363 public Forest.Ref holder() { return holder==null ? (holder = new Forest.Ref()) : holder; }
364 public Forest pending() { return Phase.this.closed ? holder().resolve() : holder; }
365 public FastSet<Node> parents() { return this; }
367 public void queueReductions() {
368 if (!reducing) return;
369 if (allqueued) return;
371 int where = parents().size();
372 state.invokeReductions(token, this, this, null);
375 public void queueReductions(Node n2) {
376 if (!allqueued) { queueReductions(); return; }
377 state.invokeReductions(token, this, this, n2);
380 public final void invoke(Reduction r, Node n, Node n2) {
382 if (r.numPop==0) r.reduce(this);
385 if (r.numPop==0) return;
386 if (n2==null) r.reduce(n);
387 else r.reduce(n, n2);
389 public void queueEmptyReductions() {
390 if (!reducing) return;
391 state.invokeReductions(token, this, null, null);
395 public boolean dead = false;
396 public boolean redo = false;
397 private Node(Node parent, Forest pending, State state, boolean fe) {
400 this.holder().merge(pending);
401 Phase start = parent==null ? null : parent.phase();
402 if (parent != null) parents().add(parent, true);
403 if (Phase.this.hash.get(code(state, start)) != null) throw new Error("severe problem!");
404 Phase.this.hash.put(code(state, start), this);
405 Phase.this.numNodes++;
412 private static boolean equal(Object a, Object b) {
413 if (a==null && b==null) return true;
414 if (a==null || b==null) return false;
418 /** this is something of a hack right now */
419 private static long code(State state, Phase start) {
420 return (((long)state.idx) << 32) | (start==null ? 0 : (start.pos+1));